blob: 50b47b99c29c14e0dbaa8d69dff7b05073d686c1 [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
28#include <packagelistparser/packagelistparser.h>
29#include <private/android_filesystem_config.h>
30#include <selinux/android.h>
31
32// The purpose of this program is to run a command as a specific
33// application user-id. Typical usage is:
34//
35// run-as <package-name> <command> <args>
36//
37// The 'run-as' binary is installed with CAP_SETUID and CAP_SETGID file
38// capabilities, but will check the following:
39//
40// - that it is invoked from the 'shell' or 'root' user (abort otherwise)
41// - that '<package-name>' is the name of an installed and debuggable package
42// - that the package's data directory is well-formed
43//
44// If so, it will drop to the application's user id / group id, cd to the
45// package's data directory, then run the command there.
46//
47// This can be useful for a number of different things on production devices:
48//
49// - Allow application developers to look at their own application data
50// during development.
51//
52// - Run the 'gdbserver' binary executable to allow native debugging
53//
54
55static bool packagelist_parse_callback(pkg_info* this_package, void* userdata) {
56 pkg_info* p = reinterpret_cast<pkg_info*>(userdata);
57 if (strcmp(p->name, this_package->name) == 0) {
58 *p = *this_package;
59 return false; // Stop searching.
60 }
61 packagelist_free(this_package);
62 return true; // Keep searching.
63}
64
65static bool check_directory(const char* path, uid_t uid) {
66 struct stat st;
67 if (TEMP_FAILURE_RETRY(lstat(path, &st)) == -1) return false;
68
69 // /data/user/0 is a known safe symlink.
70 if (strcmp("/data/user/0", path) == 0) return true;
71
72 // Must be a real directory, not a symlink.
73 if (!S_ISDIR(st.st_mode)) return false;
74
75 // Must be owned by specific uid/gid.
76 if (st.st_uid != uid || st.st_gid != uid) return false;
77
78 // Must not be readable or writable by others.
79 if ((st.st_mode & (S_IROTH|S_IWOTH)) != 0) return false;
80
81 return true;
82}
83
84// This function is used to check the data directory path for safety.
85// We check that every sub-directory is owned by the 'system' user
86// and exists and is not a symlink. We also check that the full directory
87// path is properly owned by the user ID.
88static bool check_data_path(const char* data_path, uid_t uid) {
89 // The path should be absolute.
90 if (data_path[0] != '/') return false;
91
92 // Look for all sub-paths, we do that by finding
93 // directory separators in the input path and
94 // checking each sub-path independently.
95 for (int nn = 1; data_path[nn] != '\0'; nn++) {
96 char subpath[PATH_MAX];
97
98 /* skip non-separator characters */
99 if (data_path[nn] != '/') continue;
100
101 /* handle trailing separator case */
102 if (data_path[nn+1] == '\0') break;
103
104 /* found a separator, check that data_path is not too long. */
105 if (nn >= (int)(sizeof subpath)) return false;
106
107 /* reject any '..' subpath */
108 if (nn >= 3 &&
109 data_path[nn-3] == '/' &&
110 data_path[nn-2] == '.' &&
111 data_path[nn-1] == '.') {
112 return false;
113 }
114
115 /* copy to 'subpath', then check ownership */
116 memcpy(subpath, data_path, nn);
117 subpath[nn] = '\0';
118
119 if (!check_directory(subpath, AID_SYSTEM)) return false;
120 }
121
122 // All sub-paths were checked, now verify that the full data
123 // directory is owned by the application uid.
124 return check_directory(data_path, uid);
125}
126
127int main(int argc, char* argv[]) {
128 // Check arguments.
129 if (argc < 2) {
130 error(1, 0, "usage: run-as <package-name> [--user <uid>] <command> [<args>]\n");
131 }
132
133 // This program runs with CAP_SETUID and CAP_SETGID capabilities on Android
134 // production devices. Check user id of caller --- must be 'shell' or 'root'.
135 if (getuid() != AID_SHELL && getuid() != AID_ROOT) {
136 error(1, 0, "only 'shell' or 'root' users can run this program");
137 }
138
139 __user_cap_header_struct capheader;
140 __user_cap_data_struct capdata[2];
141 memset(&capheader, 0, sizeof(capheader));
142 memset(&capdata, 0, sizeof(capdata));
143 capheader.version = _LINUX_CAPABILITY_VERSION_3;
144 capdata[CAP_TO_INDEX(CAP_SETUID)].effective |= CAP_TO_MASK(CAP_SETUID);
145 capdata[CAP_TO_INDEX(CAP_SETGID)].effective |= CAP_TO_MASK(CAP_SETGID);
146 capdata[CAP_TO_INDEX(CAP_SETUID)].permitted |= CAP_TO_MASK(CAP_SETUID);
147 capdata[CAP_TO_INDEX(CAP_SETGID)].permitted |= CAP_TO_MASK(CAP_SETGID);
148 if (capset(&capheader, &capdata[0]) == -1) {
149 error(1, errno, "couldn't set capabilities");
150 }
151
152 char* pkgname = argv[1];
153 int cmd_argv_offset = 2;
154
155 // Get user_id from command line if provided.
156 int userId = 0;
157 if ((argc >= 4) && !strcmp(argv[2], "--user")) {
158 userId = atoi(argv[3]);
159 if (userId < 0) error(1, 0, "negative user id: %d", userId);
160 cmd_argv_offset += 2;
161 }
162
163 // Retrieve package information from system, switching egid so we can read the file.
164 gid_t old_egid = getegid();
165 if (setegid(AID_PACKAGE_INFO) == -1) error(1, errno, "setegid(AID_PACKAGE_INFO) failed");
166 pkg_info info;
167 memset(&info, 0, sizeof(info));
168 info.name = pkgname;
169 if (!packagelist_parse(packagelist_parse_callback, &info)) {
170 error(1, errno, "packagelist_parse failed");
171 }
172 if (info.uid == 0) {
173 error(1, 0, "unknown package: %s", pkgname);
174 }
175 if (setegid(old_egid) == -1) error(1, errno, "couldn't restore egid");
176
177 // Verify that user id is not too big.
178 if ((UID_MAX - info.uid) / AID_USER < (uid_t)userId) {
179 error(1, 0, "user id too big: %d", userId);
180 }
181
182 // Calculate user app ID.
183 uid_t userAppId = (AID_USER * userId) + info.uid;
184
185 // Reject system packages.
186 if (userAppId < AID_APP) {
187 error(1, 0, "package not an application: %s", pkgname);
188 }
189
190 // Reject any non-debuggable package.
191 if (!info.debuggable) {
192 error(1, 0, "package not debuggable: %s", pkgname);
193 }
194
195 // Check that the data directory path is valid.
196 if (!check_data_path(info.data_dir, userAppId)) {
197 error(1, 0, "package has corrupt installation: %s", pkgname);
198 }
199
200 // Ensure that we change all real/effective/saved IDs at the
201 // same time to avoid nasty surprises.
202 uid_t uid = userAppId;
203 uid_t gid = userAppId;
204 if (setresgid(gid, gid, gid) == -1) {
205 error(1, errno, "setresgid failed");
206 }
207 if (setresuid(uid, uid, uid) == -1) {
208 error(1, errno, "setresuid failed");
209 }
210
211 // Required if caller has uid and gid all non-zero.
212 memset(&capdata, 0, sizeof(capdata));
213 if (capset(&capheader, &capdata[0]) == -1) {
214 error(1, errno, "couldn't clear all capabilities");
215 }
216
217 if (selinux_android_setcontext(uid, 0, info.seinfo, pkgname) < 0) {
218 error(1, errno, "couldn't set SELinux security context");
219 }
220
221 // cd into the data directory, and set $HOME correspondingly.
222 if (TEMP_FAILURE_RETRY(chdir(info.data_dir)) == -1) {
223 error(1, errno, "couldn't chdir to package's data directory");
224 }
225 setenv("HOME", info.data_dir, 1);
226
227 // Reset parts of the environment, like su would.
228 setenv("PATH", _PATH_DEFPATH, 1);
229 unsetenv("IFS");
230
231 // Set the user-specific parts for this user.
232 passwd* pw = getpwuid(uid);
233 setenv("LOGNAME", pw->pw_name, 1);
234 setenv("SHELL", pw->pw_shell, 1);
235 setenv("USER", pw->pw_name, 1);
236
237 // User specified command for exec.
238 if ((argc >= cmd_argv_offset + 1) &&
239 (execvp(argv[cmd_argv_offset], argv+cmd_argv_offset) == -1)) {
240 error(1, errno, "exec failed for %s", argv[cmd_argv_offset]);
241 }
242
243 // Default exec shell.
244 execlp(_PATH_BSHELL, "sh", NULL);
245 error(1, errno, "exec failed");
246}