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.
10 #include <sys/ptrace.h>
11 #include <sys/syscall.h>
13 #include <sys/types.h>
14 #include <sys/utsname.h>
16 #include <sys/socket.h>
19 // Work-around for buggy headers in Android's NDK
22 #include <linux/futex.h>
26 #include "base/bind.h"
27 #include "base/logging.h"
28 #include "base/macros.h"
29 #include "base/memory/scoped_ptr.h"
30 #include "base/posix/eintr_wrapper.h"
31 #include "build/build_config.h"
32 #include "sandbox/linux/seccomp-bpf/bpf_tests.h"
33 #include "sandbox/linux/seccomp-bpf/syscall.h"
34 #include "sandbox/linux/seccomp-bpf/trap.h"
35 #include "sandbox/linux/seccomp-bpf/verifier.h"
36 #include "sandbox/linux/services/broker_process.h"
37 #include "sandbox/linux/services/linux_syscalls.h"
38 #include "sandbox/linux/tests/scoped_temporary_file.h"
39 #include "sandbox/linux/tests/unit_tests.h"
40 #include "testing/gtest/include/gtest/gtest.h"
42 // Workaround for Android's prctl.h file.
44 #define PR_GET_ENDIAN 19
46 #ifndef PR_CAPBSET_READ
47 #define PR_CAPBSET_READ 23
48 #define PR_CAPBSET_DROP 24
55 const int kExpectedReturnValue = 42;
56 const char kSandboxDebuggingEnv[] = "CHROME_SANDBOX_DEBUGGING";
58 // Set the global environment to allow the use of UnsafeTrap() policies.
59 void EnableUnsafeTraps() {
60 // The use of UnsafeTrap() causes us to print a warning message. This is
61 // generally desirable, but it results in the unittest failing, as it doesn't
62 // expect any messages on "stderr". So, temporarily disable messages. The
63 // BPF_TEST() is guaranteed to turn messages back on, after the policy
64 // function has completed.
65 setenv(kSandboxDebuggingEnv, "t", 0);
66 Die::SuppressInfoMessages(true);
69 // This test should execute no matter whether we have kernel support. So,
70 // we make it a TEST() instead of a BPF_TEST().
71 TEST(SandboxBPF, DISABLE_ON_TSAN(CallSupports)) {
72 // We check that we don't crash, but it's ok if the kernel doesn't
74 bool seccomp_bpf_supported =
75 SandboxBPF::SupportsSeccompSandbox(-1) == SandboxBPF::STATUS_AVAILABLE;
76 // We want to log whether or not seccomp BPF is actually supported
77 // since actual test coverage depends on it.
78 RecordProperty("SeccompBPFSupported",
79 seccomp_bpf_supported ? "true." : "false.");
80 std::cout << "Seccomp BPF supported: "
81 << (seccomp_bpf_supported ? "true." : "false.") << "\n";
82 RecordProperty("PointerSize", sizeof(void*));
83 std::cout << "Pointer size: " << sizeof(void*) << "\n";
86 SANDBOX_TEST(SandboxBPF, DISABLE_ON_TSAN(CallSupportsTwice)) {
87 SandboxBPF::SupportsSeccompSandbox(-1);
88 SandboxBPF::SupportsSeccompSandbox(-1);
91 // BPF_TEST does a lot of the boiler-plate code around setting up a
92 // policy and optional passing data between the caller, the policy and
93 // any Trap() handlers. This is great for writing short and concise tests,
94 // and it helps us accidentally forgetting any of the crucial steps in
95 // setting up the sandbox. But it wouldn't hurt to have at least one test
96 // that explicitly walks through all these steps.
98 intptr_t IncreaseCounter(const struct arch_seccomp_data& args, void* aux) {
100 int* counter = static_cast<int*>(aux);
104 class VerboseAPITestingPolicy : public SandboxBPFPolicy {
106 VerboseAPITestingPolicy(int* counter_ptr) : counter_ptr_(counter_ptr) {}
108 virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
109 int sysno) const OVERRIDE {
110 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
111 if (sysno == __NR_uname) {
112 return sandbox->Trap(IncreaseCounter, counter_ptr_);
114 return ErrorCode(ErrorCode::ERR_ALLOWED);
119 DISALLOW_COPY_AND_ASSIGN(VerboseAPITestingPolicy);
122 SANDBOX_TEST(SandboxBPF, DISABLE_ON_TSAN(VerboseAPITesting)) {
123 if (SandboxBPF::SupportsSeccompSandbox(-1) ==
124 sandbox::SandboxBPF::STATUS_AVAILABLE) {
125 static int counter = 0;
128 sandbox.SetSandboxPolicy(new VerboseAPITestingPolicy(&counter));
129 BPF_ASSERT(sandbox.StartSandbox(SandboxBPF::PROCESS_SINGLE_THREADED));
131 BPF_ASSERT_EQ(0, counter);
132 BPF_ASSERT_EQ(0, syscall(__NR_uname, 0));
133 BPF_ASSERT_EQ(1, counter);
134 BPF_ASSERT_EQ(1, syscall(__NR_uname, 0));
135 BPF_ASSERT_EQ(2, counter);
139 // A simple blacklist test
141 class BlacklistNanosleepPolicy : public SandboxBPFPolicy {
143 BlacklistNanosleepPolicy() {}
144 virtual ErrorCode EvaluateSyscall(SandboxBPF*, int sysno) const OVERRIDE {
145 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
148 return ErrorCode(EACCES);
150 return ErrorCode(ErrorCode::ERR_ALLOWED);
155 DISALLOW_COPY_AND_ASSIGN(BlacklistNanosleepPolicy);
158 BPF_TEST_C(SandboxBPF, ApplyBasicBlacklistPolicy, BlacklistNanosleepPolicy) {
159 // nanosleep() should be denied
160 const struct timespec ts = {0, 0};
162 BPF_ASSERT(syscall(__NR_nanosleep, &ts, NULL) == -1);
163 BPF_ASSERT(errno == EACCES);
166 // Now do a simple whitelist test
168 class WhitelistGetpidPolicy : public SandboxBPFPolicy {
170 WhitelistGetpidPolicy() {}
171 virtual ErrorCode EvaluateSyscall(SandboxBPF*, int sysno) const OVERRIDE {
172 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
175 case __NR_exit_group:
176 return ErrorCode(ErrorCode::ERR_ALLOWED);
178 return ErrorCode(ENOMEM);
183 DISALLOW_COPY_AND_ASSIGN(WhitelistGetpidPolicy);
186 BPF_TEST_C(SandboxBPF, ApplyBasicWhitelistPolicy, WhitelistGetpidPolicy) {
187 // getpid() should be allowed
189 BPF_ASSERT(syscall(__NR_getpid) > 0);
190 BPF_ASSERT(errno == 0);
192 // getpgid() should be denied
193 BPF_ASSERT(getpgid(0) == -1);
194 BPF_ASSERT(errno == ENOMEM);
197 // A simple blacklist policy, with a SIGSYS handler
198 intptr_t EnomemHandler(const struct arch_seccomp_data& args, void* aux) {
199 // We also check that the auxiliary data is correct
201 *(static_cast<int*>(aux)) = kExpectedReturnValue;
205 ErrorCode BlacklistNanosleepPolicySigsys(SandboxBPF* sandbox,
208 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
211 return sandbox->Trap(EnomemHandler, aux);
213 return ErrorCode(ErrorCode::ERR_ALLOWED);
218 BasicBlacklistWithSigsys,
219 BlacklistNanosleepPolicySigsys,
220 int /* (*BPF_AUX) */) {
221 // getpid() should work properly
223 BPF_ASSERT(syscall(__NR_getpid) > 0);
224 BPF_ASSERT(errno == 0);
226 // Our Auxiliary Data, should be reset by the signal handler
228 const struct timespec ts = {0, 0};
229 BPF_ASSERT(syscall(__NR_nanosleep, &ts, NULL) == -1);
230 BPF_ASSERT(errno == ENOMEM);
232 // We expect the signal handler to modify AuxData
233 BPF_ASSERT(*BPF_AUX == kExpectedReturnValue);
236 // A simple test that verifies we can return arbitrary errno values.
238 class ErrnoTestPolicy : public SandboxBPFPolicy {
241 virtual ErrorCode EvaluateSyscall(SandboxBPF*, int sysno) const OVERRIDE;
244 DISALLOW_COPY_AND_ASSIGN(ErrnoTestPolicy);
247 ErrorCode ErrnoTestPolicy::EvaluateSyscall(SandboxBPF*, int sysno) const {
248 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
250 case __NR_dup3: // dup2 is a wrapper of dup3 in android
252 // Pretend that dup2() worked, but don't actually do anything.
255 #if defined(__NR_setuid32)
261 #if defined(__NR_setgid32)
264 // Return maximum errno value (typically 4095).
265 return ErrorCode(ErrorCode::ERR_MAX_ERRNO);
267 // Return errno = 42;
268 return ErrorCode(42);
270 return ErrorCode(ErrorCode::ERR_ALLOWED);
274 BPF_TEST_C(SandboxBPF, ErrnoTest, ErrnoTestPolicy) {
275 // Verify that dup2() returns success, but doesn't actually run.
277 BPF_ASSERT(pipe(fds) == 0);
278 BPF_ASSERT(pipe(fds + 2) == 0);
279 BPF_ASSERT(dup2(fds[2], fds[0]) == 0);
281 BPF_ASSERT(write(fds[1], "\x55", 1) == 1);
282 BPF_ASSERT(write(fds[3], "\xAA", 1) == 1);
283 BPF_ASSERT(read(fds[0], buf, 1) == 1);
285 // If dup2() executed, we will read \xAA, but it dup2() has been turned
286 // into a no-op by our policy, then we will read \x55.
287 BPF_ASSERT(buf[0] == '\x55');
289 // Verify that we can return the minimum and maximum errno values.
291 BPF_ASSERT(setuid(0) == -1);
292 BPF_ASSERT(errno == 1);
294 // On Android, errno is only supported up to 255, otherwise errno
295 // processing is skipped.
296 // We work around this (crbug.com/181647).
297 if (sandbox::IsAndroid() && setgid(0) != -1) {
299 BPF_ASSERT(setgid(0) == -ErrorCode::ERR_MAX_ERRNO);
300 BPF_ASSERT(errno == 0);
303 BPF_ASSERT(setgid(0) == -1);
304 BPF_ASSERT(errno == ErrorCode::ERR_MAX_ERRNO);
307 // Finally, test an errno in between the minimum and maximum.
309 struct utsname uts_buf;
310 BPF_ASSERT(uname(&uts_buf) == -1);
311 BPF_ASSERT(errno == 42);
314 // Testing the stacking of two sandboxes
316 class StackingPolicyPartOne : public SandboxBPFPolicy {
318 StackingPolicyPartOne() {}
319 virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
320 int sysno) const OVERRIDE {
321 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
324 return sandbox->Cond(0,
328 ErrorCode(ErrorCode::ERR_ALLOWED),
331 return ErrorCode(ErrorCode::ERR_ALLOWED);
336 DISALLOW_COPY_AND_ASSIGN(StackingPolicyPartOne);
339 class StackingPolicyPartTwo : public SandboxBPFPolicy {
341 StackingPolicyPartTwo() {}
342 virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
343 int sysno) const OVERRIDE {
344 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
347 return sandbox->Cond(0,
352 ErrorCode(ErrorCode::ERR_ALLOWED));
354 return ErrorCode(ErrorCode::ERR_ALLOWED);
359 DISALLOW_COPY_AND_ASSIGN(StackingPolicyPartTwo);
362 BPF_TEST_C(SandboxBPF, StackingPolicy, StackingPolicyPartOne) {
364 BPF_ASSERT(syscall(__NR_getppid, 0) > 0);
365 BPF_ASSERT(errno == 0);
367 BPF_ASSERT(syscall(__NR_getppid, 1) == -1);
368 BPF_ASSERT(errno == EPERM);
370 // Stack a second sandbox with its own policy. Verify that we can further
371 // restrict filters, but we cannot relax existing filters.
373 sandbox.SetSandboxPolicy(new StackingPolicyPartTwo());
374 BPF_ASSERT(sandbox.StartSandbox(SandboxBPF::PROCESS_SINGLE_THREADED));
377 BPF_ASSERT(syscall(__NR_getppid, 0) == -1);
378 BPF_ASSERT(errno == EINVAL);
380 BPF_ASSERT(syscall(__NR_getppid, 1) == -1);
381 BPF_ASSERT(errno == EPERM);
384 // A more complex, but synthetic policy. This tests the correctness of the BPF
385 // program by iterating through all syscalls and checking for an errno that
386 // depends on the syscall number. Unlike the Verifier, this exercises the BPF
387 // interpreter in the kernel.
389 // We try to make sure we exercise optimizations in the BPF compiler. We make
390 // sure that the compiler can have an opportunity to coalesce syscalls with
391 // contiguous numbers and we also make sure that disjoint sets can return the
393 int SysnoToRandomErrno(int sysno) {
394 // Small contiguous sets of 3 system calls return an errno equal to the
395 // index of that set + 1 (so that we never return a NUL errno).
396 return ((sysno & ~3) >> 2) % 29 + 1;
399 class SyntheticPolicy : public SandboxBPFPolicy {
402 virtual ErrorCode EvaluateSyscall(SandboxBPF*, int sysno) const OVERRIDE {
403 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
404 if (sysno == __NR_exit_group || sysno == __NR_write) {
405 // exit_group() is special, we really need it to work.
406 // write() is needed for BPF_ASSERT() to report a useful error message.
407 return ErrorCode(ErrorCode::ERR_ALLOWED);
409 return ErrorCode(SysnoToRandomErrno(sysno));
413 DISALLOW_COPY_AND_ASSIGN(SyntheticPolicy);
416 BPF_TEST_C(SandboxBPF, SyntheticPolicy, SyntheticPolicy) {
417 // Ensure that that kExpectedReturnValue + syscallnumber + 1 does not int
419 BPF_ASSERT(std::numeric_limits<int>::max() - kExpectedReturnValue - 1 >=
420 static_cast<int>(MAX_PUBLIC_SYSCALL));
422 for (int syscall_number = static_cast<int>(MIN_SYSCALL);
423 syscall_number <= static_cast<int>(MAX_PUBLIC_SYSCALL);
425 if (syscall_number == __NR_exit_group || syscall_number == __NR_write) {
426 // exit_group() is special
430 BPF_ASSERT(syscall(syscall_number) == -1);
431 BPF_ASSERT(errno == SysnoToRandomErrno(syscall_number));
436 // A simple policy that tests whether ARM private system calls are supported
437 // by our BPF compiler and by the BPF interpreter in the kernel.
439 // For ARM private system calls, return an errno equal to their offset from
440 // MIN_PRIVATE_SYSCALL plus 1 (to avoid NUL errno).
441 int ArmPrivateSysnoToErrno(int sysno) {
442 if (sysno >= static_cast<int>(MIN_PRIVATE_SYSCALL) &&
443 sysno <= static_cast<int>(MAX_PRIVATE_SYSCALL)) {
444 return (sysno - MIN_PRIVATE_SYSCALL) + 1;
450 class ArmPrivatePolicy : public SandboxBPFPolicy {
452 ArmPrivatePolicy() {}
453 virtual ErrorCode EvaluateSyscall(SandboxBPF*, int sysno) const OVERRIDE {
454 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
455 // Start from |__ARM_NR_set_tls + 1| so as not to mess with actual
456 // ARM private system calls.
457 if (sysno >= static_cast<int>(__ARM_NR_set_tls + 1) &&
458 sysno <= static_cast<int>(MAX_PRIVATE_SYSCALL)) {
459 return ErrorCode(ArmPrivateSysnoToErrno(sysno));
461 return ErrorCode(ErrorCode::ERR_ALLOWED);
465 DISALLOW_COPY_AND_ASSIGN(ArmPrivatePolicy);
468 BPF_TEST_C(SandboxBPF, ArmPrivatePolicy, ArmPrivatePolicy) {
469 for (int syscall_number = static_cast<int>(__ARM_NR_set_tls + 1);
470 syscall_number <= static_cast<int>(MAX_PRIVATE_SYSCALL);
473 BPF_ASSERT(syscall(syscall_number) == -1);
474 BPF_ASSERT(errno == ArmPrivateSysnoToErrno(syscall_number));
477 #endif // defined(__arm__)
479 intptr_t CountSyscalls(const struct arch_seccomp_data& args, void* aux) {
480 // Count all invocations of our callback function.
481 ++*reinterpret_cast<int*>(aux);
483 // Verify that within the callback function all filtering is temporarily
485 BPF_ASSERT(syscall(__NR_getpid) > 1);
487 // Verify that we can now call the underlying system call without causing
488 // infinite recursion.
489 return SandboxBPF::ForwardSyscall(args);
492 ErrorCode GreyListedPolicy(SandboxBPF* sandbox, int sysno, int* aux) {
493 // Set the global environment for unsafe traps once.
494 if (sysno == MIN_SYSCALL) {
498 // Some system calls must always be allowed, if our policy wants to make
499 // use of UnsafeTrap()
500 if (sysno == __NR_rt_sigprocmask || sysno == __NR_rt_sigreturn
501 #if defined(__NR_sigprocmask)
503 sysno == __NR_sigprocmask
505 #if defined(__NR_sigreturn)
507 sysno == __NR_sigreturn
510 return ErrorCode(ErrorCode::ERR_ALLOWED);
511 } else if (sysno == __NR_getpid) {
513 return ErrorCode(EPERM);
514 } else if (SandboxBPF::IsValidSyscallNumber(sysno)) {
515 // Allow (and count) all other system calls.
516 return sandbox->UnsafeTrap(CountSyscalls, aux);
518 return ErrorCode(ENOSYS);
522 BPF_TEST(SandboxBPF, GreyListedPolicy, GreyListedPolicy, int /* (*BPF_AUX) */) {
523 BPF_ASSERT(syscall(__NR_getpid) == -1);
524 BPF_ASSERT(errno == EPERM);
525 BPF_ASSERT(*BPF_AUX == 0);
526 BPF_ASSERT(syscall(__NR_geteuid) == syscall(__NR_getuid));
527 BPF_ASSERT(*BPF_AUX == 2);
529 BPF_ASSERT(!syscall(__NR_prctl,
535 BPF_ASSERT(*BPF_AUX == 3);
539 SANDBOX_TEST(SandboxBPF, EnableUnsafeTrapsInSigSysHandler) {
540 // Disabling warning messages that could confuse our test framework.
541 setenv(kSandboxDebuggingEnv, "t", 0);
542 Die::SuppressInfoMessages(true);
544 unsetenv(kSandboxDebuggingEnv);
545 SANDBOX_ASSERT(Trap::EnableUnsafeTrapsInSigSysHandler() == false);
546 setenv(kSandboxDebuggingEnv, "", 1);
547 SANDBOX_ASSERT(Trap::EnableUnsafeTrapsInSigSysHandler() == false);
548 setenv(kSandboxDebuggingEnv, "t", 1);
549 SANDBOX_ASSERT(Trap::EnableUnsafeTrapsInSigSysHandler() == true);
552 intptr_t PrctlHandler(const struct arch_seccomp_data& args, void*) {
553 if (args.args[0] == PR_CAPBSET_DROP && static_cast<int>(args.args[1]) == -1) {
554 // prctl(PR_CAPBSET_DROP, -1) is never valid. The kernel will always
555 // return an error. But our handler allows this call.
558 return SandboxBPF::ForwardSyscall(args);
562 class PrctlPolicy : public SandboxBPFPolicy {
565 virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
566 int sysno) const OVERRIDE {
567 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
568 setenv(kSandboxDebuggingEnv, "t", 0);
569 Die::SuppressInfoMessages(true);
571 if (sysno == __NR_prctl) {
572 // Handle prctl() inside an UnsafeTrap()
573 return sandbox->UnsafeTrap(PrctlHandler, NULL);
576 // Allow all other system calls.
577 return ErrorCode(ErrorCode::ERR_ALLOWED);
581 DISALLOW_COPY_AND_ASSIGN(PrctlPolicy);
584 BPF_TEST_C(SandboxBPF, ForwardSyscall, PrctlPolicy) {
585 // This call should never be allowed. But our policy will intercept it and
586 // let it pass successfully.
588 !prctl(PR_CAPBSET_DROP, -1, (void*)NULL, (void*)NULL, (void*)NULL));
590 // Verify that the call will fail, if it makes it all the way to the kernel.
592 prctl(PR_CAPBSET_DROP, -2, (void*)NULL, (void*)NULL, (void*)NULL) == -1);
594 // And verify that other uses of prctl() work just fine.
596 BPF_ASSERT(!syscall(__NR_prctl,
604 // Finally, verify that system calls other than prctl() are completely
605 // unaffected by our policy.
606 struct utsname uts = {};
607 BPF_ASSERT(!uname(&uts));
608 BPF_ASSERT(!strcmp(uts.sysname, "Linux"));
611 intptr_t AllowRedirectedSyscall(const struct arch_seccomp_data& args, void*) {
612 return SandboxBPF::ForwardSyscall(args);
615 class RedirectAllSyscallsPolicy : public SandboxBPFPolicy {
617 RedirectAllSyscallsPolicy() {}
618 virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
619 int sysno) const OVERRIDE;
622 DISALLOW_COPY_AND_ASSIGN(RedirectAllSyscallsPolicy);
625 ErrorCode RedirectAllSyscallsPolicy::EvaluateSyscall(SandboxBPF* sandbox,
627 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
628 setenv(kSandboxDebuggingEnv, "t", 0);
629 Die::SuppressInfoMessages(true);
631 // Some system calls must always be allowed, if our policy wants to make
632 // use of UnsafeTrap()
633 if (sysno == __NR_rt_sigprocmask || sysno == __NR_rt_sigreturn
634 #if defined(__NR_sigprocmask)
636 sysno == __NR_sigprocmask
638 #if defined(__NR_sigreturn)
640 sysno == __NR_sigreturn
643 return ErrorCode(ErrorCode::ERR_ALLOWED);
645 return sandbox->UnsafeTrap(AllowRedirectedSyscall, NULL);
648 int bus_handler_fd_ = -1;
650 void SigBusHandler(int, siginfo_t* info, void* void_context) {
651 BPF_ASSERT(write(bus_handler_fd_, "\x55", 1) == 1);
654 BPF_TEST_C(SandboxBPF, SigBus, RedirectAllSyscallsPolicy) {
655 // We use the SIGBUS bit in the signal mask as a thread-local boolean
656 // value in the implementation of UnsafeTrap(). This is obviously a bit
657 // of a hack that could conceivably interfere with code that uses SIGBUS
658 // in more traditional ways. This test verifies that basic functionality
659 // of SIGBUS is not impacted, but it is certainly possibly to construe
660 // more complex uses of signals where our use of the SIGBUS mask is not
661 // 100% transparent. This is expected behavior.
663 BPF_ASSERT(socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == 0);
664 bus_handler_fd_ = fds[1];
665 struct sigaction sa = {};
666 sa.sa_sigaction = SigBusHandler;
667 sa.sa_flags = SA_SIGINFO;
668 BPF_ASSERT(sigaction(SIGBUS, &sa, NULL) == 0);
671 BPF_ASSERT(read(fds[0], &c, 1) == 1);
672 BPF_ASSERT(close(fds[0]) == 0);
673 BPF_ASSERT(close(fds[1]) == 0);
674 BPF_ASSERT(c == 0x55);
677 BPF_TEST_C(SandboxBPF, SigMask, RedirectAllSyscallsPolicy) {
678 // Signal masks are potentially tricky to handle. For instance, if we
679 // ever tried to update them from inside a Trap() or UnsafeTrap() handler,
680 // the call to sigreturn() at the end of the signal handler would undo
681 // all of our efforts. So, it makes sense to test that sigprocmask()
682 // works, even if we have a policy in place that makes use of UnsafeTrap().
683 // In practice, this works because we force sigprocmask() to be handled
684 // entirely in the kernel.
685 sigset_t mask0, mask1, mask2;
687 // Call sigprocmask() to verify that SIGUSR2 wasn't blocked, if we didn't
688 // change the mask (it shouldn't have been, as it isn't blocked by default
691 // Use SIGUSR2 because Android seems to use SIGUSR1 for some purpose.
693 BPF_ASSERT(!sigprocmask(SIG_BLOCK, &mask0, &mask1));
694 BPF_ASSERT(!sigismember(&mask1, SIGUSR2));
696 // Try again, and this time we verify that we can block it. This
697 // requires a second call to sigprocmask().
698 sigaddset(&mask0, SIGUSR2);
699 BPF_ASSERT(!sigprocmask(SIG_BLOCK, &mask0, NULL));
700 BPF_ASSERT(!sigprocmask(SIG_BLOCK, NULL, &mask2));
701 BPF_ASSERT(sigismember(&mask2, SIGUSR2));
704 BPF_TEST_C(SandboxBPF, UnsafeTrapWithErrno, RedirectAllSyscallsPolicy) {
705 // An UnsafeTrap() (or for that matter, a Trap()) has to report error
706 // conditions by returning an exit code in the range -1..-4096. This
707 // should happen automatically if using ForwardSyscall(). If the TrapFnc()
708 // uses some other method to make system calls, then it is responsible
709 // for computing the correct return code.
710 // This test verifies that ForwardSyscall() does the correct thing.
712 // The glibc system wrapper will ultimately set errno for us. So, from normal
713 // userspace, all of this should be completely transparent.
715 BPF_ASSERT(close(-1) == -1);
716 BPF_ASSERT(errno == EBADF);
718 // Explicitly avoid the glibc wrapper. This is not normally the way anybody
719 // would make system calls, but it allows us to verify that we don't
720 // accidentally mess with errno, when we shouldn't.
722 struct arch_seccomp_data args = {};
723 args.nr = __NR_close;
725 BPF_ASSERT(SandboxBPF::ForwardSyscall(args) == -EBADF);
726 BPF_ASSERT(errno == 0);
729 bool NoOpCallback() { return true; }
731 // Test a trap handler that makes use of a broker process to open().
733 class InitializedOpenBroker {
735 InitializedOpenBroker() : initialized_(false) {
736 std::vector<std::string> allowed_files;
737 allowed_files.push_back("/proc/allowed");
738 allowed_files.push_back("/proc/cpuinfo");
740 broker_process_.reset(
741 new BrokerProcess(EPERM, allowed_files, std::vector<std::string>()));
742 BPF_ASSERT(broker_process() != NULL);
743 BPF_ASSERT(broker_process_->Init(base::Bind(&NoOpCallback)));
747 bool initialized() { return initialized_; }
748 class BrokerProcess* broker_process() { return broker_process_.get(); }
752 scoped_ptr<class BrokerProcess> broker_process_;
753 DISALLOW_COPY_AND_ASSIGN(InitializedOpenBroker);
756 intptr_t BrokerOpenTrapHandler(const struct arch_seccomp_data& args,
759 BrokerProcess* broker_process = static_cast<BrokerProcess*>(aux);
761 case __NR_faccessat: // access is a wrapper of faccessat in android
762 BPF_ASSERT(static_cast<int>(args.args[0]) == AT_FDCWD);
763 return broker_process->Access(reinterpret_cast<const char*>(args.args[1]),
764 static_cast<int>(args.args[2]));
766 return broker_process->Access(reinterpret_cast<const char*>(args.args[0]),
767 static_cast<int>(args.args[1]));
769 return broker_process->Open(reinterpret_cast<const char*>(args.args[0]),
770 static_cast<int>(args.args[1]));
772 // We only call open() so if we arrive here, it's because glibc uses
773 // the openat() system call.
774 BPF_ASSERT(static_cast<int>(args.args[0]) == AT_FDCWD);
775 return broker_process->Open(reinterpret_cast<const char*>(args.args[1]),
776 static_cast<int>(args.args[2]));
783 ErrorCode DenyOpenPolicy(SandboxBPF* sandbox,
785 InitializedOpenBroker* iob) {
786 if (!SandboxBPF::IsValidSyscallNumber(sysno)) {
787 return ErrorCode(ENOSYS);
795 // We get a InitializedOpenBroker class, but our trap handler wants
796 // the BrokerProcess object.
798 sandbox->Trap(BrokerOpenTrapHandler, iob->broker_process()));
800 return ErrorCode(ErrorCode::ERR_ALLOWED);
804 // We use a InitializedOpenBroker class, so that we can run unsandboxed
805 // code in its constructor, which is the only way to do so in a BPF_TEST.
809 InitializedOpenBroker /* (*BPF_AUX) */) {
810 BPF_ASSERT(BPF_AUX->initialized());
811 BrokerProcess* broker_process = BPF_AUX->broker_process();
812 BPF_ASSERT(broker_process != NULL);
814 // First, use the broker "manually"
815 BPF_ASSERT(broker_process->Open("/proc/denied", O_RDONLY) == -EPERM);
816 BPF_ASSERT(broker_process->Access("/proc/denied", R_OK) == -EPERM);
817 BPF_ASSERT(broker_process->Open("/proc/allowed", O_RDONLY) == -ENOENT);
818 BPF_ASSERT(broker_process->Access("/proc/allowed", R_OK) == -ENOENT);
820 // Now use glibc's open() as an external library would.
821 BPF_ASSERT(open("/proc/denied", O_RDONLY) == -1);
822 BPF_ASSERT(errno == EPERM);
824 BPF_ASSERT(open("/proc/allowed", O_RDONLY) == -1);
825 BPF_ASSERT(errno == ENOENT);
827 // Also test glibc's openat(), some versions of libc use it transparently
828 // instead of open().
829 BPF_ASSERT(openat(AT_FDCWD, "/proc/denied", O_RDONLY) == -1);
830 BPF_ASSERT(errno == EPERM);
832 BPF_ASSERT(openat(AT_FDCWD, "/proc/allowed", O_RDONLY) == -1);
833 BPF_ASSERT(errno == ENOENT);
835 // And test glibc's access().
836 BPF_ASSERT(access("/proc/denied", R_OK) == -1);
837 BPF_ASSERT(errno == EPERM);
839 BPF_ASSERT(access("/proc/allowed", R_OK) == -1);
840 BPF_ASSERT(errno == ENOENT);
842 // This is also white listed and does exist.
843 int cpu_info_access = access("/proc/cpuinfo", R_OK);
844 BPF_ASSERT(cpu_info_access == 0);
845 int cpu_info_fd = open("/proc/cpuinfo", O_RDONLY);
846 BPF_ASSERT(cpu_info_fd >= 0);
848 BPF_ASSERT(read(cpu_info_fd, buf, sizeof(buf)) > 0);
851 // Simple test demonstrating how to use SandboxBPF::Cond()
853 class SimpleCondTestPolicy : public SandboxBPFPolicy {
855 SimpleCondTestPolicy() {}
856 virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
857 int sysno) const OVERRIDE;
860 DISALLOW_COPY_AND_ASSIGN(SimpleCondTestPolicy);
863 ErrorCode SimpleCondTestPolicy::EvaluateSyscall(SandboxBPF* sandbox,
865 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
867 // We deliberately return unusual errno values upon failure, so that we
868 // can uniquely test for these values. In a "real" policy, you would want
869 // to return more traditional values.
870 int flags_argument_position = -1;
873 case __NR_openat: // open can be a wrapper for openat(2).
874 if (sysno == __NR_open) {
875 flags_argument_position = 1;
876 } else if (sysno == __NR_openat) {
877 flags_argument_position = 2;
879 // Allow opening files for reading, but don't allow writing.
880 COMPILE_ASSERT(O_RDONLY == 0, O_RDONLY_must_be_all_zero_bits);
881 return sandbox->Cond(flags_argument_position,
883 ErrorCode::OP_HAS_ANY_BITS,
886 ErrorCode(ErrorCode::ERR_ALLOWED));
888 // Allow prctl(PR_SET_DUMPABLE) and prctl(PR_GET_DUMPABLE), but
889 // disallow everything else.
890 return sandbox->Cond(0,
894 ErrorCode(ErrorCode::ERR_ALLOWED),
899 ErrorCode(ErrorCode::ERR_ALLOWED),
902 return ErrorCode(ErrorCode::ERR_ALLOWED);
906 BPF_TEST_C(SandboxBPF, SimpleCondTest, SimpleCondTestPolicy) {
908 BPF_ASSERT((fd = open("/proc/self/comm", O_RDWR)) == -1);
909 BPF_ASSERT(errno == EROFS);
910 BPF_ASSERT((fd = open("/proc/self/comm", O_RDONLY)) >= 0);
914 BPF_ASSERT((ret = prctl(PR_GET_DUMPABLE)) >= 0);
915 BPF_ASSERT(prctl(PR_SET_DUMPABLE, 1 - ret) == 0);
916 BPF_ASSERT(prctl(PR_GET_ENDIAN, &ret) == -1);
917 BPF_ASSERT(errno == ENOMEM);
920 // This test exercises the SandboxBPF::Cond() method by building a complex
921 // tree of conditional equality operations. It then makes system calls and
922 // verifies that they return the values that we expected from our BPF
924 class EqualityStressTest {
926 EqualityStressTest() {
927 // We want a deterministic test
930 // Iterates over system call numbers and builds a random tree of
932 // We are actually constructing a graph of ArgValue objects. This
933 // graph will later be used to a) compute our sandbox policy, and
934 // b) drive the code that verifies the output from the BPF program.
936 kNumTestCases < (int)(MAX_PUBLIC_SYSCALL - MIN_SYSCALL - 10),
937 num_test_cases_must_be_significantly_smaller_than_num_system_calls);
938 for (int sysno = MIN_SYSCALL, end = kNumTestCases; sysno < end; ++sysno) {
939 if (IsReservedSyscall(sysno)) {
940 // Skip reserved system calls. This ensures that our test frame
941 // work isn't impacted by the fact that we are overriding
942 // a lot of different system calls.
944 arg_values_.push_back(NULL);
946 arg_values_.push_back(
947 RandomArgValue(rand() % kMaxArgs, 0, rand() % kMaxArgs));
952 ~EqualityStressTest() {
953 for (std::vector<ArgValue*>::iterator iter = arg_values_.begin();
954 iter != arg_values_.end();
956 DeleteArgValue(*iter);
960 ErrorCode Policy(SandboxBPF* sandbox, int sysno) {
961 if (!SandboxBPF::IsValidSyscallNumber(sysno)) {
962 // FIXME: we should really not have to do that in a trivial policy
963 return ErrorCode(ENOSYS);
964 } else if (sysno < 0 || sysno >= (int)arg_values_.size() ||
965 IsReservedSyscall(sysno)) {
966 // We only return ErrorCode values for the system calls that
967 // are part of our test data. Every other system call remains
969 return ErrorCode(ErrorCode::ERR_ALLOWED);
971 // ToErrorCode() turns an ArgValue object into an ErrorCode that is
972 // suitable for use by a sandbox policy.
973 return ToErrorCode(sandbox, arg_values_[sysno]);
977 void VerifyFilter() {
978 // Iterate over all system calls. Skip the system calls that have
979 // previously been determined as being reserved.
980 for (int sysno = 0; sysno < (int)arg_values_.size(); ++sysno) {
981 if (!arg_values_[sysno]) {
982 // Skip reserved system calls.
985 // Verify that system calls return the values that we expect them to
986 // return. This involves passing different combinations of system call
987 // parameters in order to exercise all possible code paths through the
988 // BPF filter program.
989 // We arbitrarily start by setting all six system call arguments to
990 // zero. And we then recursive traverse our tree of ArgValues to
991 // determine the necessary combinations of parameters.
992 intptr_t args[6] = {};
993 Verify(sysno, args, *arg_values_[sysno]);
999 int argno; // Argument number to inspect.
1000 int size; // Number of test cases (must be > 0).
1002 uint32_t k_value; // Value to compare syscall arg against.
1003 int err; // If non-zero, errno value to return.
1004 struct ArgValue* arg_value; // Otherwise, more args needs inspecting.
1006 int err; // If none of the tests passed, this is what
1007 struct ArgValue* arg_value; // we'll return (this is the "else" branch).
1010 bool IsReservedSyscall(int sysno) {
1011 // There are a handful of system calls that we should never use in our
1012 // test cases. These system calls are needed to allow the test framework
1014 // If we wanted to write fully generic code, there are more system calls
1015 // that could be listed here, and it is quite difficult to come up with a
1016 // truly comprehensive list. After all, we are deliberately making system
1017 // calls unavailable. In practice, we have a pretty good idea of the system
1018 // calls that will be made by this particular test. So, this small list is
1019 // sufficient. But if anybody copy'n'pasted this code for other uses, they
1020 // would have to review that the list.
1021 return sysno == __NR_read || sysno == __NR_write || sysno == __NR_exit ||
1022 sysno == __NR_exit_group || sysno == __NR_restart_syscall;
1025 ArgValue* RandomArgValue(int argno, int args_mask, int remaining_args) {
1026 // Create a new ArgValue and fill it with random data. We use as bit mask
1027 // to keep track of the system call parameters that have previously been
1028 // set; this ensures that we won't accidentally define a contradictory
1029 // set of equality tests.
1030 struct ArgValue* arg_value = new ArgValue();
1031 args_mask |= 1 << argno;
1032 arg_value->argno = argno;
1034 // Apply some restrictions on just how complex our tests can be.
1035 // Otherwise, we end up with a BPF program that is too complicated for
1036 // the kernel to load.
1037 int fan_out = kMaxFanOut;
1038 if (remaining_args > 3) {
1040 } else if (remaining_args > 2) {
1044 // Create a couple of different test cases with randomized values that
1045 // we want to use when comparing system call parameter number "argno".
1046 arg_value->size = rand() % fan_out + 1;
1047 arg_value->tests = new ArgValue::Tests[arg_value->size];
1049 uint32_t k_value = rand();
1050 for (int n = 0; n < arg_value->size; ++n) {
1051 // Ensure that we have unique values
1052 k_value += rand() % (RAND_MAX / (kMaxFanOut + 1)) + 1;
1054 // There are two possible types of nodes. Either this is a leaf node;
1055 // in that case, we have completed all the equality tests that we
1056 // wanted to perform, and we can now compute a random "errno" value that
1057 // we should return. Or this is part of a more complex boolean
1058 // expression; in that case, we have to recursively add tests for some
1059 // of system call parameters that we have not yet included in our
1061 arg_value->tests[n].k_value = k_value;
1062 if (!remaining_args || (rand() & 1)) {
1063 arg_value->tests[n].err = (rand() % 1000) + 1;
1064 arg_value->tests[n].arg_value = NULL;
1066 arg_value->tests[n].err = 0;
1067 arg_value->tests[n].arg_value =
1068 RandomArgValue(RandomArg(args_mask), args_mask, remaining_args - 1);
1071 // Finally, we have to define what we should return if none of the
1072 // previous equality tests pass. Again, we can either deal with a leaf
1073 // node, or we can randomly add another couple of tests.
1074 if (!remaining_args || (rand() & 1)) {
1075 arg_value->err = (rand() % 1000) + 1;
1076 arg_value->arg_value = NULL;
1079 arg_value->arg_value =
1080 RandomArgValue(RandomArg(args_mask), args_mask, remaining_args - 1);
1082 // We have now built a new (sub-)tree of ArgValues defining a set of
1083 // boolean expressions for testing random system call arguments against
1084 // random values. Return this tree to our caller.
1088 int RandomArg(int args_mask) {
1089 // Compute a random system call parameter number.
1090 int argno = rand() % kMaxArgs;
1092 // Make sure that this same parameter number has not previously been
1093 // used. Otherwise, we could end up with a test that is impossible to
1094 // satisfy (e.g. args[0] == 1 && args[0] == 2).
1095 while (args_mask & (1 << argno)) {
1096 argno = (argno + 1) % kMaxArgs;
1101 void DeleteArgValue(ArgValue* arg_value) {
1102 // Delete an ArgValue and all of its child nodes. This requires
1103 // recursively descending into the tree.
1105 if (arg_value->size) {
1106 for (int n = 0; n < arg_value->size; ++n) {
1107 if (!arg_value->tests[n].err) {
1108 DeleteArgValue(arg_value->tests[n].arg_value);
1111 delete[] arg_value->tests;
1113 if (!arg_value->err) {
1114 DeleteArgValue(arg_value->arg_value);
1120 ErrorCode ToErrorCode(SandboxBPF* sandbox, ArgValue* arg_value) {
1121 // Compute the ErrorCode that should be returned, if none of our
1122 // tests succeed (i.e. the system call parameter doesn't match any
1123 // of the values in arg_value->tests[].k_value).
1125 if (arg_value->err) {
1126 // If this was a leaf node, return the errno value that we expect to
1127 // return from the BPF filter program.
1128 err = ErrorCode(arg_value->err);
1130 // If this wasn't a leaf node yet, recursively descend into the rest
1131 // of the tree. This will end up adding a few more SandboxBPF::Cond()
1132 // tests to our ErrorCode.
1133 err = ToErrorCode(sandbox, arg_value->arg_value);
1136 // Now, iterate over all the test cases that we want to compare against.
1137 // This builds a chain of SandboxBPF::Cond() tests
1138 // (aka "if ... elif ... elif ... elif ... fi")
1139 for (int n = arg_value->size; n-- > 0;) {
1141 // Again, we distinguish between leaf nodes and subtrees.
1142 if (arg_value->tests[n].err) {
1143 matched = ErrorCode(arg_value->tests[n].err);
1145 matched = ToErrorCode(sandbox, arg_value->tests[n].arg_value);
1147 // For now, all of our tests are limited to 32bit.
1148 // We have separate tests that check the behavior of 32bit vs. 64bit
1149 // conditional expressions.
1150 err = sandbox->Cond(arg_value->argno,
1151 ErrorCode::TP_32BIT,
1152 ErrorCode::OP_EQUAL,
1153 arg_value->tests[n].k_value,
1160 void Verify(int sysno, intptr_t* args, const ArgValue& arg_value) {
1161 uint32_t mismatched = 0;
1162 // Iterate over all the k_values in arg_value.tests[] and verify that
1163 // we see the expected return values from system calls, when we pass
1164 // the k_value as a parameter in a system call.
1165 for (int n = arg_value.size; n-- > 0;) {
1166 mismatched += arg_value.tests[n].k_value;
1167 args[arg_value.argno] = arg_value.tests[n].k_value;
1168 if (arg_value.tests[n].err) {
1169 VerifyErrno(sysno, args, arg_value.tests[n].err);
1171 Verify(sysno, args, *arg_value.tests[n].arg_value);
1174 // Find a k_value that doesn't match any of the k_values in
1175 // arg_value.tests[]. In most cases, the current value of "mismatched"
1176 // would fit this requirement. But on the off-chance that it happens
1177 // to collide, we double-check.
1179 for (int n = arg_value.size; n-- > 0;) {
1180 if (mismatched == arg_value.tests[n].k_value) {
1185 // Now verify that we see the expected return value from system calls,
1186 // if we pass a value that doesn't match any of the conditions (i.e. this
1187 // is testing the "else" clause of the conditions).
1188 args[arg_value.argno] = mismatched;
1189 if (arg_value.err) {
1190 VerifyErrno(sysno, args, arg_value.err);
1192 Verify(sysno, args, *arg_value.arg_value);
1194 // Reset args[arg_value.argno]. This is not technically needed, but it
1195 // makes it easier to reason about the correctness of our tests.
1196 args[arg_value.argno] = 0;
1199 void VerifyErrno(int sysno, intptr_t* args, int err) {
1200 // We installed BPF filters that return different errno values
1201 // based on the system call number and the parameters that we decided
1202 // to pass in. Verify that this condition holds true.
1205 sysno, args[0], args[1], args[2], args[3], args[4], args[5]) ==
1209 // Vector of ArgValue trees. These trees define all the possible boolean
1210 // expressions that we want to turn into a BPF filter program.
1211 std::vector<ArgValue*> arg_values_;
1213 // Don't increase these values. We are pushing the limits of the maximum
1214 // BPF program that the kernel will allow us to load. If the values are
1215 // increased too much, the test will start failing.
1216 static const int kNumTestCases = 40;
1217 static const int kMaxFanOut = 3;
1218 static const int kMaxArgs = 6;
1221 ErrorCode EqualityStressTestPolicy(SandboxBPF* sandbox,
1223 EqualityStressTest* aux) {
1225 return aux->Policy(sandbox, sysno);
1228 BPF_TEST(SandboxBPF,
1230 EqualityStressTestPolicy,
1231 EqualityStressTest /* (*BPF_AUX) */) {
1232 BPF_AUX->VerifyFilter();
1235 class EqualityArgumentWidthPolicy : public SandboxBPFPolicy {
1237 EqualityArgumentWidthPolicy() {}
1238 virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
1239 int sysno) const OVERRIDE;
1242 DISALLOW_COPY_AND_ASSIGN(EqualityArgumentWidthPolicy);
1245 ErrorCode EqualityArgumentWidthPolicy::EvaluateSyscall(SandboxBPF* sandbox,
1247 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
1248 if (sysno == __NR_uname) {
1249 return sandbox->Cond(
1251 ErrorCode::TP_32BIT,
1252 ErrorCode::OP_EQUAL,
1255 ErrorCode::TP_32BIT,
1256 ErrorCode::OP_EQUAL,
1260 // The BPF compiler and the BPF interpreter in the kernel are
1261 // (mostly) agnostic of the host platform's word size. The compiler
1262 // will happily generate code that tests a 64bit value, and the
1263 // interpreter will happily perform this test.
1264 // But unless there is a kernel bug, there is no way for us to pass
1265 // in a 64bit quantity on a 32bit platform. The upper 32bits should
1266 // always be zero. So, this test should always evaluate as false on
1269 ErrorCode::TP_64BIT,
1270 ErrorCode::OP_EQUAL,
1271 0x55555555AAAAAAAAULL,
1275 return ErrorCode(ErrorCode::ERR_ALLOWED);
1278 BPF_TEST_C(SandboxBPF, EqualityArgumentWidth, EqualityArgumentWidthPolicy) {
1279 BPF_ASSERT(Syscall::Call(__NR_uname, 0, 0x55555555) == -1);
1280 BPF_ASSERT(Syscall::Call(__NR_uname, 0, 0xAAAAAAAA) == -2);
1281 #if __SIZEOF_POINTER__ > 4
1282 // On 32bit machines, there is no way to pass a 64bit argument through the
1283 // syscall interface. So, we have to skip the part of the test that requires
1285 BPF_ASSERT(Syscall::Call(__NR_uname, 1, 0x55555555AAAAAAAAULL) == -1);
1286 BPF_ASSERT(Syscall::Call(__NR_uname, 1, 0x5555555500000000ULL) == -2);
1287 BPF_ASSERT(Syscall::Call(__NR_uname, 1, 0x5555555511111111ULL) == -2);
1288 BPF_ASSERT(Syscall::Call(__NR_uname, 1, 0x11111111AAAAAAAAULL) == -2);
1290 BPF_ASSERT(Syscall::Call(__NR_uname, 1, 0x55555555) == -2);
1294 #if __SIZEOF_POINTER__ > 4
1295 // On 32bit machines, there is no way to pass a 64bit argument through the
1296 // syscall interface. So, we have to skip the part of the test that requires
1298 BPF_DEATH_TEST_C(SandboxBPF,
1299 EqualityArgumentUnallowed64bit,
1300 DEATH_MESSAGE("Unexpected 64bit argument detected"),
1301 EqualityArgumentWidthPolicy) {
1302 Syscall::Call(__NR_uname, 0, 0x5555555555555555ULL);
1306 class EqualityWithNegativeArgumentsPolicy : public SandboxBPFPolicy {
1308 EqualityWithNegativeArgumentsPolicy() {}
1309 virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
1310 int sysno) const OVERRIDE {
1311 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
1312 if (sysno == __NR_uname) {
1313 return sandbox->Cond(0,
1314 ErrorCode::TP_32BIT,
1315 ErrorCode::OP_EQUAL,
1320 return ErrorCode(ErrorCode::ERR_ALLOWED);
1324 DISALLOW_COPY_AND_ASSIGN(EqualityWithNegativeArgumentsPolicy);
1327 BPF_TEST_C(SandboxBPF,
1328 EqualityWithNegativeArguments,
1329 EqualityWithNegativeArgumentsPolicy) {
1330 BPF_ASSERT(Syscall::Call(__NR_uname, 0xFFFFFFFF) == -1);
1331 BPF_ASSERT(Syscall::Call(__NR_uname, -1) == -1);
1332 BPF_ASSERT(Syscall::Call(__NR_uname, -1LL) == -1);
1335 #if __SIZEOF_POINTER__ > 4
1336 BPF_DEATH_TEST_C(SandboxBPF,
1337 EqualityWithNegative64bitArguments,
1338 DEATH_MESSAGE("Unexpected 64bit argument detected"),
1339 EqualityWithNegativeArgumentsPolicy) {
1340 // When expecting a 32bit system call argument, we look at the MSB of the
1341 // 64bit value and allow both "0" and "-1". But the latter is allowed only
1342 // iff the LSB was negative. So, this death test should error out.
1343 BPF_ASSERT(Syscall::Call(__NR_uname, 0xFFFFFFFF00000000LL) == -1);
1346 class AllBitTestPolicy : public SandboxBPFPolicy {
1348 AllBitTestPolicy() {}
1349 virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
1350 int sysno) const OVERRIDE;
1353 DISALLOW_COPY_AND_ASSIGN(AllBitTestPolicy);
1356 ErrorCode AllBitTestPolicy::EvaluateSyscall(SandboxBPF* sandbox,
1358 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
1359 // Test the OP_HAS_ALL_BITS conditional test operator with a couple of
1360 // different bitmasks. We try to find bitmasks that could conceivably
1361 // touch corner cases.
1362 // For all of these tests, we override the uname(). We can make use with
1363 // a single system call number, as we use the first system call argument to
1364 // select the different bit masks that we want to test against.
1365 if (sysno == __NR_uname) {
1366 return sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 0,
1367 sandbox->Cond(1, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ALL_BITS,
1369 ErrorCode(1), ErrorCode(0)),
1371 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 1,
1372 sandbox->Cond(1, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ALL_BITS,
1374 ErrorCode(1), ErrorCode(0)),
1376 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 2,
1377 sandbox->Cond(1, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ALL_BITS,
1379 ErrorCode(1), ErrorCode(0)),
1381 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 3,
1382 sandbox->Cond(1, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ALL_BITS,
1384 ErrorCode(1), ErrorCode(0)),
1385 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 4,
1386 sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ALL_BITS,
1388 ErrorCode(1), ErrorCode(0)),
1390 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 5,
1391 sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ALL_BITS,
1393 ErrorCode(1), ErrorCode(0)),
1395 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 6,
1396 sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ALL_BITS,
1398 ErrorCode(1), ErrorCode(0)),
1400 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 7,
1401 sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ALL_BITS,
1403 ErrorCode(1), ErrorCode(0)),
1405 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 8,
1406 sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ALL_BITS,
1408 ErrorCode(1), ErrorCode(0)),
1410 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 9,
1411 sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ALL_BITS,
1413 ErrorCode(1), ErrorCode(0)),
1415 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 10,
1416 sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ALL_BITS,
1418 ErrorCode(1), ErrorCode(0)),
1420 sandbox->Kill("Invalid test case number"))))))))))));
1422 return ErrorCode(ErrorCode::ERR_ALLOWED);
1425 // Define a macro that performs tests using our test policy.
1426 // NOTE: Not all of the arguments in this macro are actually used!
1427 // They are here just to serve as documentation of the conditions
1428 // implemented in the test policy.
1429 // Most notably, "op" and "mask" are unused by the macro. If you want
1430 // to make changes to these values, you will have to edit the
1431 // test policy instead.
1432 #define BITMASK_TEST(testcase, arg, op, mask, expected_value) \
1433 BPF_ASSERT(Syscall::Call(__NR_uname, (testcase), (arg)) == (expected_value))
1435 // Our uname() system call returns ErrorCode(1) for success and
1436 // ErrorCode(0) for failure. Syscall::Call() turns this into an
1437 // exit code of -1 or 0.
1438 #define EXPECT_FAILURE 0
1439 #define EXPECT_SUCCESS -1
1441 // A couple of our tests behave differently on 32bit and 64bit systems, as
1442 // there is no way for a 32bit system call to pass in a 64bit system call
1444 // We expect these tests to succeed on 64bit systems, but to tail on 32bit
1446 #define EXPT64_SUCCESS (sizeof(void*) > 4 ? EXPECT_SUCCESS : EXPECT_FAILURE)
1447 BPF_TEST_C(SandboxBPF, AllBitTests, AllBitTestPolicy) {
1448 // 32bit test: all of 0x0 (should always be true)
1449 BITMASK_TEST( 0, 0, ALLBITS32, 0, EXPECT_SUCCESS);
1450 BITMASK_TEST( 0, 1, ALLBITS32, 0, EXPECT_SUCCESS);
1451 BITMASK_TEST( 0, 3, ALLBITS32, 0, EXPECT_SUCCESS);
1452 BITMASK_TEST( 0, 0xFFFFFFFFU, ALLBITS32, 0, EXPECT_SUCCESS);
1453 BITMASK_TEST( 0, -1LL, ALLBITS32, 0, EXPECT_SUCCESS);
1455 // 32bit test: all of 0x1
1456 BITMASK_TEST( 1, 0, ALLBITS32, 0x1, EXPECT_FAILURE);
1457 BITMASK_TEST( 1, 1, ALLBITS32, 0x1, EXPECT_SUCCESS);
1458 BITMASK_TEST( 1, 2, ALLBITS32, 0x1, EXPECT_FAILURE);
1459 BITMASK_TEST( 1, 3, ALLBITS32, 0x1, EXPECT_SUCCESS);
1461 // 32bit test: all of 0x3
1462 BITMASK_TEST( 2, 0, ALLBITS32, 0x3, EXPECT_FAILURE);
1463 BITMASK_TEST( 2, 1, ALLBITS32, 0x3, EXPECT_FAILURE);
1464 BITMASK_TEST( 2, 2, ALLBITS32, 0x3, EXPECT_FAILURE);
1465 BITMASK_TEST( 2, 3, ALLBITS32, 0x3, EXPECT_SUCCESS);
1466 BITMASK_TEST( 2, 7, ALLBITS32, 0x3, EXPECT_SUCCESS);
1468 // 32bit test: all of 0x80000000
1469 BITMASK_TEST( 3, 0, ALLBITS32, 0x80000000, EXPECT_FAILURE);
1470 BITMASK_TEST( 3, 0x40000000U, ALLBITS32, 0x80000000, EXPECT_FAILURE);
1471 BITMASK_TEST( 3, 0x80000000U, ALLBITS32, 0x80000000, EXPECT_SUCCESS);
1472 BITMASK_TEST( 3, 0xC0000000U, ALLBITS32, 0x80000000, EXPECT_SUCCESS);
1473 BITMASK_TEST( 3, -0x80000000LL, ALLBITS32, 0x80000000, EXPECT_SUCCESS);
1475 // 64bit test: all of 0x0 (should always be true)
1476 BITMASK_TEST( 4, 0, ALLBITS64, 0, EXPECT_SUCCESS);
1477 BITMASK_TEST( 4, 1, ALLBITS64, 0, EXPECT_SUCCESS);
1478 BITMASK_TEST( 4, 3, ALLBITS64, 0, EXPECT_SUCCESS);
1479 BITMASK_TEST( 4, 0xFFFFFFFFU, ALLBITS64, 0, EXPECT_SUCCESS);
1480 BITMASK_TEST( 4, 0x100000000LL, ALLBITS64, 0, EXPECT_SUCCESS);
1481 BITMASK_TEST( 4, 0x300000000LL, ALLBITS64, 0, EXPECT_SUCCESS);
1482 BITMASK_TEST( 4,0x8000000000000000LL, ALLBITS64, 0, EXPECT_SUCCESS);
1483 BITMASK_TEST( 4, -1LL, ALLBITS64, 0, EXPECT_SUCCESS);
1485 // 64bit test: all of 0x1
1486 BITMASK_TEST( 5, 0, ALLBITS64, 1, EXPECT_FAILURE);
1487 BITMASK_TEST( 5, 1, ALLBITS64, 1, EXPECT_SUCCESS);
1488 BITMASK_TEST( 5, 2, ALLBITS64, 1, EXPECT_FAILURE);
1489 BITMASK_TEST( 5, 3, ALLBITS64, 1, EXPECT_SUCCESS);
1490 BITMASK_TEST( 5, 0x100000000LL, ALLBITS64, 1, EXPECT_FAILURE);
1491 BITMASK_TEST( 5, 0x100000001LL, ALLBITS64, 1, EXPECT_SUCCESS);
1492 BITMASK_TEST( 5, 0x100000002LL, ALLBITS64, 1, EXPECT_FAILURE);
1493 BITMASK_TEST( 5, 0x100000003LL, ALLBITS64, 1, EXPECT_SUCCESS);
1495 // 64bit test: all of 0x3
1496 BITMASK_TEST( 6, 0, ALLBITS64, 3, EXPECT_FAILURE);
1497 BITMASK_TEST( 6, 1, ALLBITS64, 3, EXPECT_FAILURE);
1498 BITMASK_TEST( 6, 2, ALLBITS64, 3, EXPECT_FAILURE);
1499 BITMASK_TEST( 6, 3, ALLBITS64, 3, EXPECT_SUCCESS);
1500 BITMASK_TEST( 6, 7, ALLBITS64, 3, EXPECT_SUCCESS);
1501 BITMASK_TEST( 6, 0x100000000LL, ALLBITS64, 3, EXPECT_FAILURE);
1502 BITMASK_TEST( 6, 0x100000001LL, ALLBITS64, 3, EXPECT_FAILURE);
1503 BITMASK_TEST( 6, 0x100000002LL, ALLBITS64, 3, EXPECT_FAILURE);
1504 BITMASK_TEST( 6, 0x100000003LL, ALLBITS64, 3, EXPECT_SUCCESS);
1505 BITMASK_TEST( 6, 0x100000007LL, ALLBITS64, 3, EXPECT_SUCCESS);
1507 // 64bit test: all of 0x80000000
1508 BITMASK_TEST( 7, 0, ALLBITS64, 0x80000000, EXPECT_FAILURE);
1509 BITMASK_TEST( 7, 0x40000000U, ALLBITS64, 0x80000000, EXPECT_FAILURE);
1510 BITMASK_TEST( 7, 0x80000000U, ALLBITS64, 0x80000000, EXPECT_SUCCESS);
1511 BITMASK_TEST( 7, 0xC0000000U, ALLBITS64, 0x80000000, EXPECT_SUCCESS);
1512 BITMASK_TEST( 7, -0x80000000LL, ALLBITS64, 0x80000000, EXPECT_SUCCESS);
1513 BITMASK_TEST( 7, 0x100000000LL, ALLBITS64, 0x80000000, EXPECT_FAILURE);
1514 BITMASK_TEST( 7, 0x140000000LL, ALLBITS64, 0x80000000, EXPECT_FAILURE);
1515 BITMASK_TEST( 7, 0x180000000LL, ALLBITS64, 0x80000000, EXPECT_SUCCESS);
1516 BITMASK_TEST( 7, 0x1C0000000LL, ALLBITS64, 0x80000000, EXPECT_SUCCESS);
1517 BITMASK_TEST( 7, -0x180000000LL, ALLBITS64, 0x80000000, EXPECT_SUCCESS);
1519 // 64bit test: all of 0x100000000
1520 BITMASK_TEST( 8, 0x000000000LL, ALLBITS64,0x100000000, EXPECT_FAILURE);
1521 BITMASK_TEST( 8, 0x100000000LL, ALLBITS64,0x100000000, EXPT64_SUCCESS);
1522 BITMASK_TEST( 8, 0x200000000LL, ALLBITS64,0x100000000, EXPECT_FAILURE);
1523 BITMASK_TEST( 8, 0x300000000LL, ALLBITS64,0x100000000, EXPT64_SUCCESS);
1524 BITMASK_TEST( 8, 0x000000001LL, ALLBITS64,0x100000000, EXPECT_FAILURE);
1525 BITMASK_TEST( 8, 0x100000001LL, ALLBITS64,0x100000000, EXPT64_SUCCESS);
1526 BITMASK_TEST( 8, 0x200000001LL, ALLBITS64,0x100000000, EXPECT_FAILURE);
1527 BITMASK_TEST( 8, 0x300000001LL, ALLBITS64,0x100000000, EXPT64_SUCCESS);
1529 // 64bit test: all of 0x300000000
1530 BITMASK_TEST( 9, 0x000000000LL, ALLBITS64,0x300000000, EXPECT_FAILURE);
1531 BITMASK_TEST( 9, 0x100000000LL, ALLBITS64,0x300000000, EXPECT_FAILURE);
1532 BITMASK_TEST( 9, 0x200000000LL, ALLBITS64,0x300000000, EXPECT_FAILURE);
1533 BITMASK_TEST( 9, 0x300000000LL, ALLBITS64,0x300000000, EXPT64_SUCCESS);
1534 BITMASK_TEST( 9, 0x700000000LL, ALLBITS64,0x300000000, EXPT64_SUCCESS);
1535 BITMASK_TEST( 9, 0x000000001LL, ALLBITS64,0x300000000, EXPECT_FAILURE);
1536 BITMASK_TEST( 9, 0x100000001LL, ALLBITS64,0x300000000, EXPECT_FAILURE);
1537 BITMASK_TEST( 9, 0x200000001LL, ALLBITS64,0x300000000, EXPECT_FAILURE);
1538 BITMASK_TEST( 9, 0x300000001LL, ALLBITS64,0x300000000, EXPT64_SUCCESS);
1539 BITMASK_TEST( 9, 0x700000001LL, ALLBITS64,0x300000000, EXPT64_SUCCESS);
1541 // 64bit test: all of 0x100000001
1542 BITMASK_TEST(10, 0x000000000LL, ALLBITS64,0x100000001, EXPECT_FAILURE);
1543 BITMASK_TEST(10, 0x000000001LL, ALLBITS64,0x100000001, EXPECT_FAILURE);
1544 BITMASK_TEST(10, 0x100000000LL, ALLBITS64,0x100000001, EXPECT_FAILURE);
1545 BITMASK_TEST(10, 0x100000001LL, ALLBITS64,0x100000001, EXPT64_SUCCESS);
1546 BITMASK_TEST(10, 0xFFFFFFFFU, ALLBITS64,0x100000001, EXPECT_FAILURE);
1547 BITMASK_TEST(10, -1L, ALLBITS64,0x100000001, EXPT64_SUCCESS);
1550 class AnyBitTestPolicy : public SandboxBPFPolicy {
1552 AnyBitTestPolicy() {}
1553 virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
1554 int sysno) const OVERRIDE;
1557 DISALLOW_COPY_AND_ASSIGN(AnyBitTestPolicy);
1560 ErrorCode AnyBitTestPolicy::EvaluateSyscall(SandboxBPF* sandbox,
1562 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
1563 // Test the OP_HAS_ANY_BITS conditional test operator with a couple of
1564 // different bitmasks. We try to find bitmasks that could conceivably
1565 // touch corner cases.
1566 // For all of these tests, we override the uname(). We can make use with
1567 // a single system call number, as we use the first system call argument to
1568 // select the different bit masks that we want to test against.
1569 if (sysno == __NR_uname) {
1570 return sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 0,
1571 sandbox->Cond(1, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ANY_BITS,
1573 ErrorCode(1), ErrorCode(0)),
1575 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 1,
1576 sandbox->Cond(1, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ANY_BITS,
1578 ErrorCode(1), ErrorCode(0)),
1580 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 2,
1581 sandbox->Cond(1, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ANY_BITS,
1583 ErrorCode(1), ErrorCode(0)),
1585 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 3,
1586 sandbox->Cond(1, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ANY_BITS,
1588 ErrorCode(1), ErrorCode(0)),
1590 // All the following tests don't really make much sense on 32bit
1591 // systems. They will always evaluate as false.
1592 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 4,
1593 sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ANY_BITS,
1595 ErrorCode(1), ErrorCode(0)),
1597 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 5,
1598 sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ANY_BITS,
1600 ErrorCode(1), ErrorCode(0)),
1602 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 6,
1603 sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ANY_BITS,
1605 ErrorCode(1), ErrorCode(0)),
1607 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 7,
1608 sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ANY_BITS,
1610 ErrorCode(1), ErrorCode(0)),
1612 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 8,
1613 sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ANY_BITS,
1615 ErrorCode(1), ErrorCode(0)),
1617 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 9,
1618 sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ANY_BITS,
1620 ErrorCode(1), ErrorCode(0)),
1622 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 10,
1623 sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ANY_BITS,
1625 ErrorCode(1), ErrorCode(0)),
1627 sandbox->Kill("Invalid test case number"))))))))))));
1629 return ErrorCode(ErrorCode::ERR_ALLOWED);
1632 BPF_TEST_C(SandboxBPF, AnyBitTests, AnyBitTestPolicy) {
1633 // 32bit test: any of 0x0 (should always be false)
1634 BITMASK_TEST( 0, 0, ANYBITS32, 0x0, EXPECT_FAILURE);
1635 BITMASK_TEST( 0, 1, ANYBITS32, 0x0, EXPECT_FAILURE);
1636 BITMASK_TEST( 0, 3, ANYBITS32, 0x0, EXPECT_FAILURE);
1637 BITMASK_TEST( 0, 0xFFFFFFFFU, ANYBITS32, 0x0, EXPECT_FAILURE);
1638 BITMASK_TEST( 0, -1LL, ANYBITS32, 0x0, EXPECT_FAILURE);
1640 // 32bit test: any of 0x1
1641 BITMASK_TEST( 1, 0, ANYBITS32, 0x1, EXPECT_FAILURE);
1642 BITMASK_TEST( 1, 1, ANYBITS32, 0x1, EXPECT_SUCCESS);
1643 BITMASK_TEST( 1, 2, ANYBITS32, 0x1, EXPECT_FAILURE);
1644 BITMASK_TEST( 1, 3, ANYBITS32, 0x1, EXPECT_SUCCESS);
1646 // 32bit test: any of 0x3
1647 BITMASK_TEST( 2, 0, ANYBITS32, 0x3, EXPECT_FAILURE);
1648 BITMASK_TEST( 2, 1, ANYBITS32, 0x3, EXPECT_SUCCESS);
1649 BITMASK_TEST( 2, 2, ANYBITS32, 0x3, EXPECT_SUCCESS);
1650 BITMASK_TEST( 2, 3, ANYBITS32, 0x3, EXPECT_SUCCESS);
1651 BITMASK_TEST( 2, 7, ANYBITS32, 0x3, EXPECT_SUCCESS);
1653 // 32bit test: any of 0x80000000
1654 BITMASK_TEST( 3, 0, ANYBITS32, 0x80000000, EXPECT_FAILURE);
1655 BITMASK_TEST( 3, 0x40000000U, ANYBITS32, 0x80000000, EXPECT_FAILURE);
1656 BITMASK_TEST( 3, 0x80000000U, ANYBITS32, 0x80000000, EXPECT_SUCCESS);
1657 BITMASK_TEST( 3, 0xC0000000U, ANYBITS32, 0x80000000, EXPECT_SUCCESS);
1658 BITMASK_TEST( 3, -0x80000000LL, ANYBITS32, 0x80000000, EXPECT_SUCCESS);
1660 // 64bit test: any of 0x0 (should always be false)
1661 BITMASK_TEST( 4, 0, ANYBITS64, 0x0, EXPECT_FAILURE);
1662 BITMASK_TEST( 4, 1, ANYBITS64, 0x0, EXPECT_FAILURE);
1663 BITMASK_TEST( 4, 3, ANYBITS64, 0x0, EXPECT_FAILURE);
1664 BITMASK_TEST( 4, 0xFFFFFFFFU, ANYBITS64, 0x0, EXPECT_FAILURE);
1665 BITMASK_TEST( 4, 0x100000000LL, ANYBITS64, 0x0, EXPECT_FAILURE);
1666 BITMASK_TEST( 4, 0x300000000LL, ANYBITS64, 0x0, EXPECT_FAILURE);
1667 BITMASK_TEST( 4,0x8000000000000000LL, ANYBITS64, 0x0, EXPECT_FAILURE);
1668 BITMASK_TEST( 4, -1LL, ANYBITS64, 0x0, EXPECT_FAILURE);
1670 // 64bit test: any of 0x1
1671 BITMASK_TEST( 5, 0, ANYBITS64, 0x1, EXPECT_FAILURE);
1672 BITMASK_TEST( 5, 1, ANYBITS64, 0x1, EXPECT_SUCCESS);
1673 BITMASK_TEST( 5, 2, ANYBITS64, 0x1, EXPECT_FAILURE);
1674 BITMASK_TEST( 5, 3, ANYBITS64, 0x1, EXPECT_SUCCESS);
1675 BITMASK_TEST( 5, 0x100000001LL, ANYBITS64, 0x1, EXPECT_SUCCESS);
1676 BITMASK_TEST( 5, 0x100000000LL, ANYBITS64, 0x1, EXPECT_FAILURE);
1677 BITMASK_TEST( 5, 0x100000002LL, ANYBITS64, 0x1, EXPECT_FAILURE);
1678 BITMASK_TEST( 5, 0x100000003LL, ANYBITS64, 0x1, EXPECT_SUCCESS);
1680 // 64bit test: any of 0x3
1681 BITMASK_TEST( 6, 0, ANYBITS64, 0x3, EXPECT_FAILURE);
1682 BITMASK_TEST( 6, 1, ANYBITS64, 0x3, EXPECT_SUCCESS);
1683 BITMASK_TEST( 6, 2, ANYBITS64, 0x3, EXPECT_SUCCESS);
1684 BITMASK_TEST( 6, 3, ANYBITS64, 0x3, EXPECT_SUCCESS);
1685 BITMASK_TEST( 6, 7, ANYBITS64, 0x3, EXPECT_SUCCESS);
1686 BITMASK_TEST( 6, 0x100000000LL, ANYBITS64, 0x3, EXPECT_FAILURE);
1687 BITMASK_TEST( 6, 0x100000001LL, ANYBITS64, 0x3, EXPECT_SUCCESS);
1688 BITMASK_TEST( 6, 0x100000002LL, ANYBITS64, 0x3, EXPECT_SUCCESS);
1689 BITMASK_TEST( 6, 0x100000003LL, ANYBITS64, 0x3, EXPECT_SUCCESS);
1690 BITMASK_TEST( 6, 0x100000007LL, ANYBITS64, 0x3, EXPECT_SUCCESS);
1692 // 64bit test: any of 0x80000000
1693 BITMASK_TEST( 7, 0, ANYBITS64, 0x80000000, EXPECT_FAILURE);
1694 BITMASK_TEST( 7, 0x40000000U, ANYBITS64, 0x80000000, EXPECT_FAILURE);
1695 BITMASK_TEST( 7, 0x80000000U, ANYBITS64, 0x80000000, EXPECT_SUCCESS);
1696 BITMASK_TEST( 7, 0xC0000000U, ANYBITS64, 0x80000000, EXPECT_SUCCESS);
1697 BITMASK_TEST( 7, -0x80000000LL, ANYBITS64, 0x80000000, EXPECT_SUCCESS);
1698 BITMASK_TEST( 7, 0x100000000LL, ANYBITS64, 0x80000000, EXPECT_FAILURE);
1699 BITMASK_TEST( 7, 0x140000000LL, ANYBITS64, 0x80000000, EXPECT_FAILURE);
1700 BITMASK_TEST( 7, 0x180000000LL, ANYBITS64, 0x80000000, EXPECT_SUCCESS);
1701 BITMASK_TEST( 7, 0x1C0000000LL, ANYBITS64, 0x80000000, EXPECT_SUCCESS);
1702 BITMASK_TEST( 7, -0x180000000LL, ANYBITS64, 0x80000000, EXPECT_SUCCESS);
1704 // 64bit test: any of 0x100000000
1705 BITMASK_TEST( 8, 0x000000000LL, ANYBITS64,0x100000000, EXPECT_FAILURE);
1706 BITMASK_TEST( 8, 0x100000000LL, ANYBITS64,0x100000000, EXPT64_SUCCESS);
1707 BITMASK_TEST( 8, 0x200000000LL, ANYBITS64,0x100000000, EXPECT_FAILURE);
1708 BITMASK_TEST( 8, 0x300000000LL, ANYBITS64,0x100000000, EXPT64_SUCCESS);
1709 BITMASK_TEST( 8, 0x000000001LL, ANYBITS64,0x100000000, EXPECT_FAILURE);
1710 BITMASK_TEST( 8, 0x100000001LL, ANYBITS64,0x100000000, EXPT64_SUCCESS);
1711 BITMASK_TEST( 8, 0x200000001LL, ANYBITS64,0x100000000, EXPECT_FAILURE);
1712 BITMASK_TEST( 8, 0x300000001LL, ANYBITS64,0x100000000, EXPT64_SUCCESS);
1714 // 64bit test: any of 0x300000000
1715 BITMASK_TEST( 9, 0x000000000LL, ANYBITS64,0x300000000, EXPECT_FAILURE);
1716 BITMASK_TEST( 9, 0x100000000LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1717 BITMASK_TEST( 9, 0x200000000LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1718 BITMASK_TEST( 9, 0x300000000LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1719 BITMASK_TEST( 9, 0x700000000LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1720 BITMASK_TEST( 9, 0x000000001LL, ANYBITS64,0x300000000, EXPECT_FAILURE);
1721 BITMASK_TEST( 9, 0x100000001LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1722 BITMASK_TEST( 9, 0x200000001LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1723 BITMASK_TEST( 9, 0x300000001LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1724 BITMASK_TEST( 9, 0x700000001LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1726 // 64bit test: any of 0x100000001
1727 BITMASK_TEST( 10, 0x000000000LL, ANYBITS64,0x100000001, EXPECT_FAILURE);
1728 BITMASK_TEST( 10, 0x000000001LL, ANYBITS64,0x100000001, EXPECT_SUCCESS);
1729 BITMASK_TEST( 10, 0x100000000LL, ANYBITS64,0x100000001, EXPT64_SUCCESS);
1730 BITMASK_TEST( 10, 0x100000001LL, ANYBITS64,0x100000001, EXPECT_SUCCESS);
1731 BITMASK_TEST( 10, 0xFFFFFFFFU, ANYBITS64,0x100000001, EXPECT_SUCCESS);
1732 BITMASK_TEST( 10, -1L, ANYBITS64,0x100000001, EXPECT_SUCCESS);
1735 intptr_t PthreadTrapHandler(const struct arch_seccomp_data& args, void* aux) {
1736 if (args.args[0] != (CLONE_CHILD_CLEARTID | CLONE_CHILD_SETTID | SIGCHLD)) {
1737 // We expect to get called for an attempt to fork(). No need to log that
1738 // call. But if we ever get called for anything else, we want to verbosely
1739 // print as much information as possible.
1740 const char* msg = (const char*)aux;
1742 "Clone() was called with unexpected arguments\n"
1752 (long long)args.args[0],
1753 (long long)args.args[1],
1754 (long long)args.args[2],
1755 (long long)args.args[3],
1756 (long long)args.args[4],
1757 (long long)args.args[5],
1763 class PthreadPolicyEquality : public SandboxBPFPolicy {
1765 PthreadPolicyEquality() {}
1766 virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
1767 int sysno) const OVERRIDE;
1770 DISALLOW_COPY_AND_ASSIGN(PthreadPolicyEquality);
1773 ErrorCode PthreadPolicyEquality::EvaluateSyscall(SandboxBPF* sandbox,
1775 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
1776 // This policy allows creating threads with pthread_create(). But it
1777 // doesn't allow any other uses of clone(). Most notably, it does not
1778 // allow callers to implement fork() or vfork() by passing suitable flags
1779 // to the clone() system call.
1780 if (sysno == __NR_clone) {
1781 // We have seen two different valid combinations of flags. Glibc
1782 // uses the more modern flags, sets the TLS from the call to clone(), and
1783 // uses futexes to monitor threads. Android's C run-time library, doesn't
1784 // do any of this, but it sets the obsolete (and no-op) CLONE_DETACHED.
1785 // More recent versions of Android don't set CLONE_DETACHED anymore, so
1786 // the last case accounts for that.
1787 // The following policy is very strict. It only allows the exact masks
1788 // that we have seen in known implementations. It is probably somewhat
1789 // stricter than what we would want to do.
1790 const uint64_t kGlibcCloneMask =
1791 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
1792 CLONE_THREAD | CLONE_SYSVSEM | CLONE_SETTLS |
1793 CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID;
1794 const uint64_t kBaseAndroidCloneMask =
1795 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
1796 CLONE_THREAD | CLONE_SYSVSEM;
1797 return sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL,
1799 ErrorCode(ErrorCode::ERR_ALLOWED),
1800 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL,
1801 kBaseAndroidCloneMask | CLONE_DETACHED,
1802 ErrorCode(ErrorCode::ERR_ALLOWED),
1803 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL,
1804 kBaseAndroidCloneMask,
1805 ErrorCode(ErrorCode::ERR_ALLOWED),
1806 sandbox->Trap(PthreadTrapHandler, "Unknown mask"))));
1808 return ErrorCode(ErrorCode::ERR_ALLOWED);
1811 class PthreadPolicyBitMask : public SandboxBPFPolicy {
1813 PthreadPolicyBitMask() {}
1814 virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
1815 int sysno) const OVERRIDE;
1818 DISALLOW_COPY_AND_ASSIGN(PthreadPolicyBitMask);
1821 ErrorCode PthreadPolicyBitMask::EvaluateSyscall(SandboxBPF* sandbox,
1823 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
1824 // This policy allows creating threads with pthread_create(). But it
1825 // doesn't allow any other uses of clone(). Most notably, it does not
1826 // allow callers to implement fork() or vfork() by passing suitable flags
1827 // to the clone() system call.
1828 if (sysno == __NR_clone) {
1829 // We have seen two different valid combinations of flags. Glibc
1830 // uses the more modern flags, sets the TLS from the call to clone(), and
1831 // uses futexes to monitor threads. Android's C run-time library, doesn't
1832 // do any of this, but it sets the obsolete (and no-op) CLONE_DETACHED.
1833 // The following policy allows for either combination of flags, but it
1834 // is generally a little more conservative than strictly necessary. We
1835 // err on the side of rather safe than sorry.
1836 // Very noticeably though, we disallow fork() (which is often just a
1837 // wrapper around clone()).
1838 return sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ANY_BITS,
1839 ~uint32(CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|
1840 CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|
1841 CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID|
1843 sandbox->Trap(PthreadTrapHandler,
1844 "Unexpected CLONE_XXX flag found"),
1845 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ALL_BITS,
1846 CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|
1847 CLONE_THREAD|CLONE_SYSVSEM,
1848 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ALL_BITS,
1849 CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID,
1850 ErrorCode(ErrorCode::ERR_ALLOWED),
1851 sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ANY_BITS,
1852 CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID,
1853 sandbox->Trap(PthreadTrapHandler,
1854 "Must set either all or none of the TLS"
1855 " and futex bits in call to clone()"),
1856 ErrorCode(ErrorCode::ERR_ALLOWED))),
1857 sandbox->Trap(PthreadTrapHandler,
1858 "Missing mandatory CLONE_XXX flags "
1859 "when creating new thread")));
1861 return ErrorCode(ErrorCode::ERR_ALLOWED);
1864 static void* ThreadFnc(void* arg) {
1865 ++*reinterpret_cast<int*>(arg);
1866 Syscall::Call(__NR_futex, arg, FUTEX_WAKE, 1, 0, 0, 0);
1870 static void PthreadTest() {
1871 // Attempt to start a joinable thread. This should succeed.
1874 BPF_ASSERT(!pthread_create(&thread, NULL, ThreadFnc, &thread_ran));
1875 BPF_ASSERT(!pthread_join(thread, NULL));
1876 BPF_ASSERT(thread_ran);
1878 // Attempt to start a detached thread. This should succeed.
1880 pthread_attr_t attr;
1881 BPF_ASSERT(!pthread_attr_init(&attr));
1882 BPF_ASSERT(!pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
1883 BPF_ASSERT(!pthread_create(&thread, &attr, ThreadFnc, &thread_ran));
1884 BPF_ASSERT(!pthread_attr_destroy(&attr));
1885 while (Syscall::Call(__NR_futex, &thread_ran, FUTEX_WAIT, 0, 0, 0, 0) ==
1888 BPF_ASSERT(thread_ran);
1890 // Attempt to fork() a process using clone(). This should fail. We use the
1891 // same flags that glibc uses when calling fork(). But we don't actually
1892 // try calling the fork() implementation in the C run-time library, as
1893 // run-time libraries other than glibc might call __NR_fork instead of
1894 // __NR_clone, and that would introduce a bogus test failure.
1896 BPF_ASSERT(Syscall::Call(__NR_clone,
1897 CLONE_CHILD_CLEARTID | CLONE_CHILD_SETTID | SIGCHLD,
1903 BPF_TEST_C(SandboxBPF, PthreadEquality, PthreadPolicyEquality) {
1907 BPF_TEST_C(SandboxBPF, PthreadBitMask, PthreadPolicyBitMask) {
1911 // libc might not define these even though the kernel supports it.
1912 #ifndef PTRACE_O_TRACESECCOMP
1913 #define PTRACE_O_TRACESECCOMP 0x00000080
1916 #ifdef PTRACE_EVENT_SECCOMP
1917 #define IS_SECCOMP_EVENT(status) ((status >> 16) == PTRACE_EVENT_SECCOMP)
1919 // When Debian/Ubuntu backported seccomp-bpf support into earlier kernels, they
1920 // changed the value of PTRACE_EVENT_SECCOMP from 7 to 8, since 7 was taken by
1921 // PTRACE_EVENT_STOP (upstream chose to renumber PTRACE_EVENT_STOP to 128). If
1922 // PTRACE_EVENT_SECCOMP isn't defined, we have no choice but to consider both
1924 #define IS_SECCOMP_EVENT(status) ((status >> 16) == 7 || (status >> 16) == 8)
1927 #if defined(__arm__)
1928 #ifndef PTRACE_SET_SYSCALL
1929 #define PTRACE_SET_SYSCALL 23
1933 // Changes the syscall to run for a child being sandboxed using seccomp-bpf with
1934 // PTRACE_O_TRACESECCOMP. Should only be called when the child is stopped on
1935 // PTRACE_EVENT_SECCOMP.
1937 // regs should contain the current set of registers of the child, obtained using
1940 // Depending on the architecture, this may modify regs, so the caller is
1941 // responsible for committing these changes using PTRACE_SETREGS.
1942 long SetSyscall(pid_t pid, regs_struct* regs, int syscall_number) {
1943 #if defined(__arm__)
1944 // On ARM, the syscall is changed using PTRACE_SET_SYSCALL. We cannot use the
1945 // libc ptrace call as the request parameter is an enum, and
1946 // PTRACE_SET_SYSCALL may not be in the enum.
1947 return syscall(__NR_ptrace, PTRACE_SET_SYSCALL, pid, NULL, syscall_number);
1950 SECCOMP_PT_SYSCALL(*regs) = syscall_number;
1954 const uint16_t kTraceData = 0xcc;
1956 class TraceAllPolicy : public SandboxBPFPolicy {
1959 virtual ~TraceAllPolicy() {}
1961 virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox_compiler,
1962 int system_call_number) const OVERRIDE {
1963 return ErrorCode(ErrorCode::ERR_TRACE + kTraceData);
1967 DISALLOW_COPY_AND_ASSIGN(TraceAllPolicy);
1970 SANDBOX_TEST(SandboxBPF, DISABLE_ON_TSAN(SeccompRetTrace)) {
1971 if (SandboxBPF::SupportsSeccompSandbox(-1) !=
1972 sandbox::SandboxBPF::STATUS_AVAILABLE) {
1976 #if defined(__arm__)
1977 printf("This test is currently disabled on ARM due to a kernel bug.");
1981 #if defined(__mips__)
1982 // TODO: Figure out how to support specificity of handling indirect syscalls
1983 // in this test and enable it.
1984 printf("This test is currently disabled on MIPS.");
1989 BPF_ASSERT_NE(-1, pid);
1991 pid_t my_pid = getpid();
1992 BPF_ASSERT_NE(-1, ptrace(PTRACE_TRACEME, -1, NULL, NULL));
1993 BPF_ASSERT_EQ(0, raise(SIGSTOP));
1995 sandbox.SetSandboxPolicy(new TraceAllPolicy);
1996 BPF_ASSERT(sandbox.StartSandbox(SandboxBPF::PROCESS_SINGLE_THREADED));
1998 // getpid is allowed.
1999 BPF_ASSERT_EQ(my_pid, syscall(__NR_getpid));
2001 // write to stdout is skipped and returns a fake value.
2002 BPF_ASSERT_EQ(kExpectedReturnValue,
2003 syscall(__NR_write, STDOUT_FILENO, "A", 1));
2005 // kill is rewritten to exit(kExpectedReturnValue).
2006 syscall(__NR_kill, my_pid, SIGKILL);
2008 // Should not be reached.
2013 BPF_ASSERT(HANDLE_EINTR(waitpid(pid, &status, WUNTRACED)) != -1);
2014 BPF_ASSERT(WIFSTOPPED(status));
2016 BPF_ASSERT_NE(-1, ptrace(PTRACE_SETOPTIONS, pid, NULL,
2017 reinterpret_cast<void*>(PTRACE_O_TRACESECCOMP)));
2018 BPF_ASSERT_NE(-1, ptrace(PTRACE_CONT, pid, NULL, NULL));
2020 BPF_ASSERT(HANDLE_EINTR(waitpid(pid, &status, 0)) != -1);
2021 if (WIFEXITED(status) || WIFSIGNALED(status)) {
2022 BPF_ASSERT(WIFEXITED(status));
2023 BPF_ASSERT_EQ(kExpectedReturnValue, WEXITSTATUS(status));
2027 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGTRAP ||
2028 !IS_SECCOMP_EVENT(status)) {
2029 BPF_ASSERT_NE(-1, ptrace(PTRACE_CONT, pid, NULL, NULL));
2034 BPF_ASSERT_NE(-1, ptrace(PTRACE_GETEVENTMSG, pid, NULL, &data));
2035 BPF_ASSERT_EQ(kTraceData, data);
2038 BPF_ASSERT_NE(-1, ptrace(PTRACE_GETREGS, pid, NULL, ®s));
2039 switch (SECCOMP_PT_SYSCALL(regs)) {
2041 // Skip writes to stdout, make it return kExpectedReturnValue. Allow
2042 // writes to stderr so that BPF_ASSERT messages show up.
2043 if (SECCOMP_PT_PARM1(regs) == STDOUT_FILENO) {
2044 BPF_ASSERT_NE(-1, SetSyscall(pid, ®s, -1));
2045 SECCOMP_PT_RESULT(regs) = kExpectedReturnValue;
2046 BPF_ASSERT_NE(-1, ptrace(PTRACE_SETREGS, pid, NULL, ®s));
2051 // Rewrite to exit(kExpectedReturnValue).
2052 BPF_ASSERT_NE(-1, SetSyscall(pid, ®s, __NR_exit));
2053 SECCOMP_PT_PARM1(regs) = kExpectedReturnValue;
2054 BPF_ASSERT_NE(-1, ptrace(PTRACE_SETREGS, pid, NULL, ®s));
2058 // Allow all other syscalls.
2062 BPF_ASSERT_NE(-1, ptrace(PTRACE_CONT, pid, NULL, NULL));
2066 // Android does not expose pread64 nor pwrite64.
2067 #if !defined(OS_ANDROID)
2069 bool FullPwrite64(int fd, const char* buffer, size_t count, off64_t offset) {
2071 const ssize_t transfered =
2072 HANDLE_EINTR(pwrite64(fd, buffer, count, offset));
2073 if (transfered <= 0 || static_cast<size_t>(transfered) > count) {
2076 count -= transfered;
2077 buffer += transfered;
2078 offset += transfered;
2083 bool FullPread64(int fd, char* buffer, size_t count, off64_t offset) {
2085 const ssize_t transfered = HANDLE_EINTR(pread64(fd, buffer, count, offset));
2086 if (transfered <= 0 || static_cast<size_t>(transfered) > count) {
2089 count -= transfered;
2090 buffer += transfered;
2091 offset += transfered;
2096 bool pread_64_was_forwarded = false;
2098 class TrapPread64Policy : public SandboxBPFPolicy {
2100 TrapPread64Policy() {}
2101 virtual ~TrapPread64Policy() {}
2103 virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox_compiler,
2104 int system_call_number) const OVERRIDE {
2105 // Set the global environment for unsafe traps once.
2106 if (system_call_number == MIN_SYSCALL) {
2107 EnableUnsafeTraps();
2110 if (system_call_number == __NR_pread64) {
2111 return sandbox_compiler->UnsafeTrap(ForwardPreadHandler, NULL);
2113 return ErrorCode(ErrorCode::ERR_ALLOWED);
2117 static intptr_t ForwardPreadHandler(const struct arch_seccomp_data& args,
2119 BPF_ASSERT(args.nr == __NR_pread64);
2120 pread_64_was_forwarded = true;
2122 return SandboxBPF::ForwardSyscall(args);
2124 DISALLOW_COPY_AND_ASSIGN(TrapPread64Policy);
2127 // pread(2) takes a 64 bits offset. On 32 bits systems, it will be split
2128 // between two arguments. In this test, we make sure that ForwardSyscall() can
2129 // forward it properly.
2130 BPF_TEST_C(SandboxBPF, Pread64, TrapPread64Policy) {
2131 ScopedTemporaryFile temp_file;
2132 const uint64_t kLargeOffset = (static_cast<uint64_t>(1) << 32) | 0xBEEF;
2133 const char kTestString[] = "This is a test!";
2134 BPF_ASSERT(FullPwrite64(
2135 temp_file.fd(), kTestString, sizeof(kTestString), kLargeOffset));
2137 char read_test_string[sizeof(kTestString)] = {0};
2138 BPF_ASSERT(FullPread64(temp_file.fd(),
2140 sizeof(read_test_string),
2142 BPF_ASSERT_EQ(0, memcmp(kTestString, read_test_string, sizeof(kTestString)));
2143 BPF_ASSERT(pread_64_was_forwarded);
2146 #endif // !defined(OS_ANDROID)
2150 } // namespace sandbox