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.
5 #include "sandbox/linux/seccomp-bpf/sandbox_bpf.h"
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).
10 #include <sys/cdefs.h>
15 #include <linux/filter.h>
18 #include <sys/prctl.h>
20 #include <sys/syscall.h>
21 #include <sys/types.h>
28 #include "base/compiler_specific.h"
29 #include "base/logging.h"
30 #include "base/macros.h"
31 #include "base/memory/scoped_ptr.h"
32 #include "base/posix/eintr_wrapper.h"
33 #include "sandbox/linux/seccomp-bpf/codegen.h"
34 #include "sandbox/linux/seccomp-bpf/die.h"
35 #include "sandbox/linux/seccomp-bpf/errorcode.h"
36 #include "sandbox/linux/seccomp-bpf/instruction.h"
37 #include "sandbox/linux/seccomp-bpf/linux_seccomp.h"
38 #include "sandbox/linux/seccomp-bpf/sandbox_bpf_policy.h"
39 #include "sandbox/linux/seccomp-bpf/syscall.h"
40 #include "sandbox/linux/seccomp-bpf/syscall_iterator.h"
41 #include "sandbox/linux/seccomp-bpf/trap.h"
42 #include "sandbox/linux/seccomp-bpf/verifier.h"
43 #include "sandbox/linux/services/linux_syscalls.h"
49 const int kExpectedExitCode = 100;
51 #if defined(__i386__) || defined(__x86_64__)
52 const bool kIsIntel = true;
54 const bool kIsIntel = false;
56 #if defined(__x86_64__) && defined(__ILP32__)
57 const bool kIsX32 = true;
59 const bool kIsX32 = false;
62 const int kSyscallsRequiredForUnsafeTraps[] = {
65 #if defined(__NR_sigprocmask)
68 #if defined(__NR_sigreturn)
73 bool HasExactlyOneBit(uint64_t x) {
74 // Common trick; e.g., see http://stackoverflow.com/a/108329.
75 return x != 0 && (x & (x - 1)) == 0;
79 void WriteFailedStderrSetupMessage(int out_fd) {
80 const char* error_string = strerror(errno);
81 static const char msg[] =
82 "You have reproduced a puzzling issue.\n"
83 "Please, report to crbug.com/152530!\n"
84 "Failed to set up stderr: ";
85 if (HANDLE_EINTR(write(out_fd, msg, sizeof(msg) - 1)) > 0 && error_string &&
86 HANDLE_EINTR(write(out_fd, error_string, strlen(error_string))) > 0 &&
87 HANDLE_EINTR(write(out_fd, "\n", 1))) {
90 #endif // !defined(NDEBUG)
92 // We define a really simple sandbox policy. It is just good enough for us
93 // to tell that the sandbox has actually been activated.
94 class ProbePolicy : public SandboxBPFPolicy {
97 virtual ErrorCode EvaluateSyscall(SandboxBPF*, int sysnum) const OVERRIDE {
100 // Return EPERM so that we can check that the filter actually ran.
101 return ErrorCode(EPERM);
102 case __NR_exit_group:
103 // Allow exit() with a non-default return code.
104 return ErrorCode(ErrorCode::ERR_ALLOWED);
106 // Make everything else fail in an easily recognizable way.
107 return ErrorCode(EINVAL);
112 DISALLOW_COPY_AND_ASSIGN(ProbePolicy);
115 void ProbeProcess(void) {
116 if (syscall(__NR_getpid) < 0 && errno == EPERM) {
117 syscall(__NR_exit_group, static_cast<intptr_t>(kExpectedExitCode));
121 class AllowAllPolicy : public SandboxBPFPolicy {
124 virtual ErrorCode EvaluateSyscall(SandboxBPF*, int sysnum) const OVERRIDE {
125 DCHECK(SandboxBPF::IsValidSyscallNumber(sysnum));
126 return ErrorCode(ErrorCode::ERR_ALLOWED);
130 DISALLOW_COPY_AND_ASSIGN(AllowAllPolicy);
133 void TryVsyscallProcess(void) {
135 // time() is implemented as a vsyscall. With an older glibc, with
136 // vsyscall=emulate and some versions of the seccomp BPF patch
137 // we may get SIGKILL-ed. Detect this!
138 if (time(¤t_time) != static_cast<time_t>(-1)) {
139 syscall(__NR_exit_group, static_cast<intptr_t>(kExpectedExitCode));
143 bool IsSingleThreaded(int proc_fd) {
145 // Cannot determine whether program is single-threaded. Hope for
152 if ((task = openat(proc_fd, "self/task", O_RDONLY | O_DIRECTORY)) < 0 ||
153 fstat(task, &sb) != 0 || sb.st_nlink != 3 || IGNORE_EINTR(close(task))) {
155 if (IGNORE_EINTR(close(task))) {
163 bool IsDenied(const ErrorCode& code) {
164 return (code.err() & SECCOMP_RET_ACTION) == SECCOMP_RET_TRAP ||
165 (code.err() >= (SECCOMP_RET_ERRNO + ErrorCode::ERR_MIN_ERRNO) &&
166 code.err() <= (SECCOMP_RET_ERRNO + ErrorCode::ERR_MAX_ERRNO));
169 // Function that can be passed as a callback function to CodeGen::Traverse().
170 // Checks whether the "insn" returns an UnsafeTrap() ErrorCode. If so, it
171 // sets the "bool" variable pointed to by "aux".
172 void CheckForUnsafeErrorCodes(Instruction* insn, void* aux) {
173 bool* is_unsafe = static_cast<bool*>(aux);
175 if (BPF_CLASS(insn->code) == BPF_RET && insn->k > SECCOMP_RET_TRAP &&
176 insn->k - SECCOMP_RET_TRAP <= SECCOMP_RET_DATA) {
177 if (!Trap::IsSafeTrapId(insn->k & SECCOMP_RET_DATA)) {
184 // A Trap() handler that returns an "errno" value. The value is encoded
185 // in the "aux" parameter.
186 intptr_t ReturnErrno(const struct arch_seccomp_data&, void* aux) {
187 // TrapFnc functions report error by following the native kernel convention
188 // of returning an exit code in the range of -1..-4096. They do not try to
189 // set errno themselves. The glibc wrapper that triggered the SIGSYS will
190 // ultimately do so for us.
191 int err = reinterpret_cast<intptr_t>(aux) & SECCOMP_RET_DATA;
195 // Function that can be passed as a callback function to CodeGen::Traverse().
196 // Checks whether the "insn" returns an errno value from a BPF filter. If so,
197 // it rewrites the instruction to instead call a Trap() handler that does
198 // the same thing. "aux" is ignored.
199 void RedirectToUserspace(Instruction* insn, void* aux) {
200 // When inside an UnsafeTrap() callback, we want to allow all system calls.
201 // This means, we must conditionally disable the sandbox -- and that's not
202 // something that kernel-side BPF filters can do, as they cannot inspect
203 // any state other than the syscall arguments.
204 // But if we redirect all error handlers to user-space, then we can easily
205 // make this decision.
206 // The performance penalty for this extra round-trip to user-space is not
207 // actually that bad, as we only ever pay it for denied system calls; and a
208 // typical program has very few of these.
209 SandboxBPF* sandbox = static_cast<SandboxBPF*>(aux);
210 if (BPF_CLASS(insn->code) == BPF_RET &&
211 (insn->k & SECCOMP_RET_ACTION) == SECCOMP_RET_ERRNO) {
212 insn->k = sandbox->Trap(ReturnErrno,
213 reinterpret_cast<void*>(insn->k & SECCOMP_RET_DATA)).err();
217 // This wraps an existing policy and changes its behavior to match the changes
218 // made by RedirectToUserspace(). This is part of the framework that allows BPF
219 // evaluation in userland.
220 // TODO(markus): document the code inside better.
221 class RedirectToUserSpacePolicyWrapper : public SandboxBPFPolicy {
223 explicit RedirectToUserSpacePolicyWrapper(
224 const SandboxBPFPolicy* wrapped_policy)
225 : wrapped_policy_(wrapped_policy) {
226 DCHECK(wrapped_policy_);
229 virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox_compiler,
230 int system_call_number) const OVERRIDE {
232 wrapped_policy_->EvaluateSyscall(sandbox_compiler, system_call_number);
233 ChangeErrnoToTraps(&err, sandbox_compiler);
237 virtual ErrorCode InvalidSyscall(
238 SandboxBPF* sandbox_compiler) const OVERRIDE {
239 return ReturnErrnoViaTrap(sandbox_compiler, ENOSYS);
243 ErrorCode ReturnErrnoViaTrap(SandboxBPF* sandbox_compiler, int err) const {
244 return sandbox_compiler->Trap(ReturnErrno, reinterpret_cast<void*>(err));
247 // ChangeErrnoToTraps recursivly iterates through the ErrorCode
248 // converting any ERRNO to a userspace trap
249 void ChangeErrnoToTraps(ErrorCode* err, SandboxBPF* sandbox_compiler) const {
250 if (err->error_type() == ErrorCode::ET_SIMPLE &&
251 (err->err() & SECCOMP_RET_ACTION) == SECCOMP_RET_ERRNO) {
252 // Have an errno, need to change this to a trap
254 ReturnErrnoViaTrap(sandbox_compiler, err->err() & SECCOMP_RET_DATA);
256 } else if (err->error_type() == ErrorCode::ET_COND) {
257 // Need to explore both paths
258 ChangeErrnoToTraps((ErrorCode*)err->passed(), sandbox_compiler);
259 ChangeErrnoToTraps((ErrorCode*)err->failed(), sandbox_compiler);
261 } else if (err->error_type() == ErrorCode::ET_TRAP) {
263 } else if (err->error_type() == ErrorCode::ET_SIMPLE &&
264 (err->err() & SECCOMP_RET_ACTION) == SECCOMP_RET_ALLOW) {
270 const SandboxBPFPolicy* wrapped_policy_;
271 DISALLOW_COPY_AND_ASSIGN(RedirectToUserSpacePolicyWrapper);
274 intptr_t BPFFailure(const struct arch_seccomp_data&, void* aux) {
275 SANDBOX_DIE(static_cast<char*>(aux));
280 SandboxBPF::SandboxBPF()
284 sandbox_has_started_(false) {}
286 SandboxBPF::~SandboxBPF() {
287 // It is generally unsafe to call any memory allocator operations or to even
288 // call arbitrary destructors after having installed a new policy. We just
289 // have no way to tell whether this policy would allow the system calls that
290 // the constructors can trigger.
291 // So, we normally destroy all of our complex state prior to starting the
292 // sandbox. But this won't happen, if the Sandbox object was created and
293 // never actually used to set up a sandbox. So, just in case, we are
294 // destroying any remaining state.
295 // The "if ()" statements are technically superfluous. But let's be explicit
296 // that we really don't want to run any code, when we already destroyed
297 // objects before setting up the sandbox.
303 bool SandboxBPF::IsValidSyscallNumber(int sysnum) {
304 return SyscallIterator::IsValid(sysnum);
307 bool SandboxBPF::RunFunctionInPolicy(void (*code_in_sandbox)(),
308 scoped_ptr<SandboxBPFPolicy> policy) {
309 // Block all signals before forking a child process. This prevents an
310 // attacker from manipulating our test by sending us an unexpected signal.
311 sigset_t old_mask, new_mask;
312 if (sigfillset(&new_mask) || sigprocmask(SIG_BLOCK, &new_mask, &old_mask)) {
313 SANDBOX_DIE("sigprocmask() failed");
316 if (pipe2(fds, O_NONBLOCK | O_CLOEXEC)) {
317 SANDBOX_DIE("pipe() failed");
320 if (fds[0] <= 2 || fds[1] <= 2) {
321 SANDBOX_DIE("Process started without standard file descriptors");
324 // This code is using fork() and should only ever run single-threaded.
325 // Most of the code below is "async-signal-safe" and only minor changes
326 // would be needed to support threads.
327 DCHECK(IsSingleThreaded(proc_fd_));
330 // Die if we cannot fork(). We would probably fail a little later
331 // anyway, as the machine is likely very close to running out of
333 // But what we don't want to do is return "false", as a crafty
334 // attacker might cause fork() to fail at will and could trick us
335 // into running without a sandbox.
336 sigprocmask(SIG_SETMASK, &old_mask, NULL); // OK, if it fails
337 SANDBOX_DIE("fork() failed unexpectedly");
340 // In the child process
342 // Test a very simple sandbox policy to verify that we can
343 // successfully turn on sandboxing.
344 Die::EnableSimpleExit();
347 if (IGNORE_EINTR(close(fds[0]))) {
348 // This call to close() has been failing in strange ways. See
349 // crbug.com/152530. So we only fail in debug mode now.
351 WriteFailedStderrSetupMessage(fds[1]);
355 if (HANDLE_EINTR(dup2(fds[1], 2)) != 2) {
356 // Stderr could very well be a file descriptor to .xsession-errors, or
357 // another file, which could be backed by a file system that could cause
358 // dup2 to fail while trying to close stderr. It's important that we do
359 // not fail on trying to close stderr.
360 // If dup2 fails here, we will continue normally, this means that our
361 // parent won't cause a fatal failure if something writes to stderr in
364 // In DEBUG builds, we still want to get a report.
365 WriteFailedStderrSetupMessage(fds[1]);
369 if (IGNORE_EINTR(close(fds[1]))) {
370 // This call to close() has been failing in strange ways. See
371 // crbug.com/152530. So we only fail in debug mode now.
373 WriteFailedStderrSetupMessage(fds[1]);
378 SetSandboxPolicy(policy.release());
379 if (!StartSandbox(PROCESS_SINGLE_THREADED)) {
383 // Run our code in the sandbox.
386 // code_in_sandbox() is not supposed to return here.
390 // In the parent process.
391 if (IGNORE_EINTR(close(fds[1]))) {
392 SANDBOX_DIE("close() failed");
394 if (sigprocmask(SIG_SETMASK, &old_mask, NULL)) {
395 SANDBOX_DIE("sigprocmask() failed");
398 if (HANDLE_EINTR(waitpid(pid, &status, 0)) != pid) {
399 SANDBOX_DIE("waitpid() failed unexpectedly");
401 bool rc = WIFEXITED(status) && WEXITSTATUS(status) == kExpectedExitCode;
403 // If we fail to support sandboxing, there might be an additional
404 // error message. If so, this was an entirely unexpected and fatal
405 // failure. We should report the failure and somebody must fix
406 // things. This is probably a security-critical bug in the sandboxing
410 ssize_t len = HANDLE_EINTR(read(fds[0], buf, sizeof(buf) - 1));
412 while (len > 1 && buf[len - 1] == '\n') {
419 if (IGNORE_EINTR(close(fds[0]))) {
420 SANDBOX_DIE("close() failed");
426 bool SandboxBPF::KernelSupportSeccompBPF() {
427 return RunFunctionInPolicy(ProbeProcess,
428 scoped_ptr<SandboxBPFPolicy>(new ProbePolicy())) &&
431 scoped_ptr<SandboxBPFPolicy>(new AllowAllPolicy()));
435 SandboxBPF::SandboxStatus SandboxBPF::SupportsSeccompSandbox(int proc_fd) {
436 // It the sandbox is currently active, we clearly must have support for
438 if (status_ == STATUS_ENABLED) {
442 // Even if the sandbox was previously available, something might have
443 // changed in our run-time environment. Check one more time.
444 if (status_ == STATUS_AVAILABLE) {
445 if (!IsSingleThreaded(proc_fd)) {
446 status_ = STATUS_UNAVAILABLE;
451 if (status_ == STATUS_UNAVAILABLE && IsSingleThreaded(proc_fd)) {
452 // All state transitions resulting in STATUS_UNAVAILABLE are immediately
453 // preceded by STATUS_AVAILABLE. Furthermore, these transitions all
454 // happen, if and only if they are triggered by the process being multi-
456 // In other words, if a single-threaded process is currently in the
457 // STATUS_UNAVAILABLE state, it is safe to assume that sandboxing is
458 // actually available.
459 status_ = STATUS_AVAILABLE;
463 // If we have not previously checked for availability of the sandbox or if
464 // we otherwise don't believe to have a good cached value, we have to
465 // perform a thorough check now.
466 if (status_ == STATUS_UNKNOWN) {
467 // We create our own private copy of a "Sandbox" object. This ensures that
468 // the object does not have any policies configured, that might interfere
469 // with the tests done by "KernelSupportSeccompBPF()".
472 // By setting "quiet_ = true" we suppress messages for expected and benign
473 // failures (e.g. if the current kernel lacks support for BPF filters).
474 sandbox.quiet_ = true;
475 sandbox.set_proc_fd(proc_fd);
476 status_ = sandbox.KernelSupportSeccompBPF() ? STATUS_AVAILABLE
477 : STATUS_UNSUPPORTED;
479 // As we are performing our tests from a child process, the run-time
480 // environment that is visible to the sandbox is always guaranteed to be
481 // single-threaded. Let's check here whether the caller is single-
482 // threaded. Otherwise, we mark the sandbox as temporarily unavailable.
483 if (status_ == STATUS_AVAILABLE && !IsSingleThreaded(proc_fd)) {
484 status_ = STATUS_UNAVAILABLE;
491 SandboxBPF::SandboxStatus
492 SandboxBPF::SupportsSeccompThreadFilterSynchronization() {
493 // Applying NO_NEW_PRIVS, a BPF filter, and synchronizing the filter across
494 // the thread group are all handled atomically by this syscall.
495 const int rv = syscall(
496 __NR_seccomp, SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_TSYNC, NULL);
498 if (rv == -1 && errno == EFAULT) {
499 return STATUS_AVAILABLE;
501 // TODO(jln): turn these into DCHECK after 417888 is considered fixed.
503 CHECK(ENOSYS == errno || EINVAL == errno);
504 return STATUS_UNSUPPORTED;
508 void SandboxBPF::set_proc_fd(int proc_fd) { proc_fd_ = proc_fd; }
510 bool SandboxBPF::StartSandbox(SandboxThreadState thread_state) {
511 CHECK(thread_state == PROCESS_SINGLE_THREADED ||
512 thread_state == PROCESS_MULTI_THREADED);
514 if (status_ == STATUS_UNSUPPORTED || status_ == STATUS_UNAVAILABLE) {
516 "Trying to start sandbox, even though it is known to be "
519 } else if (sandbox_has_started_ || !conds_) {
521 "Cannot repeatedly start sandbox. Create a separate Sandbox "
526 proc_fd_ = open("/proc", O_RDONLY | O_DIRECTORY);
529 // For now, continue in degraded mode, if we can't access /proc.
530 // In the future, we might want to tighten this requirement.
533 bool supports_tsync =
534 SupportsSeccompThreadFilterSynchronization() == STATUS_AVAILABLE;
536 if (thread_state == PROCESS_SINGLE_THREADED) {
537 if (!IsSingleThreaded(proc_fd_)) {
538 SANDBOX_DIE("Cannot start sandbox; process is already multi-threaded");
541 } else if (thread_state == PROCESS_MULTI_THREADED) {
542 if (IsSingleThreaded(proc_fd_)) {
543 SANDBOX_DIE("Cannot start sandbox; "
544 "process may be single-threaded when reported as not");
547 if (!supports_tsync) {
548 SANDBOX_DIE("Cannot start sandbox; kernel does not support synchronizing "
549 "filters for a threadgroup");
554 // We no longer need access to any files in /proc. We want to do this
555 // before installing the filters, just in case that our policy denies
558 if (IGNORE_EINTR(close(proc_fd_))) {
559 SANDBOX_DIE("Failed to close file descriptor for /proc");
565 // Install the filters.
566 InstallFilter(supports_tsync || thread_state == PROCESS_MULTI_THREADED);
568 // We are now inside the sandbox.
569 status_ = STATUS_ENABLED;
574 void SandboxBPF::PolicySanityChecks(SandboxBPFPolicy* policy) {
575 if (!IsDenied(policy->InvalidSyscall(this))) {
576 SANDBOX_DIE("Policies should deny invalid system calls.");
581 // Don't take a scoped_ptr here, polymorphism make their use awkward.
582 void SandboxBPF::SetSandboxPolicy(SandboxBPFPolicy* policy) {
584 if (sandbox_has_started_ || !conds_) {
585 SANDBOX_DIE("Cannot change policy after sandbox has started");
587 PolicySanityChecks(policy);
588 policy_.reset(policy);
591 void SandboxBPF::InstallFilter(bool must_sync_threads) {
592 // We want to be very careful in not imposing any requirements on the
593 // policies that are set with SetSandboxPolicy(). This means, as soon as
594 // the sandbox is active, we shouldn't be relying on libraries that could
595 // be making system calls. This, for example, means we should avoid
596 // using the heap and we should avoid using STL functions.
597 // Temporarily copy the contents of the "program" vector into a
598 // stack-allocated array; and then explicitly destroy that object.
599 // This makes sure we don't ex- or implicitly call new/delete after we
600 // installed the BPF filter program in the kernel. Depending on the
601 // system memory allocator that is in effect, these operators can result
602 // in system calls to things like munmap() or brk().
603 Program* program = AssembleFilter(false /* force_verification */);
605 struct sock_filter bpf[program->size()];
606 const struct sock_fprog prog = {static_cast<unsigned short>(program->size()),
608 memcpy(bpf, &(*program)[0], sizeof(bpf));
611 // Make an attempt to release memory that is no longer needed here, rather
612 // than in the destructor. Try to avoid as much as possible to presume of
613 // what will be possible to do in the new (sandboxed) execution environment.
618 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
619 SANDBOX_DIE(quiet_ ? NULL : "Kernel refuses to enable no-new-privs");
622 // Install BPF filter program. If the thread state indicates multi-threading
623 // support, then the kernel hass the seccomp system call. Otherwise, fall
624 // back on prctl, which requires the process to be single-threaded.
625 if (must_sync_threads) {
626 int rv = syscall(__NR_seccomp, SECCOMP_SET_MODE_FILTER,
627 SECCOMP_FILTER_FLAG_TSYNC, reinterpret_cast<const char*>(&prog));
629 SANDBOX_DIE(quiet_ ? NULL :
630 "Kernel refuses to turn on and synchronize threads for BPF filters");
633 if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)) {
634 SANDBOX_DIE(quiet_ ? NULL : "Kernel refuses to turn on BPF filters");
638 sandbox_has_started_ = true;
641 SandboxBPF::Program* SandboxBPF::AssembleFilter(bool force_verification) {
643 force_verification = true;
646 // Verify that the user pushed a policy.
649 // Assemble the BPF filter program.
650 CodeGen* gen = new CodeGen();
652 SANDBOX_DIE("Out of memory");
655 bool has_unsafe_traps;
656 Instruction* head = CompilePolicy(gen, &has_unsafe_traps);
658 // Turn the DAG into a vector of instructions.
659 Program* program = new Program();
660 gen->Compile(head, program);
663 // Make sure compilation resulted in BPF program that executes
664 // correctly. Otherwise, there is an internal error in our BPF compiler.
665 // There is really nothing the caller can do until the bug is fixed.
666 if (force_verification) {
667 // Verification is expensive. We only perform this step, if we are
668 // compiled in debug mode, or if the caller explicitly requested
670 VerifyProgram(*program, has_unsafe_traps);
676 Instruction* SandboxBPF::CompilePolicy(CodeGen* gen, bool* has_unsafe_traps) {
677 // A compiled policy consists of three logical parts:
678 // 1. Check that the "arch" field matches the expected architecture.
679 // 2. If the policy involves unsafe traps, check if the syscall was
680 // invoked by Syscall::Call, and then allow it unconditionally.
681 // 3. Check the system call number and jump to the appropriate compiled
682 // system call policy number.
684 gen, MaybeAddEscapeHatch(gen, has_unsafe_traps, DispatchSyscall(gen)));
687 Instruction* SandboxBPF::CheckArch(CodeGen* gen, Instruction* passed) {
688 // If the architecture doesn't match SECCOMP_ARCH, disallow the
690 return gen->MakeInstruction(
691 BPF_LD + BPF_W + BPF_ABS,
693 gen->MakeInstruction(
694 BPF_JMP + BPF_JEQ + BPF_K,
698 Kill("Invalid audit architecture in BPF filter"))));
701 Instruction* SandboxBPF::MaybeAddEscapeHatch(CodeGen* gen,
702 bool* has_unsafe_traps,
704 // If there is at least one UnsafeTrap() in our program, the entire sandbox
705 // is unsafe. We need to modify the program so that all non-
706 // SECCOMP_RET_ALLOW ErrorCodes are handled in user-space. This will then
707 // allow us to temporarily disable sandboxing rules inside of callbacks to
709 *has_unsafe_traps = false;
710 gen->Traverse(rest, CheckForUnsafeErrorCodes, has_unsafe_traps);
711 if (!*has_unsafe_traps) {
712 // If no unsafe traps, then simply return |rest|.
716 // If our BPF program has unsafe jumps, enable support for them. This
717 // test happens very early in the BPF filter program. Even before we
718 // consider looking at system call numbers.
719 // As support for unsafe jumps essentially defeats all the security
720 // measures that the sandbox provides, we print a big warning message --
721 // and of course, we make sure to only ever enable this feature if it
722 // is actually requested by the sandbox policy.
723 if (Syscall::Call(-1) == -1 && errno == ENOSYS) {
725 "Support for UnsafeTrap() has not yet been ported to this "
729 for (size_t i = 0; i < arraysize(kSyscallsRequiredForUnsafeTraps); ++i) {
730 if (!policy_->EvaluateSyscall(this, kSyscallsRequiredForUnsafeTraps[i])
731 .Equals(ErrorCode(ErrorCode::ERR_ALLOWED))) {
733 "Policies that use UnsafeTrap() must unconditionally allow all "
734 "required system calls");
738 if (!Trap::EnableUnsafeTrapsInSigSysHandler()) {
739 // We should never be able to get here, as UnsafeTrap() should never
740 // actually return a valid ErrorCode object unless the user set the
741 // CHROME_SANDBOX_DEBUGGING environment variable; and therefore,
742 // "has_unsafe_traps" would always be false. But better double-check
743 // than enabling dangerous code.
744 SANDBOX_DIE("We'd rather die than enable unsafe traps");
746 gen->Traverse(rest, RedirectToUserspace, this);
748 // Allow system calls, if they originate from our magic return address
749 // (which we can query by calling Syscall::Call(-1)).
750 uint64_t syscall_entry_point =
751 static_cast<uint64_t>(static_cast<uintptr_t>(Syscall::Call(-1)));
752 uint32_t low = static_cast<uint32_t>(syscall_entry_point);
753 uint32_t hi = static_cast<uint32_t>(syscall_entry_point >> 32);
755 // BPF cannot do native 64-bit comparisons, so we have to compare
756 // both 32-bit halves of the instruction pointer. If they match what
757 // we expect, we return ERR_ALLOWED. If either or both don't match,
758 // we continue evalutating the rest of the sandbox policy.
760 // For simplicity, we check the full 64-bit instruction pointer even
761 // on 32-bit architectures.
762 return gen->MakeInstruction(
763 BPF_LD + BPF_W + BPF_ABS,
765 gen->MakeInstruction(
766 BPF_JMP + BPF_JEQ + BPF_K,
768 gen->MakeInstruction(
769 BPF_LD + BPF_W + BPF_ABS,
771 gen->MakeInstruction(
772 BPF_JMP + BPF_JEQ + BPF_K,
774 RetExpression(gen, ErrorCode(ErrorCode::ERR_ALLOWED)),
779 Instruction* SandboxBPF::DispatchSyscall(CodeGen* gen) {
780 // Evaluate all possible system calls and group their ErrorCodes into
781 // ranges of identical codes.
785 // Compile the system call ranges to an optimized BPF jumptable
786 Instruction* jumptable = AssembleJumpTable(gen, ranges.begin(), ranges.end());
788 // Grab the system call number, so that we can check it and then
789 // execute the jump table.
790 return gen->MakeInstruction(BPF_LD + BPF_W + BPF_ABS,
792 CheckSyscallNumber(gen, jumptable));
795 Instruction* SandboxBPF::CheckSyscallNumber(CodeGen* gen, Instruction* passed) {
797 // On Intel architectures, verify that system call numbers are in the
798 // expected number range.
799 Instruction* invalidX32 =
800 RetExpression(gen, Kill("Illegal mixing of system call ABIs"));
802 // The newer x32 API always sets bit 30.
803 return gen->MakeInstruction(
804 BPF_JMP + BPF_JSET + BPF_K, 0x40000000, passed, invalidX32);
806 // The older i386 and x86-64 APIs clear bit 30 on all system calls.
807 return gen->MakeInstruction(
808 BPF_JMP + BPF_JSET + BPF_K, 0x40000000, invalidX32, passed);
812 // TODO(mdempsky): Similar validation for other architectures?
816 void SandboxBPF::VerifyProgram(const Program& program, bool has_unsafe_traps) {
817 // If we previously rewrote the BPF program so that it calls user-space
818 // whenever we return an "errno" value from the filter, then we have to
819 // wrap our system call evaluator to perform the same operation. Otherwise,
820 // the verifier would also report a mismatch in return codes.
821 scoped_ptr<const RedirectToUserSpacePolicyWrapper> redirected_policy(
822 new RedirectToUserSpacePolicyWrapper(policy_.get()));
824 const char* err = NULL;
825 if (!Verifier::VerifyBPF(this,
827 has_unsafe_traps ? *redirected_policy : *policy_,
829 CodeGen::PrintProgram(program);
834 void SandboxBPF::FindRanges(Ranges* ranges) {
835 // Please note that "struct seccomp_data" defines system calls as a signed
836 // int32_t, but BPF instructions always operate on unsigned quantities. We
837 // deal with this disparity by enumerating from MIN_SYSCALL to MAX_SYSCALL,
838 // and then verifying that the rest of the number range (both positive and
839 // negative) all return the same ErrorCode.
840 const ErrorCode invalid_err = policy_->InvalidSyscall(this);
841 uint32_t old_sysnum = 0;
842 ErrorCode old_err = IsValidSyscallNumber(old_sysnum)
843 ? policy_->EvaluateSyscall(this, old_sysnum)
846 for (SyscallIterator iter(false); !iter.Done();) {
847 uint32_t sysnum = iter.Next();
849 IsValidSyscallNumber(sysnum)
850 ? policy_->EvaluateSyscall(this, static_cast<int>(sysnum))
852 if (!err.Equals(old_err) || iter.Done()) {
853 ranges->push_back(Range(old_sysnum, sysnum - 1, old_err));
860 Instruction* SandboxBPF::AssembleJumpTable(CodeGen* gen,
861 Ranges::const_iterator start,
862 Ranges::const_iterator stop) {
863 // We convert the list of system call ranges into jump table that performs
864 // a binary search over the ranges.
865 // As a sanity check, we need to have at least one distinct ranges for us
866 // to be able to build a jump table.
867 if (stop - start <= 0) {
868 SANDBOX_DIE("Invalid set of system call ranges");
869 } else if (stop - start == 1) {
870 // If we have narrowed things down to a single range object, we can
871 // return from the BPF filter program.
872 return RetExpression(gen, start->err);
875 // Pick the range object that is located at the mid point of our list.
876 // We compare our system call number against the lowest valid system call
877 // number in this range object. If our number is lower, it is outside of
878 // this range object. If it is greater or equal, it might be inside.
879 Ranges::const_iterator mid = start + (stop - start) / 2;
881 // Sub-divide the list of ranges and continue recursively.
882 Instruction* jf = AssembleJumpTable(gen, start, mid);
883 Instruction* jt = AssembleJumpTable(gen, mid, stop);
884 return gen->MakeInstruction(BPF_JMP + BPF_JGE + BPF_K, mid->from, jt, jf);
887 Instruction* SandboxBPF::RetExpression(CodeGen* gen, const ErrorCode& err) {
888 switch (err.error_type()) {
889 case ErrorCode::ET_COND:
890 return CondExpression(gen, err);
891 case ErrorCode::ET_SIMPLE:
892 case ErrorCode::ET_TRAP:
893 return gen->MakeInstruction(BPF_RET + BPF_K, err.err());
895 SANDBOX_DIE("ErrorCode is not suitable for returning from a BPF program");
899 Instruction* SandboxBPF::CondExpression(CodeGen* gen, const ErrorCode& cond) {
900 // Sanity check that |cond| makes sense.
901 if (cond.argno_ < 0 || cond.argno_ >= 6) {
902 SANDBOX_DIE("sandbox_bpf: invalid argument number");
904 if (cond.width_ != ErrorCode::TP_32BIT &&
905 cond.width_ != ErrorCode::TP_64BIT) {
906 SANDBOX_DIE("sandbox_bpf: invalid argument width");
908 if (cond.mask_ == 0) {
909 SANDBOX_DIE("sandbox_bpf: zero mask is invalid");
911 if ((cond.value_ & cond.mask_) != cond.value_) {
912 SANDBOX_DIE("sandbox_bpf: value contains masked out bits");
914 if (cond.width_ == ErrorCode::TP_32BIT &&
915 ((cond.mask_ >> 32) != 0 || (cond.value_ >> 32) != 0)) {
916 SANDBOX_DIE("sandbox_bpf: test exceeds argument size");
918 // TODO(mdempsky): Reject TP_64BIT on 32-bit platforms. For now we allow it
919 // because some SandboxBPF unit tests exercise it.
921 Instruction* passed = RetExpression(gen, *cond.passed_);
922 Instruction* failed = RetExpression(gen, *cond.failed_);
924 // We want to emit code to check "(arg & mask) == value" where arg, mask, and
925 // value are 64-bit values, but the BPF machine is only 32-bit. We implement
926 // this by independently testing the upper and lower 32-bits and continuing to
927 // |passed| if both evaluate true, or to |failed| if either evaluate false.
928 return CondExpressionHalf(
932 CondExpressionHalf(gen, cond, LowerHalf, passed, failed),
936 Instruction* SandboxBPF::CondExpressionHalf(CodeGen* gen,
937 const ErrorCode& cond,
940 Instruction* failed) {
941 if (cond.width_ == ErrorCode::TP_32BIT && half == UpperHalf) {
942 // Special logic for sanity checking the upper 32-bits of 32-bit system
945 // TODO(mdempsky): Compile Unexpected64bitArgument() just per program.
946 Instruction* invalid_64bit = RetExpression(gen, Unexpected64bitArgument());
948 const uint32_t upper = SECCOMP_ARG_MSB_IDX(cond.argno_);
949 const uint32_t lower = SECCOMP_ARG_LSB_IDX(cond.argno_);
951 if (sizeof(void*) == 4) {
952 // On 32-bit platforms, the upper 32-bits should always be 0:
954 // JEQ 0, passed, invalid
955 return gen->MakeInstruction(
956 BPF_LD + BPF_W + BPF_ABS,
958 gen->MakeInstruction(
959 BPF_JMP + BPF_JEQ + BPF_K, 0, passed, invalid_64bit));
962 // On 64-bit platforms, the upper 32-bits may be 0 or ~0; but we only allow
963 // ~0 if the sign bit of the lower 32-bits is set too:
965 // JEQ 0, passed, (next)
966 // JEQ ~0, (next), invalid
968 // JSET (1<<31), passed, invalid
970 // TODO(mdempsky): The JSET instruction could perhaps jump to passed->next
971 // instead, as the first instruction of passed should be "LDW [lower]".
972 return gen->MakeInstruction(
973 BPF_LD + BPF_W + BPF_ABS,
975 gen->MakeInstruction(
976 BPF_JMP + BPF_JEQ + BPF_K,
979 gen->MakeInstruction(
980 BPF_JMP + BPF_JEQ + BPF_K,
981 std::numeric_limits<uint32_t>::max(),
982 gen->MakeInstruction(
983 BPF_LD + BPF_W + BPF_ABS,
985 gen->MakeInstruction(BPF_JMP + BPF_JSET + BPF_K,
992 const uint32_t idx = (half == UpperHalf) ? SECCOMP_ARG_MSB_IDX(cond.argno_)
993 : SECCOMP_ARG_LSB_IDX(cond.argno_);
994 const uint32_t mask = (half == UpperHalf) ? cond.mask_ >> 32 : cond.mask_;
995 const uint32_t value = (half == UpperHalf) ? cond.value_ >> 32 : cond.value_;
997 // Emit a suitable instruction sequence for (arg & mask) == value.
999 // For (arg & 0) == 0, just return passed.
1001 CHECK_EQ(0U, value);
1005 // For (arg & ~0) == value, emit:
1007 // JEQ value, passed, failed
1008 if (mask == std::numeric_limits<uint32_t>::max()) {
1009 return gen->MakeInstruction(
1010 BPF_LD + BPF_W + BPF_ABS,
1012 gen->MakeInstruction(BPF_JMP + BPF_JEQ + BPF_K, value, passed, failed));
1015 // For (arg & mask) == 0, emit:
1017 // JSET mask, failed, passed
1018 // (Note: failed and passed are intentionally swapped.)
1020 return gen->MakeInstruction(
1021 BPF_LD + BPF_W + BPF_ABS,
1023 gen->MakeInstruction(BPF_JMP + BPF_JSET + BPF_K, mask, failed, passed));
1026 // For (arg & x) == x where x is a single-bit value, emit:
1028 // JSET mask, passed, failed
1029 if (mask == value && HasExactlyOneBit(mask)) {
1030 return gen->MakeInstruction(
1031 BPF_LD + BPF_W + BPF_ABS,
1033 gen->MakeInstruction(BPF_JMP + BPF_JSET + BPF_K, mask, passed, failed));
1036 // Generic fallback:
1039 // JEQ value, passed, failed
1040 return gen->MakeInstruction(
1041 BPF_LD + BPF_W + BPF_ABS,
1043 gen->MakeInstruction(
1044 BPF_ALU + BPF_AND + BPF_K,
1046 gen->MakeInstruction(
1047 BPF_JMP + BPF_JEQ + BPF_K, value, passed, failed)));
1050 ErrorCode SandboxBPF::Unexpected64bitArgument() {
1051 return Kill("Unexpected 64bit argument detected");
1054 ErrorCode SandboxBPF::Trap(Trap::TrapFnc fnc, const void* aux) {
1055 return ErrorCode(fnc, aux, true /* Safe Trap */);
1058 ErrorCode SandboxBPF::UnsafeTrap(Trap::TrapFnc fnc, const void* aux) {
1059 return ErrorCode(fnc, aux, false /* Unsafe Trap */);
1062 bool SandboxBPF::IsRequiredForUnsafeTrap(int sysno) {
1063 for (size_t i = 0; i < arraysize(kSyscallsRequiredForUnsafeTraps); ++i) {
1064 if (sysno == kSyscallsRequiredForUnsafeTraps[i]) {
1071 intptr_t SandboxBPF::ForwardSyscall(const struct arch_seccomp_data& args) {
1072 return Syscall::Call(args.nr,
1073 static_cast<intptr_t>(args.args[0]),
1074 static_cast<intptr_t>(args.args[1]),
1075 static_cast<intptr_t>(args.args[2]),
1076 static_cast<intptr_t>(args.args[3]),
1077 static_cast<intptr_t>(args.args[4]),
1078 static_cast<intptr_t>(args.args[5]));
1081 ErrorCode SandboxBPF::CondMaskedEqual(int argno,
1082 ErrorCode::ArgType width,
1085 const ErrorCode& passed,
1086 const ErrorCode& failed) {
1087 return ErrorCode(argno,
1091 &*conds_->insert(passed).first,
1092 &*conds_->insert(failed).first);
1095 ErrorCode SandboxBPF::Cond(int argno,
1096 ErrorCode::ArgType width,
1097 ErrorCode::Operation op,
1099 const ErrorCode& passed,
1100 const ErrorCode& failed) {
1101 // CondExpression() currently rejects mask==0 as invalid, but there are
1102 // SandboxBPF unit tests that (questionably) expect OP_HAS_{ANY,ALL}_BITS to
1103 // work with value==0. To keep those tests working for now, we specially
1104 // convert value==0 here.
1107 case ErrorCode::OP_EQUAL: {
1108 // Convert to "(arg & ~0) == value".
1109 const uint64_t mask = (width == ErrorCode::TP_64BIT)
1110 ? std::numeric_limits<uint64_t>::max()
1111 : std::numeric_limits<uint32_t>::max();
1112 return CondMaskedEqual(argno, width, mask, value, passed, failed);
1115 case ErrorCode::OP_HAS_ALL_BITS:
1120 // Convert to "(arg & value) == value".
1121 return CondMaskedEqual(argno, width, value, value, passed, failed);
1123 case ErrorCode::OP_HAS_ANY_BITS:
1128 // Convert to "(arg & value) == 0", but swap passed and failed.
1129 return CondMaskedEqual(argno, width, value, 0, failed, passed);
1132 SANDBOX_DIE("Not implemented");
1136 ErrorCode SandboxBPF::Kill(const char* msg) {
1137 return Trap(BPFFailure, const_cast<char*>(msg));
1140 SandboxBPF::SandboxStatus SandboxBPF::status_ = STATUS_UNKNOWN;
1142 } // namespace sandbox