OSDN Git Service

Merge tag 'android-8.1.0_r33' into oreo-x86
[android-x86/frameworks-base.git] / core / jni / fd_utils.cpp
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.
35 static 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
47 static const char kFdPath[] = "/proc/self/fd";
48
49 // static
50 FileDescriptorWhitelist* FileDescriptorWhitelist::Get() {
51   if (instance_ == nullptr) {
52     instance_ = new FileDescriptorWhitelist();
53   }
54   return instance_;
55 }
56
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)
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* kApkSuffix = ".apk";
89
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) {
95     return true;
96   }
97
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) {
103     return true;
104   }
105
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) {
110     return true;
111   }
112
113   return false;
114 }
115
116 FileDescriptorWhitelist::FileDescriptorWhitelist()
117     : whitelist_() {
118 }
119
120 FileDescriptorWhitelist* FileDescriptorWhitelist::instance_ = nullptr;
121
122 // static
123 FileDescriptorInfo* FileDescriptorInfo::CreateFromFd(int fd) {
124   struct stat f_stat;
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;
129     return NULL;
130   }
131
132   const FileDescriptorWhitelist* whitelist = FileDescriptorWhitelist::Get();
133
134   if (S_ISSOCK(f_stat.st_mode)) {
135     std::string socket_name;
136     if (!GetSocketName(fd, &socket_name)) {
137       return NULL;
138     }
139
140     if (!whitelist->IsAllowed(socket_name)) {
141       LOG(ERROR) << "Socket name not whitelisted : " << socket_name
142                  << " (fd=" << fd << ")";
143       return NULL;
144     }
145
146     return new FileDescriptorInfo(fd);
147   }
148
149   // We only handle whitelisted regular files and character devices. Whitelisted
150   // character devices must provide a guarantee of sensible behaviour when
151   // reopened.
152   //
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;
161     return NULL;
162   }
163
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)) {
167     return NULL;
168   } else if (!strncmp(file_path.c_str(), "/android/", 9)) {
169     file_path = file_path.substr(8);
170   }
171
172   if (!whitelist->IsAllowed(file_path)) {
173     LOG(ERROR) << "Not whitelisted : " << file_path;
174     return NULL;
175   }
176
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)";
183     return NULL;
184   }
185
186   // File status flags :
187   // - File access mode : (O_RDONLY, O_WRONLY...) we'll pass these through
188   //   to the open() call.
189   //
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
192   //   them here.
193   //
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)";
201     return NULL;
202   }
203
204   // File offset : Ignore the offset for non seekable files.
205   const off_t offset = TEMP_FAILURE_RETRY(lseek64(fd, 0, SEEK_CUR));
206
207   // We pass the flags that open accepts to open, and use F_SETFL for
208   // the rest of them.
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));
212
213   return new FileDescriptorInfo(f_stat, file_path, fd, open_flags, fd_flags, fs_flags, offset);
214 }
215
216 bool FileDescriptorInfo::Restat() const {
217   struct stat f_stat;
218   if (TEMP_FAILURE_RETRY(fstat(fd, &f_stat)) == -1) {
219     PLOG(ERROR) << "Unable to restat fd " << fd;
220     return false;
221   }
222
223   return f_stat.st_ino == stat.st_ino && f_stat.st_dev == stat.st_dev;
224 }
225
226 bool FileDescriptorInfo::ReopenOrDetach() const {
227   if (is_sock) {
228     return DetachSocket();
229   }
230
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));
235
236   if (new_fd == -1) {
237     PLOG(ERROR) << "Failed open(" << file_path << ", " << open_flags << ")";
238     return false;
239   }
240
241   if (TEMP_FAILURE_RETRY(fcntl(new_fd, F_SETFD, fd_flags)) == -1) {
242     close(new_fd);
243     PLOG(ERROR) << "Failed fcntl(" << new_fd << ", F_SETFD, " << fd_flags << ")";
244     return false;
245   }
246
247   if (TEMP_FAILURE_RETRY(fcntl(new_fd, F_SETFL, fs_flags)) == -1) {
248     close(new_fd);
249     PLOG(ERROR) << "Failed fcntl(" << new_fd << ", F_SETFL, " << fs_flags << ")";
250     return false;
251   }
252
253   if (offset != -1 && TEMP_FAILURE_RETRY(lseek64(new_fd, offset, SEEK_SET)) == -1) {
254     close(new_fd);
255     PLOG(ERROR) << "Failed lseek64(" << new_fd << ", SEEK_SET)";
256     return false;
257   }
258
259   if (TEMP_FAILURE_RETRY(dup2(new_fd, fd)) == -1) {
260     close(new_fd);
261     PLOG(ERROR) << "Failed dup2(" << fd << ", " << new_fd << ")";
262     return false;
263   }
264
265   close(new_fd);
266
267   return true;
268 }
269
270 FileDescriptorInfo::FileDescriptorInfo(int fd) :
271   fd(fd),
272   stat(),
273   open_flags(0),
274   fd_flags(0),
275   fs_flags(0),
276   offset(0),
277   is_sock(true) {
278 }
279
280 FileDescriptorInfo::FileDescriptorInfo(struct stat stat, const std::string& file_path,
281                                        int fd, int open_flags, int fd_flags, int fs_flags,
282                                        off_t offset) :
283   fd(fd),
284   stat(stat),
285   file_path(file_path),
286   open_flags(open_flags),
287   fd_flags(fd_flags),
288   fs_flags(fs_flags),
289   offset(offset),
290   is_sock(false) {
291 }
292
293 // static
294 bool FileDescriptorInfo::GetSocketName(const int fd, std::string* result) {
295   sockaddr_storage ss;
296   sockaddr* addr = reinterpret_cast<sockaddr*>(&ss);
297   socklen_t addr_len = sizeof(ss);
298
299   if (TEMP_FAILURE_RETRY(getsockname(fd, addr, &addr_len)) == -1) {
300     PLOG(ERROR) << "Failed getsockname(" << fd << ")";
301     return false;
302   }
303
304   if (addr->sa_family != AF_UNIX) {
305     LOG(ERROR) << "Unsupported socket (fd=" << fd << ") with family " << addr->sa_family;
306     return false;
307   }
308
309   const sockaddr_un* unix_addr = reinterpret_cast<const sockaddr_un*>(&ss);
310
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.
313   if (path_len == 0) {
314     LOG(ERROR) << "Unsupported AF_UNIX socket (fd=" << fd << ") with empty path.";
315     return false;
316   }
317
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.";
321     return false;
322   }
323
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
326   // std::string.
327   if (unix_addr->sun_path[path_len - 1] ==  '\0') {
328     --path_len;
329   }
330
331   result->assign(unix_addr->sun_path, path_len);
332   return true;
333 }
334
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";
339     return false;
340   }
341
342   if (dup2(dev_null_fd, fd) == -1) {
343     PLOG(ERROR) << "Failed dup2 on socket descriptor " << fd;
344     return false;
345   }
346
347   if (close(dev_null_fd) == -1) {
348     PLOG(ERROR) << "Failed close(" << dev_null_fd << ")";
349     return false;
350   }
351
352   return true;
353 }
354
355 // static
356 FileDescriptorTable* FileDescriptorTable::Create(const std::vector<int>& fds_to_ignore) {
357   DIR* d = opendir(kFdPath);
358   if (d == NULL) {
359     PLOG(ERROR) << "Unable to open directory " << std::string(kFdPath);
360     return NULL;
361   }
362   int dir_fd = dirfd(d);
363   dirent* e;
364
365   std::unordered_map<int, FileDescriptorInfo*> open_fd_map;
366   while ((e = readdir(d)) != NULL) {
367     const int fd = ParseFd(e, dir_fd);
368     if (fd == -1) {
369       continue;
370     }
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;
373       continue;
374     }
375
376     FileDescriptorInfo* info = FileDescriptorInfo::CreateFromFd(fd);
377     if (info == NULL) {
378       if (closedir(d) == -1) {
379         PLOG(ERROR) << "Unable to close directory";
380       }
381       return NULL;
382     }
383     open_fd_map[fd] = info;
384   }
385
386   if (closedir(d) == -1) {
387     PLOG(ERROR) << "Unable to close directory";
388     return NULL;
389   }
390   return new FileDescriptorTable(open_fd_map);
391 }
392
393 bool FileDescriptorTable::Restat(const std::vector<int>& fds_to_ignore) {
394   std::set<int> open_fds;
395
396   // First get the list of open descriptors.
397   DIR* d = opendir(kFdPath);
398   if (d == NULL) {
399     PLOG(ERROR) << "Unable to open directory " << std::string(kFdPath);
400     return false;
401   }
402
403   int dir_fd = dirfd(d);
404   dirent* e;
405   while ((e = readdir(d)) != NULL) {
406     const int fd = ParseFd(e, dir_fd);
407     if (fd == -1) {
408       continue;
409     }
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;
412       continue;
413     }
414
415     open_fds.insert(fd);
416   }
417
418   if (closedir(d) == -1) {
419     PLOG(ERROR) << "Unable to close directory";
420     return false;
421   }
422
423   return RestatInternal(open_fds);
424 }
425
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
428 // error occurred.
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()) {
434       return false;
435     }
436   }
437
438   return true;
439 }
440
441 FileDescriptorTable::FileDescriptorTable(
442     const std::unordered_map<int, FileDescriptorInfo*>& map)
443     : open_fd_map_(map) {
444 }
445
446 bool FileDescriptorTable::RestatInternal(std::set<int>& open_fds) {
447   bool error = false;
448
449   // Iterate through the list of file descriptors we've already recorded
450   // and check whether :
451   //
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.
461       //
462       // TODO(narayan): This will be an error in a future android release.
463       // error = true;
464       // ALOGW("Zygote closed file descriptor %d.", it->first);
465       it = open_fd_map_.erase(it);
466     } else {
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();
470       if (!same_file) {
471         // The file descriptor refers to a different description. We must
472         // update our entry in the table.
473         delete it->second;
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
478           // tracking.
479           error = true;
480           it = open_fd_map_.erase(it);
481         } else {
482           // Successfully restatted the file, move on to the next open FD.
483           ++it;
484         }
485       } else {
486         // It's the same file. Nothing to do here. Move on to the next open
487         // FD.
488         ++it;
489       }
490
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);
494     }
495   }
496
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.
500     //
501     // TODO(narayan): This will be an error in a future android release.
502     // error = true;
503     // ALOGW("Zygote opened %zd new file descriptor(s).", open_fds.size());
504
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);
510       if (info == NULL) {
511         // A newly opened file is not on the whitelist. Flag an error and
512         // continue.
513         error = true;
514       } else {
515         // Track the newly opened file.
516         open_fd_map_[fd] = info;
517       }
518     }
519   }
520
521   return !error;
522 }
523
524 // static
525 int FileDescriptorTable::ParseFd(dirent* e, int dir_fd) {
526   char* end;
527   const int fd = strtol(e->d_name, &end, 10);
528   if ((*end) != '\0') {
529     return -1;
530   }
531
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) {
535     return -1;
536   }
537
538   return fd;
539 }