blob: e82f29ed4f8982e1d8e677f4a8d7cee9384d2a96 [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>
32
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -040033#include <cutils/fs.h>
34#include <cutils/hashmap.h>
35#include <cutils/log.h>
36#include <cutils/multiuser.h>
37#include <packagelistparser/packagelistparser.h>
38
Jorge Lucangeli Obesc96f53e2016-07-14 14:50:14 -040039#include <libminijail.h>
40#include <scoped_minijail.h>
41
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -040042#include <private/android_filesystem_config.h>
43
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -040044// README
45//
46// What is this?
47//
48// sdcard is a program that uses FUSE to emulate FAT-on-sdcard style
49// directory permissions (all files are given fixed owner, group, and
50// permissions at creation, owner, group, and permissions are not
51// changeable, symlinks and hardlinks are not createable, etc.
52//
53// See usage() for command line options.
54//
55// It must be run as root, but will drop to requested UID/GID as soon as it
56// mounts a filesystem. It will refuse to run if requested UID/GID are zero.
57//
58// Things I believe to be true:
59//
60// - ops that return a fuse_entry (LOOKUP, MKNOD, MKDIR, LINK, SYMLINK,
61// CREAT) must bump that node's refcount
62// - don't forget that FORGET can forget multiple references (req->nlookup)
63// - if an op that returns a fuse_entry fails writing the reply to the
64// kernel, you must rollback the refcount to reflect the reference the
65// kernel did not actually acquire
66//
67// This daemon can also derive custom filesystem permissions based on directory
68// structure when requested. These custom permissions support several features:
69//
70// - Apps can access their own files in /Android/data/com.example/ without
71// requiring any additional GIDs.
72// - Separate permissions for protecting directories like Pictures and Music.
73// - Multi-user separation on the same physical device.
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -040074
75#include "fuse.h"
76
77/* Supplementary groups to execute with. */
78static const gid_t kGroups[1] = { AID_PACKAGE_INFO };
79
80static int str_hash(void *key) {
81 return hashmapHash(key, strlen(static_cast<const char*>(key)));
82}
83
84/* Tests if two string keys are equal ignoring case. */
85static bool str_icase_equals(void *keyA, void *keyB) {
86 return strcasecmp(static_cast<const char*>(keyA), static_cast<const char*>(keyB)) == 0;
87}
88
89static bool remove_str_to_int(void *key, void *value, void *context) {
90 Hashmap* map = static_cast<Hashmap*>(context);
91 hashmapRemove(map, key);
92 free(key);
93 return true;
94}
95
96static bool package_parse_callback(pkg_info *info, void *userdata) {
97 struct fuse_global *global = (struct fuse_global *)userdata;
98
99 char* name = strdup(info->name);
100 hashmapPut(global->package_to_appid, name, (void*) (uintptr_t) info->uid);
101 packagelist_free(info);
102 return true;
103}
104
105static bool read_package_list(struct fuse_global* global) {
106 pthread_mutex_lock(&global->lock);
107
108 hashmapForEach(global->package_to_appid, remove_str_to_int, global->package_to_appid);
109
110 bool rc = packagelist_parse(package_parse_callback, global);
111 TRACE("read_package_list: found %zu packages\n",
112 hashmapSize(global->package_to_appid));
113
114 /* Regenerate ownership details using newly loaded mapping */
115 derive_permissions_recursive_locked(global->fuse_default, &global->root);
116
117 pthread_mutex_unlock(&global->lock);
118
119 return rc;
120}
121
122static void watch_package_list(struct fuse_global* global) {
123 struct inotify_event *event;
124 char event_buf[512];
125
126 int nfd = inotify_init();
127 if (nfd < 0) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400128 PLOG(ERROR) << "inotify_init failed";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400129 return;
130 }
131
132 bool active = false;
133 while (1) {
134 if (!active) {
135 int res = inotify_add_watch(nfd, PACKAGES_LIST_FILE, IN_DELETE_SELF);
136 if (res == -1) {
137 if (errno == ENOENT || errno == EACCES) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400138 /* Framework may not have created the file yet, sleep and retry. */
139 LOG(ERROR) << "missing \"" << PACKAGES_LIST_FILE << "\"; retrying...";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400140 sleep(3);
141 continue;
142 } else {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400143 PLOG(ERROR) << "inotify_add_watch failed";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400144 return;
145 }
146 }
147
148 /* Watch above will tell us about any future changes, so
149 * read the current state. */
150 if (read_package_list(global) == false) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400151 LOG(ERROR) << "read_package_list failed";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400152 return;
153 }
154 active = true;
155 }
156
157 int event_pos = 0;
158 int res = read(nfd, event_buf, sizeof(event_buf));
159 if (res < (int) sizeof(*event)) {
160 if (errno == EINTR)
161 continue;
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400162 PLOG(ERROR) << "failed to read inotify event";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400163 return;
164 }
165
166 while (res >= (int) sizeof(*event)) {
167 int event_size;
168 event = (struct inotify_event *) (event_buf + event_pos);
169
170 TRACE("inotify event: %08x\n", event->mask);
171 if ((event->mask & IN_IGNORED) == IN_IGNORED) {
172 /* Previously watched file was deleted, probably due to move
173 * that swapped in new data; re-arm the watch and read. */
174 active = false;
175 }
176
177 event_size = sizeof(*event) + event->len;
178 res -= event_size;
179 event_pos += event_size;
180 }
181 }
182}
183
184static int fuse_setup(struct fuse* fuse, gid_t gid, mode_t mask) {
185 char opts[256];
186
187 fuse->fd = open("/dev/fuse", O_RDWR);
188 if (fuse->fd == -1) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400189 PLOG(ERROR) << "failed to open fuse device";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400190 return -1;
191 }
192
193 umount2(fuse->dest_path, MNT_DETACH);
194
195 snprintf(opts, sizeof(opts),
196 "fd=%i,rootmode=40000,default_permissions,allow_other,user_id=%d,group_id=%d",
197 fuse->fd, fuse->global->uid, fuse->global->gid);
198 if (mount("/dev/fuse", fuse->dest_path, "fuse", MS_NOSUID | MS_NODEV | MS_NOEXEC |
199 MS_NOATIME, opts) != 0) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400200 PLOG(ERROR) << "failed to mount fuse filesystem";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400201 return -1;
202 }
203
204 fuse->gid = gid;
205 fuse->mask = mask;
206
207 return 0;
208}
209
Jorge Lucangeli Obesc96f53e2016-07-14 14:50:14 -0400210static void drop_privs(uid_t uid, gid_t gid) {
211 ScopedMinijail j(minijail_new());
212 minijail_set_supplementary_gids(j.get(), sizeof(kGroups) / sizeof(kGroups[0]), kGroups);
213 minijail_change_gid(j.get(), gid);
214 minijail_change_uid(j.get(), uid);
215 /* minijail_enter() will abort if priv-dropping fails. */
216 minijail_enter(j.get());
217}
218
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400219static void* start_handler(void* data) {
220 struct fuse_handler* handler = static_cast<fuse_handler*>(data);
221 handle_fuse_requests(handler);
222 return NULL;
223}
224
225static void run(const char* source_path, const char* label, uid_t uid,
226 gid_t gid, userid_t userid, bool multi_user, bool full_write) {
227 struct fuse_global global;
228 struct fuse fuse_default;
229 struct fuse fuse_read;
230 struct fuse fuse_write;
231 struct fuse_handler handler_default;
232 struct fuse_handler handler_read;
233 struct fuse_handler handler_write;
234 pthread_t thread_default;
235 pthread_t thread_read;
236 pthread_t thread_write;
237
238 memset(&global, 0, sizeof(global));
239 memset(&fuse_default, 0, sizeof(fuse_default));
240 memset(&fuse_read, 0, sizeof(fuse_read));
241 memset(&fuse_write, 0, sizeof(fuse_write));
242 memset(&handler_default, 0, sizeof(handler_default));
243 memset(&handler_read, 0, sizeof(handler_read));
244 memset(&handler_write, 0, sizeof(handler_write));
245
246 pthread_mutex_init(&global.lock, NULL);
247 global.package_to_appid = hashmapCreate(256, str_hash, str_icase_equals);
248 global.uid = uid;
249 global.gid = gid;
250 global.multi_user = multi_user;
251 global.next_generation = 0;
252 global.inode_ctr = 1;
253
254 memset(&global.root, 0, sizeof(global.root));
255 global.root.nid = FUSE_ROOT_ID; /* 1 */
256 global.root.refcount = 2;
257 global.root.namelen = strlen(source_path);
258 global.root.name = strdup(source_path);
259 global.root.userid = userid;
260 global.root.uid = AID_ROOT;
261 global.root.under_android = false;
262
263 strcpy(global.source_path, source_path);
264
265 if (multi_user) {
266 global.root.perm = PERM_PRE_ROOT;
267 snprintf(global.obb_path, sizeof(global.obb_path), "%s/obb", source_path);
268 } else {
269 global.root.perm = PERM_ROOT;
270 snprintf(global.obb_path, sizeof(global.obb_path), "%s/Android/obb", source_path);
271 }
272
273 fuse_default.global = &global;
274 fuse_read.global = &global;
275 fuse_write.global = &global;
276
277 global.fuse_default = &fuse_default;
278 global.fuse_read = &fuse_read;
279 global.fuse_write = &fuse_write;
280
281 snprintf(fuse_default.dest_path, PATH_MAX, "/mnt/runtime/default/%s", label);
282 snprintf(fuse_read.dest_path, PATH_MAX, "/mnt/runtime/read/%s", label);
283 snprintf(fuse_write.dest_path, PATH_MAX, "/mnt/runtime/write/%s", label);
284
285 handler_default.fuse = &fuse_default;
286 handler_read.fuse = &fuse_read;
287 handler_write.fuse = &fuse_write;
288
289 handler_default.token = 0;
290 handler_read.token = 1;
291 handler_write.token = 2;
292
293 umask(0);
294
295 if (multi_user) {
296 /* Multi-user storage is fully isolated per user, so "other"
297 * permissions are completely masked off. */
298 if (fuse_setup(&fuse_default, AID_SDCARD_RW, 0006)
299 || fuse_setup(&fuse_read, AID_EVERYBODY, 0027)
300 || fuse_setup(&fuse_write, AID_EVERYBODY, full_write ? 0007 : 0027)) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400301 PLOG(FATAL) << "failed to fuse_setup";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400302 }
303 } else {
304 /* Physical storage is readable by all users on device, but
305 * the Android directories are masked off to a single user
306 * deep inside attr_from_stat(). */
307 if (fuse_setup(&fuse_default, AID_SDCARD_RW, 0006)
308 || fuse_setup(&fuse_read, AID_EVERYBODY, full_write ? 0027 : 0022)
309 || fuse_setup(&fuse_write, AID_EVERYBODY, full_write ? 0007 : 0022)) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400310 PLOG(FATAL) << "failed to fuse_setup";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400311 }
312 }
313
Jorge Lucangeli Obesc96f53e2016-07-14 14:50:14 -0400314 // Will abort if priv-dropping fails.
315 drop_privs(uid, gid);
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400316
317 if (multi_user) {
318 fs_prepare_dir(global.obb_path, 0775, uid, gid);
319 }
320
321 if (pthread_create(&thread_default, NULL, start_handler, &handler_default)
322 || pthread_create(&thread_read, NULL, start_handler, &handler_read)
323 || pthread_create(&thread_write, NULL, start_handler, &handler_write)) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400324 LOG(FATAL) << "failed to pthread_create";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400325 }
326
327 watch_package_list(&global);
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400328 LOG(FATAL) << "terminated prematurely";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400329}
330
331static int usage() {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400332 LOG(ERROR) << "usage: sdcard [OPTIONS] <source_path> <label>"
333 << " -u: specify UID to run as"
334 << " -g: specify GID to run as"
335 << " -U: specify user ID that owns device"
336 << " -m: source_path is multi-user"
337 << " -w: runtime write mount has full write access";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400338 return 1;
339}
340
341int main(int argc, char **argv) {
342 const char *source_path = NULL;
343 const char *label = NULL;
344 uid_t uid = 0;
345 gid_t gid = 0;
346 userid_t userid = 0;
347 bool multi_user = false;
348 bool full_write = false;
349 int i;
350 struct rlimit rlim;
351 int fs_version;
352
353 int opt;
354 while ((opt = getopt(argc, argv, "u:g:U:mw")) != -1) {
355 switch (opt) {
356 case 'u':
357 uid = strtoul(optarg, NULL, 10);
358 break;
359 case 'g':
360 gid = strtoul(optarg, NULL, 10);
361 break;
362 case 'U':
363 userid = strtoul(optarg, NULL, 10);
364 break;
365 case 'm':
366 multi_user = true;
367 break;
368 case 'w':
369 full_write = true;
370 break;
371 case '?':
372 default:
373 return usage();
374 }
375 }
376
377 for (i = optind; i < argc; i++) {
378 char* arg = argv[i];
379 if (!source_path) {
380 source_path = arg;
381 } else if (!label) {
382 label = arg;
383 } else {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400384 LOG(ERROR) << "too many arguments";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400385 return usage();
386 }
387 }
388
389 if (!source_path) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400390 LOG(ERROR) << "no source path specified";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400391 return usage();
392 }
393 if (!label) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400394 LOG(ERROR) << "no label specified";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400395 return usage();
396 }
397 if (!uid || !gid) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400398 LOG(ERROR) << "uid and gid must be nonzero";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400399 return usage();
400 }
401
402 rlim.rlim_cur = 8192;
403 rlim.rlim_max = 8192;
404 if (setrlimit(RLIMIT_NOFILE, &rlim)) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400405 PLOG(ERROR) << "setting RLIMIT_NOFILE failed";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400406 }
407
408 while ((fs_read_atomic_int("/data/.layout_version", &fs_version) == -1) || (fs_version < 3)) {
Jorge Lucangeli Obesc9e17102016-07-12 17:05:32 -0400409 LOG(ERROR) << "installd fs upgrade not yet complete; waiting...";
Jorge Lucangeli Obesc255f252016-07-12 15:13:05 -0400410 sleep(1);
411 }
412
413 run(source_path, label, uid, gid, userid, multi_user, full_write);
414 return 1;
415}