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.
24 #include <sys/socket.h>
25 #include <sys/types.h>
29 #include <android-base/file.h>
30 #include <android-base/logging.h>
31 #include <android-base/stringprintf.h>
32 #include <android-base/strings.h>
34 // Static whitelist of open paths that the zygote is allowed to keep open.
35 static const char* kPathWhitelist[] = {
38 "/dev/socket/zygote_secondary",
39 "/dev/socket/webview_zygote",
40 "/sys/kernel/debug/tracing/trace_marker",
41 "/system/framework/framework-res.apk",
44 "/dev/dri/renderD129", // Fixes b/31172436
47 static const char kFdPath[] = "/proc/self/fd";
50 FileDescriptorWhitelist* FileDescriptorWhitelist::Get() {
51 if (instance_ == nullptr) {
52 instance_ = new FileDescriptorWhitelist();
57 bool FileDescriptorWhitelist::IsAllowed(const std::string& path) const {
58 // Check the static whitelist path.
59 for (const auto& whitelist_path : kPathWhitelist) {
60 if (path == whitelist_path)
64 // Check any paths added to the dynamic whitelist.
65 for (const auto& whitelist_path : whitelist_) {
66 if (path == whitelist_path)
70 static const char* kFrameworksPrefix = "/system/framework/";
71 static const char* kJarSuffix = ".jar";
72 if (android::base::StartsWith(path, kFrameworksPrefix)
73 && android::base::EndsWith(path, kJarSuffix)) {
77 // Whitelist files needed for Runtime Resource Overlay, like these:
78 // /system/vendor/overlay/framework-res.apk
79 // /system/vendor/overlay-subdir/pg/framework-res.apk
80 // /vendor/overlay/framework-res.apk
81 // /vendor/overlay/PG/android-framework-runtime-resource-overlay.apk
82 // /data/resource-cache/system@vendor@overlay@framework-res.apk@idmap
83 // /data/resource-cache/system@vendor@overlay-subdir@pg@framework-res.apk@idmap
84 // See AssetManager.cpp for more details on overlay-subdir.
85 static const char* kOverlayDir = "/system/vendor/overlay/";
86 static const char* kVendorOverlayDir = "/vendor/overlay";
87 static const char* kOverlaySubdir = "/system/vendor/overlay-subdir/";
88 static const char* kApkSuffix = ".apk";
90 if ((android::base::StartsWith(path, kOverlayDir)
91 || android::base::StartsWith(path, kOverlaySubdir)
92 || android::base::StartsWith(path, kVendorOverlayDir))
93 && android::base::EndsWith(path, kApkSuffix)
94 && path.find("/../") == std::string::npos) {
98 static const char* kOverlayIdmapPrefix = "/data/resource-cache/";
99 static const char* kOverlayIdmapSuffix = ".apk@idmap";
100 if (android::base::StartsWith(path, kOverlayIdmapPrefix)
101 && android::base::EndsWith(path, kOverlayIdmapSuffix)
102 && path.find("/../") == std::string::npos) {
106 // All regular files that are placed under this path are whitelisted automatically.
107 static const char* kZygoteWhitelistPath = "/vendor/zygote_whitelist/";
108 if (android::base::StartsWith(path, kZygoteWhitelistPath)
109 && path.find("/../") == std::string::npos) {
116 FileDescriptorWhitelist::FileDescriptorWhitelist()
120 FileDescriptorWhitelist* FileDescriptorWhitelist::instance_ = nullptr;
123 FileDescriptorInfo* FileDescriptorInfo::CreateFromFd(int fd) {
125 // This should never happen; the zygote should always have the right set
126 // of permissions required to stat all its open files.
127 if (TEMP_FAILURE_RETRY(fstat(fd, &f_stat)) == -1) {
128 PLOG(ERROR) << "Unable to stat fd " << fd;
132 const FileDescriptorWhitelist* whitelist = FileDescriptorWhitelist::Get();
134 if (S_ISSOCK(f_stat.st_mode)) {
135 std::string socket_name;
136 if (!GetSocketName(fd, &socket_name)) {
140 if (!whitelist->IsAllowed(socket_name)) {
141 LOG(ERROR) << "Socket name not whitelisted : " << socket_name
142 << " (fd=" << fd << ")";
146 return new FileDescriptorInfo(fd);
149 // We only handle whitelisted regular files and character devices. Whitelisted
150 // character devices must provide a guarantee of sensible behaviour when
153 // S_ISDIR : Not supported. (We could if we wanted to, but it's unused).
154 // S_ISLINK : Not supported.
155 // S_ISBLK : Not supported.
156 // S_ISFIFO : Not supported. Note that the zygote uses pipes to communicate
157 // with the child process across forks but those should have been closed
158 // before we got to this point.
159 if (!S_ISCHR(f_stat.st_mode) && !S_ISREG(f_stat.st_mode)) {
160 LOG(ERROR) << "Unsupported st_mode " << f_stat.st_mode;
164 std::string file_path;
165 const std::string fd_path = android::base::StringPrintf("/proc/self/fd/%d", fd);
166 if (!android::base::Readlink(fd_path, &file_path)) {
168 } else if (!strncmp(file_path.c_str(), "/android/", 9)) {
169 file_path = file_path.substr(8);
172 if (!whitelist->IsAllowed(file_path)) {
173 LOG(ERROR) << "Not whitelisted : " << file_path;
177 // File descriptor flags : currently on FD_CLOEXEC. We can set these
178 // using F_SETFD - we're single threaded at this point of execution so
179 // there won't be any races.
180 const int fd_flags = TEMP_FAILURE_RETRY(fcntl(fd, F_GETFD));
181 if (fd_flags == -1) {
182 PLOG(ERROR) << "Failed fcntl(" << fd << ", F_GETFD)";
186 // File status flags :
187 // - File access mode : (O_RDONLY, O_WRONLY...) we'll pass these through
188 // to the open() call.
190 // - File creation flags : (O_CREAT, O_EXCL...) - there's not much we can
191 // do about these, since the file has already been created. We shall ignore
194 // - Other flags : We'll have to set these via F_SETFL. On linux, F_SETFL
195 // can only set O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME, and O_NONBLOCK.
196 // In particular, it can't set O_SYNC and O_DSYNC. We'll have to test for
197 // their presence and pass them in to open().
198 int fs_flags = TEMP_FAILURE_RETRY(fcntl(fd, F_GETFL));
199 if (fs_flags == -1) {
200 PLOG(ERROR) << "Failed fcntl(" << fd << ", F_GETFL)";
204 // File offset : Ignore the offset for non seekable files.
205 const off_t offset = TEMP_FAILURE_RETRY(lseek64(fd, 0, SEEK_CUR));
207 // We pass the flags that open accepts to open, and use F_SETFL for
209 static const int kOpenFlags = (O_RDONLY | O_WRONLY | O_RDWR | O_DSYNC | O_SYNC);
210 int open_flags = fs_flags & (kOpenFlags);
211 fs_flags = fs_flags & (~(kOpenFlags));
213 return new FileDescriptorInfo(f_stat, file_path, fd, open_flags, fd_flags, fs_flags, offset);
216 bool FileDescriptorInfo::Restat() const {
218 if (TEMP_FAILURE_RETRY(fstat(fd, &f_stat)) == -1) {
219 PLOG(ERROR) << "Unable to restat fd " << fd;
223 return f_stat.st_ino == stat.st_ino && f_stat.st_dev == stat.st_dev;
226 bool FileDescriptorInfo::ReopenOrDetach() const {
228 return DetachSocket();
231 // NOTE: This might happen if the file was unlinked after being opened.
232 // It's a common pattern in the case of temporary files and the like but
233 // we should not allow such usage from the zygote.
234 const int new_fd = TEMP_FAILURE_RETRY(open(file_path.c_str(), open_flags));
237 PLOG(ERROR) << "Failed open(" << file_path << ", " << open_flags << ")";
241 if (TEMP_FAILURE_RETRY(fcntl(new_fd, F_SETFD, fd_flags)) == -1) {
243 PLOG(ERROR) << "Failed fcntl(" << new_fd << ", F_SETFD, " << fd_flags << ")";
247 if (TEMP_FAILURE_RETRY(fcntl(new_fd, F_SETFL, fs_flags)) == -1) {
249 PLOG(ERROR) << "Failed fcntl(" << new_fd << ", F_SETFL, " << fs_flags << ")";
253 if (offset != -1 && TEMP_FAILURE_RETRY(lseek64(new_fd, offset, SEEK_SET)) == -1) {
255 PLOG(ERROR) << "Failed lseek64(" << new_fd << ", SEEK_SET)";
259 if (TEMP_FAILURE_RETRY(dup2(new_fd, fd)) == -1) {
261 PLOG(ERROR) << "Failed dup2(" << fd << ", " << new_fd << ")";
270 FileDescriptorInfo::FileDescriptorInfo(int fd) :
280 FileDescriptorInfo::FileDescriptorInfo(struct stat stat, const std::string& file_path,
281 int fd, int open_flags, int fd_flags, int fs_flags,
285 file_path(file_path),
286 open_flags(open_flags),
294 bool FileDescriptorInfo::GetSocketName(const int fd, std::string* result) {
296 sockaddr* addr = reinterpret_cast<sockaddr*>(&ss);
297 socklen_t addr_len = sizeof(ss);
299 if (TEMP_FAILURE_RETRY(getsockname(fd, addr, &addr_len)) == -1) {
300 PLOG(ERROR) << "Failed getsockname(" << fd << ")";
304 if (addr->sa_family != AF_UNIX) {
305 LOG(ERROR) << "Unsupported socket (fd=" << fd << ") with family " << addr->sa_family;
309 const sockaddr_un* unix_addr = reinterpret_cast<const sockaddr_un*>(&ss);
311 size_t path_len = addr_len - offsetof(struct sockaddr_un, sun_path);
312 // This is an unnamed local socket, we do not accept it.
314 LOG(ERROR) << "Unsupported AF_UNIX socket (fd=" << fd << ") with empty path.";
318 // This is a local socket with an abstract address, we do not accept it.
319 if (unix_addr->sun_path[0] == '\0') {
320 LOG(ERROR) << "Unsupported AF_UNIX socket (fd=" << fd << ") with abstract address.";
324 // If we're here, sun_path must refer to a null terminated filesystem
325 // pathname (man 7 unix). Remove the terminator before assigning it to an
327 if (unix_addr->sun_path[path_len - 1] == '\0') {
331 result->assign(unix_addr->sun_path, path_len);
335 bool FileDescriptorInfo::DetachSocket() const {
336 const int dev_null_fd = open("/dev/null", O_RDWR);
337 if (dev_null_fd < 0) {
338 PLOG(ERROR) << "Failed to open /dev/null";
342 if (dup2(dev_null_fd, fd) == -1) {
343 PLOG(ERROR) << "Failed dup2 on socket descriptor " << fd;
347 if (close(dev_null_fd) == -1) {
348 PLOG(ERROR) << "Failed close(" << dev_null_fd << ")";
356 FileDescriptorTable* FileDescriptorTable::Create(const std::vector<int>& fds_to_ignore) {
357 DIR* d = opendir(kFdPath);
359 PLOG(ERROR) << "Unable to open directory " << std::string(kFdPath);
362 int dir_fd = dirfd(d);
365 std::unordered_map<int, FileDescriptorInfo*> open_fd_map;
366 while ((e = readdir(d)) != NULL) {
367 const int fd = ParseFd(e, dir_fd);
371 if (std::find(fds_to_ignore.begin(), fds_to_ignore.end(), fd) != fds_to_ignore.end()) {
372 LOG(INFO) << "Ignoring open file descriptor " << fd;
376 FileDescriptorInfo* info = FileDescriptorInfo::CreateFromFd(fd);
378 if (closedir(d) == -1) {
379 PLOG(ERROR) << "Unable to close directory";
383 open_fd_map[fd] = info;
386 if (closedir(d) == -1) {
387 PLOG(ERROR) << "Unable to close directory";
390 return new FileDescriptorTable(open_fd_map);
393 bool FileDescriptorTable::Restat(const std::vector<int>& fds_to_ignore) {
394 std::set<int> open_fds;
396 // First get the list of open descriptors.
397 DIR* d = opendir(kFdPath);
399 PLOG(ERROR) << "Unable to open directory " << std::string(kFdPath);
403 int dir_fd = dirfd(d);
405 while ((e = readdir(d)) != NULL) {
406 const int fd = ParseFd(e, dir_fd);
410 if (std::find(fds_to_ignore.begin(), fds_to_ignore.end(), fd) != fds_to_ignore.end()) {
411 LOG(INFO) << "Ignoring open file descriptor " << fd;
418 if (closedir(d) == -1) {
419 PLOG(ERROR) << "Unable to close directory";
423 return RestatInternal(open_fds);
426 // Reopens all file descriptors that are contained in the table. Returns true
427 // if all descriptors were successfully re-opened or detached, and false if an
429 bool FileDescriptorTable::ReopenOrDetach() {
430 std::unordered_map<int, FileDescriptorInfo*>::const_iterator it;
431 for (it = open_fd_map_.begin(); it != open_fd_map_.end(); ++it) {
432 const FileDescriptorInfo* info = it->second;
433 if (info == NULL || !info->ReopenOrDetach()) {
441 FileDescriptorTable::FileDescriptorTable(
442 const std::unordered_map<int, FileDescriptorInfo*>& map)
443 : open_fd_map_(map) {
446 bool FileDescriptorTable::RestatInternal(std::set<int>& open_fds) {
449 // Iterate through the list of file descriptors we've already recorded
450 // and check whether :
452 // (a) they continue to be open.
453 // (b) they refer to the same file.
454 std::unordered_map<int, FileDescriptorInfo*>::iterator it = open_fd_map_.begin();
455 while (it != open_fd_map_.end()) {
456 std::set<int>::const_iterator element = open_fds.find(it->first);
457 if (element == open_fds.end()) {
458 // The entry from the file descriptor table is no longer in the list
459 // of open files. We warn about this condition and remove it from
460 // the list of FDs under consideration.
462 // TODO(narayan): This will be an error in a future android release.
464 // ALOGW("Zygote closed file descriptor %d.", it->first);
465 it = open_fd_map_.erase(it);
467 // The entry from the file descriptor table is still open. Restat
468 // it and check whether it refers to the same file.
469 const bool same_file = it->second->Restat();
471 // The file descriptor refers to a different description. We must
472 // update our entry in the table.
474 it->second = FileDescriptorInfo::CreateFromFd(*element);
475 if (it->second == NULL) {
476 // The descriptor no longer no longer refers to a whitelisted file.
477 // We flag an error and remove it from the list of files we're
480 it = open_fd_map_.erase(it);
482 // Successfully restatted the file, move on to the next open FD.
486 // It's the same file. Nothing to do here. Move on to the next open
491 // Finally, remove the FD from the set of open_fds. We do this last because
492 // |element| will not remain valid after a call to erase.
493 open_fds.erase(element);
497 if (open_fds.size() > 0) {
498 // The zygote has opened new file descriptors since our last inspection.
499 // We warn about this condition and add them to our table.
501 // TODO(narayan): This will be an error in a future android release.
503 // ALOGW("Zygote opened %zd new file descriptor(s).", open_fds.size());
505 // TODO(narayan): This code will be removed in a future android release.
506 std::set<int>::const_iterator it;
507 for (it = open_fds.begin(); it != open_fds.end(); ++it) {
508 const int fd = (*it);
509 FileDescriptorInfo* info = FileDescriptorInfo::CreateFromFd(fd);
511 // A newly opened file is not on the whitelist. Flag an error and
515 // Track the newly opened file.
516 open_fd_map_[fd] = info;
525 int FileDescriptorTable::ParseFd(dirent* e, int dir_fd) {
527 const int fd = strtol(e->d_name, &end, 10);
528 if ((*end) != '\0') {
532 // Don't bother with the standard input/output/error, they're handled
533 // specially post-fork anyway.
534 if (fd <= STDERR_FILENO || fd == dir_fd) {