xref: /aosp_15_r20/system/core/run-as/run-as.cpp (revision 00c7fec1bb09f3284aad6a6f96d2f63dfc3650ad)
1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <errno.h>
18 #include <error.h>
19 #include <paths.h>
20 #include <pwd.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <sys/capability.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 #include <unistd.h>
27 
28 #include <string>
29 #include <vector>
30 
31 #include <libminijail.h>
32 #include <scoped_minijail.h>
33 
34 #include <android-base/properties.h>
35 #include <packagelistparser/packagelistparser.h>
36 #include <private/android_filesystem_config.h>
37 #include <selinux/android.h>
38 
39 // The purpose of this program is to run a command as a specific
40 // application user-id. Typical usage is:
41 //
42 //   run-as <package-name> <command> <args>
43 //
44 //  The 'run-as' binary is installed with CAP_SETUID and CAP_SETGID file
45 //  capabilities, but will check the following:
46 //
47 //  - that the ro.boot.disable_runas property is not set
48 //  - that it is invoked from the 'shell' or 'root' user (abort otherwise)
49 //  - that '<package-name>' is the name of an installed and debuggable package
50 //  - that the package's data directory is well-formed
51 //
52 //  If so, it will drop to the application's user id / group id, cd to the
53 //  package's data directory, then run the command there.
54 //
55 //  This can be useful for a number of different things on production devices:
56 //
57 //  - Allow application developers to look at their own application data
58 //    during development.
59 //
60 //  - Run the 'gdbserver' binary executable to allow native debugging
61 //
62 
packagelist_parse_callback(pkg_info * this_package,void * userdata)63 static bool packagelist_parse_callback(pkg_info* this_package, void* userdata) {
64   pkg_info* p = reinterpret_cast<pkg_info*>(userdata);
65   if (strcmp(p->name, this_package->name) == 0) {
66     *p = *this_package;
67     return false; // Stop searching.
68   }
69   packagelist_free(this_package);
70   return true; // Keep searching.
71 }
72 
check_directory(const char * path,uid_t uid)73 static void check_directory(const char* path, uid_t uid) {
74   struct stat st;
75   if (TEMP_FAILURE_RETRY(lstat(path, &st)) == -1) {
76     error(1, errno, "couldn't stat %s", path);
77   }
78 
79   // Must be a real directory, not a symlink.
80   if (!S_ISDIR(st.st_mode)) {
81     error(1, 0, "%s not a directory: %o", path, st.st_mode);
82   }
83 
84   // Must be owned by specific uid/gid.
85   if (st.st_uid != uid || st.st_gid != uid) {
86     error(1, 0, "%s has wrong owner: %d/%d, not %d", path, st.st_uid, st.st_gid, uid);
87   }
88 
89   // Must not be readable or writable by others.
90   if ((st.st_mode & (S_IROTH | S_IWOTH)) != 0) {
91     error(1, 0, "%s readable or writable by others: %o", path, st.st_mode);
92   }
93 }
94 
95 // This function is used to check the data directory path for safety.
96 // We check that every sub-directory is owned by the 'system' user
97 // and exists and is not a symlink. We also check that the full directory
98 // path is properly owned by the user ID.
check_data_path(const char * package_name,const char * data_path,uid_t uid)99 static void check_data_path(const char* package_name, const char* data_path, uid_t uid) {
100   // The path should be absolute.
101   if (data_path[0] != '/') {
102     error(1, 0, "%s data path not absolute: %s", package_name, data_path);
103   }
104 
105   // Look for all sub-paths, we do that by finding
106   // directory separators in the input path and
107   // checking each sub-path independently.
108   for (int nn = 1; data_path[nn] != '\0'; nn++) {
109     char subpath[PATH_MAX];
110 
111     /* skip non-separator characters */
112     if (data_path[nn] != '/') continue;
113 
114     /* handle trailing separator case */
115     if (data_path[nn+1] == '\0') break;
116 
117     /* found a separator, check that data_path is not too long. */
118     if (nn >= (int)(sizeof subpath)) {
119       error(1, 0, "%s data path too long: %s", package_name, data_path);
120     }
121 
122     /* reject any '..' subpath */
123     if (nn >= 3               &&
124         data_path[nn-3] == '/' &&
125         data_path[nn-2] == '.' &&
126         data_path[nn-1] == '.') {
127       error(1, 0, "%s contains '..': %s", package_name, data_path);
128     }
129 
130     /* copy to 'subpath', then check ownership */
131     memcpy(subpath, data_path, nn);
132     subpath[nn] = '\0';
133 
134     check_directory(subpath, AID_SYSTEM);
135   }
136 
137   // All sub-paths were checked, now verify that the full data
138   // directory is owned by the application uid.
139   check_directory(data_path, uid);
140 }
141 
get_supplementary_gids(uid_t userAppId)142 std::vector<gid_t> get_supplementary_gids(uid_t userAppId) {
143   std::vector<gid_t> gids;
144   int size = getgroups(0, &gids[0]);
145   if (size < 0) {
146     error(1, errno, "getgroups failed");
147   }
148   gids.resize(size);
149   size = getgroups(size, &gids[0]);
150   if (size != static_cast<int>(gids.size())) {
151     error(1, errno, "getgroups failed");
152   }
153   // Profile guide compiled oat files (like /data/app/xxx/oat/arm64/base.odex) are not readable
154   // worldwide (DEXOPT_PUBLIC flag isn't set). To support reading them (needed by simpleperf for
155   // profiling), add shared app gid to supplementary groups.
156   gid_t shared_app_gid = userAppId % AID_USER_OFFSET - AID_APP_START + AID_SHARED_GID_START;
157   gids.push_back(shared_app_gid);
158   return gids;
159 }
160 
main(int argc,char * argv[])161 int main(int argc, char* argv[]) {
162   // Check arguments.
163   if (argc < 2) {
164     error(1, 0, "usage: run-as <package-name> [--user <uid>] <command> [<args>]\n");
165   }
166 
167   // This program runs with CAP_SETUID and CAP_SETGID capabilities on Android
168   // production devices. Check user id of caller --- must be 'shell' or 'root'.
169   if (getuid() != AID_SHELL && getuid() != AID_ROOT) {
170     error(1, 0, "only 'shell' or 'root' users can run this program");
171   }
172 
173   // Some devices can disable running run-as, such as Chrome OS when running in
174   // non-developer mode.
175   if (android::base::GetBoolProperty("ro.boot.disable_runas", false)) {
176     error(1, 0, "run-as is disabled from the kernel commandline");
177   }
178 
179   char* pkgname = argv[1];
180   int cmd_argv_offset = 2;
181 
182   // Get user_id from command line if provided.
183   int userId = 0;
184   if ((argc >= 4) && !strcmp(argv[2], "--user")) {
185     userId = atoi(argv[3]);
186     if (userId < 0) error(1, 0, "negative user id: %d", userId);
187     cmd_argv_offset += 2;
188   }
189 
190   // Retrieve package information from system, switching egid so we can read the file.
191   pkg_info info = {.name = pkgname};
192   gid_t old_egid = getegid();
193   if (setegid(AID_PACKAGE_INFO) == -1) error(1, errno, "setegid(AID_PACKAGE_INFO) failed");
194   if (!packagelist_parse(packagelist_parse_callback, &info)) {
195     error(1, errno, "packagelist_parse failed");
196   }
197   if (setegid(old_egid) == -1) error(1, errno, "couldn't restore egid");
198 
199   if (info.uid == 0) {
200     error(1, 0, "unknown package: %s", pkgname);
201   }
202 
203   // Verify that user id is not too big.
204   if ((UID_MAX - info.uid) / AID_USER_OFFSET < (uid_t)userId) {
205     error(1, 0, "user id too big: %d", userId);
206   }
207 
208   // Calculate user app ID.
209   uid_t userAppId = (AID_USER_OFFSET * userId) + info.uid;
210 
211   // Reject system packages.
212   if (userAppId < AID_APP) {
213     error(1, 0, "package not an application: %s", pkgname);
214   }
215 
216   // Reject any non-debuggable package.
217   if (!info.debuggable) {
218     error(1, 0, "package not debuggable: %s", pkgname);
219   }
220 
221   // Ensure we have the right data path for the specific user.
222   free(info.data_dir);
223   if (asprintf(&info.data_dir, "/data/user/%d/%s", userId, pkgname) == -1) {
224     error(1, errno, "asprintf failed");
225   }
226 
227   // Check that the data directory path is valid.
228   check_data_path(pkgname, info.data_dir, userAppId);
229 
230   // Ensure that we change all real/effective/saved IDs at the
231   // same time to avoid nasty surprises.
232   uid_t uid = userAppId;
233   uid_t gid = userAppId;
234   std::vector<gid_t> supplementary_gids = get_supplementary_gids(userAppId);
235   ScopedMinijail j(minijail_new());
236   minijail_change_uid(j.get(), uid);
237   minijail_change_gid(j.get(), gid);
238   minijail_set_supplementary_gids(j.get(), supplementary_gids.size(), supplementary_gids.data());
239   minijail_enter(j.get());
240 
241   std::string seinfo = std::string(info.seinfo) + ":fromRunAs";
242   if (selinux_android_setcontext(uid, 0, seinfo.c_str(), pkgname) < 0) {
243     error(1, errno, "couldn't set SELinux security context '%s'", seinfo.c_str());
244   }
245 
246   // cd into the data directory, and set $HOME correspondingly.
247   if (TEMP_FAILURE_RETRY(chdir(info.data_dir)) == -1) {
248     error(1, errno, "couldn't chdir to package's data directory '%s'", info.data_dir);
249   }
250   setenv("HOME", info.data_dir, 1);
251 
252   // Reset parts of the environment, like su would.
253   setenv("PATH", _PATH_DEFPATH, 1);
254   unsetenv("IFS");
255 
256   // Set the user-specific parts for this user.
257   passwd* pw = getpwuid(uid);
258   setenv("LOGNAME", pw->pw_name, 1);
259   setenv("SHELL", pw->pw_shell, 1);
260   setenv("USER", pw->pw_name, 1);
261 
262   // User specified command for exec.
263   if ((argc >= cmd_argv_offset + 1) &&
264       (execvp(argv[cmd_argv_offset], argv+cmd_argv_offset) == -1)) {
265     error(1, errno, "exec failed for %s", argv[cmd_argv_offset]);
266   }
267 
268   // Default exec shell.
269   execlp(_PATH_BSHELL, "sh", NULL);
270   error(1, errno, "exec failed");
271 }
272