OSDN Git Service

Zygote: Additional whitelisting for legacy devices.
[android-x86/frameworks-base.git] / core / jni / fd_utils-inl.h
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 <string>
18 #include <unordered_map>
19 #include <set>
20 #include <vector>
21 #include <algorithm>
22
23 #include <dirent.h>
24 #include <fcntl.h>
25 #include <grp.h>
26 #include <inttypes.h>
27 #include <stdlib.h>
28 #include <sys/socket.h>
29 #include <sys/stat.h>
30 #include <sys/types.h>
31 #include <sys/un.h>
32 #include <unistd.h>
33
34 #include <cutils/log.h>
35 #include "JNIHelp.h"
36 #include "ScopedPrimitiveArray.h"
37
38 // Whitelist of open paths that the zygote is allowed to keep open.
39 //
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.
43 //
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. */
51   "/dev/null",
52   "/dev/socket/zygote",
53   "/dev/socket/zygote_secondary",
54   "/system/etc/event-log-tags",
55   "/sys/kernel/debug/tracing/trace_marker",
56   "/system/framework/framework-res.apk",
57   "/dev/urandom",
58   "/dev/ion",
59   "@netlink@"
60 };
61
62 static const char* kFdPath = "/proc/self/fd";
63
64 // Keeps track of all relevant information (flags, offset etc.) of an
65 // open zygote file descriptor.
66 class FileDescriptorInfo {
67  public:
68   // Create a FileDescriptorInfo for a given file descriptor. Returns
69   // |NULL| if an error occurred.
70   static FileDescriptorInfo* createFromFd(int fd) {
71     struct stat f_stat;
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));
76       return NULL;
77     }
78
79     if (S_ISSOCK(f_stat.st_mode)) {
80       std::string socket_name;
81       if (!GetSocketName(fd, &socket_name)) {
82         return NULL;
83       }
84
85       if (!IsWhitelisted(socket_name)) {
86         ALOGE("Socket name not whitelisted : %s (fd=%d)", socket_name.c_str(), fd);
87         return NULL;
88       }
89
90       return new FileDescriptorInfo(fd);
91     }
92
93     // We only handle whitelisted regular files and character devices. Whitelisted
94     // character devices must provide a guarantee of sensible behaviour when
95     // reopened.
96     //
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);
105       return NULL;
106     }
107
108     std::string file_path;
109     if (!Readlink(fd, &file_path)) {
110       return NULL;
111     }
112
113     if (!IsWhitelisted(file_path)) {
114       ALOGE("Not whitelisted : %s", file_path.c_str());
115       return NULL;
116     }
117
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));
124       return NULL;
125     }
126
127     // File status flags :
128     // - File access mode : (O_RDONLY, O_WRONLY...) we'll pass these through
129     //   to the open() call.
130     //
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
133     //   them here.
134     //
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));
142       return NULL;
143     }
144
145     // File offset : Ignore the offset for non seekable files.
146     const off_t offset = TEMP_FAILURE_RETRY(lseek64(fd, 0, SEEK_CUR));
147
148     // We pass the flags that open accepts to open, and use F_SETFL for
149     // the rest of them.
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));
153
154     return new FileDescriptorInfo(f_stat, file_path, fd, open_flags, fd_flags, fs_flags, offset);
155   }
156
157   // Checks whether the file descriptor associated with this object
158   // refers to the same description.
159   bool Restat() const {
160     struct stat f_stat;
161     if (TEMP_FAILURE_RETRY(fstat(fd, &f_stat)) == -1) {
162       return false;
163     }
164
165     return f_stat.st_ino == stat.st_ino && f_stat.st_dev == stat.st_dev;
166   }
167
168   bool ReopenOrDetach() const {
169     if (is_sock) {
170       return DetachSocket();
171     }
172
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));
177
178     if (new_fd == -1) {
179       ALOGE("Failed open(%s, %d) : %s", file_path.c_str(), open_flags, strerror(errno));
180       return false;
181     }
182
183     if (TEMP_FAILURE_RETRY(fcntl(new_fd, F_SETFD, fd_flags)) == -1) {
184       close(new_fd);
185       ALOGE("Failed fcntl(%d, F_SETFD, %x) : %s", new_fd, fd_flags, strerror(errno));
186       return false;
187     }
188
189     if (TEMP_FAILURE_RETRY(fcntl(new_fd, F_SETFL, fs_flags)) == -1) {
190       close(new_fd);
191       ALOGE("Failed fcntl(%d, F_SETFL, %x) : %s", new_fd, fs_flags, strerror(errno));
192       return false;
193     }
194
195     if (offset != -1 && TEMP_FAILURE_RETRY(lseek64(new_fd, offset, SEEK_SET)) == -1) {
196       close(new_fd);
197       ALOGE("Failed lseek64(%d, SEEK_SET) : %s", new_fd, strerror(errno));
198       return false;
199     }
200
201     if (TEMP_FAILURE_RETRY(dup2(new_fd, fd)) == -1) {
202       close(new_fd);
203       ALOGE("Failed dup2(%d, %d) : %s", fd, new_fd, strerror(errno));
204       return false;
205     }
206
207     close(new_fd);
208
209     return true;
210   }
211
212   const int fd;
213   const struct stat stat;
214   const std::string file_path;
215   const int open_flags;
216   const int fd_flags;
217   const int fs_flags;
218   const off_t offset;
219   const bool is_sock;
220
221  private:
222   FileDescriptorInfo(int fd) :
223     fd(fd),
224     stat(),
225     open_flags(0),
226     fd_flags(0),
227     fs_flags(0),
228     offset(0),
229     is_sock(true) {
230   }
231
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) :
234     fd(fd),
235     stat(stat),
236     file_path(file_path),
237     open_flags(open_flags),
238     fd_flags(fd_flags),
239     fs_flags(fs_flags),
240     offset(offset),
241     is_sock(false) {
242   }
243
244   static bool StartsWith(const std::string& str, const std::string& prefix) {
245     return str.compare(0, prefix.size(), prefix) == 0;
246   }
247
248   static bool EndsWith(const std::string& str, const std::string& suffix) {
249     if (suffix.size() > str.size()) {
250       return false;
251     }
252
253     return str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
254   }
255
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) {
263         return true;
264       }
265     }
266
267     static const std::string kFrameworksPrefix = "/system/framework/";
268     static const std::string kJarSuffix = ".jar";
269     if (StartsWith(path, kFrameworksPrefix) && EndsWith(path, kJarSuffix)) {
270       return true;
271     }
272
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";
283
284     if ((StartsWith(path, kOverlayDir) || StartsWith(path, kOverlaySubdir)
285          || StartsWith(path, kVendorOverlayDir))
286         && EndsWith(path, kApkSuffix)
287         && path.find("/../") == std::string::npos) {
288       return true;
289     }
290
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) {
295       return true;
296     }
297
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) {
301       return true;
302     }
303
304     return false;
305   }
306
307   // TODO: Call android::base::Readlink instead of copying the code here.
308   static bool Readlink(const int fd, std::string* result) {
309     char path[64];
310     snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
311
312     // Code copied from android::base::Readlink starts here :
313
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.
319     char buf[4096];
320     ssize_t len = readlink(path, buf, sizeof(buf));
321     if (len == -1) return false;
322
323     result->assign(buf, len);
324     return true;
325   }
326
327   // Returns the locally-bound name of the socket |fd|. Returns true
328   // iff. all of the following hold :
329   //
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
333   //   address).
334   static bool GetSocketName(const int fd, std::string* result) {
335     sockaddr_storage ss;
336     sockaddr* addr = reinterpret_cast<sockaddr*>(&ss);
337     socklen_t addr_len = sizeof(ss);
338
339     if (TEMP_FAILURE_RETRY(getsockname(fd, addr, &addr_len)) == -1) {
340       ALOGE("Failed getsockname(%d) : %s", fd, strerror(errno));
341       return false;
342     }
343
344
345     if (addr->sa_family == AF_NETLINK) {
346       (*result) = "@netlink@";
347       return true;
348     }
349
350     if (addr->sa_family != AF_UNIX) {
351       ALOGE("Unsupported socket (fd=%d) with family %d", fd, addr->sa_family);
352       return false;
353     }
354
355     const sockaddr_un* unix_addr = reinterpret_cast<const sockaddr_un*>(&ss);
356
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.
359     if (path_len == 0) {
360       ALOGE("Unsupported AF_UNIX socket (fd=%d) with empty path.", fd);
361       return false;
362     }
363
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);
367       return false;
368     }
369
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
372     // std::string.
373     if (unix_addr->sun_path[path_len - 1] ==  '\0') {
374       --path_len;
375     }
376
377     result->assign(unix_addr->sun_path, path_len);
378     return true;
379   }
380
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));
385       return false;
386     }
387
388     if (dup2(dev_null_fd, fd) == -1) {
389       ALOGE("Failed dup2 on socket descriptor %d : %s", fd, strerror(errno));
390       return false;
391     }
392
393     if (close(dev_null_fd) == -1) {
394       ALOGE("Failed close(%d) : %s", dev_null_fd, strerror(errno));
395       return false;
396     }
397
398     return true;
399   }
400
401
402   // DISALLOW_COPY_AND_ASSIGN(FileDescriptorInfo);
403   FileDescriptorInfo(const FileDescriptorInfo&);
404   void operator=(const FileDescriptorInfo&);
405 };
406
407 // A FileDescriptorTable is a collection of FileDescriptorInfo objects
408 // keyed by their FDs.
409 class FileDescriptorTable {
410  public:
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);
416     if (d == NULL) {
417       ALOGE("Unable to open directory %s: %s", kFdPath, strerror(errno));
418       return NULL;
419     }
420     int dir_fd = dirfd(d);
421     dirent* e;
422
423     std::unordered_map<int, FileDescriptorInfo*> open_fd_map;
424     while ((e = readdir(d)) != NULL) {
425       const int fd = ParseFd(e, dir_fd);
426       if (fd == -1) {
427         continue;
428       }
429
430       FileDescriptorInfo* info = FileDescriptorInfo::createFromFd(fd);
431       if (info == NULL) {
432         if (closedir(d) == -1) {
433           ALOGE("Unable to close directory : %s", strerror(errno));
434         }
435         return NULL;
436       }
437       open_fd_map[fd] = info;
438     }
439
440     if (closedir(d) == -1) {
441       ALOGE("Unable to close directory : %s", strerror(errno));
442       return NULL;
443     }
444     return new FileDescriptorTable(open_fd_map);
445   }
446
447   bool Restat() {
448     std::set<int> open_fds;
449
450     // First get the list of open descriptors.
451     DIR* d = opendir(kFdPath);
452     if (d == NULL) {
453       ALOGE("Unable to open directory %s: %s", kFdPath, strerror(errno));
454       return false;
455     }
456
457     int dir_fd = dirfd(d);
458     dirent* e;
459     while ((e = readdir(d)) != NULL) {
460       const int fd = ParseFd(e, dir_fd);
461       if (fd == -1) {
462         continue;
463       }
464
465       open_fds.insert(fd);
466     }
467
468     if (closedir(d) == -1) {
469       ALOGE("Unable to close directory : %s", strerror(errno));
470       return false;
471     }
472
473     return RestatInternal(open_fds);
474   }
475
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
478   // error occurred.
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()) {
484         return false;
485       }
486     }
487
488     return true;
489   }
490
491  private:
492   FileDescriptorTable(const std::unordered_map<int, FileDescriptorInfo*>& map)
493       : open_fd_map_(map) {
494   }
495
496   bool RestatInternal(std::set<int>& open_fds) {
497     bool error = false;
498
499     // Iterate through the list of file descriptors we've already recorded
500     // and check whether :
501     //
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.
511         //
512         // TODO(narayan): This will be an error in a future android release.
513         // error = true;
514         // ALOGW("Zygote closed file descriptor %d.", it->first);
515         it = open_fd_map_.erase(it);
516       } else {
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();
520         if (!same_file) {
521           // The file descriptor refers to a different description. We must
522           // update our entry in the table.
523           delete it->second;
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
528             // tracking.
529             error = true;
530             it = open_fd_map_.erase(it);
531           } else {
532             // Successfully restatted the file, move on to the next open FD.
533             ++it;
534           }
535         } else {
536           // It's the same file. Nothing to do here. Move on to the next open
537           // FD.
538           ++it;
539         }
540
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);
544       }
545     }
546
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.
550       //
551       // TODO(narayan): This will be an error in a future android release.
552       // error = true;
553       // ALOGW("Zygote opened %zd new file descriptor(s).", open_fds.size());
554
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);
560         if (info == NULL) {
561           // A newly opened file is not on the whitelist. Flag an error and
562           // continue.
563           error = true;
564         } else {
565           // Track the newly opened file.
566           open_fd_map_[fd] = info;
567         }
568       }
569     }
570
571     return !error;
572   }
573
574   static int ParseFd(dirent* e, int dir_fd) {
575     char* end;
576     const int fd = strtol(e->d_name, &end, 10);
577     if ((*end) != '\0') {
578       return -1;
579     }
580
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) {
584       return -1;
585     }
586
587     return fd;
588   }
589
590   // Invariant: All values in this unordered_map are non-NULL.
591   std::unordered_map<int, FileDescriptorInfo*> open_fd_map_;
592
593   // DISALLOW_COPY_AND_ASSIGN(FileDescriptorTable);
594   FileDescriptorTable(const FileDescriptorTable&);
595   void operator=(const FileDescriptorTable&);
596 };