blob: ba636366fbf80ecc7af56306460aeadafb447351 [file] [log] [blame]
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -04001// Copyright (C) 2016 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#define LOG_TAG "sdcard"
16
17#include <dirent.h>
18#include <errno.h>
19#include <fcntl.h>
20#include <linux/fuse.h>
21#include <pthread.h>
22#include <stdlib.h>
23#include <string.h>
24#include <sys/inotify.h>
25#include <sys/mount.h>
26#include <sys/resource.h>
27#include <sys/stat.h>
28#include <sys/types.h>
29#include <unistd.h>
30
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -040031#include <android-base/logging.h>
Jorge Lucangeli Obesbae15b42016-07-18 13:46:42 -040032#include <android-base/macros.h>
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -040033
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -040034#include <cutils/fs.h>
35#include <cutils/hashmap.h>
36#include <cutils/log.h>
37#include <cutils/multiuser.h>
38#include <packagelistparser/packagelistparser.h>
39
Jorge Lucangeli Obesc96f53e2016-07-14 14:50:14 -040040#include <libminijail.h>
41#include <scoped_minijail.h>
42
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -040043#include <private/android_filesystem_config.h>
44
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -040045// README
46//
47// What is this?
48//
49// sdcard is a program that uses FUSE to emulate FAT-on-sdcard style
50// directory permissions (all files are given fixed owner, group, and
51// permissions at creation, owner, group, and permissions are not
52// changeable, symlinks and hardlinks are not createable, etc.
53//
54// See usage() for command line options.
55//
56// It must be run as root, but will drop to requested UID/GID as soon as it
57// mounts a filesystem. It will refuse to run if requested UID/GID are zero.
58//
59// Things I believe to be true:
60//
61// - ops that return a fuse_entry (LOOKUP, MKNOD, MKDIR, LINK, SYMLINK,
62// CREAT) must bump that node's refcount
63// - don't forget that FORGET can forget multiple references (req->nlookup)
64// - if an op that returns a fuse_entry fails writing the reply to the
65// kernel, you must rollback the refcount to reflect the reference the
66// kernel did not actually acquire
67//
68// This daemon can also derive custom filesystem permissions based on directory
69// structure when requested. These custom permissions support several features:
70//
71// - Apps can access their own files in /Android/data/com.example/ without
72// requiring any additional GIDs.
73// - Separate permissions for protecting directories like Pictures and Music.
74// - Multi-user separation on the same physical device.
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -040075
76#include "fuse.h"
77
78/* Supplementary groups to execute with. */
79static const gid_t kGroups[1] = { AID_PACKAGE_INFO };
80
81static int str_hash(void *key) {
82 return hashmapHash(key, strlen(static_cast<const char*>(key)));
83}
84
85/* Tests if two string keys are equal ignoring case. */
86static bool str_icase_equals(void *keyA, void *keyB) {
87 return strcasecmp(static_cast<const char*>(keyA), static_cast<const char*>(keyB)) == 0;
88}
89
90static bool remove_str_to_int(void *key, void *value, void *context) {
91 Hashmap* map = static_cast<Hashmap*>(context);
92 hashmapRemove(map, key);
93 free(key);
94 return true;
95}
96
97static bool package_parse_callback(pkg_info *info, void *userdata) {
98 struct fuse_global *global = (struct fuse_global *)userdata;
99
100 char* name = strdup(info->name);
101 hashmapPut(global->package_to_appid, name, (void*) (uintptr_t) info->uid);
102 packagelist_free(info);
103 return true;
104}
105
106static bool read_package_list(struct fuse_global* global) {
107 pthread_mutex_lock(&global->lock);
108
109 hashmapForEach(global->package_to_appid, remove_str_to_int, global->package_to_appid);
110
111 bool rc = packagelist_parse(package_parse_callback, global);
112 TRACE("read_package_list: found %zu packages\n",
113 hashmapSize(global->package_to_appid));
114
115 /* Regenerate ownership details using newly loaded mapping */
116 derive_permissions_recursive_locked(global->fuse_default, &global->root);
117
118 pthread_mutex_unlock(&global->lock);
119
120 return rc;
121}
122
123static void watch_package_list(struct fuse_global* global) {
124 struct inotify_event *event;
125 char event_buf[512];
126
127 int nfd = inotify_init();
128 if (nfd < 0) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400129 PLOG(ERROR) << "inotify_init failed";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400130 return;
131 }
132
133 bool active = false;
134 while (1) {
135 if (!active) {
136 int res = inotify_add_watch(nfd, PACKAGES_LIST_FILE, IN_DELETE_SELF);
137 if (res == -1) {
138 if (errno == ENOENT || errno == EACCES) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400139 /* Framework may not have created the file yet, sleep and retry. */
140 LOG(ERROR) << "missing \"" << PACKAGES_LIST_FILE << "\"; retrying...";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400141 sleep(3);
142 continue;
143 } else {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400144 PLOG(ERROR) << "inotify_add_watch failed";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400145 return;
146 }
147 }
148
149 /* Watch above will tell us about any future changes, so
150 * read the current state. */
151 if (read_package_list(global) == false) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400152 LOG(ERROR) << "read_package_list failed";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400153 return;
154 }
155 active = true;
156 }
157
158 int event_pos = 0;
159 int res = read(nfd, event_buf, sizeof(event_buf));
160 if (res < (int) sizeof(*event)) {
161 if (errno == EINTR)
162 continue;
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400163 PLOG(ERROR) << "failed to read inotify event";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400164 return;
165 }
166
167 while (res >= (int) sizeof(*event)) {
168 int event_size;
169 event = (struct inotify_event *) (event_buf + event_pos);
170
171 TRACE("inotify event: %08x\n", event->mask);
172 if ((event->mask & IN_IGNORED) == IN_IGNORED) {
173 /* Previously watched file was deleted, probably due to move
174 * that swapped in new data; re-arm the watch and read. */
175 active = false;
176 }
177
178 event_size = sizeof(*event) + event->len;
179 res -= event_size;
180 event_pos += event_size;
181 }
182 }
183}
184
185static int fuse_setup(struct fuse* fuse, gid_t gid, mode_t mask) {
186 char opts[256];
187
188 fuse->fd = open("/dev/fuse", O_RDWR);
189 if (fuse->fd == -1) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400190 PLOG(ERROR) << "failed to open fuse device";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400191 return -1;
192 }
193
194 umount2(fuse->dest_path, MNT_DETACH);
195
196 snprintf(opts, sizeof(opts),
197 "fd=%i,rootmode=40000,default_permissions,allow_other,user_id=%d,group_id=%d",
198 fuse->fd, fuse->global->uid, fuse->global->gid);
199 if (mount("/dev/fuse", fuse->dest_path, "fuse", MS_NOSUID | MS_NODEV | MS_NOEXEC |
200 MS_NOATIME, opts) != 0) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400201 PLOG(ERROR) << "failed to mount fuse filesystem";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400202 return -1;
203 }
204
205 fuse->gid = gid;
206 fuse->mask = mask;
207
208 return 0;
209}
210
Jorge Lucangeli Obesc96f53e2016-07-14 14:50:14 -0400211static void drop_privs(uid_t uid, gid_t gid) {
212 ScopedMinijail j(minijail_new());
Jorge Lucangeli Obesbae15b42016-07-18 13:46:42 -0400213 minijail_set_supplementary_gids(j.get(), arraysize(kGroups), kGroups);
Jorge Lucangeli Obesc96f53e2016-07-14 14:50:14 -0400214 minijail_change_gid(j.get(), gid);
215 minijail_change_uid(j.get(), uid);
216 /* minijail_enter() will abort if priv-dropping fails. */
217 minijail_enter(j.get());
218}
219
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400220static void* start_handler(void* data) {
221 struct fuse_handler* handler = static_cast<fuse_handler*>(data);
222 handle_fuse_requests(handler);
223 return NULL;
224}
225
226static void run(const char* source_path, const char* label, uid_t uid,
227 gid_t gid, userid_t userid, bool multi_user, bool full_write) {
228 struct fuse_global global;
229 struct fuse fuse_default;
230 struct fuse fuse_read;
231 struct fuse fuse_write;
232 struct fuse_handler handler_default;
233 struct fuse_handler handler_read;
234 struct fuse_handler handler_write;
235 pthread_t thread_default;
236 pthread_t thread_read;
237 pthread_t thread_write;
238
239 memset(&global, 0, sizeof(global));
240 memset(&fuse_default, 0, sizeof(fuse_default));
241 memset(&fuse_read, 0, sizeof(fuse_read));
242 memset(&fuse_write, 0, sizeof(fuse_write));
243 memset(&handler_default, 0, sizeof(handler_default));
244 memset(&handler_read, 0, sizeof(handler_read));
245 memset(&handler_write, 0, sizeof(handler_write));
246
247 pthread_mutex_init(&global.lock, NULL);
248 global.package_to_appid = hashmapCreate(256, str_hash, str_icase_equals);
249 global.uid = uid;
250 global.gid = gid;
251 global.multi_user = multi_user;
252 global.next_generation = 0;
253 global.inode_ctr = 1;
254
255 memset(&global.root, 0, sizeof(global.root));
256 global.root.nid = FUSE_ROOT_ID; /* 1 */
257 global.root.refcount = 2;
258 global.root.namelen = strlen(source_path);
259 global.root.name = strdup(source_path);
260 global.root.userid = userid;
261 global.root.uid = AID_ROOT;
262 global.root.under_android = false;
263
264 strcpy(global.source_path, source_path);
265
266 if (multi_user) {
267 global.root.perm = PERM_PRE_ROOT;
268 snprintf(global.obb_path, sizeof(global.obb_path), "%s/obb", source_path);
269 } else {
270 global.root.perm = PERM_ROOT;
271 snprintf(global.obb_path, sizeof(global.obb_path), "%s/Android/obb", source_path);
272 }
273
274 fuse_default.global = &global;
275 fuse_read.global = &global;
276 fuse_write.global = &global;
277
278 global.fuse_default = &fuse_default;
279 global.fuse_read = &fuse_read;
280 global.fuse_write = &fuse_write;
281
282 snprintf(fuse_default.dest_path, PATH_MAX, "/mnt/runtime/default/%s", label);
283 snprintf(fuse_read.dest_path, PATH_MAX, "/mnt/runtime/read/%s", label);
284 snprintf(fuse_write.dest_path, PATH_MAX, "/mnt/runtime/write/%s", label);
285
286 handler_default.fuse = &fuse_default;
287 handler_read.fuse = &fuse_read;
288 handler_write.fuse = &fuse_write;
289
290 handler_default.token = 0;
291 handler_read.token = 1;
292 handler_write.token = 2;
293
294 umask(0);
295
296 if (multi_user) {
297 /* Multi-user storage is fully isolated per user, so "other"
298 * permissions are completely masked off. */
299 if (fuse_setup(&fuse_default, AID_SDCARD_RW, 0006)
300 || fuse_setup(&fuse_read, AID_EVERYBODY, 0027)
301 || fuse_setup(&fuse_write, AID_EVERYBODY, full_write ? 0007 : 0027)) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400302 PLOG(FATAL) << "failed to fuse_setup";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400303 }
304 } else {
305 /* Physical storage is readable by all users on device, but
306 * the Android directories are masked off to a single user
307 * deep inside attr_from_stat(). */
308 if (fuse_setup(&fuse_default, AID_SDCARD_RW, 0006)
309 || fuse_setup(&fuse_read, AID_EVERYBODY, full_write ? 0027 : 0022)
310 || fuse_setup(&fuse_write, AID_EVERYBODY, full_write ? 0007 : 0022)) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400311 PLOG(FATAL) << "failed to fuse_setup";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400312 }
313 }
314
Jorge Lucangeli Obesc96f53e2016-07-14 14:50:14 -0400315 // Will abort if priv-dropping fails.
316 drop_privs(uid, gid);
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400317
318 if (multi_user) {
319 fs_prepare_dir(global.obb_path, 0775, uid, gid);
320 }
321
322 if (pthread_create(&thread_default, NULL, start_handler, &handler_default)
323 || pthread_create(&thread_read, NULL, start_handler, &handler_read)
324 || pthread_create(&thread_write, NULL, start_handler, &handler_write)) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400325 LOG(FATAL) << "failed to pthread_create";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400326 }
327
328 watch_package_list(&global);
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400329 LOG(FATAL) << "terminated prematurely";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400330}
331
332static int usage() {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400333 LOG(ERROR) << "usage: sdcard [OPTIONS] <source_path> <label>"
334 << " -u: specify UID to run as"
335 << " -g: specify GID to run as"
336 << " -U: specify user ID that owns device"
337 << " -m: source_path is multi-user"
338 << " -w: runtime write mount has full write access";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400339 return 1;
340}
341
342int main(int argc, char **argv) {
343 const char *source_path = NULL;
344 const char *label = NULL;
345 uid_t uid = 0;
346 gid_t gid = 0;
347 userid_t userid = 0;
348 bool multi_user = false;
349 bool full_write = false;
350 int i;
351 struct rlimit rlim;
352 int fs_version;
353
354 int opt;
355 while ((opt = getopt(argc, argv, "u:g:U:mw")) != -1) {
356 switch (opt) {
357 case 'u':
358 uid = strtoul(optarg, NULL, 10);
359 break;
360 case 'g':
361 gid = strtoul(optarg, NULL, 10);
362 break;
363 case 'U':
364 userid = strtoul(optarg, NULL, 10);
365 break;
366 case 'm':
367 multi_user = true;
368 break;
369 case 'w':
370 full_write = true;
371 break;
372 case '?':
373 default:
374 return usage();
375 }
376 }
377
378 for (i = optind; i < argc; i++) {
379 char* arg = argv[i];
380 if (!source_path) {
381 source_path = arg;
382 } else if (!label) {
383 label = arg;
384 } else {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400385 LOG(ERROR) << "too many arguments";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400386 return usage();
387 }
388 }
389
390 if (!source_path) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400391 LOG(ERROR) << "no source path specified";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400392 return usage();
393 }
394 if (!label) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400395 LOG(ERROR) << "no label specified";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400396 return usage();
397 }
398 if (!uid || !gid) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400399 LOG(ERROR) << "uid and gid must be nonzero";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400400 return usage();
401 }
402
403 rlim.rlim_cur = 8192;
404 rlim.rlim_max = 8192;
405 if (setrlimit(RLIMIT_NOFILE, &rlim)) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400406 PLOG(ERROR) << "setting RLIMIT_NOFILE failed";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400407 }
408
409 while ((fs_read_atomic_int("/data/.layout_version", &fs_version) == -1) || (fs_version < 3)) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400410 LOG(ERROR) << "installd fs upgrade not yet complete; waiting...";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400411 sleep(1);
412 }
413
414 run(source_path, label, uid, gid, userid, multi_user, full_write);
415 return 1;
416}