blob: 9ebe799e119348c60e031d309a934e547e89f902 [file] [log] [blame]
Elliott Hughes0c8bf572016-07-07 16:22:19 -07001/*
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
Yabin Cui97e3bb32018-11-02 15:22:13 -070028#include <string>
Yabin Cui3a60e682019-01-10 15:08:22 -080029#include <vector>
Yabin Cui97e3bb32018-11-02 15:22:13 -070030
Jorge Lucangeli Obesa377ff02016-07-15 11:24:20 -040031#include <libminijail.h>
32#include <scoped_minijail.h>
33
Luis Hector Chavezef62f3f2018-06-27 10:40:10 -070034#include <android-base/properties.h>
Elliott Hughes0c8bf572016-07-07 16:22:19 -070035#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//
Luis Hector Chavezef62f3f2018-06-27 10:40:10 -070047// - that the ro.boot.disable_runas property is not set
Elliott Hughes0c8bf572016-07-07 16:22:19 -070048// - 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
63static 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
Elliott Hughes964932d2019-03-13 11:15:06 -070073static void check_directory(const char* path, uid_t uid) {
Elliott Hughes0c8bf572016-07-07 16:22:19 -070074 struct stat st;
Elliott Hughes964932d2019-03-13 11:15:06 -070075 if (TEMP_FAILURE_RETRY(lstat(path, &st)) == -1) {
76 error(1, errno, "couldn't stat %s", path);
77 }
Elliott Hughes0c8bf572016-07-07 16:22:19 -070078
79 // /data/user/0 is a known safe symlink.
Elliott Hughes964932d2019-03-13 11:15:06 -070080 if (strcmp("/data/user/0", path) == 0) return;
Elliott Hughes0c8bf572016-07-07 16:22:19 -070081
82 // Must be a real directory, not a symlink.
Elliott Hughes964932d2019-03-13 11:15:06 -070083 if (!S_ISDIR(st.st_mode)) {
84 error(1, 0, "%s not a directory: %o", path, st.st_mode);
85 }
Elliott Hughes0c8bf572016-07-07 16:22:19 -070086
87 // Must be owned by specific uid/gid.
Elliott Hughes964932d2019-03-13 11:15:06 -070088 if (st.st_uid != uid || st.st_gid != uid) {
89 error(1, 0, "%s has wrong owner: %d/%d, not %d", path, st.st_uid, st.st_gid, uid);
90 }
Elliott Hughes0c8bf572016-07-07 16:22:19 -070091
92 // Must not be readable or writable by others.
Elliott Hughes964932d2019-03-13 11:15:06 -070093 if ((st.st_mode & (S_IROTH | S_IWOTH)) != 0) {
94 error(1, 0, "%s readable or writable by others: %o", path, st.st_mode);
95 }
Elliott Hughes0c8bf572016-07-07 16:22:19 -070096}
97
98// This function is used to check the data directory path for safety.
99// We check that every sub-directory is owned by the 'system' user
100// and exists and is not a symlink. We also check that the full directory
101// path is properly owned by the user ID.
Elliott Hughes964932d2019-03-13 11:15:06 -0700102static void check_data_path(const char* package_name, const char* data_path, uid_t uid) {
Elliott Hughes0c8bf572016-07-07 16:22:19 -0700103 // The path should be absolute.
Elliott Hughes964932d2019-03-13 11:15:06 -0700104 if (data_path[0] != '/') {
105 error(1, 0, "%s data path not absolute: %s", package_name, data_path);
106 }
Elliott Hughes0c8bf572016-07-07 16:22:19 -0700107
108 // Look for all sub-paths, we do that by finding
109 // directory separators in the input path and
110 // checking each sub-path independently.
111 for (int nn = 1; data_path[nn] != '\0'; nn++) {
112 char subpath[PATH_MAX];
113
114 /* skip non-separator characters */
115 if (data_path[nn] != '/') continue;
116
117 /* handle trailing separator case */
118 if (data_path[nn+1] == '\0') break;
119
120 /* found a separator, check that data_path is not too long. */
Elliott Hughes964932d2019-03-13 11:15:06 -0700121 if (nn >= (int)(sizeof subpath)) {
122 error(1, 0, "%s data path too long: %s", package_name, data_path);
123 }
Elliott Hughes0c8bf572016-07-07 16:22:19 -0700124
125 /* reject any '..' subpath */
126 if (nn >= 3 &&
127 data_path[nn-3] == '/' &&
128 data_path[nn-2] == '.' &&
129 data_path[nn-1] == '.') {
Elliott Hughes964932d2019-03-13 11:15:06 -0700130 error(1, 0, "%s contains '..': %s", package_name, data_path);
Elliott Hughes0c8bf572016-07-07 16:22:19 -0700131 }
132
133 /* copy to 'subpath', then check ownership */
134 memcpy(subpath, data_path, nn);
135 subpath[nn] = '\0';
136
Elliott Hughes964932d2019-03-13 11:15:06 -0700137 check_directory(subpath, AID_SYSTEM);
Elliott Hughes0c8bf572016-07-07 16:22:19 -0700138 }
139
140 // All sub-paths were checked, now verify that the full data
141 // directory is owned by the application uid.
Elliott Hughes964932d2019-03-13 11:15:06 -0700142 check_directory(data_path, uid);
Elliott Hughes0c8bf572016-07-07 16:22:19 -0700143}
144
Yabin Cui3a60e682019-01-10 15:08:22 -0800145std::vector<gid_t> get_supplementary_gids(uid_t userAppId) {
146 std::vector<gid_t> gids;
147 int size = getgroups(0, &gids[0]);
148 if (size < 0) {
149 error(1, errno, "getgroups failed");
150 }
151 gids.resize(size);
152 size = getgroups(size, &gids[0]);
153 if (size != static_cast<int>(gids.size())) {
154 error(1, errno, "getgroups failed");
155 }
156 // Profile guide compiled oat files (like /data/app/xxx/oat/arm64/base.odex) are not readable
157 // worldwide (DEXOPT_PUBLIC flag isn't set). To support reading them (needed by simpleperf for
158 // profiling), add shared app gid to supplementary groups.
159 gid_t shared_app_gid = userAppId % AID_USER_OFFSET - AID_APP_START + AID_SHARED_GID_START;
160 gids.push_back(shared_app_gid);
161 return gids;
162}
163
Elliott Hughes0c8bf572016-07-07 16:22:19 -0700164int main(int argc, char* argv[]) {
165 // Check arguments.
166 if (argc < 2) {
167 error(1, 0, "usage: run-as <package-name> [--user <uid>] <command> [<args>]\n");
168 }
169
170 // This program runs with CAP_SETUID and CAP_SETGID capabilities on Android
171 // production devices. Check user id of caller --- must be 'shell' or 'root'.
172 if (getuid() != AID_SHELL && getuid() != AID_ROOT) {
173 error(1, 0, "only 'shell' or 'root' users can run this program");
174 }
175
Luis Hector Chavezef62f3f2018-06-27 10:40:10 -0700176 // Some devices can disable running run-as, such as Chrome OS when running in
177 // non-developer mode.
178 if (android::base::GetBoolProperty("ro.boot.disable_runas", false)) {
Yabin Cuibcbffdd2018-11-06 11:18:44 -0800179 error(1, 0, "run-as is disabled from the kernel commandline");
Luis Hector Chavezef62f3f2018-06-27 10:40:10 -0700180 }
181
Elliott Hughes0c8bf572016-07-07 16:22:19 -0700182 char* pkgname = argv[1];
183 int cmd_argv_offset = 2;
184
185 // Get user_id from command line if provided.
186 int userId = 0;
187 if ((argc >= 4) && !strcmp(argv[2], "--user")) {
188 userId = atoi(argv[3]);
189 if (userId < 0) error(1, 0, "negative user id: %d", userId);
190 cmd_argv_offset += 2;
191 }
192
193 // Retrieve package information from system, switching egid so we can read the file.
Elliott Hughesbfc11532023-11-07 14:44:24 -0800194 pkg_info info = {.name = pkgname};
Elliott Hughes0c8bf572016-07-07 16:22:19 -0700195 gid_t old_egid = getegid();
196 if (setegid(AID_PACKAGE_INFO) == -1) error(1, errno, "setegid(AID_PACKAGE_INFO) failed");
Elliott Hughes0c8bf572016-07-07 16:22:19 -0700197 if (!packagelist_parse(packagelist_parse_callback, &info)) {
198 error(1, errno, "packagelist_parse failed");
199 }
Elliott Hughesbfc11532023-11-07 14:44:24 -0800200 if (setegid(old_egid) == -1) error(1, errno, "couldn't restore egid");
Nicholas Sauer0c5411c2018-11-02 17:04:52 -0700201
202 // Handle a multi-user data path
203 if (userId > 0) {
204 free(info.data_dir);
205 if (asprintf(&info.data_dir, "/data/user/%d/%s", userId, pkgname) == -1) {
206 error(1, errno, "asprintf failed");
207 }
208 }
209
Elliott Hughes0c8bf572016-07-07 16:22:19 -0700210 if (info.uid == 0) {
211 error(1, 0, "unknown package: %s", pkgname);
212 }
Elliott Hughes0c8bf572016-07-07 16:22:19 -0700213
214 // Verify that user id is not too big.
Jeff Sharkeydff44702016-12-13 11:55:19 -0700215 if ((UID_MAX - info.uid) / AID_USER_OFFSET < (uid_t)userId) {
Elliott Hughes0c8bf572016-07-07 16:22:19 -0700216 error(1, 0, "user id too big: %d", userId);
217 }
218
219 // Calculate user app ID.
Jeff Sharkeydff44702016-12-13 11:55:19 -0700220 uid_t userAppId = (AID_USER_OFFSET * userId) + info.uid;
Elliott Hughes0c8bf572016-07-07 16:22:19 -0700221
222 // Reject system packages.
223 if (userAppId < AID_APP) {
224 error(1, 0, "package not an application: %s", pkgname);
225 }
226
227 // Reject any non-debuggable package.
228 if (!info.debuggable) {
229 error(1, 0, "package not debuggable: %s", pkgname);
230 }
231
232 // Check that the data directory path is valid.
Elliott Hughes964932d2019-03-13 11:15:06 -0700233 check_data_path(pkgname, info.data_dir, userAppId);
Elliott Hughes0c8bf572016-07-07 16:22:19 -0700234
235 // Ensure that we change all real/effective/saved IDs at the
236 // same time to avoid nasty surprises.
237 uid_t uid = userAppId;
238 uid_t gid = userAppId;
Yabin Cui3a60e682019-01-10 15:08:22 -0800239 std::vector<gid_t> supplementary_gids = get_supplementary_gids(userAppId);
Jorge Lucangeli Obesa377ff02016-07-15 11:24:20 -0400240 ScopedMinijail j(minijail_new());
241 minijail_change_uid(j.get(), uid);
242 minijail_change_gid(j.get(), gid);
Yabin Cui3a60e682019-01-10 15:08:22 -0800243 minijail_set_supplementary_gids(j.get(), supplementary_gids.size(), supplementary_gids.data());
Jorge Lucangeli Obesa377ff02016-07-15 11:24:20 -0400244 minijail_enter(j.get());
Elliott Hughes0c8bf572016-07-07 16:22:19 -0700245
Yabin Cui97e3bb32018-11-02 15:22:13 -0700246 std::string seinfo = std::string(info.seinfo) + ":fromRunAs";
247 if (selinux_android_setcontext(uid, 0, seinfo.c_str(), pkgname) < 0) {
Elliott Hughes4a77a842020-03-04 18:11:18 -0800248 error(1, errno, "couldn't set SELinux security context '%s'", seinfo.c_str());
Elliott Hughes0c8bf572016-07-07 16:22:19 -0700249 }
250
251 // cd into the data directory, and set $HOME correspondingly.
252 if (TEMP_FAILURE_RETRY(chdir(info.data_dir)) == -1) {
Elliott Hughes4a77a842020-03-04 18:11:18 -0800253 error(1, errno, "couldn't chdir to package's data directory '%s'", info.data_dir);
Elliott Hughes0c8bf572016-07-07 16:22:19 -0700254 }
255 setenv("HOME", info.data_dir, 1);
256
257 // Reset parts of the environment, like su would.
258 setenv("PATH", _PATH_DEFPATH, 1);
259 unsetenv("IFS");
260
261 // Set the user-specific parts for this user.
262 passwd* pw = getpwuid(uid);
263 setenv("LOGNAME", pw->pw_name, 1);
264 setenv("SHELL", pw->pw_shell, 1);
265 setenv("USER", pw->pw_name, 1);
266
267 // User specified command for exec.
268 if ((argc >= cmd_argv_offset + 1) &&
269 (execvp(argv[cmd_argv_offset], argv+cmd_argv_offset) == -1)) {
270 error(1, errno, "exec failed for %s", argv[cmd_argv_offset]);
271 }
272
273 // Default exec shell.
274 execlp(_PATH_BSHELL, "sh", NULL);
275 error(1, errno, "exec failed");
276}