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>
16 #include <sys/prctl.h>
18 #include <sys/syscall.h>
19 #include <sys/types.h>
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"
38 const int kExpectedExitCode = 100;
40 int popcount(uint32_t x) {
41 return __builtin_popcount(x);
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))) {
56 #endif // !defined(NDEBUG)
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 {
63 virtual ErrorCode EvaluateSyscall(SandboxBPF*, int sysnum) const OVERRIDE {
66 // Return EPERM so that we can check that the filter actually ran.
67 return ErrorCode(EPERM);
69 // Allow exit() with a non-default return code.
70 return ErrorCode(ErrorCode::ERR_ALLOWED);
72 // Make everything else fail in an easily recognizable way.
73 return ErrorCode(EINVAL);
78 DISALLOW_COPY_AND_ASSIGN(ProbePolicy);
81 void ProbeProcess(void) {
82 if (syscall(__NR_getpid) < 0 && errno == EPERM) {
83 syscall(__NR_exit_group, static_cast<intptr_t>(kExpectedExitCode));
87 class AllowAllPolicy : public SandboxBPFPolicy {
90 virtual ErrorCode EvaluateSyscall(SandboxBPF*, int sysnum) const OVERRIDE {
91 DCHECK(SandboxBPF::IsValidSyscallNumber(sysnum));
92 return ErrorCode(ErrorCode::ERR_ALLOWED);
96 DISALLOW_COPY_AND_ASSIGN(AllowAllPolicy);
99 void TryVsyscallProcess(void) {
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(¤t_time) != static_cast<time_t>(-1)) {
105 syscall(__NR_exit_group, static_cast<intptr_t>(kExpectedExitCode));
109 bool IsSingleThreaded(int proc_fd) {
111 // Cannot determine whether program is single-threaded. Hope for
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))) {
121 if (IGNORE_EINTR(close(task))) {
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));
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);
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()) {
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;
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();
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 {
191 explicit RedirectToUserSpacePolicyWrapper(
192 const SandboxBPFPolicy* wrapped_policy)
193 : wrapped_policy_(wrapped_policy) {
194 DCHECK(wrapped_policy_);
197 virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox_compiler,
198 int system_call_number) const OVERRIDE {
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);
207 virtual ErrorCode InvalidSyscall(
208 SandboxBPF* sandbox_compiler) const OVERRIDE {
209 return ReturnErrnoViaTrap(sandbox_compiler, ENOSYS);
213 ErrorCode ReturnErrnoViaTrap(SandboxBPF* sandbox_compiler, int err) const {
214 return sandbox_compiler->Trap(ReturnErrno, reinterpret_cast<void*>(err));
217 const SandboxBPFPolicy* wrapped_policy_;
218 DISALLOW_COPY_AND_ASSIGN(RedirectToUserSpacePolicyWrapper);
221 intptr_t BPFFailure(const struct arch_seccomp_data&, void* aux) {
222 SANDBOX_DIE(static_cast<char*>(aux));
227 SandboxBPF::SandboxBPF()
231 sandbox_has_started_(false) {}
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.
250 bool SandboxBPF::IsValidSyscallNumber(int sysnum) {
251 return SyscallIterator::IsValid(sysnum);
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");
263 if (pipe2(fds, O_NONBLOCK | O_CLOEXEC)) {
264 SANDBOX_DIE("pipe() failed");
267 if (fds[0] <= 2 || fds[1] <= 2) {
268 SANDBOX_DIE("Process started without standard file descriptors");
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_));
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
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");
287 // In the child process
289 // Test a very simple sandbox policy to verify that we can
290 // successfully turn on sandboxing.
291 Die::EnableSimpleExit();
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.
298 WriteFailedStderrSetupMessage(fds[1]);
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
311 // In DEBUG builds, we still want to get a report.
312 WriteFailedStderrSetupMessage(fds[1]);
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.
320 WriteFailedStderrSetupMessage(fds[1]);
325 SetSandboxPolicy(policy.release());
326 if (!StartSandbox(PROCESS_SINGLE_THREADED)) {
330 // Run our code in the sandbox.
333 // code_in_sandbox() is not supposed to return here.
337 // In the parent process.
338 if (IGNORE_EINTR(close(fds[1]))) {
339 SANDBOX_DIE("close() failed");
341 if (sigprocmask(SIG_SETMASK, &old_mask, NULL)) {
342 SANDBOX_DIE("sigprocmask() failed");
345 if (HANDLE_EINTR(waitpid(pid, &status, 0)) != pid) {
346 SANDBOX_DIE("waitpid() failed unexpectedly");
348 bool rc = WIFEXITED(status) && WEXITSTATUS(status) == kExpectedExitCode;
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
357 ssize_t len = HANDLE_EINTR(read(fds[0], buf, sizeof(buf) - 1));
359 while (len > 1 && buf[len - 1] == '\n') {
366 if (IGNORE_EINTR(close(fds[0]))) {
367 SANDBOX_DIE("close() failed");
373 bool SandboxBPF::KernelSupportSeccompBPF() {
374 return RunFunctionInPolicy(ProbeProcess,
375 scoped_ptr<SandboxBPFPolicy>(new ProbePolicy())) &&
378 scoped_ptr<SandboxBPFPolicy>(new AllowAllPolicy()));
381 SandboxBPF::SandboxStatus SandboxBPF::SupportsSeccompSandbox(int proc_fd) {
382 // It the sandbox is currently active, we clearly must have support for
384 if (status_ == STATUS_ENABLED) {
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;
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-
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;
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()".
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;
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;
436 void SandboxBPF::set_proc_fd(int proc_fd) { proc_fd_ = proc_fd; }
438 bool SandboxBPF::StartSandbox(SandboxThreadState thread_state) {
439 CHECK(thread_state == PROCESS_SINGLE_THREADED ||
440 thread_state == PROCESS_MULTI_THREADED);
442 if (status_ == STATUS_UNSUPPORTED || status_ == STATUS_UNAVAILABLE) {
444 "Trying to start sandbox, even though it is known to be "
447 } else if (sandbox_has_started_ || !conds_) {
449 "Cannot repeatedly start sandbox. Create a separate Sandbox "
454 proc_fd_ = open("/proc", O_RDONLY | O_DIRECTORY);
457 // For now, continue in degraded mode, if we can't access /proc.
458 // In the future, we might want to tighten this requirement.
461 if (thread_state == PROCESS_SINGLE_THREADED && !IsSingleThreaded(proc_fd_)) {
462 SANDBOX_DIE("Cannot start sandbox, if process is already multi-threaded");
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
470 if (IGNORE_EINTR(close(proc_fd_))) {
471 SANDBOX_DIE("Failed to close file descriptor for /proc");
477 // Install the filters.
478 InstallFilter(thread_state);
480 // We are now inside the sandbox.
481 status_ = STATUS_ENABLED;
486 void SandboxBPF::PolicySanityChecks(SandboxBPFPolicy* policy) {
487 if (!IsDenied(policy->InvalidSyscall(this))) {
488 SANDBOX_DIE("Policies should deny invalid system calls.");
493 // Don't take a scoped_ptr here, polymorphism make their use awkward.
494 void SandboxBPF::SetSandboxPolicy(SandboxBPFPolicy* policy) {
496 if (sandbox_has_started_ || !conds_) {
497 SANDBOX_DIE("Cannot change policy after sandbox has started");
499 PolicySanityChecks(policy);
500 policy_.reset(policy);
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 */);
517 struct sock_filter bpf[program->size()];
518 const struct sock_fprog prog = {static_cast<unsigned short>(program->size()),
520 memcpy(bpf, &(*program)[0], sizeof(bpf));
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.
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");
534 if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)) {
535 SANDBOX_DIE(quiet_ ? NULL : "Kernel refuses to turn on BPF filters");
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.
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 "
555 sandbox_has_started_ = true;
558 SandboxBPF::Program* SandboxBPF::AssembleFilter(bool force_verification) {
560 force_verification = true;
563 // Verify that the user pushed a policy.
566 // Assemble the BPF filter program.
567 CodeGen* gen = new CodeGen();
569 SANDBOX_DIE("Out of memory");
572 // If the architecture doesn't match SECCOMP_ARCH, disallow the
575 Instruction* head = gen->MakeInstruction(
576 BPF_LD + BPF_W + BPF_ABS,
578 tail = gen->MakeInstruction(
579 BPF_JMP + BPF_JEQ + BPF_K,
582 gen->MakeInstruction(
584 Kill("Invalid audit architecture in BPF filter"))));
586 bool has_unsafe_traps = false;
588 // Evaluate all possible system calls and group their ErrorCodes into
589 // ranges of identical codes.
593 // Compile the system call ranges to an optimized BPF jumptable
594 Instruction* jumptable =
595 AssembleJumpTable(gen, ranges.begin(), ranges.end());
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
602 gen->Traverse(jumptable, CheckForUnsafeErrorCodes, &has_unsafe_traps);
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);
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) {
618 "Support for UnsafeTrap() has not yet been ported to this "
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)
628 !policy_->EvaluateSyscall(this, __NR_sigprocmask)
629 .Equals(ErrorCode(ErrorCode::ERR_ALLOWED))
631 #if defined(__NR_sigreturn)
633 !policy_->EvaluateSyscall(this, __NR_sigreturn)
634 .Equals(ErrorCode(ErrorCode::ERR_ALLOWED))
638 "Invalid seccomp policy; if using UnsafeTrap(), you must "
639 "unconditionally allow sigreturn() and sigprocmask()");
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");
650 gen->Traverse(jumptable, RedirectToUserspace, this);
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);
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,
667 gen->MakeInstruction(
668 BPF_JMP + BPF_JEQ + BPF_K,
670 #if __SIZEOF_POINTER__ > 4
671 gen->MakeInstruction(
672 BPF_LD + BPF_W + BPF_ABS,
674 gen->MakeInstruction(
675 BPF_JMP + BPF_JEQ + BPF_K,
678 gen->MakeInstruction(BPF_RET + BPF_K,
679 ErrorCode(ErrorCode::ERR_ALLOWED)),
680 #if __SIZEOF_POINTER__ > 4
684 gen->JoinInstructions(tail, escape_hatch);
686 gen->JoinInstructions(tail, load_nr);
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);
701 gen->MakeInstruction(
702 BPF_JMP + BPF_JSET + BPF_K, 0x40000000, invalidX32, 0);
704 gen->JoinInstructions(tail, checkX32);
708 // Append jump table to our pre-amble
709 gen->JoinInstructions(tail, jumptable);
712 // Turn the DAG into a vector of instructions.
713 Program* program = new Program();
714 gen->Compile(head, program);
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
724 VerifyProgram(*program, has_unsafe_traps);
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()));
738 const char* err = NULL;
739 if (!Verifier::VerifyBPF(this,
741 has_unsafe_traps ? *redirected_policy : *policy_,
743 CodeGen::PrintProgram(program);
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)
760 for (SyscallIterator iter(false); !iter.Done();) {
761 uint32_t sysnum = iter.Next();
763 IsValidSyscallNumber(sysnum)
764 ? policy_->EvaluateSyscall(this, static_cast<int>(sysnum))
766 if (!err.Equals(old_err) || iter.Done()) {
767 ranges->push_back(Range(old_sysnum, sysnum - 1, old_err));
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);
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;
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);
801 Instruction* SandboxBPF::RetExpression(CodeGen* gen, const ErrorCode& err) {
802 if (err.error_type_ == ErrorCode::ET_COND) {
803 return CondExpression(gen, err);
805 return gen->MakeInstruction(BPF_RET + BPF_K, err);
809 Instruction* SandboxBPF::CondExpression(CodeGen* gen, const ErrorCode& cond) {
810 // We can only inspect the six system call arguments that are passed in
812 if (cond.argno_ < 0 || cond.argno_ >= 6) {
814 "Internal compiler error; invalid argument number "
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;
827 // Emit a suitable comparison statement.
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);
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) {
841 gen->MakeInstruction(BPF_JMP + BPF_JEQ + BPF_K,
842 static_cast<uint32_t>(cond.value_ >> 32),
844 RetExpression(gen, *cond.failed_));
845 gen->JoinInstructions(msb_head, msb_tail);
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
853 // Of course, if there is only a single set bit (or none at all), then
854 // things get easier.
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_);
862 } else if (lsb_bit_count == 1) {
863 // Exactly one bit is set in the LSB half. We can use the BPF_JSET
865 lsb_tail = gen->MakeInstruction(BPF_JMP + BPF_JSET + BPF_K,
867 RetExpression(gen, *cond.passed_),
868 RetExpression(gen, *cond.failed_));
869 gen->JoinInstructions(lsb_head, lsb_tail);
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(
876 gen->MakeInstruction(BPF_ALU + BPF_AND + BPF_K,
878 lsb_tail = gen->MakeInstruction(
879 BPF_JMP + BPF_JEQ + BPF_K,
881 RetExpression(gen, *cond.passed_),
882 RetExpression(gen, *cond.failed_))));
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.
894 } else if (msb_bit_count == 1) {
895 // Exactly one bit is set in the MSB half. We can use the BPF_JSET
897 msb_tail = gen->MakeInstruction(BPF_JMP + BPF_JSET + BPF_K,
900 RetExpression(gen, *cond.failed_));
901 gen->JoinInstructions(msb_head, msb_tail);
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(
908 gen->MakeInstruction(
909 BPF_ALU + BPF_AND + BPF_K,
911 gen->MakeInstruction(BPF_JMP + BPF_JEQ + BPF_K,
914 RetExpression(gen, *cond.failed_))));
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.
923 uint32_t lsb_bits = static_cast<uint32_t>(cond.value_);
925 // No bits are set in the LSB half. The test will always fail.
926 lsb_head = RetExpression(gen, *cond.failed_);
929 lsb_tail = gen->MakeInstruction(BPF_JMP + BPF_JSET + BPF_K,
931 RetExpression(gen, *cond.passed_),
932 RetExpression(gen, *cond.failed_));
933 gen->JoinInstructions(lsb_head, lsb_tail);
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);
942 // No bits are set in the MSB half. The test will always fail.
945 msb_tail = gen->MakeInstruction(BPF_JMP + BPF_JSET + BPF_K,
947 RetExpression(gen, *cond.passed_),
949 gen->JoinInstructions(msb_head, msb_tail);
954 // TODO(markus): Need to add support for OP_GREATER
955 SANDBOX_DIE("Not implemented");
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) {
966 "Invalid comparison of a 32bit system call argument "
967 "against a 64bit constant; this test is always false.");
970 Instruction* invalid_64bit = RetExpression(gen, Unexpected64bitArgument());
971 #if __SIZEOF_POINTER__ > 4
972 invalid_64bit = gen->MakeInstruction(
973 BPF_JMP + BPF_JEQ + BPF_K,
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,
983 gen->JoinInstructions(
985 gen->MakeInstruction(
986 BPF_JMP + BPF_JEQ + BPF_K, 0, lsb_head, invalid_64bit));
992 ErrorCode SandboxBPF::Unexpected64bitArgument() {
993 return Kill("Unexpected 64bit argument detected");
996 ErrorCode SandboxBPF::Trap(Trap::TrapFnc fnc, const void* aux) {
997 return Trap::MakeTrap(fnc, aux, true /* Safe Trap */);
1000 ErrorCode SandboxBPF::UnsafeTrap(Trap::TrapFnc fnc, const void* aux) {
1001 return Trap::MakeTrap(fnc, aux, false /* Unsafe Trap */);
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]));
1014 ErrorCode SandboxBPF::Cond(int argno,
1015 ErrorCode::ArgType width,
1016 ErrorCode::Operation op,
1018 const ErrorCode& passed,
1019 const ErrorCode& failed) {
1020 return ErrorCode(argno,
1024 &*conds_->insert(passed).first,
1025 &*conds_->insert(failed).first);
1028 ErrorCode SandboxBPF::Kill(const char* msg) {
1029 return Trap(BPFFailure, const_cast<char*>(msg));
1032 SandboxBPF::SandboxStatus SandboxBPF::status_ = STATUS_UNKNOWN;
1034 } // namespace sandbox