2 * Copyright (C) 2016 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include <unordered_map>
28 #include <sys/socket.h>
30 #include <sys/types.h>
34 #include <cutils/log.h>
36 #include "ScopedPrimitiveArray.h"
38 // Whitelist of open paths that the zygote is allowed to keep open.
40 // In addition to the paths listed here, all files ending with
41 // ".jar" under /system/framework" are whitelisted. See
42 // FileDescriptorInfo::IsWhitelisted for the canonical definition.
44 // If the whitelisted path is associated with a regular file or a
45 // character device, the file is reopened after a fork with the same
46 // offset and mode. If the whilelisted path is associated with a
47 // AF_UNIX socket, the socket will refer to /dev/null after each
48 // fork, and all operations on it will fail.
49 static const char* kPathWhitelist[] = {
50 "/dev/__properties__", /* Only on Android Lollipop and below. */
53 "/dev/socket/zygote_secondary",
54 "/system/etc/event-log-tags",
55 "/sys/kernel/debug/tracing/trace_marker",
56 "/system/framework/framework-res.apk",
62 static const char* kFdPath = "/proc/self/fd";
64 // Keeps track of all relevant information (flags, offset etc.) of an
65 // open zygote file descriptor.
66 class FileDescriptorInfo {
68 // Create a FileDescriptorInfo for a given file descriptor. Returns
69 // |NULL| if an error occurred.
70 static FileDescriptorInfo* createFromFd(int fd) {
72 // This should never happen; the zygote should always have the right set
73 // of permissions required to stat all its open files.
74 if (TEMP_FAILURE_RETRY(fstat(fd, &f_stat)) == -1) {
75 ALOGE("Unable to stat fd %d : %s", fd, strerror(errno));
79 if (S_ISSOCK(f_stat.st_mode)) {
80 std::string socket_name;
81 if (!GetSocketName(fd, &socket_name)) {
85 if (!IsWhitelisted(socket_name)) {
86 ALOGE("Socket name not whitelisted : %s (fd=%d)", socket_name.c_str(), fd);
90 return new FileDescriptorInfo(fd);
93 // We only handle whitelisted regular files and character devices. Whitelisted
94 // character devices must provide a guarantee of sensible behaviour when
97 // S_ISDIR : Not supported. (We could if we wanted to, but it's unused).
98 // S_ISLINK : Not supported.
99 // S_ISBLK : Not supported.
100 // S_ISFIFO : Not supported. Note that the zygote uses pipes to communicate
101 // with the child process across forks but those should have been closed
102 // before we got to this point.
103 if (!S_ISCHR(f_stat.st_mode) && !S_ISREG(f_stat.st_mode)) {
104 ALOGE("Unsupported st_mode %d", f_stat.st_mode);
108 std::string file_path;
109 if (!Readlink(fd, &file_path)) {
113 if (!IsWhitelisted(file_path)) {
114 ALOGE("Not whitelisted : %s", file_path.c_str());
118 // File descriptor flags : currently on FD_CLOEXEC. We can set these
119 // using F_SETFD - we're single threaded at this point of execution so
120 // there won't be any races.
121 const int fd_flags = TEMP_FAILURE_RETRY(fcntl(fd, F_GETFD));
122 if (fd_flags == -1) {
123 ALOGE("Failed fcntl(%d, F_GETFD) : %s", fd, strerror(errno));
127 // File status flags :
128 // - File access mode : (O_RDONLY, O_WRONLY...) we'll pass these through
129 // to the open() call.
131 // - File creation flags : (O_CREAT, O_EXCL...) - there's not much we can
132 // do about these, since the file has already been created. We shall ignore
135 // - Other flags : We'll have to set these via F_SETFL. On linux, F_SETFL
136 // can only set O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME, and O_NONBLOCK.
137 // In particular, it can't set O_SYNC and O_DSYNC. We'll have to test for
138 // their presence and pass them in to open().
139 int fs_flags = TEMP_FAILURE_RETRY(fcntl(fd, F_GETFL));
140 if (fs_flags == -1) {
141 ALOGE("Failed fcntl(%d, F_GETFL) : %s", fd, strerror(errno));
145 // File offset : Ignore the offset for non seekable files.
146 const off_t offset = TEMP_FAILURE_RETRY(lseek64(fd, 0, SEEK_CUR));
148 // We pass the flags that open accepts to open, and use F_SETFL for
150 static const int kOpenFlags = (O_RDONLY | O_WRONLY | O_RDWR | O_DSYNC | O_SYNC);
151 int open_flags = fs_flags & (kOpenFlags);
152 fs_flags = fs_flags & (~(kOpenFlags));
154 return new FileDescriptorInfo(f_stat, file_path, fd, open_flags, fd_flags, fs_flags, offset);
157 // Checks whether the file descriptor associated with this object
158 // refers to the same description.
159 bool Restat() const {
161 if (TEMP_FAILURE_RETRY(fstat(fd, &f_stat)) == -1) {
165 return f_stat.st_ino == stat.st_ino && f_stat.st_dev == stat.st_dev;
168 bool ReopenOrDetach() const {
170 return DetachSocket();
173 // NOTE: This might happen if the file was unlinked after being opened.
174 // It's a common pattern in the case of temporary files and the like but
175 // we should not allow such usage from the zygote.
176 const int new_fd = TEMP_FAILURE_RETRY(open(file_path.c_str(), open_flags));
179 ALOGE("Failed open(%s, %d) : %s", file_path.c_str(), open_flags, strerror(errno));
183 if (TEMP_FAILURE_RETRY(fcntl(new_fd, F_SETFD, fd_flags)) == -1) {
185 ALOGE("Failed fcntl(%d, F_SETFD, %x) : %s", new_fd, fd_flags, strerror(errno));
189 if (TEMP_FAILURE_RETRY(fcntl(new_fd, F_SETFL, fs_flags)) == -1) {
191 ALOGE("Failed fcntl(%d, F_SETFL, %x) : %s", new_fd, fs_flags, strerror(errno));
195 if (offset != -1 && TEMP_FAILURE_RETRY(lseek64(new_fd, offset, SEEK_SET)) == -1) {
197 ALOGE("Failed lseek64(%d, SEEK_SET) : %s", new_fd, strerror(errno));
201 if (TEMP_FAILURE_RETRY(dup2(new_fd, fd)) == -1) {
203 ALOGE("Failed dup2(%d, %d) : %s", fd, new_fd, strerror(errno));
213 const struct stat stat;
214 const std::string file_path;
215 const int open_flags;
222 FileDescriptorInfo(int fd) :
232 FileDescriptorInfo(struct stat stat, const std::string& file_path, int fd, int open_flags,
233 int fd_flags, int fs_flags, off_t offset) :
236 file_path(file_path),
237 open_flags(open_flags),
244 static bool StartsWith(const std::string& str, const std::string& prefix) {
245 return str.compare(0, prefix.size(), prefix) == 0;
248 static bool EndsWith(const std::string& str, const std::string& suffix) {
249 if (suffix.size() > str.size()) {
253 return str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
256 // Returns true iff. a given path is whitelisted. A path is whitelisted
257 // if it belongs to the whitelist (see kPathWhitelist) or if it's a path
258 // under /system/framework that ends with ".jar" or if it is a system
259 // framework overlay.
260 static bool IsWhitelisted(const std::string& path) {
261 for (size_t i = 0; i < (sizeof(kPathWhitelist) / sizeof(kPathWhitelist[0])); ++i) {
262 if (kPathWhitelist[i] == path) {
267 static const std::string kFrameworksPrefix = "/system/framework/";
268 static const std::string kJarSuffix = ".jar";
269 if (StartsWith(path, kFrameworksPrefix) && EndsWith(path, kJarSuffix)) {
273 // Whitelist files needed for Runtime Resource Overlay, like these:
274 // /system/vendor/overlay/framework-res.apk
275 // /system/vendor/overlay-subdir/pg/framework-res.apk
276 // /data/resource-cache/system@vendor@overlay@framework-res.apk@idmap
277 // /data/resource-cache/system@vendor@overlay-subdir@pg@framework-res.apk@idmap
278 // See AssetManager.cpp for more details on overlay-subdir.
279 static const std::string kOverlayDir = "/system/vendor/overlay/";
280 static const std::string kVendorOverlayDir = "/vendor/overlay";
281 static const std::string kOverlaySubdir = "/system/vendor/overlay-subdir/";
282 static const std::string kApkSuffix = ".apk";
284 if ((StartsWith(path, kOverlayDir) || StartsWith(path, kOverlaySubdir)
285 || StartsWith(path, kVendorOverlayDir))
286 && EndsWith(path, kApkSuffix)
287 && path.find("/../") == std::string::npos) {
291 static const std::string kOverlayIdmapPrefix = "/data/resource-cache/";
292 static const std::string kOverlayIdmapSuffix = ".apk@idmap";
293 if (StartsWith(path, kOverlayIdmapPrefix) && EndsWith(path, kOverlayIdmapSuffix)
294 && path.find("/../") == std::string::npos) {
298 // All regular files that are placed under this path are whitelisted automatically.
299 static const std::string kZygoteWhitelistPath = "/vendor/zygote_whitelist/";
300 if (StartsWith(path, kZygoteWhitelistPath) && path.find("/../") == std::string::npos) {
307 // TODO: Call android::base::Readlink instead of copying the code here.
308 static bool Readlink(const int fd, std::string* result) {
310 snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
312 // Code copied from android::base::Readlink starts here :
314 // Annoyingly, the readlink system call returns EINVAL for a zero-sized buffer,
315 // and truncates to whatever size you do supply, so it can't be used to query.
316 // We could call lstat first, but that would introduce a race condition that
317 // we couldn't detect.
318 // ext2 and ext4 both have PAGE_SIZE limitations, so we assume that here.
320 ssize_t len = readlink(path, buf, sizeof(buf));
321 if (len == -1) return false;
323 result->assign(buf, len);
327 // Returns the locally-bound name of the socket |fd|. Returns true
328 // iff. all of the following hold :
330 // - the socket's sa_family is AF_UNIX.
331 // - the length of the path is greater than zero (i.e, not an unnamed socket).
332 // - the first byte of the path isn't zero (i.e, not a socket with an abstract
334 static bool GetSocketName(const int fd, std::string* result) {
336 sockaddr* addr = reinterpret_cast<sockaddr*>(&ss);
337 socklen_t addr_len = sizeof(ss);
339 if (TEMP_FAILURE_RETRY(getsockname(fd, addr, &addr_len)) == -1) {
340 ALOGE("Failed getsockname(%d) : %s", fd, strerror(errno));
345 if (addr->sa_family == AF_NETLINK) {
346 (*result) = "@netlink@";
350 if (addr->sa_family != AF_UNIX) {
351 ALOGE("Unsupported socket (fd=%d) with family %d", fd, addr->sa_family);
355 const sockaddr_un* unix_addr = reinterpret_cast<const sockaddr_un*>(&ss);
357 size_t path_len = addr_len - offsetof(struct sockaddr_un, sun_path);
358 // This is an unnamed local socket, we do not accept it.
360 ALOGE("Unsupported AF_UNIX socket (fd=%d) with empty path.", fd);
364 // This is a local socket with an abstract address, we do not accept it.
365 if (unix_addr->sun_path[0] == '\0') {
366 ALOGE("Unsupported AF_UNIX socket (fd=%d) with abstract address.", fd);
370 // If we're here, sun_path must refer to a null terminated filesystem
371 // pathname (man 7 unix). Remove the terminator before assigning it to an
373 if (unix_addr->sun_path[path_len - 1] == '\0') {
377 result->assign(unix_addr->sun_path, path_len);
381 bool DetachSocket() const {
382 const int dev_null_fd = open("/dev/null", O_RDWR);
383 if (dev_null_fd < 0) {
384 ALOGE("Failed to open /dev/null : %s", strerror(errno));
388 if (dup2(dev_null_fd, fd) == -1) {
389 ALOGE("Failed dup2 on socket descriptor %d : %s", fd, strerror(errno));
393 if (close(dev_null_fd) == -1) {
394 ALOGE("Failed close(%d) : %s", dev_null_fd, strerror(errno));
402 // DISALLOW_COPY_AND_ASSIGN(FileDescriptorInfo);
403 FileDescriptorInfo(const FileDescriptorInfo&);
404 void operator=(const FileDescriptorInfo&);
407 // A FileDescriptorTable is a collection of FileDescriptorInfo objects
408 // keyed by their FDs.
409 class FileDescriptorTable {
411 // Creates a new FileDescriptorTable. This function scans
412 // /proc/self/fd for the list of open file descriptors and collects
413 // information about them. Returns NULL if an error occurs.
414 static FileDescriptorTable* Create() {
415 DIR* d = opendir(kFdPath);
417 ALOGE("Unable to open directory %s: %s", kFdPath, strerror(errno));
420 int dir_fd = dirfd(d);
423 std::unordered_map<int, FileDescriptorInfo*> open_fd_map;
424 while ((e = readdir(d)) != NULL) {
425 const int fd = ParseFd(e, dir_fd);
430 FileDescriptorInfo* info = FileDescriptorInfo::createFromFd(fd);
432 if (closedir(d) == -1) {
433 ALOGE("Unable to close directory : %s", strerror(errno));
437 open_fd_map[fd] = info;
440 if (closedir(d) == -1) {
441 ALOGE("Unable to close directory : %s", strerror(errno));
444 return new FileDescriptorTable(open_fd_map);
448 std::set<int> open_fds;
450 // First get the list of open descriptors.
451 DIR* d = opendir(kFdPath);
453 ALOGE("Unable to open directory %s: %s", kFdPath, strerror(errno));
457 int dir_fd = dirfd(d);
459 while ((e = readdir(d)) != NULL) {
460 const int fd = ParseFd(e, dir_fd);
468 if (closedir(d) == -1) {
469 ALOGE("Unable to close directory : %s", strerror(errno));
473 return RestatInternal(open_fds);
476 // Reopens all file descriptors that are contained in the table. Returns true
477 // if all descriptors were successfully re-opened or detached, and false if an
479 bool ReopenOrDetach() {
480 std::unordered_map<int, FileDescriptorInfo*>::const_iterator it;
481 for (it = open_fd_map_.begin(); it != open_fd_map_.end(); ++it) {
482 const FileDescriptorInfo* info = it->second;
483 if (info == NULL || !info->ReopenOrDetach()) {
492 FileDescriptorTable(const std::unordered_map<int, FileDescriptorInfo*>& map)
493 : open_fd_map_(map) {
496 bool RestatInternal(std::set<int>& open_fds) {
499 // Iterate through the list of file descriptors we've already recorded
500 // and check whether :
502 // (a) they continue to be open.
503 // (b) they refer to the same file.
504 std::unordered_map<int, FileDescriptorInfo*>::iterator it = open_fd_map_.begin();
505 while (it != open_fd_map_.end()) {
506 std::set<int>::const_iterator element = open_fds.find(it->first);
507 if (element == open_fds.end()) {
508 // The entry from the file descriptor table is no longer in the list
509 // of open files. We warn about this condition and remove it from
510 // the list of FDs under consideration.
512 // TODO(narayan): This will be an error in a future android release.
514 // ALOGW("Zygote closed file descriptor %d.", it->first);
515 it = open_fd_map_.erase(it);
517 // The entry from the file descriptor table is still open. Restat
518 // it and check whether it refers to the same file.
519 const bool same_file = it->second->Restat();
521 // The file descriptor refers to a different description. We must
522 // update our entry in the table.
524 it->second = FileDescriptorInfo::createFromFd(*element);
525 if (it->second == NULL) {
526 // The descriptor no longer no longer refers to a whitelisted file.
527 // We flag an error and remove it from the list of files we're
530 it = open_fd_map_.erase(it);
532 // Successfully restatted the file, move on to the next open FD.
536 // It's the same file. Nothing to do here. Move on to the next open
541 // Finally, remove the FD from the set of open_fds. We do this last because
542 // |element| will not remain valid after a call to erase.
543 open_fds.erase(*element);
547 if (open_fds.size() > 0) {
548 // The zygote has opened new file descriptors since our last inspection.
549 // We warn about this condition and add them to our table.
551 // TODO(narayan): This will be an error in a future android release.
553 // ALOGW("Zygote opened %zd new file descriptor(s).", open_fds.size());
555 // TODO(narayan): This code will be removed in a future android release.
556 std::set<int>::const_iterator it;
557 for (it = open_fds.begin(); it != open_fds.end(); ++it) {
558 const int fd = (*it);
559 FileDescriptorInfo* info = FileDescriptorInfo::createFromFd(fd);
561 // A newly opened file is not on the whitelist. Flag an error and
565 // Track the newly opened file.
566 open_fd_map_[fd] = info;
574 static int ParseFd(dirent* e, int dir_fd) {
576 const int fd = strtol(e->d_name, &end, 10);
577 if ((*end) != '\0') {
581 // Don't bother with the standard input/output/error, they're handled
582 // specially post-fork anyway.
583 if (fd <= STDERR_FILENO || fd == dir_fd) {
590 // Invariant: All values in this unordered_map are non-NULL.
591 std::unordered_map<int, FileDescriptorInfo*> open_fd_map_;
593 // DISALLOW_COPY_AND_ASSIGN(FileDescriptorTable);
594 FileDescriptorTable(const FileDescriptorTable&);
595 void operator=(const FileDescriptorTable&);