Home | History | Annotate | Download | only in services
      1 // Copyright (c) 2012 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/broker_process.h"
      6 
      7 #include <fcntl.h>
      8 #include <sys/socket.h>
      9 #include <sys/stat.h>
     10 #include <sys/syscall.h>
     11 #include <sys/types.h>
     12 #include <unistd.h>
     13 
     14 #include <algorithm>
     15 #include <string>
     16 #include <vector>
     17 
     18 #include "base/basictypes.h"
     19 #include "base/compiler_specific.h"
     20 #include "base/logging.h"
     21 #include "base/pickle.h"
     22 #include "base/posix/eintr_wrapper.h"
     23 #include "base/posix/unix_domain_socket_linux.h"
     24 #include "base/process/process_metrics.h"
     25 #include "build/build_config.h"
     26 #include "sandbox/linux/services/linux_syscalls.h"
     27 
     28 #if defined(OS_ANDROID) && !defined(MSG_CMSG_CLOEXEC)
     29 #define MSG_CMSG_CLOEXEC 0x40000000
     30 #endif
     31 
     32 namespace {
     33 
     34 static const size_t kMaxMessageLength = 4096;
     35 
     36 // Some flags are local to the current process and cannot be sent over a Unix
     37 // socket. They need special treatment from the client.
     38 // O_CLOEXEC is tricky because in theory another thread could call execve()
     39 // before special treatment is made on the client, so a client needs to call
     40 // recvmsg(2) with MSG_CMSG_CLOEXEC.
     41 // To make things worse, there are two CLOEXEC related flags, FD_CLOEXEC (see
     42 // F_GETFD in fcntl(2)) and O_CLOEXEC (see F_GETFL in fcntl(2)). O_CLOEXEC
     43 // doesn't affect the semantics on execve(), it's merely a note that the
     44 // descriptor was originally opened with O_CLOEXEC as a flag. And it is sent
     45 // over unix sockets just fine, so a receiver that would (incorrectly) look at
     46 // O_CLOEXEC instead of FD_CLOEXEC may be tricked in thinking that the file
     47 // descriptor will or won't be closed on execve().
     48 static const int kCurrentProcessOpenFlagsMask = O_CLOEXEC;
     49 
     50 // Check whether |requested_filename| is in |allowed_file_names|.
     51 // See GetFileNameIfAllowedToOpen() for an explanation of |file_to_open|.
     52 // async signal safe if |file_to_open| is NULL.
     53 // TODO(jln): assert signal safety.
     54 bool GetFileNameInWhitelist(const std::vector<std::string>& allowed_file_names,
     55                             const char* requested_filename,
     56                             const char** file_to_open) {
     57   if (file_to_open && *file_to_open) {
     58     // Make sure that callers never pass a non-empty string. In case callers
     59     // wrongly forget to check the return value and look at the string
     60     // instead, this could catch bugs.
     61     RAW_LOG(FATAL, "*file_to_open should be NULL");
     62     return false;
     63   }
     64 
     65   // Look for |requested_filename| in |allowed_file_names|.
     66   // We don't use ::find() because it takes a std::string and
     67   // the conversion allocates memory.
     68   std::vector<std::string>::const_iterator it;
     69   for (it = allowed_file_names.begin(); it != allowed_file_names.end(); it++) {
     70     if (strcmp(requested_filename, it->c_str()) == 0) {
     71       if (file_to_open)
     72         *file_to_open = it->c_str();
     73       return true;
     74     }
     75   }
     76   return false;
     77 }
     78 
     79 // We maintain a list of flags that have been reviewed for "sanity" and that
     80 // we're ok to allow in the broker.
     81 // I.e. here is where we wouldn't add O_RESET_FILE_SYSTEM.
     82 bool IsAllowedOpenFlags(int flags) {
     83   // First, check the access mode.
     84   const int access_mode = flags & O_ACCMODE;
     85   if (access_mode != O_RDONLY && access_mode != O_WRONLY &&
     86       access_mode != O_RDWR) {
     87     return false;
     88   }
     89 
     90   // We only support a 2-parameters open, so we forbid O_CREAT.
     91   if (flags & O_CREAT) {
     92     return false;
     93   }
     94 
     95   // Some flags affect the behavior of the current process. We don't support
     96   // them and don't allow them for now.
     97   if (flags & kCurrentProcessOpenFlagsMask)
     98     return false;
     99 
    100   // Now check that all the flags are known to us.
    101   const int creation_and_status_flags = flags & ~O_ACCMODE;
    102 
    103   const int known_flags =
    104     O_APPEND | O_ASYNC | O_CLOEXEC | O_CREAT | O_DIRECT |
    105     O_DIRECTORY | O_EXCL | O_LARGEFILE | O_NOATIME | O_NOCTTY |
    106     O_NOFOLLOW | O_NONBLOCK | O_NDELAY | O_SYNC | O_TRUNC;
    107 
    108   const int unknown_flags = ~known_flags;
    109   const bool has_unknown_flags = creation_and_status_flags & unknown_flags;
    110   return !has_unknown_flags;
    111 }
    112 
    113 }  // namespace
    114 
    115 namespace sandbox {
    116 
    117 BrokerProcess::BrokerProcess(int denied_errno,
    118                              const std::vector<std::string>& allowed_r_files,
    119                              const std::vector<std::string>& allowed_w_files,
    120                              bool fast_check_in_client,
    121                              bool quiet_failures_for_tests)
    122     : denied_errno_(denied_errno),
    123       initialized_(false),
    124       is_child_(false),
    125       fast_check_in_client_(fast_check_in_client),
    126       quiet_failures_for_tests_(quiet_failures_for_tests),
    127       broker_pid_(-1),
    128       allowed_r_files_(allowed_r_files),
    129       allowed_w_files_(allowed_w_files),
    130       ipc_socketpair_(-1) {
    131 }
    132 
    133 BrokerProcess::~BrokerProcess() {
    134   if (initialized_ && ipc_socketpair_ != -1) {
    135     close(ipc_socketpair_);
    136   }
    137 }
    138 
    139 bool BrokerProcess::Init(bool (*sandbox_callback)(void)) {
    140   CHECK(!initialized_);
    141   int socket_pair[2];
    142   // Use SOCK_SEQPACKET, because we need to preserve message boundaries
    143   // but we also want to be notified (recvmsg should return and not block)
    144   // when the connection has been broken (one of the processes died).
    145   if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, socket_pair)) {
    146     LOG(ERROR) << "Failed to create socketpair";
    147     return false;
    148   }
    149 
    150   DCHECK_EQ(1, base::GetNumberOfThreads(base::GetCurrentProcessHandle()));
    151   int child_pid = fork();
    152   if (child_pid == -1) {
    153     close(socket_pair[0]);
    154     close(socket_pair[1]);
    155     return false;
    156   }
    157   if (child_pid) {
    158     // We are the parent and we have just forked our broker process.
    159     close(socket_pair[0]);
    160     // We should only be able to write to the IPC channel. We'll always send
    161     // a new file descriptor to receive the reply on.
    162     shutdown(socket_pair[1], SHUT_RD);
    163     ipc_socketpair_ = socket_pair[1];
    164     is_child_ = false;
    165     broker_pid_ = child_pid;
    166     initialized_ = true;
    167     return true;
    168   } else {
    169     // We are the broker.
    170     close(socket_pair[1]);
    171     // We should only be able to read from this IPC channel. We will send our
    172     // replies on a new file descriptor attached to the requests.
    173     shutdown(socket_pair[0], SHUT_WR);
    174     ipc_socketpair_ = socket_pair[0];
    175     is_child_ = true;
    176     // Enable the sandbox if provided.
    177     if (sandbox_callback) {
    178       CHECK(sandbox_callback());
    179     }
    180     initialized_ = true;
    181     for (;;) {
    182       HandleRequest();
    183     }
    184     _exit(1);
    185   }
    186   NOTREACHED();
    187 }
    188 
    189 int BrokerProcess::Access(const char* pathname, int mode) const {
    190   return PathAndFlagsSyscall(kCommandAccess, pathname, mode);
    191 }
    192 
    193 int BrokerProcess::Open(const char* pathname, int flags) const {
    194   return PathAndFlagsSyscall(kCommandOpen, pathname, flags);
    195 }
    196 
    197 // Make a remote system call over IPC for syscalls that take a path and flags
    198 // as arguments, currently open() and access().
    199 // Will return -errno like a real system call.
    200 // This function needs to be async signal safe.
    201 int BrokerProcess::PathAndFlagsSyscall(enum IPCCommands syscall_type,
    202                                        const char* pathname, int flags) const {
    203   int recvmsg_flags = 0;
    204   RAW_CHECK(initialized_);  // async signal safe CHECK().
    205   RAW_CHECK(syscall_type == kCommandOpen || syscall_type == kCommandAccess);
    206   if (!pathname)
    207     return -EFAULT;
    208 
    209   // For this "remote system call" to work, we need to handle any flag that
    210   // cannot be sent over a Unix socket in a special way.
    211   // See the comments around kCurrentProcessOpenFlagsMask.
    212   if (syscall_type == kCommandOpen && (flags & kCurrentProcessOpenFlagsMask)) {
    213     // This implementation only knows about O_CLOEXEC, someone needs to look at
    214     // this code if other flags are added.
    215     RAW_CHECK(kCurrentProcessOpenFlagsMask == O_CLOEXEC);
    216     recvmsg_flags |= MSG_CMSG_CLOEXEC;
    217     flags &= ~O_CLOEXEC;
    218   }
    219 
    220   // There is no point in forwarding a request that we know will be denied.
    221   // Of course, the real security check needs to be on the other side of the
    222   // IPC.
    223   if (fast_check_in_client_) {
    224     if (syscall_type == kCommandOpen &&
    225         !GetFileNameIfAllowedToOpen(pathname, flags, NULL)) {
    226       return -denied_errno_;
    227     }
    228     if (syscall_type == kCommandAccess &&
    229         !GetFileNameIfAllowedToAccess(pathname, flags, NULL)) {
    230       return -denied_errno_;
    231     }
    232   }
    233 
    234   Pickle write_pickle;
    235   write_pickle.WriteInt(syscall_type);
    236   write_pickle.WriteString(pathname);
    237   write_pickle.WriteInt(flags);
    238   RAW_CHECK(write_pickle.size() <= kMaxMessageLength);
    239 
    240   int returned_fd = -1;
    241   uint8_t reply_buf[kMaxMessageLength];
    242 
    243   // Send a request (in write_pickle) as well that will include a new
    244   // temporary socketpair (created internally by SendRecvMsg()).
    245   // Then read the reply on this new socketpair in reply_buf and put an
    246   // eventual attached file descriptor in |returned_fd|.
    247   ssize_t msg_len = UnixDomainSocket::SendRecvMsgWithFlags(ipc_socketpair_,
    248                                                            reply_buf,
    249                                                            sizeof(reply_buf),
    250                                                            recvmsg_flags,
    251                                                            &returned_fd,
    252                                                            write_pickle);
    253   if (msg_len <= 0) {
    254     if (!quiet_failures_for_tests_)
    255       RAW_LOG(ERROR, "Could not make request to broker process");
    256     return -ENOMEM;
    257   }
    258 
    259   Pickle read_pickle(reinterpret_cast<char*>(reply_buf), msg_len);
    260   PickleIterator iter(read_pickle);
    261   int return_value = -1;
    262   // Now deserialize the return value and eventually return the file
    263   // descriptor.
    264   if (read_pickle.ReadInt(&iter, &return_value)) {
    265     switch (syscall_type) {
    266       case kCommandAccess:
    267         // We should never have a fd to return.
    268         RAW_CHECK(returned_fd == -1);
    269         return return_value;
    270       case kCommandOpen:
    271         if (return_value < 0) {
    272           RAW_CHECK(returned_fd == -1);
    273           return return_value;
    274         } else {
    275           // We have a real file descriptor to return.
    276           RAW_CHECK(returned_fd >= 0);
    277           return returned_fd;
    278         }
    279       default:
    280         RAW_LOG(ERROR, "Unsupported command");
    281         return -ENOSYS;
    282     }
    283   } else {
    284     RAW_LOG(ERROR, "Could not read pickle");
    285     NOTREACHED();
    286     return -ENOMEM;
    287   }
    288 }
    289 
    290 // Handle a request on the IPC channel ipc_socketpair_.
    291 // A request should have a file descriptor attached on which we will reply and
    292 // that we will then close.
    293 // A request should start with an int that will be used as the command type.
    294 bool BrokerProcess::HandleRequest() const {
    295 
    296   std::vector<int> fds;
    297   char buf[kMaxMessageLength];
    298   errno = 0;
    299   const ssize_t msg_len = UnixDomainSocket::RecvMsg(ipc_socketpair_, buf,
    300                                                     sizeof(buf), &fds);
    301 
    302   if (msg_len == 0 || (msg_len == -1 && errno == ECONNRESET)) {
    303     // EOF from our parent, or our parent died, we should die.
    304     _exit(0);
    305   }
    306 
    307   // The parent should send exactly one file descriptor, on which we
    308   // will write the reply.
    309   if (msg_len < 0 || fds.size() != 1 || fds.at(0) < 0) {
    310     PLOG(ERROR) << "Error reading message from the client";
    311     return false;
    312   }
    313 
    314   const int temporary_ipc = fds.at(0);
    315 
    316   Pickle pickle(buf, msg_len);
    317   PickleIterator iter(pickle);
    318   int command_type;
    319   if (pickle.ReadInt(&iter, &command_type)) {
    320     bool r = false;
    321     // Go through all the possible IPC messages.
    322     switch (command_type) {
    323       case kCommandAccess:
    324       case kCommandOpen:
    325         // We reply on the file descriptor sent to us via the IPC channel.
    326         r = HandleRemoteCommand(static_cast<IPCCommands>(command_type),
    327                                 temporary_ipc, pickle, iter);
    328         break;
    329       default:
    330         NOTREACHED();
    331         r = false;
    332         break;
    333     }
    334     int ret = IGNORE_EINTR(close(temporary_ipc));
    335     DCHECK(!ret) << "Could not close temporary IPC channel";
    336     return r;
    337   }
    338 
    339   LOG(ERROR) << "Error parsing IPC request";
    340   return false;
    341 }
    342 
    343 // Handle a |command_type| request contained in |read_pickle| and send the reply
    344 // on |reply_ipc|.
    345 // Currently kCommandOpen and kCommandAccess are supported.
    346 bool BrokerProcess::HandleRemoteCommand(IPCCommands command_type, int reply_ipc,
    347                                         const Pickle& read_pickle,
    348                                         PickleIterator iter) const {
    349   // Currently all commands have two arguments: filename and flags.
    350   std::string requested_filename;
    351   int flags = 0;
    352   if (!read_pickle.ReadString(&iter, &requested_filename) ||
    353       !read_pickle.ReadInt(&iter, &flags)) {
    354     return -1;
    355   }
    356 
    357   Pickle write_pickle;
    358   std::vector<int> opened_files;
    359 
    360   switch (command_type) {
    361     case kCommandAccess:
    362       AccessFileForIPC(requested_filename, flags, &write_pickle);
    363       break;
    364     case kCommandOpen:
    365       OpenFileForIPC(requested_filename, flags, &write_pickle, &opened_files);
    366       break;
    367     default:
    368       LOG(ERROR) << "Invalid IPC command";
    369       break;
    370   }
    371 
    372   CHECK_LE(write_pickle.size(), kMaxMessageLength);
    373   ssize_t sent = UnixDomainSocket::SendMsg(reply_ipc, write_pickle.data(),
    374                                            write_pickle.size(), opened_files);
    375 
    376   // Close anything we have opened in this process.
    377   for (std::vector<int>::iterator it = opened_files.begin();
    378        it < opened_files.end(); ++it) {
    379     int ret = IGNORE_EINTR(close(*it));
    380     DCHECK(!ret) << "Could not close file descriptor";
    381   }
    382 
    383   if (sent <= 0) {
    384     LOG(ERROR) << "Could not send IPC reply";
    385     return false;
    386   }
    387   return true;
    388 }
    389 
    390 // Perform access(2) on |requested_filename| with mode |mode| if allowed by our
    391 // policy. Write the syscall return value (-errno) to |write_pickle|.
    392 void BrokerProcess::AccessFileForIPC(const std::string& requested_filename,
    393                                      int mode, Pickle* write_pickle) const {
    394   DCHECK(write_pickle);
    395   const char* file_to_access = NULL;
    396   const bool safe_to_access_file = GetFileNameIfAllowedToAccess(
    397       requested_filename.c_str(), mode, &file_to_access);
    398 
    399   if (safe_to_access_file) {
    400     CHECK(file_to_access);
    401     int access_ret = access(file_to_access, mode);
    402     int access_errno = errno;
    403     if (!access_ret)
    404       write_pickle->WriteInt(0);
    405     else
    406       write_pickle->WriteInt(-access_errno);
    407   } else {
    408     write_pickle->WriteInt(-denied_errno_);
    409   }
    410 }
    411 
    412 // Open |requested_filename| with |flags| if allowed by our policy.
    413 // Write the syscall return value (-errno) to |write_pickle| and append
    414 // a file descriptor to |opened_files| if relevant.
    415 void BrokerProcess::OpenFileForIPC(const std::string& requested_filename,
    416                                    int flags, Pickle* write_pickle,
    417                                    std::vector<int>* opened_files) const {
    418   DCHECK(write_pickle);
    419   DCHECK(opened_files);
    420   const char* file_to_open = NULL;
    421   const bool safe_to_open_file = GetFileNameIfAllowedToOpen(
    422       requested_filename.c_str(), flags, &file_to_open);
    423 
    424   if (safe_to_open_file) {
    425     CHECK(file_to_open);
    426     // We're doing a 2-parameter open, so we don't support O_CREAT. It doesn't
    427     // hurt to always pass a third argument though.
    428     int opened_fd = syscall(__NR_open, file_to_open, flags, 0);
    429     if (opened_fd < 0) {
    430       write_pickle->WriteInt(-errno);
    431     } else {
    432       // Success.
    433       opened_files->push_back(opened_fd);
    434       write_pickle->WriteInt(0);
    435     }
    436   } else {
    437     write_pickle->WriteInt(-denied_errno_);
    438   }
    439 }
    440 
    441 
    442 // Check if calling access() should be allowed on |requested_filename| with
    443 // mode |requested_mode|.
    444 // Note: access() being a system call to check permissions, this can get a bit
    445 // confusing. We're checking if calling access() should even be allowed with
    446 // the same policy we would use for open().
    447 // If |file_to_access| is not NULL, we will return the matching pointer from
    448 // the whitelist. For paranoia a caller should then use |file_to_access|. See
    449 // GetFileNameIfAllowedToOpen() fore more explanation.
    450 // return true if calling access() on this file should be allowed, false
    451 // otherwise.
    452 // Async signal safe if and only if |file_to_access| is NULL.
    453 bool BrokerProcess::GetFileNameIfAllowedToAccess(const char* requested_filename,
    454     int requested_mode, const char** file_to_access) const {
    455   // First, check if |requested_mode| is existence, ability to read or ability
    456   // to write. We do not support X_OK.
    457   if (requested_mode != F_OK &&
    458       requested_mode & ~(R_OK | W_OK)) {
    459     return false;
    460   }
    461   switch (requested_mode) {
    462     case F_OK:
    463       // We allow to check for file existence if we can either read or write.
    464       return GetFileNameInWhitelist(allowed_r_files_, requested_filename,
    465                                     file_to_access) ||
    466              GetFileNameInWhitelist(allowed_w_files_, requested_filename,
    467                                     file_to_access);
    468     case R_OK:
    469       return GetFileNameInWhitelist(allowed_r_files_, requested_filename,
    470                                     file_to_access);
    471     case W_OK:
    472       return GetFileNameInWhitelist(allowed_w_files_, requested_filename,
    473                                     file_to_access);
    474     case R_OK | W_OK:
    475     {
    476       bool allowed_for_read_and_write =
    477           GetFileNameInWhitelist(allowed_r_files_, requested_filename, NULL) &&
    478           GetFileNameInWhitelist(allowed_w_files_, requested_filename,
    479                                  file_to_access);
    480       return allowed_for_read_and_write;
    481     }
    482     default:
    483       return false;
    484   }
    485 }
    486 
    487 // Check if |requested_filename| can be opened with flags |requested_flags|.
    488 // If |file_to_open| is not NULL, we will return the matching pointer from the
    489 // whitelist. For paranoia, a caller should then use |file_to_open| rather
    490 // than |requested_filename|, so that it never attempts to open an
    491 // attacker-controlled file name, even if an attacker managed to fool the
    492 // string comparison mechanism.
    493 // Return true if opening should be allowed, false otherwise.
    494 // Async signal safe if and only if |file_to_open| is NULL.
    495 bool BrokerProcess::GetFileNameIfAllowedToOpen(const char* requested_filename,
    496     int requested_flags, const char** file_to_open) const {
    497   if (!IsAllowedOpenFlags(requested_flags)) {
    498     return false;
    499   }
    500   switch (requested_flags & O_ACCMODE) {
    501     case O_RDONLY:
    502       return GetFileNameInWhitelist(allowed_r_files_, requested_filename,
    503                                     file_to_open);
    504     case O_WRONLY:
    505       return GetFileNameInWhitelist(allowed_w_files_, requested_filename,
    506                                     file_to_open);
    507     case O_RDWR:
    508     {
    509       bool allowed_for_read_and_write =
    510           GetFileNameInWhitelist(allowed_r_files_, requested_filename, NULL) &&
    511           GetFileNameInWhitelist(allowed_w_files_, requested_filename,
    512                                  file_to_open);
    513       return allowed_for_read_and_write;
    514     }
    515     default:
    516       return false;
    517   }
    518 }
    519 
    520 }  // namespace sandbox.
    521