fd_utils.cpp revision 1713d9e97aada3dc695800c18b1025238a11629d
1/*
2 * Copyright (C) 2016 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 "fd_utils.h"
18
19#include <algorithm>
20
21#include <fcntl.h>
22#include <grp.h>
23#include <stdlib.h>
24#include <sys/socket.h>
25#include <sys/types.h>
26#include <sys/un.h>
27#include <unistd.h>
28
29#include <android-base/file.h>
30#include <android-base/logging.h>
31#include <android-base/stringprintf.h>
32#include <android-base/strings.h>
33
34// Static whitelist of open paths that the zygote is allowed to keep open.
35static const char* kPathWhitelist[] = {
36  "/dev/null",
37  "/dev/socket/zygote",
38  "/dev/socket/zygote_secondary",
39  "/dev/socket/webview_zygote",
40  "/sys/kernel/debug/tracing/trace_marker",
41  "/system/framework/framework-res.apk",
42  "/dev/urandom",
43  "/dev/ion",
44  "/dev/dri/renderD129", // Fixes b/31172436
45};
46
47static const char kFdPath[] = "/proc/self/fd";
48
49// static
50FileDescriptorWhitelist* FileDescriptorWhitelist::Get() {
51  if (instance_ == nullptr) {
52    instance_ = new FileDescriptorWhitelist();
53  }
54  return instance_;
55}
56
57bool 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)
61      return true;
62  }
63
64  // Check any paths added to the dynamic whitelist.
65  for (const auto& whitelist_path : whitelist_) {
66    if (path == whitelist_path)
67      return true;
68  }
69
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)) {
74    return true;
75  }
76
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* kSystemProductOverlayDir = "/system/product/overlay/";
89  static const char* kProductOverlayDir = "/product/overlay";
90  static const char* kApkSuffix = ".apk";
91
92  if ((android::base::StartsWith(path, kOverlayDir)
93       || android::base::StartsWith(path, kOverlaySubdir)
94       || android::base::StartsWith(path, kVendorOverlayDir)
95       || android::base::StartsWith(path, kSystemProductOverlayDir)
96       || android::base::StartsWith(path, kProductOverlayDir))
97      && android::base::EndsWith(path, kApkSuffix)
98      && path.find("/../") == std::string::npos) {
99    return true;
100  }
101
102  static const char* kOverlayIdmapPrefix = "/data/resource-cache/";
103  static const char* kOverlayIdmapSuffix = ".apk@idmap";
104  if (android::base::StartsWith(path, kOverlayIdmapPrefix)
105      && android::base::EndsWith(path, kOverlayIdmapSuffix)
106      && path.find("/../") == std::string::npos) {
107    return true;
108  }
109
110  // All regular files that are placed under this path are whitelisted automatically.
111  static const char* kZygoteWhitelistPath = "/vendor/zygote_whitelist/";
112  if (android::base::StartsWith(path, kZygoteWhitelistPath)
113      && path.find("/../") == std::string::npos) {
114    return true;
115  }
116
117  return false;
118}
119
120FileDescriptorWhitelist::FileDescriptorWhitelist()
121    : whitelist_() {
122}
123
124FileDescriptorWhitelist* FileDescriptorWhitelist::instance_ = nullptr;
125
126// static
127FileDescriptorInfo* FileDescriptorInfo::CreateFromFd(int fd) {
128  struct stat f_stat;
129  // This should never happen; the zygote should always have the right set
130  // of permissions required to stat all its open files.
131  if (TEMP_FAILURE_RETRY(fstat(fd, &f_stat)) == -1) {
132    PLOG(ERROR) << "Unable to stat fd " << fd;
133    return NULL;
134  }
135
136  const FileDescriptorWhitelist* whitelist = FileDescriptorWhitelist::Get();
137
138  if (S_ISSOCK(f_stat.st_mode)) {
139    std::string socket_name;
140    if (!GetSocketName(fd, &socket_name)) {
141      return NULL;
142    }
143
144    if (!whitelist->IsAllowed(socket_name)) {
145      LOG(ERROR) << "Socket name not whitelisted : " << socket_name
146                 << " (fd=" << fd << ")";
147      return NULL;
148    }
149
150    return new FileDescriptorInfo(fd);
151  }
152
153  // We only handle whitelisted regular files and character devices. Whitelisted
154  // character devices must provide a guarantee of sensible behaviour when
155  // reopened.
156  //
157  // S_ISDIR : Not supported. (We could if we wanted to, but it's unused).
158  // S_ISLINK : Not supported.
159  // S_ISBLK : Not supported.
160  // S_ISFIFO : Not supported. Note that the zygote uses pipes to communicate
161  // with the child process across forks but those should have been closed
162  // before we got to this point.
163  if (!S_ISCHR(f_stat.st_mode) && !S_ISREG(f_stat.st_mode)) {
164    LOG(ERROR) << "Unsupported st_mode " << f_stat.st_mode;
165    return NULL;
166  }
167
168  std::string file_path;
169  const std::string fd_path = android::base::StringPrintf("/proc/self/fd/%d", fd);
170  if (!android::base::Readlink(fd_path, &file_path)) {
171    return NULL;
172  }
173
174  if (!whitelist->IsAllowed(file_path)) {
175    LOG(ERROR) << "Not whitelisted : " << file_path;
176    return NULL;
177  }
178
179  // File descriptor flags : currently on FD_CLOEXEC. We can set these
180  // using F_SETFD - we're single threaded at this point of execution so
181  // there won't be any races.
182  const int fd_flags = TEMP_FAILURE_RETRY(fcntl(fd, F_GETFD));
183  if (fd_flags == -1) {
184    PLOG(ERROR) << "Failed fcntl(" << fd << ", F_GETFD)";
185    return NULL;
186  }
187
188  // File status flags :
189  // - File access mode : (O_RDONLY, O_WRONLY...) we'll pass these through
190  //   to the open() call.
191  //
192  // - File creation flags : (O_CREAT, O_EXCL...) - there's not much we can
193  //   do about these, since the file has already been created. We shall ignore
194  //   them here.
195  //
196  // - Other flags : We'll have to set these via F_SETFL. On linux, F_SETFL
197  //   can only set O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME, and O_NONBLOCK.
198  //   In particular, it can't set O_SYNC and O_DSYNC. We'll have to test for
199  //   their presence and pass them in to open().
200  int fs_flags = TEMP_FAILURE_RETRY(fcntl(fd, F_GETFL));
201  if (fs_flags == -1) {
202    PLOG(ERROR) << "Failed fcntl(" << fd << ", F_GETFL)";
203    return NULL;
204  }
205
206  // File offset : Ignore the offset for non seekable files.
207  const off_t offset = TEMP_FAILURE_RETRY(lseek64(fd, 0, SEEK_CUR));
208
209  // We pass the flags that open accepts to open, and use F_SETFL for
210  // the rest of them.
211  static const int kOpenFlags = (O_RDONLY | O_WRONLY | O_RDWR | O_DSYNC | O_SYNC);
212  int open_flags = fs_flags & (kOpenFlags);
213  fs_flags = fs_flags & (~(kOpenFlags));
214
215  return new FileDescriptorInfo(f_stat, file_path, fd, open_flags, fd_flags, fs_flags, offset);
216}
217
218bool FileDescriptorInfo::Restat() const {
219  struct stat f_stat;
220  if (TEMP_FAILURE_RETRY(fstat(fd, &f_stat)) == -1) {
221    PLOG(ERROR) << "Unable to restat fd " << fd;
222    return false;
223  }
224
225  return f_stat.st_ino == stat.st_ino && f_stat.st_dev == stat.st_dev;
226}
227
228bool FileDescriptorInfo::ReopenOrDetach() const {
229  if (is_sock) {
230    return DetachSocket();
231  }
232
233  // NOTE: This might happen if the file was unlinked after being opened.
234  // It's a common pattern in the case of temporary files and the like but
235  // we should not allow such usage from the zygote.
236  const int new_fd = TEMP_FAILURE_RETRY(open(file_path.c_str(), open_flags));
237
238  if (new_fd == -1) {
239    PLOG(ERROR) << "Failed open(" << file_path << ", " << open_flags << ")";
240    return false;
241  }
242
243  if (TEMP_FAILURE_RETRY(fcntl(new_fd, F_SETFD, fd_flags)) == -1) {
244    close(new_fd);
245    PLOG(ERROR) << "Failed fcntl(" << new_fd << ", F_SETFD, " << fd_flags << ")";
246    return false;
247  }
248
249  if (TEMP_FAILURE_RETRY(fcntl(new_fd, F_SETFL, fs_flags)) == -1) {
250    close(new_fd);
251    PLOG(ERROR) << "Failed fcntl(" << new_fd << ", F_SETFL, " << fs_flags << ")";
252    return false;
253  }
254
255  if (offset != -1 && TEMP_FAILURE_RETRY(lseek64(new_fd, offset, SEEK_SET)) == -1) {
256    close(new_fd);
257    PLOG(ERROR) << "Failed lseek64(" << new_fd << ", SEEK_SET)";
258    return false;
259  }
260
261  if (TEMP_FAILURE_RETRY(dup2(new_fd, fd)) == -1) {
262    close(new_fd);
263    PLOG(ERROR) << "Failed dup2(" << fd << ", " << new_fd << ")";
264    return false;
265  }
266
267  close(new_fd);
268
269  return true;
270}
271
272FileDescriptorInfo::FileDescriptorInfo(int fd) :
273  fd(fd),
274  stat(),
275  open_flags(0),
276  fd_flags(0),
277  fs_flags(0),
278  offset(0),
279  is_sock(true) {
280}
281
282FileDescriptorInfo::FileDescriptorInfo(struct stat stat, const std::string& file_path,
283                                       int fd, int open_flags, int fd_flags, int fs_flags,
284                                       off_t offset) :
285  fd(fd),
286  stat(stat),
287  file_path(file_path),
288  open_flags(open_flags),
289  fd_flags(fd_flags),
290  fs_flags(fs_flags),
291  offset(offset),
292  is_sock(false) {
293}
294
295// static
296bool FileDescriptorInfo::GetSocketName(const int fd, std::string* result) {
297  sockaddr_storage ss;
298  sockaddr* addr = reinterpret_cast<sockaddr*>(&ss);
299  socklen_t addr_len = sizeof(ss);
300
301  if (TEMP_FAILURE_RETRY(getsockname(fd, addr, &addr_len)) == -1) {
302    PLOG(ERROR) << "Failed getsockname(" << fd << ")";
303    return false;
304  }
305
306  if (addr->sa_family != AF_UNIX) {
307    LOG(ERROR) << "Unsupported socket (fd=" << fd << ") with family " << addr->sa_family;
308    return false;
309  }
310
311  const sockaddr_un* unix_addr = reinterpret_cast<const sockaddr_un*>(&ss);
312
313  size_t path_len = addr_len - offsetof(struct sockaddr_un, sun_path);
314  // This is an unnamed local socket, we do not accept it.
315  if (path_len == 0) {
316    LOG(ERROR) << "Unsupported AF_UNIX socket (fd=" << fd << ") with empty path.";
317    return false;
318  }
319
320  // This is a local socket with an abstract address, we do not accept it.
321  if (unix_addr->sun_path[0] == '\0') {
322    LOG(ERROR) << "Unsupported AF_UNIX socket (fd=" << fd << ") with abstract address.";
323    return false;
324  }
325
326  // If we're here, sun_path must refer to a null terminated filesystem
327  // pathname (man 7 unix). Remove the terminator before assigning it to an
328  // std::string.
329  if (unix_addr->sun_path[path_len - 1] ==  '\0') {
330    --path_len;
331  }
332
333  result->assign(unix_addr->sun_path, path_len);
334  return true;
335}
336
337bool FileDescriptorInfo::DetachSocket() const {
338  const int dev_null_fd = open("/dev/null", O_RDWR);
339  if (dev_null_fd < 0) {
340    PLOG(ERROR) << "Failed to open /dev/null";
341    return false;
342  }
343
344  if (dup2(dev_null_fd, fd) == -1) {
345    PLOG(ERROR) << "Failed dup2 on socket descriptor " << fd;
346    return false;
347  }
348
349  if (close(dev_null_fd) == -1) {
350    PLOG(ERROR) << "Failed close(" << dev_null_fd << ")";
351    return false;
352  }
353
354  return true;
355}
356
357// static
358FileDescriptorTable* FileDescriptorTable::Create(const std::vector<int>& fds_to_ignore) {
359  DIR* d = opendir(kFdPath);
360  if (d == NULL) {
361    PLOG(ERROR) << "Unable to open directory " << std::string(kFdPath);
362    return NULL;
363  }
364  int dir_fd = dirfd(d);
365  dirent* e;
366
367  std::unordered_map<int, FileDescriptorInfo*> open_fd_map;
368  while ((e = readdir(d)) != NULL) {
369    const int fd = ParseFd(e, dir_fd);
370    if (fd == -1) {
371      continue;
372    }
373    if (std::find(fds_to_ignore.begin(), fds_to_ignore.end(), fd) != fds_to_ignore.end()) {
374      LOG(INFO) << "Ignoring open file descriptor " << fd;
375      continue;
376    }
377
378    FileDescriptorInfo* info = FileDescriptorInfo::CreateFromFd(fd);
379    if (info == NULL) {
380      if (closedir(d) == -1) {
381        PLOG(ERROR) << "Unable to close directory";
382      }
383      return NULL;
384    }
385    open_fd_map[fd] = info;
386  }
387
388  if (closedir(d) == -1) {
389    PLOG(ERROR) << "Unable to close directory";
390    return NULL;
391  }
392  return new FileDescriptorTable(open_fd_map);
393}
394
395bool FileDescriptorTable::Restat(const std::vector<int>& fds_to_ignore) {
396  std::set<int> open_fds;
397
398  // First get the list of open descriptors.
399  DIR* d = opendir(kFdPath);
400  if (d == NULL) {
401    PLOG(ERROR) << "Unable to open directory " << std::string(kFdPath);
402    return false;
403  }
404
405  int dir_fd = dirfd(d);
406  dirent* e;
407  while ((e = readdir(d)) != NULL) {
408    const int fd = ParseFd(e, dir_fd);
409    if (fd == -1) {
410      continue;
411    }
412    if (std::find(fds_to_ignore.begin(), fds_to_ignore.end(), fd) != fds_to_ignore.end()) {
413      LOG(INFO) << "Ignoring open file descriptor " << fd;
414      continue;
415    }
416
417    open_fds.insert(fd);
418  }
419
420  if (closedir(d) == -1) {
421    PLOG(ERROR) << "Unable to close directory";
422    return false;
423  }
424
425  return RestatInternal(open_fds);
426}
427
428// Reopens all file descriptors that are contained in the table. Returns true
429// if all descriptors were successfully re-opened or detached, and false if an
430// error occurred.
431bool FileDescriptorTable::ReopenOrDetach() {
432  std::unordered_map<int, FileDescriptorInfo*>::const_iterator it;
433  for (it = open_fd_map_.begin(); it != open_fd_map_.end(); ++it) {
434    const FileDescriptorInfo* info = it->second;
435    if (info == NULL || !info->ReopenOrDetach()) {
436      return false;
437    }
438  }
439
440  return true;
441}
442
443FileDescriptorTable::FileDescriptorTable(
444    const std::unordered_map<int, FileDescriptorInfo*>& map)
445    : open_fd_map_(map) {
446}
447
448bool FileDescriptorTable::RestatInternal(std::set<int>& open_fds) {
449  bool error = false;
450
451  // Iterate through the list of file descriptors we've already recorded
452  // and check whether :
453  //
454  // (a) they continue to be open.
455  // (b) they refer to the same file.
456  std::unordered_map<int, FileDescriptorInfo*>::iterator it = open_fd_map_.begin();
457  while (it != open_fd_map_.end()) {
458    std::set<int>::const_iterator element = open_fds.find(it->first);
459    if (element == open_fds.end()) {
460      // The entry from the file descriptor table is no longer in the list
461      // of open files. We warn about this condition and remove it from
462      // the list of FDs under consideration.
463      //
464      // TODO(narayan): This will be an error in a future android release.
465      // error = true;
466      // ALOGW("Zygote closed file descriptor %d.", it->first);
467      it = open_fd_map_.erase(it);
468    } else {
469      // The entry from the file descriptor table is still open. Restat
470      // it and check whether it refers to the same file.
471      const bool same_file = it->second->Restat();
472      if (!same_file) {
473        // The file descriptor refers to a different description. We must
474        // update our entry in the table.
475        delete it->second;
476        it->second = FileDescriptorInfo::CreateFromFd(*element);
477        if (it->second == NULL) {
478          // The descriptor no longer no longer refers to a whitelisted file.
479          // We flag an error and remove it from the list of files we're
480          // tracking.
481          error = true;
482          it = open_fd_map_.erase(it);
483        } else {
484          // Successfully restatted the file, move on to the next open FD.
485          ++it;
486        }
487      } else {
488        // It's the same file. Nothing to do here. Move on to the next open
489        // FD.
490        ++it;
491      }
492
493      // Finally, remove the FD from the set of open_fds. We do this last because
494      // |element| will not remain valid after a call to erase.
495      open_fds.erase(element);
496    }
497  }
498
499  if (open_fds.size() > 0) {
500    // The zygote has opened new file descriptors since our last inspection.
501    // We warn about this condition and add them to our table.
502    //
503    // TODO(narayan): This will be an error in a future android release.
504    // error = true;
505    // ALOGW("Zygote opened %zd new file descriptor(s).", open_fds.size());
506
507    // TODO(narayan): This code will be removed in a future android release.
508    std::set<int>::const_iterator it;
509    for (it = open_fds.begin(); it != open_fds.end(); ++it) {
510      const int fd = (*it);
511      FileDescriptorInfo* info = FileDescriptorInfo::CreateFromFd(fd);
512      if (info == NULL) {
513        // A newly opened file is not on the whitelist. Flag an error and
514        // continue.
515        error = true;
516      } else {
517        // Track the newly opened file.
518        open_fd_map_[fd] = info;
519      }
520    }
521  }
522
523  return !error;
524}
525
526// static
527int FileDescriptorTable::ParseFd(dirent* e, int dir_fd) {
528  char* end;
529  const int fd = strtol(e->d_name, &end, 10);
530  if ((*end) != '\0') {
531    return -1;
532  }
533
534  // Don't bother with the standard input/output/error, they're handled
535  // specially post-fork anyway.
536  if (fd <= STDERR_FILENO || fd == dir_fd) {
537    return -1;
538  }
539
540  return fd;
541}
542