Home | History | Annotate | Download | only in seccomp-bpf
      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/seccomp-bpf/sandbox_bpf.h"
      6 
      7 // Some headers on Android are missing cdefs: crbug.com/172337.
      8 // (We can't use OS_ANDROID here since build_config.h is not included).
      9 #if defined(ANDROID)
     10 #include <sys/cdefs.h>
     11 #endif
     12 
     13 #include <errno.h>
     14 #include <fcntl.h>
     15 #include <string.h>
     16 #include <sys/prctl.h>
     17 #include <sys/stat.h>
     18 #include <sys/syscall.h>
     19 #include <sys/types.h>
     20 #include <time.h>
     21 #include <unistd.h>
     22 
     23 #include "base/compiler_specific.h"
     24 #include "base/logging.h"
     25 #include "base/macros.h"
     26 #include "base/memory/scoped_ptr.h"
     27 #include "base/posix/eintr_wrapper.h"
     28 #include "sandbox/linux/seccomp-bpf/codegen.h"
     29 #include "sandbox/linux/seccomp-bpf/sandbox_bpf_policy.h"
     30 #include "sandbox/linux/seccomp-bpf/syscall.h"
     31 #include "sandbox/linux/seccomp-bpf/syscall_iterator.h"
     32 #include "sandbox/linux/seccomp-bpf/verifier.h"
     33 
     34 namespace sandbox {
     35 
     36 namespace {
     37 
     38 const int kExpectedExitCode = 100;
     39 
     40 int popcount(uint32_t x) {
     41   return __builtin_popcount(x);
     42 }
     43 
     44 #if !defined(NDEBUG)
     45 void WriteFailedStderrSetupMessage(int out_fd) {
     46   const char* error_string = strerror(errno);
     47   static const char msg[] =
     48       "You have reproduced a puzzling issue.\n"
     49       "Please, report to crbug.com/152530!\n"
     50       "Failed to set up stderr: ";
     51   if (HANDLE_EINTR(write(out_fd, msg, sizeof(msg) - 1)) > 0 && error_string &&
     52       HANDLE_EINTR(write(out_fd, error_string, strlen(error_string))) > 0 &&
     53       HANDLE_EINTR(write(out_fd, "\n", 1))) {
     54   }
     55 }
     56 #endif  // !defined(NDEBUG)
     57 
     58 // We define a really simple sandbox policy. It is just good enough for us
     59 // to tell that the sandbox has actually been activated.
     60 class ProbePolicy : public SandboxBPFPolicy {
     61  public:
     62   ProbePolicy() {}
     63   virtual ErrorCode EvaluateSyscall(SandboxBPF*, int sysnum) const OVERRIDE {
     64     switch (sysnum) {
     65       case __NR_getpid:
     66         // Return EPERM so that we can check that the filter actually ran.
     67         return ErrorCode(EPERM);
     68       case __NR_exit_group:
     69         // Allow exit() with a non-default return code.
     70         return ErrorCode(ErrorCode::ERR_ALLOWED);
     71       default:
     72         // Make everything else fail in an easily recognizable way.
     73         return ErrorCode(EINVAL);
     74     }
     75   }
     76 
     77  private:
     78   DISALLOW_COPY_AND_ASSIGN(ProbePolicy);
     79 };
     80 
     81 void ProbeProcess(void) {
     82   if (syscall(__NR_getpid) < 0 && errno == EPERM) {
     83     syscall(__NR_exit_group, static_cast<intptr_t>(kExpectedExitCode));
     84   }
     85 }
     86 
     87 class AllowAllPolicy : public SandboxBPFPolicy {
     88  public:
     89   AllowAllPolicy() {}
     90   virtual ErrorCode EvaluateSyscall(SandboxBPF*, int sysnum) const OVERRIDE {
     91     DCHECK(SandboxBPF::IsValidSyscallNumber(sysnum));
     92     return ErrorCode(ErrorCode::ERR_ALLOWED);
     93   }
     94 
     95  private:
     96   DISALLOW_COPY_AND_ASSIGN(AllowAllPolicy);
     97 };
     98 
     99 void TryVsyscallProcess(void) {
    100   time_t current_time;
    101   // time() is implemented as a vsyscall. With an older glibc, with
    102   // vsyscall=emulate and some versions of the seccomp BPF patch
    103   // we may get SIGKILL-ed. Detect this!
    104   if (time(&current_time) != static_cast<time_t>(-1)) {
    105     syscall(__NR_exit_group, static_cast<intptr_t>(kExpectedExitCode));
    106   }
    107 }
    108 
    109 bool IsSingleThreaded(int proc_fd) {
    110   if (proc_fd < 0) {
    111     // Cannot determine whether program is single-threaded. Hope for
    112     // the best...
    113     return true;
    114   }
    115 
    116   struct stat sb;
    117   int task = -1;
    118   if ((task = openat(proc_fd, "self/task", O_RDONLY | O_DIRECTORY)) < 0 ||
    119       fstat(task, &sb) != 0 || sb.st_nlink != 3 || IGNORE_EINTR(close(task))) {
    120     if (task >= 0) {
    121       if (IGNORE_EINTR(close(task))) {
    122       }
    123     }
    124     return false;
    125   }
    126   return true;
    127 }
    128 
    129 bool IsDenied(const ErrorCode& code) {
    130   return (code.err() & SECCOMP_RET_ACTION) == SECCOMP_RET_TRAP ||
    131          (code.err() >= (SECCOMP_RET_ERRNO + ErrorCode::ERR_MIN_ERRNO) &&
    132           code.err() <= (SECCOMP_RET_ERRNO + ErrorCode::ERR_MAX_ERRNO));
    133 }
    134 
    135 // Function that can be passed as a callback function to CodeGen::Traverse().
    136 // Checks whether the "insn" returns an UnsafeTrap() ErrorCode. If so, it
    137 // sets the "bool" variable pointed to by "aux".
    138 void CheckForUnsafeErrorCodes(Instruction* insn, void* aux) {
    139   bool* is_unsafe = static_cast<bool*>(aux);
    140   if (!*is_unsafe) {
    141     if (BPF_CLASS(insn->code) == BPF_RET && insn->k > SECCOMP_RET_TRAP &&
    142         insn->k - SECCOMP_RET_TRAP <= SECCOMP_RET_DATA) {
    143       const ErrorCode& err =
    144           Trap::ErrorCodeFromTrapId(insn->k & SECCOMP_RET_DATA);
    145       if (err.error_type() != ErrorCode::ET_INVALID && !err.safe()) {
    146         *is_unsafe = true;
    147       }
    148     }
    149   }
    150 }
    151 
    152 // A Trap() handler that returns an "errno" value. The value is encoded
    153 // in the "aux" parameter.
    154 intptr_t ReturnErrno(const struct arch_seccomp_data&, void* aux) {
    155   // TrapFnc functions report error by following the native kernel convention
    156   // of returning an exit code in the range of -1..-4096. They do not try to
    157   // set errno themselves. The glibc wrapper that triggered the SIGSYS will
    158   // ultimately do so for us.
    159   int err = reinterpret_cast<intptr_t>(aux) & SECCOMP_RET_DATA;
    160   return -err;
    161 }
    162 
    163 // Function that can be passed as a callback function to CodeGen::Traverse().
    164 // Checks whether the "insn" returns an errno value from a BPF filter. If so,
    165 // it rewrites the instruction to instead call a Trap() handler that does
    166 // the same thing. "aux" is ignored.
    167 void RedirectToUserspace(Instruction* insn, void* aux) {
    168   // When inside an UnsafeTrap() callback, we want to allow all system calls.
    169   // This means, we must conditionally disable the sandbox -- and that's not
    170   // something that kernel-side BPF filters can do, as they cannot inspect
    171   // any state other than the syscall arguments.
    172   // But if we redirect all error handlers to user-space, then we can easily
    173   // make this decision.
    174   // The performance penalty for this extra round-trip to user-space is not
    175   // actually that bad, as we only ever pay it for denied system calls; and a
    176   // typical program has very few of these.
    177   SandboxBPF* sandbox = static_cast<SandboxBPF*>(aux);
    178   if (BPF_CLASS(insn->code) == BPF_RET &&
    179       (insn->k & SECCOMP_RET_ACTION) == SECCOMP_RET_ERRNO) {
    180     insn->k = sandbox->Trap(ReturnErrno,
    181         reinterpret_cast<void*>(insn->k & SECCOMP_RET_DATA)).err();
    182   }
    183 }
    184 
    185 // This wraps an existing policy and changes its behavior to match the changes
    186 // made by RedirectToUserspace(). This is part of the framework that allows BPF
    187 // evaluation in userland.
    188 // TODO(markus): document the code inside better.
    189 class RedirectToUserSpacePolicyWrapper : public SandboxBPFPolicy {
    190  public:
    191   explicit RedirectToUserSpacePolicyWrapper(
    192       const SandboxBPFPolicy* wrapped_policy)
    193       : wrapped_policy_(wrapped_policy) {
    194     DCHECK(wrapped_policy_);
    195   }
    196 
    197   virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox_compiler,
    198                                     int system_call_number) const OVERRIDE {
    199     ErrorCode err =
    200         wrapped_policy_->EvaluateSyscall(sandbox_compiler, system_call_number);
    201     if ((err.err() & SECCOMP_RET_ACTION) == SECCOMP_RET_ERRNO) {
    202       return ReturnErrnoViaTrap(sandbox_compiler, err.err() & SECCOMP_RET_DATA);
    203     }
    204     return err;
    205   }
    206 
    207   virtual ErrorCode InvalidSyscall(
    208       SandboxBPF* sandbox_compiler) const OVERRIDE {
    209     return ReturnErrnoViaTrap(sandbox_compiler, ENOSYS);
    210   }
    211 
    212  private:
    213   ErrorCode ReturnErrnoViaTrap(SandboxBPF* sandbox_compiler, int err) const {
    214     return sandbox_compiler->Trap(ReturnErrno, reinterpret_cast<void*>(err));
    215   }
    216 
    217   const SandboxBPFPolicy* wrapped_policy_;
    218   DISALLOW_COPY_AND_ASSIGN(RedirectToUserSpacePolicyWrapper);
    219 };
    220 
    221 intptr_t BPFFailure(const struct arch_seccomp_data&, void* aux) {
    222   SANDBOX_DIE(static_cast<char*>(aux));
    223 }
    224 
    225 }  // namespace
    226 
    227 SandboxBPF::SandboxBPF()
    228     : quiet_(false),
    229       proc_fd_(-1),
    230       conds_(new Conds),
    231       sandbox_has_started_(false) {}
    232 
    233 SandboxBPF::~SandboxBPF() {
    234   // It is generally unsafe to call any memory allocator operations or to even
    235   // call arbitrary destructors after having installed a new policy. We just
    236   // have no way to tell whether this policy would allow the system calls that
    237   // the constructors can trigger.
    238   // So, we normally destroy all of our complex state prior to starting the
    239   // sandbox. But this won't happen, if the Sandbox object was created and
    240   // never actually used to set up a sandbox. So, just in case, we are
    241   // destroying any remaining state.
    242   // The "if ()" statements are technically superfluous. But let's be explicit
    243   // that we really don't want to run any code, when we already destroyed
    244   // objects before setting up the sandbox.
    245   if (conds_) {
    246     delete conds_;
    247   }
    248 }
    249 
    250 bool SandboxBPF::IsValidSyscallNumber(int sysnum) {
    251   return SyscallIterator::IsValid(sysnum);
    252 }
    253 
    254 bool SandboxBPF::RunFunctionInPolicy(void (*code_in_sandbox)(),
    255                                      scoped_ptr<SandboxBPFPolicy> policy) {
    256   // Block all signals before forking a child process. This prevents an
    257   // attacker from manipulating our test by sending us an unexpected signal.
    258   sigset_t old_mask, new_mask;
    259   if (sigfillset(&new_mask) || sigprocmask(SIG_BLOCK, &new_mask, &old_mask)) {
    260     SANDBOX_DIE("sigprocmask() failed");
    261   }
    262   int fds[2];
    263   if (pipe2(fds, O_NONBLOCK | O_CLOEXEC)) {
    264     SANDBOX_DIE("pipe() failed");
    265   }
    266 
    267   if (fds[0] <= 2 || fds[1] <= 2) {
    268     SANDBOX_DIE("Process started without standard file descriptors");
    269   }
    270 
    271   // This code is using fork() and should only ever run single-threaded.
    272   // Most of the code below is "async-signal-safe" and only minor changes
    273   // would be needed to support threads.
    274   DCHECK(IsSingleThreaded(proc_fd_));
    275   pid_t pid = fork();
    276   if (pid < 0) {
    277     // Die if we cannot fork(). We would probably fail a little later
    278     // anyway, as the machine is likely very close to running out of
    279     // memory.
    280     // But what we don't want to do is return "false", as a crafty
    281     // attacker might cause fork() to fail at will and could trick us
    282     // into running without a sandbox.
    283     sigprocmask(SIG_SETMASK, &old_mask, NULL);  // OK, if it fails
    284     SANDBOX_DIE("fork() failed unexpectedly");
    285   }
    286 
    287   // In the child process
    288   if (!pid) {
    289     // Test a very simple sandbox policy to verify that we can
    290     // successfully turn on sandboxing.
    291     Die::EnableSimpleExit();
    292 
    293     errno = 0;
    294     if (IGNORE_EINTR(close(fds[0]))) {
    295       // This call to close() has been failing in strange ways. See
    296       // crbug.com/152530. So we only fail in debug mode now.
    297 #if !defined(NDEBUG)
    298       WriteFailedStderrSetupMessage(fds[1]);
    299       SANDBOX_DIE(NULL);
    300 #endif
    301     }
    302     if (HANDLE_EINTR(dup2(fds[1], 2)) != 2) {
    303       // Stderr could very well be a file descriptor to .xsession-errors, or
    304       // another file, which could be backed by a file system that could cause
    305       // dup2 to fail while trying to close stderr. It's important that we do
    306       // not fail on trying to close stderr.
    307       // If dup2 fails here, we will continue normally, this means that our
    308       // parent won't cause a fatal failure if something writes to stderr in
    309       // this child.
    310 #if !defined(NDEBUG)
    311       // In DEBUG builds, we still want to get a report.
    312       WriteFailedStderrSetupMessage(fds[1]);
    313       SANDBOX_DIE(NULL);
    314 #endif
    315     }
    316     if (IGNORE_EINTR(close(fds[1]))) {
    317       // This call to close() has been failing in strange ways. See
    318       // crbug.com/152530. So we only fail in debug mode now.
    319 #if !defined(NDEBUG)
    320       WriteFailedStderrSetupMessage(fds[1]);
    321       SANDBOX_DIE(NULL);
    322 #endif
    323     }
    324 
    325     SetSandboxPolicy(policy.release());
    326     if (!StartSandbox(PROCESS_SINGLE_THREADED)) {
    327       SANDBOX_DIE(NULL);
    328     }
    329 
    330     // Run our code in the sandbox.
    331     code_in_sandbox();
    332 
    333     // code_in_sandbox() is not supposed to return here.
    334     SANDBOX_DIE(NULL);
    335   }
    336 
    337   // In the parent process.
    338   if (IGNORE_EINTR(close(fds[1]))) {
    339     SANDBOX_DIE("close() failed");
    340   }
    341   if (sigprocmask(SIG_SETMASK, &old_mask, NULL)) {
    342     SANDBOX_DIE("sigprocmask() failed");
    343   }
    344   int status;
    345   if (HANDLE_EINTR(waitpid(pid, &status, 0)) != pid) {
    346     SANDBOX_DIE("waitpid() failed unexpectedly");
    347   }
    348   bool rc = WIFEXITED(status) && WEXITSTATUS(status) == kExpectedExitCode;
    349 
    350   // If we fail to support sandboxing, there might be an additional
    351   // error message. If so, this was an entirely unexpected and fatal
    352   // failure. We should report the failure and somebody must fix
    353   // things. This is probably a security-critical bug in the sandboxing
    354   // code.
    355   if (!rc) {
    356     char buf[4096];
    357     ssize_t len = HANDLE_EINTR(read(fds[0], buf, sizeof(buf) - 1));
    358     if (len > 0) {
    359       while (len > 1 && buf[len - 1] == '\n') {
    360         --len;
    361       }
    362       buf[len] = '\000';
    363       SANDBOX_DIE(buf);
    364     }
    365   }
    366   if (IGNORE_EINTR(close(fds[0]))) {
    367     SANDBOX_DIE("close() failed");
    368   }
    369 
    370   return rc;
    371 }
    372 
    373 bool SandboxBPF::KernelSupportSeccompBPF() {
    374   return RunFunctionInPolicy(ProbeProcess,
    375                              scoped_ptr<SandboxBPFPolicy>(new ProbePolicy())) &&
    376          RunFunctionInPolicy(
    377              TryVsyscallProcess,
    378              scoped_ptr<SandboxBPFPolicy>(new AllowAllPolicy()));
    379 }
    380 
    381 SandboxBPF::SandboxStatus SandboxBPF::SupportsSeccompSandbox(int proc_fd) {
    382   // It the sandbox is currently active, we clearly must have support for
    383   // sandboxing.
    384   if (status_ == STATUS_ENABLED) {
    385     return status_;
    386   }
    387 
    388   // Even if the sandbox was previously available, something might have
    389   // changed in our run-time environment. Check one more time.
    390   if (status_ == STATUS_AVAILABLE) {
    391     if (!IsSingleThreaded(proc_fd)) {
    392       status_ = STATUS_UNAVAILABLE;
    393     }
    394     return status_;
    395   }
    396 
    397   if (status_ == STATUS_UNAVAILABLE && IsSingleThreaded(proc_fd)) {
    398     // All state transitions resulting in STATUS_UNAVAILABLE are immediately
    399     // preceded by STATUS_AVAILABLE. Furthermore, these transitions all
    400     // happen, if and only if they are triggered by the process being multi-
    401     // threaded.
    402     // In other words, if a single-threaded process is currently in the
    403     // STATUS_UNAVAILABLE state, it is safe to assume that sandboxing is
    404     // actually available.
    405     status_ = STATUS_AVAILABLE;
    406     return status_;
    407   }
    408 
    409   // If we have not previously checked for availability of the sandbox or if
    410   // we otherwise don't believe to have a good cached value, we have to
    411   // perform a thorough check now.
    412   if (status_ == STATUS_UNKNOWN) {
    413     // We create our own private copy of a "Sandbox" object. This ensures that
    414     // the object does not have any policies configured, that might interfere
    415     // with the tests done by "KernelSupportSeccompBPF()".
    416     SandboxBPF sandbox;
    417 
    418     // By setting "quiet_ = true" we suppress messages for expected and benign
    419     // failures (e.g. if the current kernel lacks support for BPF filters).
    420     sandbox.quiet_ = true;
    421     sandbox.set_proc_fd(proc_fd);
    422     status_ = sandbox.KernelSupportSeccompBPF() ? STATUS_AVAILABLE
    423                                                 : STATUS_UNSUPPORTED;
    424 
    425     // As we are performing our tests from a child process, the run-time
    426     // environment that is visible to the sandbox is always guaranteed to be
    427     // single-threaded. Let's check here whether the caller is single-
    428     // threaded. Otherwise, we mark the sandbox as temporarily unavailable.
    429     if (status_ == STATUS_AVAILABLE && !IsSingleThreaded(proc_fd)) {
    430       status_ = STATUS_UNAVAILABLE;
    431     }
    432   }
    433   return status_;
    434 }
    435 
    436 void SandboxBPF::set_proc_fd(int proc_fd) { proc_fd_ = proc_fd; }
    437 
    438 bool SandboxBPF::StartSandbox(SandboxThreadState thread_state) {
    439   CHECK(thread_state == PROCESS_SINGLE_THREADED ||
    440         thread_state == PROCESS_MULTI_THREADED);
    441 
    442   if (status_ == STATUS_UNSUPPORTED || status_ == STATUS_UNAVAILABLE) {
    443     SANDBOX_DIE(
    444         "Trying to start sandbox, even though it is known to be "
    445         "unavailable");
    446     return false;
    447   } else if (sandbox_has_started_ || !conds_) {
    448     SANDBOX_DIE(
    449         "Cannot repeatedly start sandbox. Create a separate Sandbox "
    450         "object instead.");
    451     return false;
    452   }
    453   if (proc_fd_ < 0) {
    454     proc_fd_ = open("/proc", O_RDONLY | O_DIRECTORY);
    455   }
    456   if (proc_fd_ < 0) {
    457     // For now, continue in degraded mode, if we can't access /proc.
    458     // In the future, we might want to tighten this requirement.
    459   }
    460 
    461   if (thread_state == PROCESS_SINGLE_THREADED && !IsSingleThreaded(proc_fd_)) {
    462     SANDBOX_DIE("Cannot start sandbox, if process is already multi-threaded");
    463     return false;
    464   }
    465 
    466   // We no longer need access to any files in /proc. We want to do this
    467   // before installing the filters, just in case that our policy denies
    468   // close().
    469   if (proc_fd_ >= 0) {
    470     if (IGNORE_EINTR(close(proc_fd_))) {
    471       SANDBOX_DIE("Failed to close file descriptor for /proc");
    472       return false;
    473     }
    474     proc_fd_ = -1;
    475   }
    476 
    477   // Install the filters.
    478   InstallFilter(thread_state);
    479 
    480   // We are now inside the sandbox.
    481   status_ = STATUS_ENABLED;
    482 
    483   return true;
    484 }
    485 
    486 void SandboxBPF::PolicySanityChecks(SandboxBPFPolicy* policy) {
    487   if (!IsDenied(policy->InvalidSyscall(this))) {
    488     SANDBOX_DIE("Policies should deny invalid system calls.");
    489   }
    490   return;
    491 }
    492 
    493 // Don't take a scoped_ptr here, polymorphism make their use awkward.
    494 void SandboxBPF::SetSandboxPolicy(SandboxBPFPolicy* policy) {
    495   DCHECK(!policy_);
    496   if (sandbox_has_started_ || !conds_) {
    497     SANDBOX_DIE("Cannot change policy after sandbox has started");
    498   }
    499   PolicySanityChecks(policy);
    500   policy_.reset(policy);
    501 }
    502 
    503 void SandboxBPF::InstallFilter(SandboxThreadState thread_state) {
    504   // We want to be very careful in not imposing any requirements on the
    505   // policies that are set with SetSandboxPolicy(). This means, as soon as
    506   // the sandbox is active, we shouldn't be relying on libraries that could
    507   // be making system calls. This, for example, means we should avoid
    508   // using the heap and we should avoid using STL functions.
    509   // Temporarily copy the contents of the "program" vector into a
    510   // stack-allocated array; and then explicitly destroy that object.
    511   // This makes sure we don't ex- or implicitly call new/delete after we
    512   // installed the BPF filter program in the kernel. Depending on the
    513   // system memory allocator that is in effect, these operators can result
    514   // in system calls to things like munmap() or brk().
    515   Program* program = AssembleFilter(false /* force_verification */);
    516 
    517   struct sock_filter bpf[program->size()];
    518   const struct sock_fprog prog = {static_cast<unsigned short>(program->size()),
    519                                   bpf};
    520   memcpy(bpf, &(*program)[0], sizeof(bpf));
    521   delete program;
    522 
    523   // Make an attempt to release memory that is no longer needed here, rather
    524   // than in the destructor. Try to avoid as much as possible to presume of
    525   // what will be possible to do in the new (sandboxed) execution environment.
    526   delete conds_;
    527   conds_ = NULL;
    528   policy_.reset();
    529 
    530   // Install BPF filter program
    531   if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
    532     SANDBOX_DIE(quiet_ ? NULL : "Kernel refuses to enable no-new-privs");
    533   } else {
    534     if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)) {
    535       SANDBOX_DIE(quiet_ ? NULL : "Kernel refuses to turn on BPF filters");
    536     }
    537   }
    538 
    539   // TODO(rsesek): Always try to engage the sandbox with the
    540   // PROCESS_MULTI_THREADED path first, and if that fails, assert that the
    541   // process IsSingleThreaded() or SANDBOX_DIE.
    542 
    543   if (thread_state == PROCESS_MULTI_THREADED) {
    544     // TODO(rsesek): Move these to a more reasonable place once the kernel
    545     // patch has landed upstream and these values are formalized.
    546     #define PR_SECCOMP_EXT 41
    547     #define SECCOMP_EXT_ACT 1
    548     #define SECCOMP_EXT_ACT_TSYNC 1
    549     if (prctl(PR_SECCOMP_EXT, SECCOMP_EXT_ACT, SECCOMP_EXT_ACT_TSYNC, 0, 0)) {
    550       SANDBOX_DIE(quiet_ ? NULL : "Kernel refuses to synchronize threadgroup "
    551                                   "BPF filters.");
    552     }
    553   }
    554 
    555   sandbox_has_started_ = true;
    556 }
    557 
    558 SandboxBPF::Program* SandboxBPF::AssembleFilter(bool force_verification) {
    559 #if !defined(NDEBUG)
    560   force_verification = true;
    561 #endif
    562 
    563   // Verify that the user pushed a policy.
    564   DCHECK(policy_);
    565 
    566   // Assemble the BPF filter program.
    567   CodeGen* gen = new CodeGen();
    568   if (!gen) {
    569     SANDBOX_DIE("Out of memory");
    570   }
    571 
    572   // If the architecture doesn't match SECCOMP_ARCH, disallow the
    573   // system call.
    574   Instruction* tail;
    575   Instruction* head = gen->MakeInstruction(
    576       BPF_LD + BPF_W + BPF_ABS,
    577       SECCOMP_ARCH_IDX,
    578       tail = gen->MakeInstruction(
    579           BPF_JMP + BPF_JEQ + BPF_K,
    580           SECCOMP_ARCH,
    581           NULL,
    582           gen->MakeInstruction(
    583               BPF_RET + BPF_K,
    584               Kill("Invalid audit architecture in BPF filter"))));
    585 
    586   bool has_unsafe_traps = false;
    587   {
    588     // Evaluate all possible system calls and group their ErrorCodes into
    589     // ranges of identical codes.
    590     Ranges ranges;
    591     FindRanges(&ranges);
    592 
    593     // Compile the system call ranges to an optimized BPF jumptable
    594     Instruction* jumptable =
    595         AssembleJumpTable(gen, ranges.begin(), ranges.end());
    596 
    597     // If there is at least one UnsafeTrap() in our program, the entire sandbox
    598     // is unsafe. We need to modify the program so that all non-
    599     // SECCOMP_RET_ALLOW ErrorCodes are handled in user-space. This will then
    600     // allow us to temporarily disable sandboxing rules inside of callbacks to
    601     // UnsafeTrap().
    602     gen->Traverse(jumptable, CheckForUnsafeErrorCodes, &has_unsafe_traps);
    603 
    604     // Grab the system call number, so that we can implement jump tables.
    605     Instruction* load_nr =
    606         gen->MakeInstruction(BPF_LD + BPF_W + BPF_ABS, SECCOMP_NR_IDX);
    607 
    608     // If our BPF program has unsafe jumps, enable support for them. This
    609     // test happens very early in the BPF filter program. Even before we
    610     // consider looking at system call numbers.
    611     // As support for unsafe jumps essentially defeats all the security
    612     // measures that the sandbox provides, we print a big warning message --
    613     // and of course, we make sure to only ever enable this feature if it
    614     // is actually requested by the sandbox policy.
    615     if (has_unsafe_traps) {
    616       if (Syscall::Call(-1) == -1 && errno == ENOSYS) {
    617         SANDBOX_DIE(
    618             "Support for UnsafeTrap() has not yet been ported to this "
    619             "architecture");
    620       }
    621 
    622       if (!policy_->EvaluateSyscall(this, __NR_rt_sigprocmask)
    623                .Equals(ErrorCode(ErrorCode::ERR_ALLOWED)) ||
    624           !policy_->EvaluateSyscall(this, __NR_rt_sigreturn)
    625                .Equals(ErrorCode(ErrorCode::ERR_ALLOWED))
    626 #if defined(__NR_sigprocmask)
    627           ||
    628           !policy_->EvaluateSyscall(this, __NR_sigprocmask)
    629                .Equals(ErrorCode(ErrorCode::ERR_ALLOWED))
    630 #endif
    631 #if defined(__NR_sigreturn)
    632           ||
    633           !policy_->EvaluateSyscall(this, __NR_sigreturn)
    634                .Equals(ErrorCode(ErrorCode::ERR_ALLOWED))
    635 #endif
    636           ) {
    637         SANDBOX_DIE(
    638             "Invalid seccomp policy; if using UnsafeTrap(), you must "
    639             "unconditionally allow sigreturn() and sigprocmask()");
    640       }
    641 
    642       if (!Trap::EnableUnsafeTrapsInSigSysHandler()) {
    643         // We should never be able to get here, as UnsafeTrap() should never
    644         // actually return a valid ErrorCode object unless the user set the
    645         // CHROME_SANDBOX_DEBUGGING environment variable; and therefore,
    646         // "has_unsafe_traps" would always be false. But better double-check
    647         // than enabling dangerous code.
    648         SANDBOX_DIE("We'd rather die than enable unsafe traps");
    649       }
    650       gen->Traverse(jumptable, RedirectToUserspace, this);
    651 
    652       // Allow system calls, if they originate from our magic return address
    653       // (which we can query by calling Syscall::Call(-1)).
    654       uintptr_t syscall_entry_point = static_cast<uintptr_t>(Syscall::Call(-1));
    655       uint32_t low = static_cast<uint32_t>(syscall_entry_point);
    656 #if __SIZEOF_POINTER__ > 4
    657       uint32_t hi = static_cast<uint32_t>(syscall_entry_point >> 32);
    658 #endif
    659 
    660       // BPF cannot do native 64bit comparisons. On 64bit architectures, we
    661       // have to compare both 32bit halves of the instruction pointer. If they
    662       // match what we expect, we return ERR_ALLOWED. If either or both don't
    663       // match, we continue evalutating the rest of the sandbox policy.
    664       Instruction* escape_hatch = gen->MakeInstruction(
    665           BPF_LD + BPF_W + BPF_ABS,
    666           SECCOMP_IP_LSB_IDX,
    667           gen->MakeInstruction(
    668               BPF_JMP + BPF_JEQ + BPF_K,
    669               low,
    670 #if __SIZEOF_POINTER__ > 4
    671               gen->MakeInstruction(
    672                   BPF_LD + BPF_W + BPF_ABS,
    673                   SECCOMP_IP_MSB_IDX,
    674                   gen->MakeInstruction(
    675                       BPF_JMP + BPF_JEQ + BPF_K,
    676                       hi,
    677 #endif
    678                       gen->MakeInstruction(BPF_RET + BPF_K,
    679                                            ErrorCode(ErrorCode::ERR_ALLOWED)),
    680 #if __SIZEOF_POINTER__ > 4
    681                       load_nr)),
    682 #endif
    683               load_nr));
    684       gen->JoinInstructions(tail, escape_hatch);
    685     } else {
    686       gen->JoinInstructions(tail, load_nr);
    687     }
    688     tail = load_nr;
    689 
    690 // On Intel architectures, verify that system call numbers are in the
    691 // expected number range. The older i386 and x86-64 APIs clear bit 30
    692 // on all system calls. The newer x32 API always sets bit 30.
    693 #if defined(__i386__) || defined(__x86_64__)
    694     Instruction* invalidX32 = gen->MakeInstruction(
    695         BPF_RET + BPF_K, Kill("Illegal mixing of system call ABIs").err_);
    696     Instruction* checkX32 =
    697 #if defined(__x86_64__) && defined(__ILP32__)
    698         gen->MakeInstruction(
    699             BPF_JMP + BPF_JSET + BPF_K, 0x40000000, 0, invalidX32);
    700 #else
    701         gen->MakeInstruction(
    702             BPF_JMP + BPF_JSET + BPF_K, 0x40000000, invalidX32, 0);
    703 #endif
    704     gen->JoinInstructions(tail, checkX32);
    705     tail = checkX32;
    706 #endif
    707 
    708     // Append jump table to our pre-amble
    709     gen->JoinInstructions(tail, jumptable);
    710   }
    711 
    712   // Turn the DAG into a vector of instructions.
    713   Program* program = new Program();
    714   gen->Compile(head, program);
    715   delete gen;
    716 
    717   // Make sure compilation resulted in BPF program that executes
    718   // correctly. Otherwise, there is an internal error in our BPF compiler.
    719   // There is really nothing the caller can do until the bug is fixed.
    720   if (force_verification) {
    721     // Verification is expensive. We only perform this step, if we are
    722     // compiled in debug mode, or if the caller explicitly requested
    723     // verification.
    724     VerifyProgram(*program, has_unsafe_traps);
    725   }
    726 
    727   return program;
    728 }
    729 
    730 void SandboxBPF::VerifyProgram(const Program& program, bool has_unsafe_traps) {
    731   // If we previously rewrote the BPF program so that it calls user-space
    732   // whenever we return an "errno" value from the filter, then we have to
    733   // wrap our system call evaluator to perform the same operation. Otherwise,
    734   // the verifier would also report a mismatch in return codes.
    735   scoped_ptr<const RedirectToUserSpacePolicyWrapper> redirected_policy(
    736       new RedirectToUserSpacePolicyWrapper(policy_.get()));
    737 
    738   const char* err = NULL;
    739   if (!Verifier::VerifyBPF(this,
    740                            program,
    741                            has_unsafe_traps ? *redirected_policy : *policy_,
    742                            &err)) {
    743     CodeGen::PrintProgram(program);
    744     SANDBOX_DIE(err);
    745   }
    746 }
    747 
    748 void SandboxBPF::FindRanges(Ranges* ranges) {
    749   // Please note that "struct seccomp_data" defines system calls as a signed
    750   // int32_t, but BPF instructions always operate on unsigned quantities. We
    751   // deal with this disparity by enumerating from MIN_SYSCALL to MAX_SYSCALL,
    752   // and then verifying that the rest of the number range (both positive and
    753   // negative) all return the same ErrorCode.
    754   const ErrorCode invalid_err = policy_->InvalidSyscall(this);
    755   uint32_t old_sysnum = 0;
    756   ErrorCode old_err = IsValidSyscallNumber(old_sysnum)
    757                           ? policy_->EvaluateSyscall(this, old_sysnum)
    758                           : invalid_err;
    759 
    760   for (SyscallIterator iter(false); !iter.Done();) {
    761     uint32_t sysnum = iter.Next();
    762     ErrorCode err =
    763         IsValidSyscallNumber(sysnum)
    764             ? policy_->EvaluateSyscall(this, static_cast<int>(sysnum))
    765             : invalid_err;
    766     if (!err.Equals(old_err) || iter.Done()) {
    767       ranges->push_back(Range(old_sysnum, sysnum - 1, old_err));
    768       old_sysnum = sysnum;
    769       old_err = err;
    770     }
    771   }
    772 }
    773 
    774 Instruction* SandboxBPF::AssembleJumpTable(CodeGen* gen,
    775                                            Ranges::const_iterator start,
    776                                            Ranges::const_iterator stop) {
    777   // We convert the list of system call ranges into jump table that performs
    778   // a binary search over the ranges.
    779   // As a sanity check, we need to have at least one distinct ranges for us
    780   // to be able to build a jump table.
    781   if (stop - start <= 0) {
    782     SANDBOX_DIE("Invalid set of system call ranges");
    783   } else if (stop - start == 1) {
    784     // If we have narrowed things down to a single range object, we can
    785     // return from the BPF filter program.
    786     return RetExpression(gen, start->err);
    787   }
    788 
    789   // Pick the range object that is located at the mid point of our list.
    790   // We compare our system call number against the lowest valid system call
    791   // number in this range object. If our number is lower, it is outside of
    792   // this range object. If it is greater or equal, it might be inside.
    793   Ranges::const_iterator mid = start + (stop - start) / 2;
    794 
    795   // Sub-divide the list of ranges and continue recursively.
    796   Instruction* jf = AssembleJumpTable(gen, start, mid);
    797   Instruction* jt = AssembleJumpTable(gen, mid, stop);
    798   return gen->MakeInstruction(BPF_JMP + BPF_JGE + BPF_K, mid->from, jt, jf);
    799 }
    800 
    801 Instruction* SandboxBPF::RetExpression(CodeGen* gen, const ErrorCode& err) {
    802   if (err.error_type_ == ErrorCode::ET_COND) {
    803     return CondExpression(gen, err);
    804   } else {
    805     return gen->MakeInstruction(BPF_RET + BPF_K, err);
    806   }
    807 }
    808 
    809 Instruction* SandboxBPF::CondExpression(CodeGen* gen, const ErrorCode& cond) {
    810   // We can only inspect the six system call arguments that are passed in
    811   // CPU registers.
    812   if (cond.argno_ < 0 || cond.argno_ >= 6) {
    813     SANDBOX_DIE(
    814         "Internal compiler error; invalid argument number "
    815         "encountered");
    816   }
    817 
    818   // BPF programs operate on 32bit entities. Load both halfs of the 64bit
    819   // system call argument and then generate suitable conditional statements.
    820   Instruction* msb_head = gen->MakeInstruction(
    821       BPF_LD + BPF_W + BPF_ABS, SECCOMP_ARG_MSB_IDX(cond.argno_));
    822   Instruction* msb_tail = msb_head;
    823   Instruction* lsb_head = gen->MakeInstruction(
    824       BPF_LD + BPF_W + BPF_ABS, SECCOMP_ARG_LSB_IDX(cond.argno_));
    825   Instruction* lsb_tail = lsb_head;
    826 
    827   // Emit a suitable comparison statement.
    828   switch (cond.op_) {
    829     case ErrorCode::OP_EQUAL:
    830       // Compare the least significant bits for equality
    831       lsb_tail = gen->MakeInstruction(BPF_JMP + BPF_JEQ + BPF_K,
    832                                       static_cast<uint32_t>(cond.value_),
    833                                       RetExpression(gen, *cond.passed_),
    834                                       RetExpression(gen, *cond.failed_));
    835       gen->JoinInstructions(lsb_head, lsb_tail);
    836 
    837       // If we are looking at a 64bit argument, we need to also compare the
    838       // most significant bits.
    839       if (cond.width_ == ErrorCode::TP_64BIT) {
    840         msb_tail =
    841             gen->MakeInstruction(BPF_JMP + BPF_JEQ + BPF_K,
    842                                  static_cast<uint32_t>(cond.value_ >> 32),
    843                                  lsb_head,
    844                                  RetExpression(gen, *cond.failed_));
    845         gen->JoinInstructions(msb_head, msb_tail);
    846       }
    847       break;
    848     case ErrorCode::OP_HAS_ALL_BITS:
    849       // Check the bits in the LSB half of the system call argument. Our
    850       // OP_HAS_ALL_BITS operator passes, iff all of the bits are set. This is
    851       // different from the kernel's BPF_JSET operation which passes, if any of
    852       // the bits are set.
    853       // Of course, if there is only a single set bit (or none at all), then
    854       // things get easier.
    855       {
    856         uint32_t lsb_bits = static_cast<uint32_t>(cond.value_);
    857         int lsb_bit_count = popcount(lsb_bits);
    858         if (lsb_bit_count == 0) {
    859           // No bits are set in the LSB half. The test will always pass.
    860           lsb_head = RetExpression(gen, *cond.passed_);
    861           lsb_tail = NULL;
    862         } else if (lsb_bit_count == 1) {
    863           // Exactly one bit is set in the LSB half. We can use the BPF_JSET
    864           // operator.
    865           lsb_tail = gen->MakeInstruction(BPF_JMP + BPF_JSET + BPF_K,
    866                                           lsb_bits,
    867                                           RetExpression(gen, *cond.passed_),
    868                                           RetExpression(gen, *cond.failed_));
    869           gen->JoinInstructions(lsb_head, lsb_tail);
    870         } else {
    871           // More than one bit is set in the LSB half. We need to combine
    872           // BPF_AND and BPF_JEQ to test whether all of these bits are in fact
    873           // set in the system call argument.
    874           gen->JoinInstructions(
    875               lsb_head,
    876               gen->MakeInstruction(BPF_ALU + BPF_AND + BPF_K,
    877                                    lsb_bits,
    878                                    lsb_tail = gen->MakeInstruction(
    879                                        BPF_JMP + BPF_JEQ + BPF_K,
    880                                        lsb_bits,
    881                                        RetExpression(gen, *cond.passed_),
    882                                        RetExpression(gen, *cond.failed_))));
    883         }
    884       }
    885 
    886       // If we are looking at a 64bit argument, we need to also check the bits
    887       // in the MSB half of the system call argument.
    888       if (cond.width_ == ErrorCode::TP_64BIT) {
    889         uint32_t msb_bits = static_cast<uint32_t>(cond.value_ >> 32);
    890         int msb_bit_count = popcount(msb_bits);
    891         if (msb_bit_count == 0) {
    892           // No bits are set in the MSB half. The test will always pass.
    893           msb_head = lsb_head;
    894         } else if (msb_bit_count == 1) {
    895           // Exactly one bit is set in the MSB half. We can use the BPF_JSET
    896           // operator.
    897           msb_tail = gen->MakeInstruction(BPF_JMP + BPF_JSET + BPF_K,
    898                                           msb_bits,
    899                                           lsb_head,
    900                                           RetExpression(gen, *cond.failed_));
    901           gen->JoinInstructions(msb_head, msb_tail);
    902         } else {
    903           // More than one bit is set in the MSB half. We need to combine
    904           // BPF_AND and BPF_JEQ to test whether all of these bits are in fact
    905           // set in the system call argument.
    906           gen->JoinInstructions(
    907               msb_head,
    908               gen->MakeInstruction(
    909                   BPF_ALU + BPF_AND + BPF_K,
    910                   msb_bits,
    911                   gen->MakeInstruction(BPF_JMP + BPF_JEQ + BPF_K,
    912                                        msb_bits,
    913                                        lsb_head,
    914                                        RetExpression(gen, *cond.failed_))));
    915         }
    916       }
    917       break;
    918     case ErrorCode::OP_HAS_ANY_BITS:
    919       // Check the bits in the LSB half of the system call argument. Our
    920       // OP_HAS_ANY_BITS operator passes, iff any of the bits are set. This maps
    921       // nicely to the kernel's BPF_JSET operation.
    922       {
    923         uint32_t lsb_bits = static_cast<uint32_t>(cond.value_);
    924         if (!lsb_bits) {
    925           // No bits are set in the LSB half. The test will always fail.
    926           lsb_head = RetExpression(gen, *cond.failed_);
    927           lsb_tail = NULL;
    928         } else {
    929           lsb_tail = gen->MakeInstruction(BPF_JMP + BPF_JSET + BPF_K,
    930                                           lsb_bits,
    931                                           RetExpression(gen, *cond.passed_),
    932                                           RetExpression(gen, *cond.failed_));
    933           gen->JoinInstructions(lsb_head, lsb_tail);
    934         }
    935       }
    936 
    937       // If we are looking at a 64bit argument, we need to also check the bits
    938       // in the MSB half of the system call argument.
    939       if (cond.width_ == ErrorCode::TP_64BIT) {
    940         uint32_t msb_bits = static_cast<uint32_t>(cond.value_ >> 32);
    941         if (!msb_bits) {
    942           // No bits are set in the MSB half. The test will always fail.
    943           msb_head = lsb_head;
    944         } else {
    945           msb_tail = gen->MakeInstruction(BPF_JMP + BPF_JSET + BPF_K,
    946                                           msb_bits,
    947                                           RetExpression(gen, *cond.passed_),
    948                                           lsb_head);
    949           gen->JoinInstructions(msb_head, msb_tail);
    950         }
    951       }
    952       break;
    953     default:
    954       // TODO(markus): Need to add support for OP_GREATER
    955       SANDBOX_DIE("Not implemented");
    956       break;
    957   }
    958 
    959   // Ensure that we never pass a 64bit value, when we only expect a 32bit
    960   // value. This is somewhat complicated by the fact that on 64bit systems,
    961   // callers could legitimately pass in a non-zero value in the MSB, iff the
    962   // LSB has been sign-extended into the MSB.
    963   if (cond.width_ == ErrorCode::TP_32BIT) {
    964     if (cond.value_ >> 32) {
    965       SANDBOX_DIE(
    966           "Invalid comparison of a 32bit system call argument "
    967           "against a 64bit constant; this test is always false.");
    968     }
    969 
    970     Instruction* invalid_64bit = RetExpression(gen, Unexpected64bitArgument());
    971 #if __SIZEOF_POINTER__ > 4
    972     invalid_64bit = gen->MakeInstruction(
    973         BPF_JMP + BPF_JEQ + BPF_K,
    974         0xFFFFFFFF,
    975         gen->MakeInstruction(BPF_LD + BPF_W + BPF_ABS,
    976                              SECCOMP_ARG_LSB_IDX(cond.argno_),
    977                              gen->MakeInstruction(BPF_JMP + BPF_JGE + BPF_K,
    978                                                   0x80000000,
    979                                                   lsb_head,
    980                                                   invalid_64bit)),
    981         invalid_64bit);
    982 #endif
    983     gen->JoinInstructions(
    984         msb_tail,
    985         gen->MakeInstruction(
    986             BPF_JMP + BPF_JEQ + BPF_K, 0, lsb_head, invalid_64bit));
    987   }
    988 
    989   return msb_head;
    990 }
    991 
    992 ErrorCode SandboxBPF::Unexpected64bitArgument() {
    993   return Kill("Unexpected 64bit argument detected");
    994 }
    995 
    996 ErrorCode SandboxBPF::Trap(Trap::TrapFnc fnc, const void* aux) {
    997   return Trap::MakeTrap(fnc, aux, true /* Safe Trap */);
    998 }
    999 
   1000 ErrorCode SandboxBPF::UnsafeTrap(Trap::TrapFnc fnc, const void* aux) {
   1001   return Trap::MakeTrap(fnc, aux, false /* Unsafe Trap */);
   1002 }
   1003 
   1004 intptr_t SandboxBPF::ForwardSyscall(const struct arch_seccomp_data& args) {
   1005   return Syscall::Call(args.nr,
   1006                        static_cast<intptr_t>(args.args[0]),
   1007                        static_cast<intptr_t>(args.args[1]),
   1008                        static_cast<intptr_t>(args.args[2]),
   1009                        static_cast<intptr_t>(args.args[3]),
   1010                        static_cast<intptr_t>(args.args[4]),
   1011                        static_cast<intptr_t>(args.args[5]));
   1012 }
   1013 
   1014 ErrorCode SandboxBPF::Cond(int argno,
   1015                            ErrorCode::ArgType width,
   1016                            ErrorCode::Operation op,
   1017                            uint64_t value,
   1018                            const ErrorCode& passed,
   1019                            const ErrorCode& failed) {
   1020   return ErrorCode(argno,
   1021                    width,
   1022                    op,
   1023                    value,
   1024                    &*conds_->insert(passed).first,
   1025                    &*conds_->insert(failed).first);
   1026 }
   1027 
   1028 ErrorCode SandboxBPF::Kill(const char* msg) {
   1029   return Trap(BPFFailure, const_cast<char*>(msg));
   1030 }
   1031 
   1032 SandboxBPF::SandboxStatus SandboxBPF::status_ = STATUS_UNKNOWN;
   1033 
   1034 }  // namespace sandbox
   1035