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/null", 51 "/dev/socket/zygote", 52 "/dev/socket/zygote_secondary", 53 "/system/etc/event-log-tags", 54 "/sys/kernel/debug/tracing/trace_marker", 55 "/system/framework/framework-res.apk", 56 "/dev/urandom", 57 "/dev/ion", 58 "/dev/dri/renderD129", // Fixes b/31172436 59 }; 60 61 static const char* kFdPath = "/proc/self/fd"; 62 63 // Keeps track of all relevant information (flags, offset etc.) of an 64 // open zygote file descriptor. 65 class FileDescriptorInfo { 66 public: 67 // Create a FileDescriptorInfo for a given file descriptor. Returns 68 // |NULL| if an error occurred. createFromFd(int fd)69 static FileDescriptorInfo* createFromFd(int fd) { 70 struct stat f_stat; 71 // This should never happen; the zygote should always have the right set 72 // of permissions required to stat all its open files. 73 if (TEMP_FAILURE_RETRY(fstat(fd, &f_stat)) == -1) { 74 ALOGE("Unable to stat fd %d : %s", fd, strerror(errno)); 75 return NULL; 76 } 77 78 if (S_ISSOCK(f_stat.st_mode)) { 79 std::string socket_name; 80 if (!GetSocketName(fd, &socket_name)) { 81 return NULL; 82 } 83 84 if (!IsWhitelisted(socket_name)) { 85 ALOGE("Socket name not whitelisted : %s (fd=%d)", socket_name.c_str(), fd); 86 return NULL; 87 } 88 89 return new FileDescriptorInfo(fd); 90 } 91 92 // We only handle whitelisted regular files and character devices. Whitelisted 93 // character devices must provide a guarantee of sensible behaviour when 94 // reopened. 95 // 96 // S_ISDIR : Not supported. (We could if we wanted to, but it's unused). 97 // S_ISLINK : Not supported. 98 // S_ISBLK : Not supported. 99 // S_ISFIFO : Not supported. Note that the zygote uses pipes to communicate 100 // with the child process across forks but those should have been closed 101 // before we got to this point. 102 if (!S_ISCHR(f_stat.st_mode) && !S_ISREG(f_stat.st_mode)) { 103 ALOGE("Unsupported st_mode %d", f_stat.st_mode); 104 return NULL; 105 } 106 107 std::string file_path; 108 if (!Readlink(fd, &file_path)) { 109 return NULL; 110 } 111 112 if (!IsWhitelisted(file_path)) { 113 ALOGE("Not whitelisted : %s", file_path.c_str()); 114 return NULL; 115 } 116 117 // File descriptor flags : currently on FD_CLOEXEC. We can set these 118 // using F_SETFD - we're single threaded at this point of execution so 119 // there won't be any races. 120 const int fd_flags = TEMP_FAILURE_RETRY(fcntl(fd, F_GETFD)); 121 if (fd_flags == -1) { 122 ALOGE("Failed fcntl(%d, F_GETFD) : %s", fd, strerror(errno)); 123 return NULL; 124 } 125 126 // File status flags : 127 // - File access mode : (O_RDONLY, O_WRONLY...) we'll pass these through 128 // to the open() call. 129 // 130 // - File creation flags : (O_CREAT, O_EXCL...) - there's not much we can 131 // do about these, since the file has already been created. We shall ignore 132 // them here. 133 // 134 // - Other flags : We'll have to set these via F_SETFL. On linux, F_SETFL 135 // can only set O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME, and O_NONBLOCK. 136 // In particular, it can't set O_SYNC and O_DSYNC. We'll have to test for 137 // their presence and pass them in to open(). 138 int fs_flags = TEMP_FAILURE_RETRY(fcntl(fd, F_GETFL)); 139 if (fs_flags == -1) { 140 ALOGE("Failed fcntl(%d, F_GETFL) : %s", fd, strerror(errno)); 141 return NULL; 142 } 143 144 // File offset : Ignore the offset for non seekable files. 145 const off_t offset = TEMP_FAILURE_RETRY(lseek64(fd, 0, SEEK_CUR)); 146 147 // We pass the flags that open accepts to open, and use F_SETFL for 148 // the rest of them. 149 static const int kOpenFlags = (O_RDONLY | O_WRONLY | O_RDWR | O_DSYNC | O_SYNC); 150 int open_flags = fs_flags & (kOpenFlags); 151 fs_flags = fs_flags & (~(kOpenFlags)); 152 153 return new FileDescriptorInfo(f_stat, file_path, fd, open_flags, fd_flags, fs_flags, offset); 154 } 155 156 // Checks whether the file descriptor associated with this object 157 // refers to the same description. Restat()158 bool Restat() const { 159 struct stat f_stat; 160 if (TEMP_FAILURE_RETRY(fstat(fd, &f_stat)) == -1) { 161 return false; 162 } 163 164 return f_stat.st_ino == stat.st_ino && f_stat.st_dev == stat.st_dev; 165 } 166 ReopenOrDetach()167 bool ReopenOrDetach() const { 168 if (is_sock) { 169 return DetachSocket(); 170 } 171 172 // NOTE: This might happen if the file was unlinked after being opened. 173 // It's a common pattern in the case of temporary files and the like but 174 // we should not allow such usage from the zygote. 175 const int new_fd = TEMP_FAILURE_RETRY(open(file_path.c_str(), open_flags)); 176 177 if (new_fd == -1) { 178 ALOGE("Failed open(%s, %d) : %s", file_path.c_str(), open_flags, strerror(errno)); 179 return false; 180 } 181 182 if (TEMP_FAILURE_RETRY(fcntl(new_fd, F_SETFD, fd_flags)) == -1) { 183 close(new_fd); 184 ALOGE("Failed fcntl(%d, F_SETFD, %x) : %s", new_fd, fd_flags, strerror(errno)); 185 return false; 186 } 187 188 if (TEMP_FAILURE_RETRY(fcntl(new_fd, F_SETFL, fs_flags)) == -1) { 189 close(new_fd); 190 ALOGE("Failed fcntl(%d, F_SETFL, %x) : %s", new_fd, fs_flags, strerror(errno)); 191 return false; 192 } 193 194 if (offset != -1 && TEMP_FAILURE_RETRY(lseek64(new_fd, offset, SEEK_SET)) == -1) { 195 close(new_fd); 196 ALOGE("Failed lseek64(%d, SEEK_SET) : %s", new_fd, strerror(errno)); 197 return false; 198 } 199 200 if (TEMP_FAILURE_RETRY(dup2(new_fd, fd)) == -1) { 201 close(new_fd); 202 ALOGE("Failed dup2(%d, %d) : %s", fd, new_fd, strerror(errno)); 203 return false; 204 } 205 206 close(new_fd); 207 208 return true; 209 } 210 211 const int fd; 212 const struct stat stat; 213 const std::string file_path; 214 const int open_flags; 215 const int fd_flags; 216 const int fs_flags; 217 const off_t offset; 218 const bool is_sock; 219 220 private: FileDescriptorInfo(int fd)221 FileDescriptorInfo(int fd) : 222 fd(fd), 223 stat(), 224 open_flags(0), 225 fd_flags(0), 226 fs_flags(0), 227 offset(0), 228 is_sock(true) { 229 } 230 FileDescriptorInfo(struct stat stat,const std::string & file_path,int fd,int open_flags,int fd_flags,int fs_flags,off_t offset)231 FileDescriptorInfo(struct stat stat, const std::string& file_path, int fd, int open_flags, 232 int fd_flags, int fs_flags, off_t offset) : 233 fd(fd), 234 stat(stat), 235 file_path(file_path), 236 open_flags(open_flags), 237 fd_flags(fd_flags), 238 fs_flags(fs_flags), 239 offset(offset), 240 is_sock(false) { 241 } 242 243 // Returns true iff. a given path is whitelisted. A path is whitelisted 244 // if it belongs to the whitelist (see kPathWhitelist) or if it's a path 245 // under /system/framework that ends with ".jar". IsWhitelisted(const std::string & path)246 static bool IsWhitelisted(const std::string& path) { 247 for (size_t i = 0; i < (sizeof(kPathWhitelist) / sizeof(kPathWhitelist[0])); ++i) { 248 if (kPathWhitelist[i] == path) { 249 return true; 250 } 251 } 252 253 static const std::string kFrameworksPrefix = "/system/framework/"; 254 static const std::string kJarSuffix = ".jar"; 255 if (path.compare(0, kFrameworksPrefix.size(), kFrameworksPrefix) == 0 && 256 path.compare(path.size() - kJarSuffix.size(), kJarSuffix.size(), kJarSuffix) == 0) { 257 return true; 258 } 259 return false; 260 } 261 262 // TODO: Call android::base::Readlink instead of copying the code here. Readlink(const int fd,std::string * result)263 static bool Readlink(const int fd, std::string* result) { 264 char path[64]; 265 snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); 266 267 // Code copied from android::base::Readlink starts here : 268 269 // Annoyingly, the readlink system call returns EINVAL for a zero-sized buffer, 270 // and truncates to whatever size you do supply, so it can't be used to query. 271 // We could call lstat first, but that would introduce a race condition that 272 // we couldn't detect. 273 // ext2 and ext4 both have PAGE_SIZE limitations, so we assume that here. 274 char buf[4096]; 275 ssize_t len = readlink(path, buf, sizeof(buf)); 276 if (len == -1) return false; 277 278 result->assign(buf, len); 279 return true; 280 } 281 282 // Returns the locally-bound name of the socket |fd|. Returns true 283 // iff. all of the following hold : 284 // 285 // - the socket's sa_family is AF_UNIX. 286 // - the length of the path is greater than zero (i.e, not an unnamed socket). 287 // - the first byte of the path isn't zero (i.e, not a socket with an abstract 288 // address). GetSocketName(const int fd,std::string * result)289 static bool GetSocketName(const int fd, std::string* result) { 290 sockaddr_storage ss; 291 sockaddr* addr = reinterpret_cast<sockaddr*>(&ss); 292 socklen_t addr_len = sizeof(ss); 293 294 if (TEMP_FAILURE_RETRY(getsockname(fd, addr, &addr_len)) == -1) { 295 ALOGE("Failed getsockname(%d) : %s", fd, strerror(errno)); 296 return false; 297 } 298 299 if (addr->sa_family != AF_UNIX) { 300 ALOGE("Unsupported socket (fd=%d) with family %d", fd, addr->sa_family); 301 return false; 302 } 303 304 const sockaddr_un* unix_addr = reinterpret_cast<const sockaddr_un*>(&ss); 305 306 size_t path_len = addr_len - offsetof(struct sockaddr_un, sun_path); 307 // This is an unnamed local socket, we do not accept it. 308 if (path_len == 0) { 309 ALOGE("Unsupported AF_UNIX socket (fd=%d) with empty path.", fd); 310 return false; 311 } 312 313 // This is a local socket with an abstract address, we do not accept it. 314 if (unix_addr->sun_path[0] == '\0') { 315 ALOGE("Unsupported AF_UNIX socket (fd=%d) with abstract address.", fd); 316 return false; 317 } 318 319 // If we're here, sun_path must refer to a null terminated filesystem 320 // pathname (man 7 unix). Remove the terminator before assigning it to an 321 // std::string. 322 if (unix_addr->sun_path[path_len - 1] == '\0') { 323 --path_len; 324 } 325 326 result->assign(unix_addr->sun_path, path_len); 327 return true; 328 } 329 DetachSocket()330 bool DetachSocket() const { 331 const int dev_null_fd = open("/dev/null", O_RDWR); 332 if (dev_null_fd < 0) { 333 ALOGE("Failed to open /dev/null : %s", strerror(errno)); 334 return false; 335 } 336 337 if (dup2(dev_null_fd, fd) == -1) { 338 ALOGE("Failed dup2 on socket descriptor %d : %s", fd, strerror(errno)); 339 return false; 340 } 341 342 if (close(dev_null_fd) == -1) { 343 ALOGE("Failed close(%d) : %s", dev_null_fd, strerror(errno)); 344 return false; 345 } 346 347 return true; 348 } 349 350 DISALLOW_COPY_AND_ASSIGN(FileDescriptorInfo); 351 }; 352 353 // A FileDescriptorTable is a collection of FileDescriptorInfo objects 354 // keyed by their FDs. 355 class FileDescriptorTable { 356 public: 357 // Creates a new FileDescriptorTable. This function scans 358 // /proc/self/fd for the list of open file descriptors and collects 359 // information about them. Returns NULL if an error occurs. Create()360 static FileDescriptorTable* Create() { 361 DIR* d = opendir(kFdPath); 362 if (d == NULL) { 363 ALOGE("Unable to open directory %s: %s", kFdPath, strerror(errno)); 364 return NULL; 365 } 366 int dir_fd = dirfd(d); 367 dirent* e; 368 369 std::unordered_map<int, FileDescriptorInfo*> open_fd_map; 370 while ((e = readdir(d)) != NULL) { 371 const int fd = ParseFd(e, dir_fd); 372 if (fd == -1) { 373 continue; 374 } 375 376 FileDescriptorInfo* info = FileDescriptorInfo::createFromFd(fd); 377 if (info == NULL) { 378 if (closedir(d) == -1) { 379 ALOGE("Unable to close directory : %s", strerror(errno)); 380 } 381 return NULL; 382 } 383 open_fd_map[fd] = info; 384 } 385 386 if (closedir(d) == -1) { 387 ALOGE("Unable to close directory : %s", strerror(errno)); 388 return NULL; 389 } 390 return new FileDescriptorTable(open_fd_map); 391 } 392 Restat()393 bool Restat() { 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 ALOGE("Unable to open directory %s: %s", kFdPath, strerror(errno)); 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 411 open_fds.insert(fd); 412 } 413 414 if (closedir(d) == -1) { 415 ALOGE("Unable to close directory : %s", strerror(errno)); 416 return false; 417 } 418 419 return RestatInternal(open_fds); 420 } 421 422 // Reopens all file descriptors that are contained in the table. Returns true 423 // if all descriptors were successfully re-opened or detached, and false if an 424 // error occurred. ReopenOrDetach()425 bool ReopenOrDetach() { 426 std::unordered_map<int, FileDescriptorInfo*>::const_iterator it; 427 for (it = open_fd_map_.begin(); it != open_fd_map_.end(); ++it) { 428 const FileDescriptorInfo* info = it->second; 429 if (info == NULL || !info->ReopenOrDetach()) { 430 return false; 431 } 432 } 433 434 return true; 435 } 436 437 private: FileDescriptorTable(const std::unordered_map<int,FileDescriptorInfo * > & map)438 FileDescriptorTable(const std::unordered_map<int, FileDescriptorInfo*>& map) 439 : open_fd_map_(map) { 440 } 441 RestatInternal(std::set<int> & open_fds)442 bool RestatInternal(std::set<int>& open_fds) { 443 bool error = false; 444 445 // Iterate through the list of file descriptors we've already recorded 446 // and check whether : 447 // 448 // (a) they continue to be open. 449 // (b) they refer to the same file. 450 std::unordered_map<int, FileDescriptorInfo*>::iterator it = open_fd_map_.begin(); 451 while (it != open_fd_map_.end()) { 452 std::set<int>::const_iterator element = open_fds.find(it->first); 453 if (element == open_fds.end()) { 454 // The entry from the file descriptor table is no longer in the list 455 // of open files. We warn about this condition and remove it from 456 // the list of FDs under consideration. 457 // 458 // TODO(narayan): This will be an error in a future android release. 459 // error = true; 460 // ALOGW("Zygote closed file descriptor %d.", it->first); 461 it = open_fd_map_.erase(it); 462 } else { 463 // The entry from the file descriptor table is still open. Restat 464 // it and check whether it refers to the same file. 465 const bool same_file = it->second->Restat(); 466 if (!same_file) { 467 // The file descriptor refers to a different description. We must 468 // update our entry in the table. 469 delete it->second; 470 it->second = FileDescriptorInfo::createFromFd(*element); 471 if (it->second == NULL) { 472 // The descriptor no longer no longer refers to a whitelisted file. 473 // We flag an error and remove it from the list of files we're 474 // tracking. 475 error = true; 476 it = open_fd_map_.erase(it); 477 } else { 478 // Successfully restatted the file, move on to the next open FD. 479 ++it; 480 } 481 } else { 482 // It's the same file. Nothing to do here. Move on to the next open 483 // FD. 484 ++it; 485 } 486 487 // Finally, remove the FD from the set of open_fds. We do this last because 488 // |element| will not remain valid after a call to erase. 489 open_fds.erase(element); 490 } 491 } 492 493 if (open_fds.size() > 0) { 494 // The zygote has opened new file descriptors since our last inspection. 495 // We warn about this condition and add them to our table. 496 // 497 // TODO(narayan): This will be an error in a future android release. 498 // error = true; 499 // ALOGW("Zygote opened %zd new file descriptor(s).", open_fds.size()); 500 501 // TODO(narayan): This code will be removed in a future android release. 502 std::set<int>::const_iterator it; 503 for (it = open_fds.begin(); it != open_fds.end(); ++it) { 504 const int fd = (*it); 505 FileDescriptorInfo* info = FileDescriptorInfo::createFromFd(fd); 506 if (info == NULL) { 507 // A newly opened file is not on the whitelist. Flag an error and 508 // continue. 509 error = true; 510 } else { 511 // Track the newly opened file. 512 open_fd_map_[fd] = info; 513 } 514 } 515 } 516 517 return !error; 518 } 519 ParseFd(dirent * e,int dir_fd)520 static int ParseFd(dirent* e, int dir_fd) { 521 char* end; 522 const int fd = strtol(e->d_name, &end, 10); 523 if ((*end) != '\0') { 524 return -1; 525 } 526 527 // Don't bother with the standard input/output/error, they're handled 528 // specially post-fork anyway. 529 if (fd <= STDERR_FILENO || fd == dir_fd) { 530 return -1; 531 } 532 533 return fd; 534 } 535 536 // Invariant: All values in this unordered_map are non-NULL. 537 std::unordered_map<int, FileDescriptorInfo*> open_fd_map_; 538 539 DISALLOW_COPY_AND_ASSIGN(FileDescriptorTable); 540 }; 541