Home | History | Annotate | Download | only in services
      1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #include "sandbox/linux/services/credentials.h"
      6 
      7 #include <dirent.h>
      8 #include <errno.h>
      9 #include <fcntl.h>
     10 #include <stdio.h>
     11 #include <sys/capability.h>
     12 #include <sys/stat.h>
     13 #include <sys/types.h>
     14 #include <unistd.h>
     15 
     16 #include "base/basictypes.h"
     17 #include "base/bind.h"
     18 #include "base/logging.h"
     19 #include "base/strings/string_number_conversions.h"
     20 #include "base/template_util.h"
     21 #include "base/threading/thread.h"
     22 
     23 namespace {
     24 
     25 struct CapFreeDeleter {
     26   inline void operator()(cap_t cap) const {
     27     int ret = cap_free(cap);
     28     CHECK_EQ(0, ret);
     29   }
     30 };
     31 
     32 // Wrapper to manage libcap2's cap_t type.
     33 typedef scoped_ptr<typeof(*((cap_t)0)), CapFreeDeleter> ScopedCap;
     34 
     35 struct CapTextFreeDeleter {
     36   inline void operator()(char* cap_text) const {
     37     int ret = cap_free(cap_text);
     38     CHECK_EQ(0, ret);
     39   }
     40 };
     41 
     42 // Wrapper to manage the result from libcap2's cap_from_text().
     43 typedef scoped_ptr<char, CapTextFreeDeleter> ScopedCapText;
     44 
     45 struct FILECloser {
     46   inline void operator()(FILE* f) const {
     47     DCHECK(f);
     48     PCHECK(0 == fclose(f));
     49   }
     50 };
     51 
     52 // Don't use ScopedFILE in base/file_util.h since it doesn't check fclose().
     53 // TODO(jln): fix base/.
     54 typedef scoped_ptr<FILE, FILECloser> ScopedFILE;
     55 
     56 struct DIRCloser {
     57   void operator()(DIR* d) const {
     58     DCHECK(d);
     59     PCHECK(0 == closedir(d));
     60   }
     61 };
     62 
     63 typedef scoped_ptr<DIR, DIRCloser> ScopedDIR;
     64 
     65 COMPILE_ASSERT((base::is_same<uid_t, gid_t>::value), UidAndGidAreSameType);
     66 // generic_id_t can be used for either uid_t or gid_t.
     67 typedef uid_t generic_id_t;
     68 
     69 // Write a uid or gid mapping from |id| to |id| in |map_file|.
     70 bool WriteToIdMapFile(const char* map_file, generic_id_t id) {
     71   ScopedFILE f(fopen(map_file, "w"));
     72   PCHECK(f);
     73   const uid_t inside_id = id;
     74   const uid_t outside_id = id;
     75   int num = fprintf(f.get(), "%d %d 1\n", inside_id, outside_id);
     76   if (num < 0) return false;
     77   // Manually call fflush() to catch permission failures.
     78   int ret = fflush(f.get());
     79   if (ret) {
     80     VLOG(1) << "Could not write to id map file";
     81     return false;
     82   }
     83   return true;
     84 }
     85 
     86 // Checks that the set of RES-uids and the set of RES-gids have
     87 // one element each and return that element in |resuid| and |resgid|
     88 // respectively. It's ok to pass NULL as one or both of the ids.
     89 bool GetRESIds(uid_t* resuid, gid_t* resgid) {
     90   uid_t ruid, euid, suid;
     91   gid_t rgid, egid, sgid;
     92   PCHECK(getresuid(&ruid, &euid, &suid) == 0);
     93   PCHECK(getresgid(&rgid, &egid, &sgid) == 0);
     94   const bool uids_are_equal = (ruid == euid) && (ruid == suid);
     95   const bool gids_are_equal = (rgid == egid) && (rgid == sgid);
     96   if (!uids_are_equal || !gids_are_equal) return false;
     97   if (resuid) *resuid = euid;
     98   if (resgid) *resgid = egid;
     99   return true;
    100 }
    101 
    102 // chroot() and chdir() to /proc/<tid>/fdinfo.
    103 void ChrootToThreadFdInfo(base::PlatformThreadId tid, bool* result) {
    104   DCHECK(result);
    105   *result = false;
    106 
    107   COMPILE_ASSERT((base::is_same<base::PlatformThreadId, int>::value),
    108                  TidIsAnInt);
    109   const std::string current_thread_fdinfo = "/proc/" +
    110       base::IntToString(tid) + "/fdinfo/";
    111 
    112   // Make extra sure that /proc/<tid>/fdinfo is unique to the thread.
    113   CHECK(0 == unshare(CLONE_FILES));
    114   int chroot_ret = chroot(current_thread_fdinfo.c_str());
    115   if (chroot_ret) {
    116     PLOG(ERROR) << "Could not chroot";
    117     return;
    118   }
    119 
    120   // CWD is essentially an implicit file descriptor, so be careful to not leave
    121   // it behind.
    122   PCHECK(0 == chdir("/"));
    123 
    124   *result = true;
    125   return;
    126 }
    127 
    128 // chroot() to an empty dir that is "safe". To be safe, it must not contain
    129 // any subdirectory (chroot-ing there would allow a chroot escape) and it must
    130 // be impossible to create an empty directory there.
    131 // We achieve this by doing the following:
    132 // 1. We create a new thread, which will create a new /proc/<tid>/ directory
    133 // 2. We chroot to /proc/<tid>/fdinfo/
    134 // This is already "safe", since fdinfo/ does not contain another directory and
    135 // one cannot create another directory there.
    136 // 3. The thread dies
    137 // After (3) happens, the directory is not available anymore in /proc.
    138 bool ChrootToSafeEmptyDir() {
    139   base::Thread chrooter("sandbox_chrooter");
    140   if (!chrooter.Start()) return false;
    141   bool is_chrooted = false;
    142   chrooter.message_loop()->PostTask(FROM_HERE,
    143       base::Bind(&ChrootToThreadFdInfo, chrooter.thread_id(), &is_chrooted));
    144   // Make sure our task has run before committing the return value.
    145   chrooter.Stop();
    146   return is_chrooted;
    147 }
    148 
    149 }  // namespace.
    150 
    151 namespace sandbox {
    152 
    153 Credentials::Credentials() {
    154 }
    155 
    156 Credentials::~Credentials() {
    157 }
    158 
    159 bool Credentials::HasOpenDirectory(int proc_fd) {
    160   int proc_self_fd = -1;
    161   if (proc_fd >= 0) {
    162     proc_self_fd = openat(proc_fd, "self/fd", O_DIRECTORY | O_RDONLY);
    163   } else {
    164     proc_self_fd = openat(AT_FDCWD, "/proc/self/fd", O_DIRECTORY | O_RDONLY);
    165     if (proc_self_fd < 0) {
    166       // If this process has been chrooted (eg into /proc/self/fdinfo) then
    167       // the new root dir will not have directory listing permissions for us
    168       // (hence EACCES).  And if we do have this permission, then /proc won't
    169       // exist anyway (hence ENOENT).
    170       DPCHECK(errno == EACCES || errno == ENOENT)
    171         << "Unexpected failure when trying to open /proc/self/fd: ("
    172         << errno << ") " << strerror(errno);
    173 
    174       // If not available, guess false.
    175       return false;
    176     }
    177   }
    178   CHECK_GE(proc_self_fd, 0);
    179 
    180   // Ownership of proc_self_fd is transferred here, it must not be closed
    181   // or modified afterwards except via dir.
    182   ScopedDIR dir(fdopendir(proc_self_fd));
    183   CHECK(dir);
    184 
    185   struct dirent e;
    186   struct dirent* de;
    187   while (!readdir_r(dir.get(), &e, &de) && de) {
    188     if (strcmp(e.d_name, ".") == 0 || strcmp(e.d_name, "..") == 0) {
    189       continue;
    190     }
    191 
    192     int fd_num;
    193     CHECK(base::StringToInt(e.d_name, &fd_num));
    194     if (fd_num == proc_fd || fd_num == proc_self_fd) {
    195       continue;
    196     }
    197 
    198     struct stat s;
    199     // It's OK to use proc_self_fd here, fstatat won't modify it.
    200     CHECK(fstatat(proc_self_fd, e.d_name, &s, 0) == 0);
    201     if (S_ISDIR(s.st_mode)) {
    202       return true;
    203     }
    204   }
    205 
    206   // No open unmanaged directories found.
    207   return false;
    208 }
    209 
    210 bool Credentials::DropAllCapabilities() {
    211   ScopedCap cap(cap_init());
    212   CHECK(cap);
    213   PCHECK(0 == cap_set_proc(cap.get()));
    214   // We never let this function fail.
    215   return true;
    216 }
    217 
    218 bool Credentials::HasAnyCapability() const {
    219   ScopedCap current_cap(cap_get_proc());
    220   CHECK(current_cap);
    221   ScopedCap empty_cap(cap_init());
    222   CHECK(empty_cap);
    223   return cap_compare(current_cap.get(), empty_cap.get()) != 0;
    224 }
    225 
    226 scoped_ptr<std::string> Credentials::GetCurrentCapString() const {
    227   ScopedCap current_cap(cap_get_proc());
    228   CHECK(current_cap);
    229   ScopedCapText cap_text(cap_to_text(current_cap.get(), NULL));
    230   CHECK(cap_text);
    231   return scoped_ptr<std::string> (new std::string(cap_text.get()));
    232 }
    233 
    234 bool Credentials::MoveToNewUserNS() {
    235   uid_t uid;
    236   gid_t gid;
    237   if (!GetRESIds(&uid, &gid)) {
    238     // If all the uids (or gids) are not equal to each other, the security
    239     // model will most likely confuse the caller, abort.
    240     DVLOG(1) << "uids or gids differ!";
    241     return false;
    242   }
    243   int ret = unshare(CLONE_NEWUSER);
    244   // EPERM can happen if already in a chroot. EUSERS if too many nested
    245   // namespaces are used. EINVAL for kernels that don't support the feature.
    246   // Valgrind will ENOSYS unshare().
    247   PCHECK(!ret || errno == EPERM || errno == EUSERS || errno == EINVAL ||
    248          errno == ENOSYS);
    249   if (ret) {
    250     VLOG(1) << "Looks like unprivileged CLONE_NEWUSER may not be available "
    251             << "on this kernel.";
    252     return false;
    253   }
    254   // The current {r,e,s}{u,g}id is now an overflow id (c.f.
    255   // /proc/sys/kernel/overflowuid). Setup the uid and gid maps.
    256   DCHECK(GetRESIds(NULL, NULL));
    257   const char kGidMapFile[] = "/proc/self/gid_map";
    258   const char kUidMapFile[] = "/proc/self/uid_map";
    259   CHECK(WriteToIdMapFile(kGidMapFile, gid));
    260   CHECK(WriteToIdMapFile(kUidMapFile, uid));
    261   DCHECK(GetRESIds(NULL, NULL));
    262   return true;
    263 }
    264 
    265 bool Credentials::DropFileSystemAccess() {
    266   // Chrooting to a safe empty dir will only be safe if no directory file
    267   // descriptor is available to the process.
    268   DCHECK(!HasOpenDirectory(-1));
    269   return ChrootToSafeEmptyDir();
    270 }
    271 
    272 }  // namespace sandbox.
    273