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/bpf_dsl/bpf_dsl.h"
12 #include <sys/prctl.h>
13 #include <sys/ptrace.h>
14 #include <sys/syscall.h>
16 #include <sys/types.h>
17 #include <sys/utsname.h>
19 #include <sys/socket.h>
22 // Work-around for buggy headers in Android's NDK
25 #include <linux/futex.h>
27 #include "base/bind.h"
28 #include "base/logging.h"
29 #include "base/macros.h"
30 #include "base/memory/scoped_ptr.h"
31 #include "base/posix/eintr_wrapper.h"
32 #include "base/synchronization/waitable_event.h"
33 #include "base/threading/thread.h"
34 #include "build/build_config.h"
35 #include "sandbox/linux/bpf_dsl/policy.h"
36 #include "sandbox/linux/seccomp-bpf/bpf_tests.h"
37 #include "sandbox/linux/seccomp-bpf/die.h"
38 #include "sandbox/linux/seccomp-bpf/errorcode.h"
39 #include "sandbox/linux/seccomp-bpf/linux_seccomp.h"
40 #include "sandbox/linux/seccomp-bpf/sandbox_bpf.h"
41 #include "sandbox/linux/seccomp-bpf/syscall.h"
42 #include "sandbox/linux/seccomp-bpf/trap.h"
43 #include "sandbox/linux/services/linux_syscalls.h"
44 #include "sandbox/linux/syscall_broker/broker_process.h"
45 #include "sandbox/linux/tests/scoped_temporary_file.h"
46 #include "sandbox/linux/tests/unit_tests.h"
47 #include "testing/gtest/include/gtest/gtest.h"
49 // Workaround for Android's prctl.h file.
51 #define PR_GET_ENDIAN 19
53 #ifndef PR_CAPBSET_READ
54 #define PR_CAPBSET_READ 23
55 #define PR_CAPBSET_DROP 24
63 const int kExpectedReturnValue = 42;
64 const char kSandboxDebuggingEnv[] = "CHROME_SANDBOX_DEBUGGING";
66 // Set the global environment to allow the use of UnsafeTrap() policies.
67 void EnableUnsafeTraps() {
68 // The use of UnsafeTrap() causes us to print a warning message. This is
69 // generally desirable, but it results in the unittest failing, as it doesn't
70 // expect any messages on "stderr". So, temporarily disable messages. The
71 // BPF_TEST() is guaranteed to turn messages back on, after the policy
72 // function has completed.
73 setenv(kSandboxDebuggingEnv, "t", 0);
74 Die::SuppressInfoMessages(true);
77 // This test should execute no matter whether we have kernel support. So,
78 // we make it a TEST() instead of a BPF_TEST().
79 TEST(SandboxBPF, DISABLE_ON_TSAN(CallSupports)) {
80 // We check that we don't crash, but it's ok if the kernel doesn't
82 bool seccomp_bpf_supported =
83 SandboxBPF::SupportsSeccompSandbox(-1) == SandboxBPF::STATUS_AVAILABLE;
84 // We want to log whether or not seccomp BPF is actually supported
85 // since actual test coverage depends on it.
86 RecordProperty("SeccompBPFSupported",
87 seccomp_bpf_supported ? "true." : "false.");
88 std::cout << "Seccomp BPF supported: "
89 << (seccomp_bpf_supported ? "true." : "false.") << "\n";
90 RecordProperty("PointerSize", sizeof(void*));
91 std::cout << "Pointer size: " << sizeof(void*) << "\n";
94 SANDBOX_TEST(SandboxBPF, DISABLE_ON_TSAN(CallSupportsTwice)) {
95 SandboxBPF::SupportsSeccompSandbox(-1);
96 SandboxBPF::SupportsSeccompSandbox(-1);
99 // BPF_TEST does a lot of the boiler-plate code around setting up a
100 // policy and optional passing data between the caller, the policy and
101 // any Trap() handlers. This is great for writing short and concise tests,
102 // and it helps us accidentally forgetting any of the crucial steps in
103 // setting up the sandbox. But it wouldn't hurt to have at least one test
104 // that explicitly walks through all these steps.
106 intptr_t IncreaseCounter(const struct arch_seccomp_data& args, void* aux) {
108 int* counter = static_cast<int*>(aux);
112 class VerboseAPITestingPolicy : public Policy {
114 explicit VerboseAPITestingPolicy(int* counter_ptr)
115 : counter_ptr_(counter_ptr) {}
116 ~VerboseAPITestingPolicy() override {}
118 ResultExpr EvaluateSyscall(int sysno) const override {
119 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
120 if (sysno == __NR_uname) {
121 return Trap(IncreaseCounter, counter_ptr_);
129 DISALLOW_COPY_AND_ASSIGN(VerboseAPITestingPolicy);
132 SANDBOX_TEST(SandboxBPF, DISABLE_ON_TSAN(VerboseAPITesting)) {
133 if (SandboxBPF::SupportsSeccompSandbox(-1) ==
134 sandbox::SandboxBPF::STATUS_AVAILABLE) {
135 static int counter = 0;
138 sandbox.SetSandboxPolicy(new VerboseAPITestingPolicy(&counter));
139 BPF_ASSERT(sandbox.StartSandbox(SandboxBPF::PROCESS_SINGLE_THREADED));
141 BPF_ASSERT_EQ(0, counter);
142 BPF_ASSERT_EQ(0, syscall(__NR_uname, 0));
143 BPF_ASSERT_EQ(1, counter);
144 BPF_ASSERT_EQ(1, syscall(__NR_uname, 0));
145 BPF_ASSERT_EQ(2, counter);
149 // A simple blacklist test
151 class BlacklistNanosleepPolicy : public Policy {
153 BlacklistNanosleepPolicy() {}
154 ~BlacklistNanosleepPolicy() override {}
156 ResultExpr EvaluateSyscall(int sysno) const override {
157 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
160 return Error(EACCES);
166 static void AssertNanosleepFails() {
167 const struct timespec ts = {0, 0};
169 BPF_ASSERT_EQ(-1, HANDLE_EINTR(syscall(__NR_nanosleep, &ts, NULL)));
170 BPF_ASSERT_EQ(EACCES, errno);
174 DISALLOW_COPY_AND_ASSIGN(BlacklistNanosleepPolicy);
177 BPF_TEST_C(SandboxBPF, ApplyBasicBlacklistPolicy, BlacklistNanosleepPolicy) {
178 BlacklistNanosleepPolicy::AssertNanosleepFails();
181 // Now do a simple whitelist test
183 class WhitelistGetpidPolicy : public Policy {
185 WhitelistGetpidPolicy() {}
186 ~WhitelistGetpidPolicy() override {}
188 ResultExpr EvaluateSyscall(int sysno) const override {
189 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
192 case __NR_exit_group:
195 return Error(ENOMEM);
200 DISALLOW_COPY_AND_ASSIGN(WhitelistGetpidPolicy);
203 BPF_TEST_C(SandboxBPF, ApplyBasicWhitelistPolicy, WhitelistGetpidPolicy) {
204 // getpid() should be allowed
206 BPF_ASSERT(syscall(__NR_getpid) > 0);
207 BPF_ASSERT(errno == 0);
209 // getpgid() should be denied
210 BPF_ASSERT(getpgid(0) == -1);
211 BPF_ASSERT(errno == ENOMEM);
214 // A simple blacklist policy, with a SIGSYS handler
215 intptr_t EnomemHandler(const struct arch_seccomp_data& args, void* aux) {
216 // We also check that the auxiliary data is correct
218 *(static_cast<int*>(aux)) = kExpectedReturnValue;
222 class BlacklistNanosleepTrapPolicy : public Policy {
224 explicit BlacklistNanosleepTrapPolicy(int* aux) : aux_(aux) {}
225 ~BlacklistNanosleepTrapPolicy() override {}
227 ResultExpr EvaluateSyscall(int sysno) const override {
228 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
231 return Trap(EnomemHandler, aux_);
240 DISALLOW_COPY_AND_ASSIGN(BlacklistNanosleepTrapPolicy);
244 BasicBlacklistWithSigsys,
245 BlacklistNanosleepTrapPolicy,
246 int /* (*BPF_AUX) */) {
247 // getpid() should work properly
249 BPF_ASSERT(syscall(__NR_getpid) > 0);
250 BPF_ASSERT(errno == 0);
252 // Our Auxiliary Data, should be reset by the signal handler
254 const struct timespec ts = {0, 0};
255 BPF_ASSERT(syscall(__NR_nanosleep, &ts, NULL) == -1);
256 BPF_ASSERT(errno == ENOMEM);
258 // We expect the signal handler to modify AuxData
259 BPF_ASSERT(*BPF_AUX == kExpectedReturnValue);
262 // A simple test that verifies we can return arbitrary errno values.
264 class ErrnoTestPolicy : public Policy {
267 ~ErrnoTestPolicy() override {}
269 ResultExpr EvaluateSyscall(int sysno) const override;
272 DISALLOW_COPY_AND_ASSIGN(ErrnoTestPolicy);
275 ResultExpr ErrnoTestPolicy::EvaluateSyscall(int sysno) const {
276 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
278 case __NR_dup3: // dup2 is a wrapper of dup3 in android
279 #if defined(__NR_dup2)
282 // Pretend that dup2() worked, but don't actually do anything.
285 #if defined(__NR_setuid32)
291 #if defined(__NR_setgid32)
294 // Return maximum errno value (typically 4095).
295 return Error(ErrorCode::ERR_MAX_ERRNO);
297 // Return errno = 42;
304 BPF_TEST_C(SandboxBPF, ErrnoTest, ErrnoTestPolicy) {
305 // Verify that dup2() returns success, but doesn't actually run.
307 BPF_ASSERT(pipe(fds) == 0);
308 BPF_ASSERT(pipe(fds + 2) == 0);
309 BPF_ASSERT(dup2(fds[2], fds[0]) == 0);
311 BPF_ASSERT(write(fds[1], "\x55", 1) == 1);
312 BPF_ASSERT(write(fds[3], "\xAA", 1) == 1);
313 BPF_ASSERT(read(fds[0], buf, 1) == 1);
315 // If dup2() executed, we will read \xAA, but it dup2() has been turned
316 // into a no-op by our policy, then we will read \x55.
317 BPF_ASSERT(buf[0] == '\x55');
319 // Verify that we can return the minimum and maximum errno values.
321 BPF_ASSERT(setuid(0) == -1);
322 BPF_ASSERT(errno == 1);
324 // On Android, errno is only supported up to 255, otherwise errno
325 // processing is skipped.
326 // We work around this (crbug.com/181647).
327 if (sandbox::IsAndroid() && setgid(0) != -1) {
329 BPF_ASSERT(setgid(0) == -ErrorCode::ERR_MAX_ERRNO);
330 BPF_ASSERT(errno == 0);
333 BPF_ASSERT(setgid(0) == -1);
334 BPF_ASSERT(errno == ErrorCode::ERR_MAX_ERRNO);
337 // Finally, test an errno in between the minimum and maximum.
339 struct utsname uts_buf;
340 BPF_ASSERT(uname(&uts_buf) == -1);
341 BPF_ASSERT(errno == 42);
344 // Testing the stacking of two sandboxes
346 class StackingPolicyPartOne : public Policy {
348 StackingPolicyPartOne() {}
349 ~StackingPolicyPartOne() override {}
351 ResultExpr EvaluateSyscall(int sysno) const override {
352 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
355 const Arg<int> arg(0);
356 return If(arg == 0, Allow()).Else(Error(EPERM));
364 DISALLOW_COPY_AND_ASSIGN(StackingPolicyPartOne);
367 class StackingPolicyPartTwo : public Policy {
369 StackingPolicyPartTwo() {}
370 ~StackingPolicyPartTwo() override {}
372 ResultExpr EvaluateSyscall(int sysno) const override {
373 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
376 const Arg<int> arg(0);
377 return If(arg == 0, Error(EINVAL)).Else(Allow());
385 DISALLOW_COPY_AND_ASSIGN(StackingPolicyPartTwo);
388 BPF_TEST_C(SandboxBPF, StackingPolicy, StackingPolicyPartOne) {
390 BPF_ASSERT(syscall(__NR_getppid, 0) > 0);
391 BPF_ASSERT(errno == 0);
393 BPF_ASSERT(syscall(__NR_getppid, 1) == -1);
394 BPF_ASSERT(errno == EPERM);
396 // Stack a second sandbox with its own policy. Verify that we can further
397 // restrict filters, but we cannot relax existing filters.
399 sandbox.SetSandboxPolicy(new StackingPolicyPartTwo());
400 BPF_ASSERT(sandbox.StartSandbox(SandboxBPF::PROCESS_SINGLE_THREADED));
403 BPF_ASSERT(syscall(__NR_getppid, 0) == -1);
404 BPF_ASSERT(errno == EINVAL);
406 BPF_ASSERT(syscall(__NR_getppid, 1) == -1);
407 BPF_ASSERT(errno == EPERM);
410 // A more complex, but synthetic policy. This tests the correctness of the BPF
411 // program by iterating through all syscalls and checking for an errno that
412 // depends on the syscall number. Unlike the Verifier, this exercises the BPF
413 // interpreter in the kernel.
415 // We try to make sure we exercise optimizations in the BPF compiler. We make
416 // sure that the compiler can have an opportunity to coalesce syscalls with
417 // contiguous numbers and we also make sure that disjoint sets can return the
419 int SysnoToRandomErrno(int sysno) {
420 // Small contiguous sets of 3 system calls return an errno equal to the
421 // index of that set + 1 (so that we never return a NUL errno).
422 return ((sysno & ~3) >> 2) % 29 + 1;
425 class SyntheticPolicy : public Policy {
428 ~SyntheticPolicy() override {}
430 ResultExpr EvaluateSyscall(int sysno) const override {
431 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
432 if (sysno == __NR_exit_group || sysno == __NR_write) {
433 // exit_group() is special, we really need it to work.
434 // write() is needed for BPF_ASSERT() to report a useful error message.
437 return Error(SysnoToRandomErrno(sysno));
441 DISALLOW_COPY_AND_ASSIGN(SyntheticPolicy);
444 BPF_TEST_C(SandboxBPF, SyntheticPolicy, SyntheticPolicy) {
445 // Ensure that that kExpectedReturnValue + syscallnumber + 1 does not int
447 BPF_ASSERT(std::numeric_limits<int>::max() - kExpectedReturnValue - 1 >=
448 static_cast<int>(MAX_PUBLIC_SYSCALL));
450 for (int syscall_number = static_cast<int>(MIN_SYSCALL);
451 syscall_number <= static_cast<int>(MAX_PUBLIC_SYSCALL);
453 if (syscall_number == __NR_exit_group || syscall_number == __NR_write) {
454 // exit_group() is special
458 BPF_ASSERT(syscall(syscall_number) == -1);
459 BPF_ASSERT(errno == SysnoToRandomErrno(syscall_number));
464 // A simple policy that tests whether ARM private system calls are supported
465 // by our BPF compiler and by the BPF interpreter in the kernel.
467 // For ARM private system calls, return an errno equal to their offset from
468 // MIN_PRIVATE_SYSCALL plus 1 (to avoid NUL errno).
469 int ArmPrivateSysnoToErrno(int sysno) {
470 if (sysno >= static_cast<int>(MIN_PRIVATE_SYSCALL) &&
471 sysno <= static_cast<int>(MAX_PRIVATE_SYSCALL)) {
472 return (sysno - MIN_PRIVATE_SYSCALL) + 1;
478 class ArmPrivatePolicy : public Policy {
480 ArmPrivatePolicy() {}
481 virtual ~ArmPrivatePolicy() {}
483 virtual ResultExpr EvaluateSyscall(int sysno) const override {
484 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
485 // Start from |__ARM_NR_set_tls + 1| so as not to mess with actual
486 // ARM private system calls.
487 if (sysno >= static_cast<int>(__ARM_NR_set_tls + 1) &&
488 sysno <= static_cast<int>(MAX_PRIVATE_SYSCALL)) {
489 return Error(ArmPrivateSysnoToErrno(sysno));
495 DISALLOW_COPY_AND_ASSIGN(ArmPrivatePolicy);
498 BPF_TEST_C(SandboxBPF, ArmPrivatePolicy, ArmPrivatePolicy) {
499 for (int syscall_number = static_cast<int>(__ARM_NR_set_tls + 1);
500 syscall_number <= static_cast<int>(MAX_PRIVATE_SYSCALL);
503 BPF_ASSERT(syscall(syscall_number) == -1);
504 BPF_ASSERT(errno == ArmPrivateSysnoToErrno(syscall_number));
507 #endif // defined(__arm__)
509 intptr_t CountSyscalls(const struct arch_seccomp_data& args, void* aux) {
510 // Count all invocations of our callback function.
511 ++*reinterpret_cast<int*>(aux);
513 // Verify that within the callback function all filtering is temporarily
515 BPF_ASSERT(syscall(__NR_getpid) > 1);
517 // Verify that we can now call the underlying system call without causing
518 // infinite recursion.
519 return SandboxBPF::ForwardSyscall(args);
522 class GreyListedPolicy : public Policy {
524 explicit GreyListedPolicy(int* aux) : aux_(aux) {
525 // Set the global environment for unsafe traps once.
528 ~GreyListedPolicy() override {}
530 ResultExpr EvaluateSyscall(int sysno) const override {
531 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
532 // Some system calls must always be allowed, if our policy wants to make
533 // use of UnsafeTrap()
534 if (SandboxBPF::IsRequiredForUnsafeTrap(sysno)) {
536 } else if (sysno == __NR_getpid) {
540 // Allow (and count) all other system calls.
541 return UnsafeTrap(CountSyscalls, aux_);
548 DISALLOW_COPY_AND_ASSIGN(GreyListedPolicy);
551 BPF_TEST(SandboxBPF, GreyListedPolicy, GreyListedPolicy, int /* (*BPF_AUX) */) {
552 BPF_ASSERT(syscall(__NR_getpid) == -1);
553 BPF_ASSERT(errno == EPERM);
554 BPF_ASSERT(*BPF_AUX == 0);
555 BPF_ASSERT(syscall(__NR_geteuid) == syscall(__NR_getuid));
556 BPF_ASSERT(*BPF_AUX == 2);
558 BPF_ASSERT(!syscall(__NR_prctl,
564 BPF_ASSERT(*BPF_AUX == 3);
568 SANDBOX_TEST(SandboxBPF, EnableUnsafeTrapsInSigSysHandler) {
569 // Disabling warning messages that could confuse our test framework.
570 setenv(kSandboxDebuggingEnv, "t", 0);
571 Die::SuppressInfoMessages(true);
573 unsetenv(kSandboxDebuggingEnv);
574 SANDBOX_ASSERT(Trap::EnableUnsafeTrapsInSigSysHandler() == false);
575 setenv(kSandboxDebuggingEnv, "", 1);
576 SANDBOX_ASSERT(Trap::EnableUnsafeTrapsInSigSysHandler() == false);
577 setenv(kSandboxDebuggingEnv, "t", 1);
578 SANDBOX_ASSERT(Trap::EnableUnsafeTrapsInSigSysHandler() == true);
581 intptr_t PrctlHandler(const struct arch_seccomp_data& args, void*) {
582 if (args.args[0] == PR_CAPBSET_DROP && static_cast<int>(args.args[1]) == -1) {
583 // prctl(PR_CAPBSET_DROP, -1) is never valid. The kernel will always
584 // return an error. But our handler allows this call.
587 return SandboxBPF::ForwardSyscall(args);
591 class PrctlPolicy : public Policy {
594 ~PrctlPolicy() override {}
596 ResultExpr EvaluateSyscall(int sysno) const override {
597 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
598 setenv(kSandboxDebuggingEnv, "t", 0);
599 Die::SuppressInfoMessages(true);
601 if (sysno == __NR_prctl) {
602 // Handle prctl() inside an UnsafeTrap()
603 return UnsafeTrap(PrctlHandler, NULL);
606 // Allow all other system calls.
611 DISALLOW_COPY_AND_ASSIGN(PrctlPolicy);
614 BPF_TEST_C(SandboxBPF, ForwardSyscall, PrctlPolicy) {
615 // This call should never be allowed. But our policy will intercept it and
616 // let it pass successfully.
618 !prctl(PR_CAPBSET_DROP, -1, (void*)NULL, (void*)NULL, (void*)NULL));
620 // Verify that the call will fail, if it makes it all the way to the kernel.
622 prctl(PR_CAPBSET_DROP, -2, (void*)NULL, (void*)NULL, (void*)NULL) == -1);
624 // And verify that other uses of prctl() work just fine.
626 BPF_ASSERT(!syscall(__NR_prctl,
634 // Finally, verify that system calls other than prctl() are completely
635 // unaffected by our policy.
636 struct utsname uts = {};
637 BPF_ASSERT(!uname(&uts));
638 BPF_ASSERT(!strcmp(uts.sysname, "Linux"));
641 intptr_t AllowRedirectedSyscall(const struct arch_seccomp_data& args, void*) {
642 return SandboxBPF::ForwardSyscall(args);
645 class RedirectAllSyscallsPolicy : public Policy {
647 RedirectAllSyscallsPolicy() {}
648 ~RedirectAllSyscallsPolicy() override {}
650 ResultExpr EvaluateSyscall(int sysno) const override;
653 DISALLOW_COPY_AND_ASSIGN(RedirectAllSyscallsPolicy);
656 ResultExpr RedirectAllSyscallsPolicy::EvaluateSyscall(int sysno) const {
657 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
658 setenv(kSandboxDebuggingEnv, "t", 0);
659 Die::SuppressInfoMessages(true);
661 // Some system calls must always be allowed, if our policy wants to make
662 // use of UnsafeTrap()
663 if (SandboxBPF::IsRequiredForUnsafeTrap(sysno))
665 return UnsafeTrap(AllowRedirectedSyscall, NULL);
668 int bus_handler_fd_ = -1;
670 void SigBusHandler(int, siginfo_t* info, void* void_context) {
671 BPF_ASSERT(write(bus_handler_fd_, "\x55", 1) == 1);
674 BPF_TEST_C(SandboxBPF, SigBus, RedirectAllSyscallsPolicy) {
675 // We use the SIGBUS bit in the signal mask as a thread-local boolean
676 // value in the implementation of UnsafeTrap(). This is obviously a bit
677 // of a hack that could conceivably interfere with code that uses SIGBUS
678 // in more traditional ways. This test verifies that basic functionality
679 // of SIGBUS is not impacted, but it is certainly possibly to construe
680 // more complex uses of signals where our use of the SIGBUS mask is not
681 // 100% transparent. This is expected behavior.
683 BPF_ASSERT(socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == 0);
684 bus_handler_fd_ = fds[1];
685 struct sigaction sa = {};
686 sa.sa_sigaction = SigBusHandler;
687 sa.sa_flags = SA_SIGINFO;
688 BPF_ASSERT(sigaction(SIGBUS, &sa, NULL) == 0);
691 BPF_ASSERT(read(fds[0], &c, 1) == 1);
692 BPF_ASSERT(close(fds[0]) == 0);
693 BPF_ASSERT(close(fds[1]) == 0);
694 BPF_ASSERT(c == 0x55);
697 BPF_TEST_C(SandboxBPF, SigMask, RedirectAllSyscallsPolicy) {
698 // Signal masks are potentially tricky to handle. For instance, if we
699 // ever tried to update them from inside a Trap() or UnsafeTrap() handler,
700 // the call to sigreturn() at the end of the signal handler would undo
701 // all of our efforts. So, it makes sense to test that sigprocmask()
702 // works, even if we have a policy in place that makes use of UnsafeTrap().
703 // In practice, this works because we force sigprocmask() to be handled
704 // entirely in the kernel.
705 sigset_t mask0, mask1, mask2;
707 // Call sigprocmask() to verify that SIGUSR2 wasn't blocked, if we didn't
708 // change the mask (it shouldn't have been, as it isn't blocked by default
711 // Use SIGUSR2 because Android seems to use SIGUSR1 for some purpose.
713 BPF_ASSERT(!sigprocmask(SIG_BLOCK, &mask0, &mask1));
714 BPF_ASSERT(!sigismember(&mask1, SIGUSR2));
716 // Try again, and this time we verify that we can block it. This
717 // requires a second call to sigprocmask().
718 sigaddset(&mask0, SIGUSR2);
719 BPF_ASSERT(!sigprocmask(SIG_BLOCK, &mask0, NULL));
720 BPF_ASSERT(!sigprocmask(SIG_BLOCK, NULL, &mask2));
721 BPF_ASSERT(sigismember(&mask2, SIGUSR2));
724 BPF_TEST_C(SandboxBPF, UnsafeTrapWithErrno, RedirectAllSyscallsPolicy) {
725 // An UnsafeTrap() (or for that matter, a Trap()) has to report error
726 // conditions by returning an exit code in the range -1..-4096. This
727 // should happen automatically if using ForwardSyscall(). If the TrapFnc()
728 // uses some other method to make system calls, then it is responsible
729 // for computing the correct return code.
730 // This test verifies that ForwardSyscall() does the correct thing.
732 // The glibc system wrapper will ultimately set errno for us. So, from normal
733 // userspace, all of this should be completely transparent.
735 BPF_ASSERT(close(-1) == -1);
736 BPF_ASSERT(errno == EBADF);
738 // Explicitly avoid the glibc wrapper. This is not normally the way anybody
739 // would make system calls, but it allows us to verify that we don't
740 // accidentally mess with errno, when we shouldn't.
742 struct arch_seccomp_data args = {};
743 args.nr = __NR_close;
745 BPF_ASSERT(SandboxBPF::ForwardSyscall(args) == -EBADF);
746 BPF_ASSERT(errno == 0);
749 bool NoOpCallback() {
753 // Test a trap handler that makes use of a broker process to open().
755 class InitializedOpenBroker {
757 InitializedOpenBroker() : initialized_(false) {
758 std::vector<std::string> allowed_files;
759 allowed_files.push_back("/proc/allowed");
760 allowed_files.push_back("/proc/cpuinfo");
762 broker_process_.reset(
763 new BrokerProcess(EPERM, allowed_files, std::vector<std::string>()));
764 BPF_ASSERT(broker_process() != NULL);
765 BPF_ASSERT(broker_process_->Init(base::Bind(&NoOpCallback)));
769 bool initialized() { return initialized_; }
770 class BrokerProcess* broker_process() { return broker_process_.get(); }
774 scoped_ptr<class BrokerProcess> broker_process_;
775 DISALLOW_COPY_AND_ASSIGN(InitializedOpenBroker);
778 intptr_t BrokerOpenTrapHandler(const struct arch_seccomp_data& args,
781 BrokerProcess* broker_process = static_cast<BrokerProcess*>(aux);
783 case __NR_faccessat: // access is a wrapper of faccessat in android
784 BPF_ASSERT(static_cast<int>(args.args[0]) == AT_FDCWD);
785 return broker_process->Access(reinterpret_cast<const char*>(args.args[1]),
786 static_cast<int>(args.args[2]));
787 #if defined(__NR_access)
789 return broker_process->Access(reinterpret_cast<const char*>(args.args[0]),
790 static_cast<int>(args.args[1]));
792 #if defined(__NR_open)
794 return broker_process->Open(reinterpret_cast<const char*>(args.args[0]),
795 static_cast<int>(args.args[1]));
798 // We only call open() so if we arrive here, it's because glibc uses
799 // the openat() system call.
800 BPF_ASSERT(static_cast<int>(args.args[0]) == AT_FDCWD);
801 return broker_process->Open(reinterpret_cast<const char*>(args.args[1]),
802 static_cast<int>(args.args[2]));
809 class DenyOpenPolicy : public Policy {
811 explicit DenyOpenPolicy(InitializedOpenBroker* iob) : iob_(iob) {}
812 ~DenyOpenPolicy() override {}
814 ResultExpr EvaluateSyscall(int sysno) const override {
815 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
819 #if defined(__NR_access)
822 #if defined(__NR_open)
826 // We get a InitializedOpenBroker class, but our trap handler wants
827 // the BrokerProcess object.
828 return Trap(BrokerOpenTrapHandler, iob_->broker_process());
835 InitializedOpenBroker* iob_;
837 DISALLOW_COPY_AND_ASSIGN(DenyOpenPolicy);
840 // We use a InitializedOpenBroker class, so that we can run unsandboxed
841 // code in its constructor, which is the only way to do so in a BPF_TEST.
845 InitializedOpenBroker /* (*BPF_AUX) */) {
846 BPF_ASSERT(BPF_AUX->initialized());
847 BrokerProcess* broker_process = BPF_AUX->broker_process();
848 BPF_ASSERT(broker_process != NULL);
850 // First, use the broker "manually"
851 BPF_ASSERT(broker_process->Open("/proc/denied", O_RDONLY) == -EPERM);
852 BPF_ASSERT(broker_process->Access("/proc/denied", R_OK) == -EPERM);
853 BPF_ASSERT(broker_process->Open("/proc/allowed", O_RDONLY) == -ENOENT);
854 BPF_ASSERT(broker_process->Access("/proc/allowed", R_OK) == -ENOENT);
856 // Now use glibc's open() as an external library would.
857 BPF_ASSERT(open("/proc/denied", O_RDONLY) == -1);
858 BPF_ASSERT(errno == EPERM);
860 BPF_ASSERT(open("/proc/allowed", O_RDONLY) == -1);
861 BPF_ASSERT(errno == ENOENT);
863 // Also test glibc's openat(), some versions of libc use it transparently
864 // instead of open().
865 BPF_ASSERT(openat(AT_FDCWD, "/proc/denied", O_RDONLY) == -1);
866 BPF_ASSERT(errno == EPERM);
868 BPF_ASSERT(openat(AT_FDCWD, "/proc/allowed", O_RDONLY) == -1);
869 BPF_ASSERT(errno == ENOENT);
871 // And test glibc's access().
872 BPF_ASSERT(access("/proc/denied", R_OK) == -1);
873 BPF_ASSERT(errno == EPERM);
875 BPF_ASSERT(access("/proc/allowed", R_OK) == -1);
876 BPF_ASSERT(errno == ENOENT);
878 // This is also white listed and does exist.
879 int cpu_info_access = access("/proc/cpuinfo", R_OK);
880 BPF_ASSERT(cpu_info_access == 0);
881 int cpu_info_fd = open("/proc/cpuinfo", O_RDONLY);
882 BPF_ASSERT(cpu_info_fd >= 0);
884 BPF_ASSERT(read(cpu_info_fd, buf, sizeof(buf)) > 0);
887 // Simple test demonstrating how to use SandboxBPF::Cond()
889 class SimpleCondTestPolicy : public Policy {
891 SimpleCondTestPolicy() {}
892 ~SimpleCondTestPolicy() override {}
894 ResultExpr EvaluateSyscall(int sysno) const override;
897 DISALLOW_COPY_AND_ASSIGN(SimpleCondTestPolicy);
900 ResultExpr SimpleCondTestPolicy::EvaluateSyscall(int sysno) const {
901 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
903 // We deliberately return unusual errno values upon failure, so that we
904 // can uniquely test for these values. In a "real" policy, you would want
905 // to return more traditional values.
906 int flags_argument_position = -1;
908 #if defined(__NR_open)
910 flags_argument_position = 1;
912 case __NR_openat: { // open can be a wrapper for openat(2).
913 if (sysno == __NR_openat)
914 flags_argument_position = 2;
916 // Allow opening files for reading, but don't allow writing.
917 COMPILE_ASSERT(O_RDONLY == 0, O_RDONLY_must_be_all_zero_bits);
918 const Arg<int> flags(flags_argument_position);
919 return If((flags & O_ACCMODE) != 0, Error(EROFS)).Else(Allow());
922 // Allow prctl(PR_SET_DUMPABLE) and prctl(PR_GET_DUMPABLE), but
923 // disallow everything else.
924 const Arg<int> option(0);
925 return If(option == PR_SET_DUMPABLE || option == PR_GET_DUMPABLE, Allow())
926 .Else(Error(ENOMEM));
933 BPF_TEST_C(SandboxBPF, SimpleCondTest, SimpleCondTestPolicy) {
935 BPF_ASSERT((fd = open("/proc/self/comm", O_RDWR)) == -1);
936 BPF_ASSERT(errno == EROFS);
937 BPF_ASSERT((fd = open("/proc/self/comm", O_RDONLY)) >= 0);
941 BPF_ASSERT((ret = prctl(PR_GET_DUMPABLE)) >= 0);
942 BPF_ASSERT(prctl(PR_SET_DUMPABLE, 1 - ret) == 0);
943 BPF_ASSERT(prctl(PR_GET_ENDIAN, &ret) == -1);
944 BPF_ASSERT(errno == ENOMEM);
947 // This test exercises the SandboxBPF::Cond() method by building a complex
948 // tree of conditional equality operations. It then makes system calls and
949 // verifies that they return the values that we expected from our BPF
951 class EqualityStressTest {
953 EqualityStressTest() {
954 // We want a deterministic test
957 // Iterates over system call numbers and builds a random tree of
959 // We are actually constructing a graph of ArgValue objects. This
960 // graph will later be used to a) compute our sandbox policy, and
961 // b) drive the code that verifies the output from the BPF program.
963 kNumTestCases < (int)(MAX_PUBLIC_SYSCALL - MIN_SYSCALL - 10),
964 num_test_cases_must_be_significantly_smaller_than_num_system_calls);
965 for (int sysno = MIN_SYSCALL, end = kNumTestCases; sysno < end; ++sysno) {
966 if (IsReservedSyscall(sysno)) {
967 // Skip reserved system calls. This ensures that our test frame
968 // work isn't impacted by the fact that we are overriding
969 // a lot of different system calls.
971 arg_values_.push_back(NULL);
973 arg_values_.push_back(
974 RandomArgValue(rand() % kMaxArgs, 0, rand() % kMaxArgs));
979 ~EqualityStressTest() {
980 for (std::vector<ArgValue*>::iterator iter = arg_values_.begin();
981 iter != arg_values_.end();
983 DeleteArgValue(*iter);
987 ResultExpr Policy(int sysno) {
988 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
989 if (sysno < 0 || sysno >= (int)arg_values_.size() ||
990 IsReservedSyscall(sysno)) {
991 // We only return ErrorCode values for the system calls that
992 // are part of our test data. Every other system call remains
996 // ToErrorCode() turns an ArgValue object into an ErrorCode that is
997 // suitable for use by a sandbox policy.
998 return ToErrorCode(arg_values_[sysno]);
1002 void VerifyFilter() {
1003 // Iterate over all system calls. Skip the system calls that have
1004 // previously been determined as being reserved.
1005 for (int sysno = 0; sysno < (int)arg_values_.size(); ++sysno) {
1006 if (!arg_values_[sysno]) {
1007 // Skip reserved system calls.
1010 // Verify that system calls return the values that we expect them to
1011 // return. This involves passing different combinations of system call
1012 // parameters in order to exercise all possible code paths through the
1013 // BPF filter program.
1014 // We arbitrarily start by setting all six system call arguments to
1015 // zero. And we then recursive traverse our tree of ArgValues to
1016 // determine the necessary combinations of parameters.
1017 intptr_t args[6] = {};
1018 Verify(sysno, args, *arg_values_[sysno]);
1024 int argno; // Argument number to inspect.
1025 int size; // Number of test cases (must be > 0).
1027 uint32_t k_value; // Value to compare syscall arg against.
1028 int err; // If non-zero, errno value to return.
1029 struct ArgValue* arg_value; // Otherwise, more args needs inspecting.
1031 int err; // If none of the tests passed, this is what
1032 struct ArgValue* arg_value; // we'll return (this is the "else" branch).
1035 bool IsReservedSyscall(int sysno) {
1036 // There are a handful of system calls that we should never use in our
1037 // test cases. These system calls are needed to allow the test framework
1039 // If we wanted to write fully generic code, there are more system calls
1040 // that could be listed here, and it is quite difficult to come up with a
1041 // truly comprehensive list. After all, we are deliberately making system
1042 // calls unavailable. In practice, we have a pretty good idea of the system
1043 // calls that will be made by this particular test. So, this small list is
1044 // sufficient. But if anybody copy'n'pasted this code for other uses, they
1045 // would have to review that the list.
1046 return sysno == __NR_read || sysno == __NR_write || sysno == __NR_exit ||
1047 sysno == __NR_exit_group || sysno == __NR_restart_syscall;
1050 ArgValue* RandomArgValue(int argno, int args_mask, int remaining_args) {
1051 // Create a new ArgValue and fill it with random data. We use as bit mask
1052 // to keep track of the system call parameters that have previously been
1053 // set; this ensures that we won't accidentally define a contradictory
1054 // set of equality tests.
1055 struct ArgValue* arg_value = new ArgValue();
1056 args_mask |= 1 << argno;
1057 arg_value->argno = argno;
1059 // Apply some restrictions on just how complex our tests can be.
1060 // Otherwise, we end up with a BPF program that is too complicated for
1061 // the kernel to load.
1062 int fan_out = kMaxFanOut;
1063 if (remaining_args > 3) {
1065 } else if (remaining_args > 2) {
1069 // Create a couple of different test cases with randomized values that
1070 // we want to use when comparing system call parameter number "argno".
1071 arg_value->size = rand() % fan_out + 1;
1072 arg_value->tests = new ArgValue::Tests[arg_value->size];
1074 uint32_t k_value = rand();
1075 for (int n = 0; n < arg_value->size; ++n) {
1076 // Ensure that we have unique values
1077 k_value += rand() % (RAND_MAX / (kMaxFanOut + 1)) + 1;
1079 // There are two possible types of nodes. Either this is a leaf node;
1080 // in that case, we have completed all the equality tests that we
1081 // wanted to perform, and we can now compute a random "errno" value that
1082 // we should return. Or this is part of a more complex boolean
1083 // expression; in that case, we have to recursively add tests for some
1084 // of system call parameters that we have not yet included in our
1086 arg_value->tests[n].k_value = k_value;
1087 if (!remaining_args || (rand() & 1)) {
1088 arg_value->tests[n].err = (rand() % 1000) + 1;
1089 arg_value->tests[n].arg_value = NULL;
1091 arg_value->tests[n].err = 0;
1092 arg_value->tests[n].arg_value =
1093 RandomArgValue(RandomArg(args_mask), args_mask, remaining_args - 1);
1096 // Finally, we have to define what we should return if none of the
1097 // previous equality tests pass. Again, we can either deal with a leaf
1098 // node, or we can randomly add another couple of tests.
1099 if (!remaining_args || (rand() & 1)) {
1100 arg_value->err = (rand() % 1000) + 1;
1101 arg_value->arg_value = NULL;
1104 arg_value->arg_value =
1105 RandomArgValue(RandomArg(args_mask), args_mask, remaining_args - 1);
1107 // We have now built a new (sub-)tree of ArgValues defining a set of
1108 // boolean expressions for testing random system call arguments against
1109 // random values. Return this tree to our caller.
1113 int RandomArg(int args_mask) {
1114 // Compute a random system call parameter number.
1115 int argno = rand() % kMaxArgs;
1117 // Make sure that this same parameter number has not previously been
1118 // used. Otherwise, we could end up with a test that is impossible to
1119 // satisfy (e.g. args[0] == 1 && args[0] == 2).
1120 while (args_mask & (1 << argno)) {
1121 argno = (argno + 1) % kMaxArgs;
1126 void DeleteArgValue(ArgValue* arg_value) {
1127 // Delete an ArgValue and all of its child nodes. This requires
1128 // recursively descending into the tree.
1130 if (arg_value->size) {
1131 for (int n = 0; n < arg_value->size; ++n) {
1132 if (!arg_value->tests[n].err) {
1133 DeleteArgValue(arg_value->tests[n].arg_value);
1136 delete[] arg_value->tests;
1138 if (!arg_value->err) {
1139 DeleteArgValue(arg_value->arg_value);
1145 ResultExpr ToErrorCode(ArgValue* arg_value) {
1146 // Compute the ResultExpr that should be returned, if none of our
1147 // tests succeed (i.e. the system call parameter doesn't match any
1148 // of the values in arg_value->tests[].k_value).
1150 if (arg_value->err) {
1151 // If this was a leaf node, return the errno value that we expect to
1152 // return from the BPF filter program.
1153 err = Error(arg_value->err);
1155 // If this wasn't a leaf node yet, recursively descend into the rest
1156 // of the tree. This will end up adding a few more SandboxBPF::Cond()
1157 // tests to our ErrorCode.
1158 err = ToErrorCode(arg_value->arg_value);
1161 // Now, iterate over all the test cases that we want to compare against.
1162 // This builds a chain of SandboxBPF::Cond() tests
1163 // (aka "if ... elif ... elif ... elif ... fi")
1164 for (int n = arg_value->size; n-- > 0;) {
1166 // Again, we distinguish between leaf nodes and subtrees.
1167 if (arg_value->tests[n].err) {
1168 matched = Error(arg_value->tests[n].err);
1170 matched = ToErrorCode(arg_value->tests[n].arg_value);
1172 // For now, all of our tests are limited to 32bit.
1173 // We have separate tests that check the behavior of 32bit vs. 64bit
1174 // conditional expressions.
1175 const Arg<uint32_t> arg(arg_value->argno);
1176 err = If(arg == arg_value->tests[n].k_value, matched).Else(err);
1181 void Verify(int sysno, intptr_t* args, const ArgValue& arg_value) {
1182 uint32_t mismatched = 0;
1183 // Iterate over all the k_values in arg_value.tests[] and verify that
1184 // we see the expected return values from system calls, when we pass
1185 // the k_value as a parameter in a system call.
1186 for (int n = arg_value.size; n-- > 0;) {
1187 mismatched += arg_value.tests[n].k_value;
1188 args[arg_value.argno] = arg_value.tests[n].k_value;
1189 if (arg_value.tests[n].err) {
1190 VerifyErrno(sysno, args, arg_value.tests[n].err);
1192 Verify(sysno, args, *arg_value.tests[n].arg_value);
1195 // Find a k_value that doesn't match any of the k_values in
1196 // arg_value.tests[]. In most cases, the current value of "mismatched"
1197 // would fit this requirement. But on the off-chance that it happens
1198 // to collide, we double-check.
1200 for (int n = arg_value.size; n-- > 0;) {
1201 if (mismatched == arg_value.tests[n].k_value) {
1206 // Now verify that we see the expected return value from system calls,
1207 // if we pass a value that doesn't match any of the conditions (i.e. this
1208 // is testing the "else" clause of the conditions).
1209 args[arg_value.argno] = mismatched;
1210 if (arg_value.err) {
1211 VerifyErrno(sysno, args, arg_value.err);
1213 Verify(sysno, args, *arg_value.arg_value);
1215 // Reset args[arg_value.argno]. This is not technically needed, but it
1216 // makes it easier to reason about the correctness of our tests.
1217 args[arg_value.argno] = 0;
1220 void VerifyErrno(int sysno, intptr_t* args, int err) {
1221 // We installed BPF filters that return different errno values
1222 // based on the system call number and the parameters that we decided
1223 // to pass in. Verify that this condition holds true.
1226 sysno, args[0], args[1], args[2], args[3], args[4], args[5]) ==
1230 // Vector of ArgValue trees. These trees define all the possible boolean
1231 // expressions that we want to turn into a BPF filter program.
1232 std::vector<ArgValue*> arg_values_;
1234 // Don't increase these values. We are pushing the limits of the maximum
1235 // BPF program that the kernel will allow us to load. If the values are
1236 // increased too much, the test will start failing.
1237 #if defined(__aarch64__)
1238 static const int kNumTestCases = 30;
1240 static const int kNumTestCases = 40;
1242 static const int kMaxFanOut = 3;
1243 static const int kMaxArgs = 6;
1246 class EqualityStressTestPolicy : public Policy {
1248 explicit EqualityStressTestPolicy(EqualityStressTest* aux) : aux_(aux) {}
1249 ~EqualityStressTestPolicy() override {}
1251 ResultExpr EvaluateSyscall(int sysno) const override {
1252 return aux_->Policy(sysno);
1256 EqualityStressTest* aux_;
1258 DISALLOW_COPY_AND_ASSIGN(EqualityStressTestPolicy);
1261 BPF_TEST(SandboxBPF,
1263 EqualityStressTestPolicy,
1264 EqualityStressTest /* (*BPF_AUX) */) {
1265 BPF_AUX->VerifyFilter();
1268 class EqualityArgumentWidthPolicy : public Policy {
1270 EqualityArgumentWidthPolicy() {}
1271 ~EqualityArgumentWidthPolicy() override {}
1273 ResultExpr EvaluateSyscall(int sysno) const override;
1276 DISALLOW_COPY_AND_ASSIGN(EqualityArgumentWidthPolicy);
1279 ResultExpr EqualityArgumentWidthPolicy::EvaluateSyscall(int sysno) const {
1280 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
1281 if (sysno == __NR_uname) {
1282 const Arg<int> option(0);
1283 const Arg<uint32_t> arg32(1);
1284 const Arg<uint64_t> arg64(1);
1285 return Switch(option)
1286 .Case(0, If(arg32 == 0x55555555, Error(1)).Else(Error(2)))
1287 #if __SIZEOF_POINTER__ > 4
1288 .Case(1, If(arg64 == 0x55555555AAAAAAAAULL, Error(1)).Else(Error(2)))
1295 BPF_TEST_C(SandboxBPF, EqualityArgumentWidth, EqualityArgumentWidthPolicy) {
1296 BPF_ASSERT(Syscall::Call(__NR_uname, 0, 0x55555555) == -1);
1297 BPF_ASSERT(Syscall::Call(__NR_uname, 0, 0xAAAAAAAA) == -2);
1298 #if __SIZEOF_POINTER__ > 4
1299 // On 32bit machines, there is no way to pass a 64bit argument through the
1300 // syscall interface. So, we have to skip the part of the test that requires
1302 BPF_ASSERT(Syscall::Call(__NR_uname, 1, 0x55555555AAAAAAAAULL) == -1);
1303 BPF_ASSERT(Syscall::Call(__NR_uname, 1, 0x5555555500000000ULL) == -2);
1304 BPF_ASSERT(Syscall::Call(__NR_uname, 1, 0x5555555511111111ULL) == -2);
1305 BPF_ASSERT(Syscall::Call(__NR_uname, 1, 0x11111111AAAAAAAAULL) == -2);
1309 #if __SIZEOF_POINTER__ > 4
1310 // On 32bit machines, there is no way to pass a 64bit argument through the
1311 // syscall interface. So, we have to skip the part of the test that requires
1313 BPF_DEATH_TEST_C(SandboxBPF,
1314 EqualityArgumentUnallowed64bit,
1315 DEATH_MESSAGE("Unexpected 64bit argument detected"),
1316 EqualityArgumentWidthPolicy) {
1317 Syscall::Call(__NR_uname, 0, 0x5555555555555555ULL);
1321 class EqualityWithNegativeArgumentsPolicy : public Policy {
1323 EqualityWithNegativeArgumentsPolicy() {}
1324 ~EqualityWithNegativeArgumentsPolicy() override {}
1326 ResultExpr EvaluateSyscall(int sysno) const override {
1327 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
1328 if (sysno == __NR_uname) {
1329 // TODO(mdempsky): This currently can't be Arg<int> because then
1330 // 0xFFFFFFFF will be treated as a (signed) int, and then when
1331 // Arg::EqualTo casts it to uint64_t, it will be sign extended.
1332 const Arg<unsigned> arg(0);
1333 return If(arg == 0xFFFFFFFF, Error(1)).Else(Error(2));
1339 DISALLOW_COPY_AND_ASSIGN(EqualityWithNegativeArgumentsPolicy);
1342 BPF_TEST_C(SandboxBPF,
1343 EqualityWithNegativeArguments,
1344 EqualityWithNegativeArgumentsPolicy) {
1345 BPF_ASSERT(Syscall::Call(__NR_uname, 0xFFFFFFFF) == -1);
1346 BPF_ASSERT(Syscall::Call(__NR_uname, -1) == -1);
1347 BPF_ASSERT(Syscall::Call(__NR_uname, -1LL) == -1);
1350 #if __SIZEOF_POINTER__ > 4
1351 BPF_DEATH_TEST_C(SandboxBPF,
1352 EqualityWithNegative64bitArguments,
1353 DEATH_MESSAGE("Unexpected 64bit argument detected"),
1354 EqualityWithNegativeArgumentsPolicy) {
1355 // When expecting a 32bit system call argument, we look at the MSB of the
1356 // 64bit value and allow both "0" and "-1". But the latter is allowed only
1357 // iff the LSB was negative. So, this death test should error out.
1358 BPF_ASSERT(Syscall::Call(__NR_uname, 0xFFFFFFFF00000000LL) == -1);
1362 class AllBitTestPolicy : public Policy {
1364 AllBitTestPolicy() {}
1365 ~AllBitTestPolicy() override {}
1367 ResultExpr EvaluateSyscall(int sysno) const override;
1370 static ResultExpr HasAllBits32(uint32_t bits);
1371 static ResultExpr HasAllBits64(uint64_t bits);
1373 DISALLOW_COPY_AND_ASSIGN(AllBitTestPolicy);
1376 ResultExpr AllBitTestPolicy::HasAllBits32(uint32_t bits) {
1380 const Arg<uint32_t> arg(1);
1381 return If((arg & bits) == bits, Error(1)).Else(Error(0));
1384 ResultExpr AllBitTestPolicy::HasAllBits64(uint64_t bits) {
1388 const Arg<uint64_t> arg(1);
1389 return If((arg & bits) == bits, Error(1)).Else(Error(0));
1392 ResultExpr AllBitTestPolicy::EvaluateSyscall(int sysno) const {
1393 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
1394 // Test masked-equality cases that should trigger the "has all bits"
1395 // peephole optimizations. We try to find bitmasks that could conceivably
1396 // touch corner cases.
1397 // For all of these tests, we override the uname(). We can make use with
1398 // a single system call number, as we use the first system call argument to
1399 // select the different bit masks that we want to test against.
1400 if (sysno == __NR_uname) {
1401 const Arg<int> option(0);
1402 return Switch(option)
1403 .Case(0, HasAllBits32(0x0))
1404 .Case(1, HasAllBits32(0x1))
1405 .Case(2, HasAllBits32(0x3))
1406 .Case(3, HasAllBits32(0x80000000))
1407 #if __SIZEOF_POINTER__ > 4
1408 .Case(4, HasAllBits64(0x0))
1409 .Case(5, HasAllBits64(0x1))
1410 .Case(6, HasAllBits64(0x3))
1411 .Case(7, HasAllBits64(0x80000000))
1412 .Case(8, HasAllBits64(0x100000000ULL))
1413 .Case(9, HasAllBits64(0x300000000ULL))
1414 .Case(10, HasAllBits64(0x100000001ULL))
1416 .Default(Kill("Invalid test case number"));
1421 // Define a macro that performs tests using our test policy.
1422 // NOTE: Not all of the arguments in this macro are actually used!
1423 // They are here just to serve as documentation of the conditions
1424 // implemented in the test policy.
1425 // Most notably, "op" and "mask" are unused by the macro. If you want
1426 // to make changes to these values, you will have to edit the
1427 // test policy instead.
1428 #define BITMASK_TEST(testcase, arg, op, mask, expected_value) \
1429 BPF_ASSERT(Syscall::Call(__NR_uname, (testcase), (arg)) == (expected_value))
1431 // Our uname() system call returns ErrorCode(1) for success and
1432 // ErrorCode(0) for failure. Syscall::Call() turns this into an
1433 // exit code of -1 or 0.
1434 #define EXPECT_FAILURE 0
1435 #define EXPECT_SUCCESS -1
1437 // A couple of our tests behave differently on 32bit and 64bit systems, as
1438 // there is no way for a 32bit system call to pass in a 64bit system call
1440 // We expect these tests to succeed on 64bit systems, but to tail on 32bit
1442 #define EXPT64_SUCCESS (sizeof(void*) > 4 ? EXPECT_SUCCESS : EXPECT_FAILURE)
1443 BPF_TEST_C(SandboxBPF, AllBitTests, AllBitTestPolicy) {
1444 // 32bit test: all of 0x0 (should always be true)
1445 BITMASK_TEST( 0, 0, ALLBITS32, 0, EXPECT_SUCCESS);
1446 BITMASK_TEST( 0, 1, ALLBITS32, 0, EXPECT_SUCCESS);
1447 BITMASK_TEST( 0, 3, ALLBITS32, 0, EXPECT_SUCCESS);
1448 BITMASK_TEST( 0, 0xFFFFFFFFU, ALLBITS32, 0, EXPECT_SUCCESS);
1449 BITMASK_TEST( 0, -1LL, ALLBITS32, 0, EXPECT_SUCCESS);
1451 // 32bit test: all of 0x1
1452 BITMASK_TEST( 1, 0, ALLBITS32, 0x1, EXPECT_FAILURE);
1453 BITMASK_TEST( 1, 1, ALLBITS32, 0x1, EXPECT_SUCCESS);
1454 BITMASK_TEST( 1, 2, ALLBITS32, 0x1, EXPECT_FAILURE);
1455 BITMASK_TEST( 1, 3, ALLBITS32, 0x1, EXPECT_SUCCESS);
1457 // 32bit test: all of 0x3
1458 BITMASK_TEST( 2, 0, ALLBITS32, 0x3, EXPECT_FAILURE);
1459 BITMASK_TEST( 2, 1, ALLBITS32, 0x3, EXPECT_FAILURE);
1460 BITMASK_TEST( 2, 2, ALLBITS32, 0x3, EXPECT_FAILURE);
1461 BITMASK_TEST( 2, 3, ALLBITS32, 0x3, EXPECT_SUCCESS);
1462 BITMASK_TEST( 2, 7, ALLBITS32, 0x3, EXPECT_SUCCESS);
1464 // 32bit test: all of 0x80000000
1465 BITMASK_TEST( 3, 0, ALLBITS32, 0x80000000, EXPECT_FAILURE);
1466 BITMASK_TEST( 3, 0x40000000U, ALLBITS32, 0x80000000, EXPECT_FAILURE);
1467 BITMASK_TEST( 3, 0x80000000U, ALLBITS32, 0x80000000, EXPECT_SUCCESS);
1468 BITMASK_TEST( 3, 0xC0000000U, ALLBITS32, 0x80000000, EXPECT_SUCCESS);
1469 BITMASK_TEST( 3, -0x80000000LL, ALLBITS32, 0x80000000, EXPECT_SUCCESS);
1471 #if __SIZEOF_POINTER__ > 4
1472 // 64bit test: all of 0x0 (should always be true)
1473 BITMASK_TEST( 4, 0, ALLBITS64, 0, EXPECT_SUCCESS);
1474 BITMASK_TEST( 4, 1, ALLBITS64, 0, EXPECT_SUCCESS);
1475 BITMASK_TEST( 4, 3, ALLBITS64, 0, EXPECT_SUCCESS);
1476 BITMASK_TEST( 4, 0xFFFFFFFFU, ALLBITS64, 0, EXPECT_SUCCESS);
1477 BITMASK_TEST( 4, 0x100000000LL, ALLBITS64, 0, EXPECT_SUCCESS);
1478 BITMASK_TEST( 4, 0x300000000LL, ALLBITS64, 0, EXPECT_SUCCESS);
1479 BITMASK_TEST( 4,0x8000000000000000LL, ALLBITS64, 0, EXPECT_SUCCESS);
1480 BITMASK_TEST( 4, -1LL, ALLBITS64, 0, EXPECT_SUCCESS);
1482 // 64bit test: all of 0x1
1483 BITMASK_TEST( 5, 0, ALLBITS64, 1, EXPECT_FAILURE);
1484 BITMASK_TEST( 5, 1, ALLBITS64, 1, EXPECT_SUCCESS);
1485 BITMASK_TEST( 5, 2, ALLBITS64, 1, EXPECT_FAILURE);
1486 BITMASK_TEST( 5, 3, ALLBITS64, 1, EXPECT_SUCCESS);
1487 BITMASK_TEST( 5, 0x100000000LL, ALLBITS64, 1, EXPECT_FAILURE);
1488 BITMASK_TEST( 5, 0x100000001LL, ALLBITS64, 1, EXPECT_SUCCESS);
1489 BITMASK_TEST( 5, 0x100000002LL, ALLBITS64, 1, EXPECT_FAILURE);
1490 BITMASK_TEST( 5, 0x100000003LL, ALLBITS64, 1, EXPECT_SUCCESS);
1492 // 64bit test: all of 0x3
1493 BITMASK_TEST( 6, 0, ALLBITS64, 3, EXPECT_FAILURE);
1494 BITMASK_TEST( 6, 1, ALLBITS64, 3, EXPECT_FAILURE);
1495 BITMASK_TEST( 6, 2, ALLBITS64, 3, EXPECT_FAILURE);
1496 BITMASK_TEST( 6, 3, ALLBITS64, 3, EXPECT_SUCCESS);
1497 BITMASK_TEST( 6, 7, ALLBITS64, 3, EXPECT_SUCCESS);
1498 BITMASK_TEST( 6, 0x100000000LL, ALLBITS64, 3, EXPECT_FAILURE);
1499 BITMASK_TEST( 6, 0x100000001LL, ALLBITS64, 3, EXPECT_FAILURE);
1500 BITMASK_TEST( 6, 0x100000002LL, ALLBITS64, 3, EXPECT_FAILURE);
1501 BITMASK_TEST( 6, 0x100000003LL, ALLBITS64, 3, EXPECT_SUCCESS);
1502 BITMASK_TEST( 6, 0x100000007LL, ALLBITS64, 3, EXPECT_SUCCESS);
1504 // 64bit test: all of 0x80000000
1505 BITMASK_TEST( 7, 0, ALLBITS64, 0x80000000, EXPECT_FAILURE);
1506 BITMASK_TEST( 7, 0x40000000U, ALLBITS64, 0x80000000, EXPECT_FAILURE);
1507 BITMASK_TEST( 7, 0x80000000U, ALLBITS64, 0x80000000, EXPECT_SUCCESS);
1508 BITMASK_TEST( 7, 0xC0000000U, ALLBITS64, 0x80000000, EXPECT_SUCCESS);
1509 BITMASK_TEST( 7, -0x80000000LL, ALLBITS64, 0x80000000, EXPECT_SUCCESS);
1510 BITMASK_TEST( 7, 0x100000000LL, ALLBITS64, 0x80000000, EXPECT_FAILURE);
1511 BITMASK_TEST( 7, 0x140000000LL, ALLBITS64, 0x80000000, EXPECT_FAILURE);
1512 BITMASK_TEST( 7, 0x180000000LL, ALLBITS64, 0x80000000, EXPECT_SUCCESS);
1513 BITMASK_TEST( 7, 0x1C0000000LL, ALLBITS64, 0x80000000, EXPECT_SUCCESS);
1514 BITMASK_TEST( 7, -0x180000000LL, ALLBITS64, 0x80000000, EXPECT_SUCCESS);
1516 // 64bit test: all of 0x100000000
1517 BITMASK_TEST( 8, 0x000000000LL, ALLBITS64,0x100000000, EXPECT_FAILURE);
1518 BITMASK_TEST( 8, 0x100000000LL, ALLBITS64,0x100000000, EXPT64_SUCCESS);
1519 BITMASK_TEST( 8, 0x200000000LL, ALLBITS64,0x100000000, EXPECT_FAILURE);
1520 BITMASK_TEST( 8, 0x300000000LL, ALLBITS64,0x100000000, EXPT64_SUCCESS);
1521 BITMASK_TEST( 8, 0x000000001LL, ALLBITS64,0x100000000, EXPECT_FAILURE);
1522 BITMASK_TEST( 8, 0x100000001LL, ALLBITS64,0x100000000, EXPT64_SUCCESS);
1523 BITMASK_TEST( 8, 0x200000001LL, ALLBITS64,0x100000000, EXPECT_FAILURE);
1524 BITMASK_TEST( 8, 0x300000001LL, ALLBITS64,0x100000000, EXPT64_SUCCESS);
1526 // 64bit test: all of 0x300000000
1527 BITMASK_TEST( 9, 0x000000000LL, ALLBITS64,0x300000000, EXPECT_FAILURE);
1528 BITMASK_TEST( 9, 0x100000000LL, ALLBITS64,0x300000000, EXPECT_FAILURE);
1529 BITMASK_TEST( 9, 0x200000000LL, ALLBITS64,0x300000000, EXPECT_FAILURE);
1530 BITMASK_TEST( 9, 0x300000000LL, ALLBITS64,0x300000000, EXPT64_SUCCESS);
1531 BITMASK_TEST( 9, 0x700000000LL, ALLBITS64,0x300000000, EXPT64_SUCCESS);
1532 BITMASK_TEST( 9, 0x000000001LL, ALLBITS64,0x300000000, EXPECT_FAILURE);
1533 BITMASK_TEST( 9, 0x100000001LL, ALLBITS64,0x300000000, EXPECT_FAILURE);
1534 BITMASK_TEST( 9, 0x200000001LL, ALLBITS64,0x300000000, EXPECT_FAILURE);
1535 BITMASK_TEST( 9, 0x300000001LL, ALLBITS64,0x300000000, EXPT64_SUCCESS);
1536 BITMASK_TEST( 9, 0x700000001LL, ALLBITS64,0x300000000, EXPT64_SUCCESS);
1538 // 64bit test: all of 0x100000001
1539 BITMASK_TEST(10, 0x000000000LL, ALLBITS64,0x100000001, EXPECT_FAILURE);
1540 BITMASK_TEST(10, 0x000000001LL, ALLBITS64,0x100000001, EXPECT_FAILURE);
1541 BITMASK_TEST(10, 0x100000000LL, ALLBITS64,0x100000001, EXPECT_FAILURE);
1542 BITMASK_TEST(10, 0x100000001LL, ALLBITS64,0x100000001, EXPT64_SUCCESS);
1543 BITMASK_TEST(10, 0xFFFFFFFFU, ALLBITS64,0x100000001, EXPECT_FAILURE);
1544 BITMASK_TEST(10, -1L, ALLBITS64,0x100000001, EXPT64_SUCCESS);
1548 class AnyBitTestPolicy : public Policy {
1550 AnyBitTestPolicy() {}
1551 ~AnyBitTestPolicy() override {}
1553 ResultExpr EvaluateSyscall(int sysno) const override;
1556 static ResultExpr HasAnyBits32(uint32_t);
1557 static ResultExpr HasAnyBits64(uint64_t);
1559 DISALLOW_COPY_AND_ASSIGN(AnyBitTestPolicy);
1562 ResultExpr AnyBitTestPolicy::HasAnyBits32(uint32_t bits) {
1566 const Arg<uint32_t> arg(1);
1567 return If((arg & bits) != 0, Error(1)).Else(Error(0));
1570 ResultExpr AnyBitTestPolicy::HasAnyBits64(uint64_t bits) {
1574 const Arg<uint64_t> arg(1);
1575 return If((arg & bits) != 0, Error(1)).Else(Error(0));
1578 ResultExpr AnyBitTestPolicy::EvaluateSyscall(int sysno) const {
1579 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
1580 // Test masked-equality cases that should trigger the "has any bits"
1581 // peephole optimizations. We try to find bitmasks that could conceivably
1582 // touch corner cases.
1583 // For all of these tests, we override the uname(). We can make use with
1584 // a single system call number, as we use the first system call argument to
1585 // select the different bit masks that we want to test against.
1586 if (sysno == __NR_uname) {
1587 const Arg<int> option(0);
1588 return Switch(option)
1589 .Case(0, HasAnyBits32(0x0))
1590 .Case(1, HasAnyBits32(0x1))
1591 .Case(2, HasAnyBits32(0x3))
1592 .Case(3, HasAnyBits32(0x80000000))
1593 #if __SIZEOF_POINTER__ > 4
1594 .Case(4, HasAnyBits64(0x0))
1595 .Case(5, HasAnyBits64(0x1))
1596 .Case(6, HasAnyBits64(0x3))
1597 .Case(7, HasAnyBits64(0x80000000))
1598 .Case(8, HasAnyBits64(0x100000000ULL))
1599 .Case(9, HasAnyBits64(0x300000000ULL))
1600 .Case(10, HasAnyBits64(0x100000001ULL))
1602 .Default(Kill("Invalid test case number"));
1607 BPF_TEST_C(SandboxBPF, AnyBitTests, AnyBitTestPolicy) {
1608 // 32bit test: any of 0x0 (should always be false)
1609 BITMASK_TEST( 0, 0, ANYBITS32, 0x0, EXPECT_FAILURE);
1610 BITMASK_TEST( 0, 1, ANYBITS32, 0x0, EXPECT_FAILURE);
1611 BITMASK_TEST( 0, 3, ANYBITS32, 0x0, EXPECT_FAILURE);
1612 BITMASK_TEST( 0, 0xFFFFFFFFU, ANYBITS32, 0x0, EXPECT_FAILURE);
1613 BITMASK_TEST( 0, -1LL, ANYBITS32, 0x0, EXPECT_FAILURE);
1615 // 32bit test: any of 0x1
1616 BITMASK_TEST( 1, 0, ANYBITS32, 0x1, EXPECT_FAILURE);
1617 BITMASK_TEST( 1, 1, ANYBITS32, 0x1, EXPECT_SUCCESS);
1618 BITMASK_TEST( 1, 2, ANYBITS32, 0x1, EXPECT_FAILURE);
1619 BITMASK_TEST( 1, 3, ANYBITS32, 0x1, EXPECT_SUCCESS);
1621 // 32bit test: any of 0x3
1622 BITMASK_TEST( 2, 0, ANYBITS32, 0x3, EXPECT_FAILURE);
1623 BITMASK_TEST( 2, 1, ANYBITS32, 0x3, EXPECT_SUCCESS);
1624 BITMASK_TEST( 2, 2, ANYBITS32, 0x3, EXPECT_SUCCESS);
1625 BITMASK_TEST( 2, 3, ANYBITS32, 0x3, EXPECT_SUCCESS);
1626 BITMASK_TEST( 2, 7, ANYBITS32, 0x3, EXPECT_SUCCESS);
1628 // 32bit test: any of 0x80000000
1629 BITMASK_TEST( 3, 0, ANYBITS32, 0x80000000, EXPECT_FAILURE);
1630 BITMASK_TEST( 3, 0x40000000U, ANYBITS32, 0x80000000, EXPECT_FAILURE);
1631 BITMASK_TEST( 3, 0x80000000U, ANYBITS32, 0x80000000, EXPECT_SUCCESS);
1632 BITMASK_TEST( 3, 0xC0000000U, ANYBITS32, 0x80000000, EXPECT_SUCCESS);
1633 BITMASK_TEST( 3, -0x80000000LL, ANYBITS32, 0x80000000, EXPECT_SUCCESS);
1635 #if __SIZEOF_POINTER__ > 4
1636 // 64bit test: any of 0x0 (should always be false)
1637 BITMASK_TEST( 4, 0, ANYBITS64, 0x0, EXPECT_FAILURE);
1638 BITMASK_TEST( 4, 1, ANYBITS64, 0x0, EXPECT_FAILURE);
1639 BITMASK_TEST( 4, 3, ANYBITS64, 0x0, EXPECT_FAILURE);
1640 BITMASK_TEST( 4, 0xFFFFFFFFU, ANYBITS64, 0x0, EXPECT_FAILURE);
1641 BITMASK_TEST( 4, 0x100000000LL, ANYBITS64, 0x0, EXPECT_FAILURE);
1642 BITMASK_TEST( 4, 0x300000000LL, ANYBITS64, 0x0, EXPECT_FAILURE);
1643 BITMASK_TEST( 4,0x8000000000000000LL, ANYBITS64, 0x0, EXPECT_FAILURE);
1644 BITMASK_TEST( 4, -1LL, ANYBITS64, 0x0, EXPECT_FAILURE);
1646 // 64bit test: any of 0x1
1647 BITMASK_TEST( 5, 0, ANYBITS64, 0x1, EXPECT_FAILURE);
1648 BITMASK_TEST( 5, 1, ANYBITS64, 0x1, EXPECT_SUCCESS);
1649 BITMASK_TEST( 5, 2, ANYBITS64, 0x1, EXPECT_FAILURE);
1650 BITMASK_TEST( 5, 3, ANYBITS64, 0x1, EXPECT_SUCCESS);
1651 BITMASK_TEST( 5, 0x100000001LL, ANYBITS64, 0x1, EXPECT_SUCCESS);
1652 BITMASK_TEST( 5, 0x100000000LL, ANYBITS64, 0x1, EXPECT_FAILURE);
1653 BITMASK_TEST( 5, 0x100000002LL, ANYBITS64, 0x1, EXPECT_FAILURE);
1654 BITMASK_TEST( 5, 0x100000003LL, ANYBITS64, 0x1, EXPECT_SUCCESS);
1656 // 64bit test: any of 0x3
1657 BITMASK_TEST( 6, 0, ANYBITS64, 0x3, EXPECT_FAILURE);
1658 BITMASK_TEST( 6, 1, ANYBITS64, 0x3, EXPECT_SUCCESS);
1659 BITMASK_TEST( 6, 2, ANYBITS64, 0x3, EXPECT_SUCCESS);
1660 BITMASK_TEST( 6, 3, ANYBITS64, 0x3, EXPECT_SUCCESS);
1661 BITMASK_TEST( 6, 7, ANYBITS64, 0x3, EXPECT_SUCCESS);
1662 BITMASK_TEST( 6, 0x100000000LL, ANYBITS64, 0x3, EXPECT_FAILURE);
1663 BITMASK_TEST( 6, 0x100000001LL, ANYBITS64, 0x3, EXPECT_SUCCESS);
1664 BITMASK_TEST( 6, 0x100000002LL, ANYBITS64, 0x3, EXPECT_SUCCESS);
1665 BITMASK_TEST( 6, 0x100000003LL, ANYBITS64, 0x3, EXPECT_SUCCESS);
1666 BITMASK_TEST( 6, 0x100000007LL, ANYBITS64, 0x3, EXPECT_SUCCESS);
1668 // 64bit test: any of 0x80000000
1669 BITMASK_TEST( 7, 0, ANYBITS64, 0x80000000, EXPECT_FAILURE);
1670 BITMASK_TEST( 7, 0x40000000U, ANYBITS64, 0x80000000, EXPECT_FAILURE);
1671 BITMASK_TEST( 7, 0x80000000U, ANYBITS64, 0x80000000, EXPECT_SUCCESS);
1672 BITMASK_TEST( 7, 0xC0000000U, ANYBITS64, 0x80000000, EXPECT_SUCCESS);
1673 BITMASK_TEST( 7, -0x80000000LL, ANYBITS64, 0x80000000, EXPECT_SUCCESS);
1674 BITMASK_TEST( 7, 0x100000000LL, ANYBITS64, 0x80000000, EXPECT_FAILURE);
1675 BITMASK_TEST( 7, 0x140000000LL, ANYBITS64, 0x80000000, EXPECT_FAILURE);
1676 BITMASK_TEST( 7, 0x180000000LL, ANYBITS64, 0x80000000, EXPECT_SUCCESS);
1677 BITMASK_TEST( 7, 0x1C0000000LL, ANYBITS64, 0x80000000, EXPECT_SUCCESS);
1678 BITMASK_TEST( 7, -0x180000000LL, ANYBITS64, 0x80000000, EXPECT_SUCCESS);
1680 // 64bit test: any of 0x100000000
1681 BITMASK_TEST( 8, 0x000000000LL, ANYBITS64,0x100000000, EXPECT_FAILURE);
1682 BITMASK_TEST( 8, 0x100000000LL, ANYBITS64,0x100000000, EXPT64_SUCCESS);
1683 BITMASK_TEST( 8, 0x200000000LL, ANYBITS64,0x100000000, EXPECT_FAILURE);
1684 BITMASK_TEST( 8, 0x300000000LL, ANYBITS64,0x100000000, EXPT64_SUCCESS);
1685 BITMASK_TEST( 8, 0x000000001LL, ANYBITS64,0x100000000, EXPECT_FAILURE);
1686 BITMASK_TEST( 8, 0x100000001LL, ANYBITS64,0x100000000, EXPT64_SUCCESS);
1687 BITMASK_TEST( 8, 0x200000001LL, ANYBITS64,0x100000000, EXPECT_FAILURE);
1688 BITMASK_TEST( 8, 0x300000001LL, ANYBITS64,0x100000000, EXPT64_SUCCESS);
1690 // 64bit test: any of 0x300000000
1691 BITMASK_TEST( 9, 0x000000000LL, ANYBITS64,0x300000000, EXPECT_FAILURE);
1692 BITMASK_TEST( 9, 0x100000000LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1693 BITMASK_TEST( 9, 0x200000000LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1694 BITMASK_TEST( 9, 0x300000000LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1695 BITMASK_TEST( 9, 0x700000000LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1696 BITMASK_TEST( 9, 0x000000001LL, ANYBITS64,0x300000000, EXPECT_FAILURE);
1697 BITMASK_TEST( 9, 0x100000001LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1698 BITMASK_TEST( 9, 0x200000001LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1699 BITMASK_TEST( 9, 0x300000001LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1700 BITMASK_TEST( 9, 0x700000001LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1702 // 64bit test: any of 0x100000001
1703 BITMASK_TEST( 10, 0x000000000LL, ANYBITS64,0x100000001, EXPECT_FAILURE);
1704 BITMASK_TEST( 10, 0x000000001LL, ANYBITS64,0x100000001, EXPECT_SUCCESS);
1705 BITMASK_TEST( 10, 0x100000000LL, ANYBITS64,0x100000001, EXPT64_SUCCESS);
1706 BITMASK_TEST( 10, 0x100000001LL, ANYBITS64,0x100000001, EXPECT_SUCCESS);
1707 BITMASK_TEST( 10, 0xFFFFFFFFU, ANYBITS64,0x100000001, EXPECT_SUCCESS);
1708 BITMASK_TEST( 10, -1L, ANYBITS64,0x100000001, EXPECT_SUCCESS);
1712 class MaskedEqualTestPolicy : public Policy {
1714 MaskedEqualTestPolicy() {}
1715 ~MaskedEqualTestPolicy() override {}
1717 ResultExpr EvaluateSyscall(int sysno) const override;
1720 static ResultExpr MaskedEqual32(uint32_t mask, uint32_t value);
1721 static ResultExpr MaskedEqual64(uint64_t mask, uint64_t value);
1723 DISALLOW_COPY_AND_ASSIGN(MaskedEqualTestPolicy);
1726 ResultExpr MaskedEqualTestPolicy::MaskedEqual32(uint32_t mask, uint32_t value) {
1727 const Arg<uint32_t> arg(1);
1728 return If((arg & mask) == value, Error(1)).Else(Error(0));
1731 ResultExpr MaskedEqualTestPolicy::MaskedEqual64(uint64_t mask, uint64_t value) {
1732 const Arg<uint64_t> arg(1);
1733 return If((arg & mask) == value, Error(1)).Else(Error(0));
1736 ResultExpr MaskedEqualTestPolicy::EvaluateSyscall(int sysno) const {
1737 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
1739 if (sysno == __NR_uname) {
1740 const Arg<int> option(0);
1741 return Switch(option)
1742 .Case(0, MaskedEqual32(0x00ff00ff, 0x005500aa))
1743 #if __SIZEOF_POINTER__ > 4
1744 .Case(1, MaskedEqual64(0x00ff00ff00000000, 0x005500aa00000000))
1745 .Case(2, MaskedEqual64(0x00ff00ff00ff00ff, 0x005500aa005500aa))
1747 .Default(Kill("Invalid test case number"));
1753 #define MASKEQ_TEST(rulenum, arg, expected_result) \
1754 BPF_ASSERT(Syscall::Call(__NR_uname, (rulenum), (arg)) == (expected_result))
1756 BPF_TEST_C(SandboxBPF, MaskedEqualTests, MaskedEqualTestPolicy) {
1757 // Allowed: 0x__55__aa
1758 MASKEQ_TEST(0, 0x00000000, EXPECT_FAILURE);
1759 MASKEQ_TEST(0, 0x00000001, EXPECT_FAILURE);
1760 MASKEQ_TEST(0, 0x00000003, EXPECT_FAILURE);
1761 MASKEQ_TEST(0, 0x00000100, EXPECT_FAILURE);
1762 MASKEQ_TEST(0, 0x00000300, EXPECT_FAILURE);
1763 MASKEQ_TEST(0, 0x005500aa, EXPECT_SUCCESS);
1764 MASKEQ_TEST(0, 0x005500ab, EXPECT_FAILURE);
1765 MASKEQ_TEST(0, 0x005600aa, EXPECT_FAILURE);
1766 MASKEQ_TEST(0, 0x005501aa, EXPECT_SUCCESS);
1767 MASKEQ_TEST(0, 0x005503aa, EXPECT_SUCCESS);
1768 MASKEQ_TEST(0, 0x555500aa, EXPECT_SUCCESS);
1769 MASKEQ_TEST(0, 0xaa5500aa, EXPECT_SUCCESS);
1771 #if __SIZEOF_POINTER__ > 4
1772 // Allowed: 0x__55__aa________
1773 MASKEQ_TEST(1, 0x0000000000000000, EXPECT_FAILURE);
1774 MASKEQ_TEST(1, 0x0000000000000010, EXPECT_FAILURE);
1775 MASKEQ_TEST(1, 0x0000000000000050, EXPECT_FAILURE);
1776 MASKEQ_TEST(1, 0x0000000100000000, EXPECT_FAILURE);
1777 MASKEQ_TEST(1, 0x0000000300000000, EXPECT_FAILURE);
1778 MASKEQ_TEST(1, 0x0000010000000000, EXPECT_FAILURE);
1779 MASKEQ_TEST(1, 0x0000030000000000, EXPECT_FAILURE);
1780 MASKEQ_TEST(1, 0x005500aa00000000, EXPECT_SUCCESS);
1781 MASKEQ_TEST(1, 0x005500ab00000000, EXPECT_FAILURE);
1782 MASKEQ_TEST(1, 0x005600aa00000000, EXPECT_FAILURE);
1783 MASKEQ_TEST(1, 0x005501aa00000000, EXPECT_SUCCESS);
1784 MASKEQ_TEST(1, 0x005503aa00000000, EXPECT_SUCCESS);
1785 MASKEQ_TEST(1, 0x555500aa00000000, EXPECT_SUCCESS);
1786 MASKEQ_TEST(1, 0xaa5500aa00000000, EXPECT_SUCCESS);
1787 MASKEQ_TEST(1, 0xaa5500aa00000000, EXPECT_SUCCESS);
1788 MASKEQ_TEST(1, 0xaa5500aa0000cafe, EXPECT_SUCCESS);
1790 // Allowed: 0x__55__aa__55__aa
1791 MASKEQ_TEST(2, 0x0000000000000000, EXPECT_FAILURE);
1792 MASKEQ_TEST(2, 0x0000000000000010, EXPECT_FAILURE);
1793 MASKEQ_TEST(2, 0x0000000000000050, EXPECT_FAILURE);
1794 MASKEQ_TEST(2, 0x0000000100000000, EXPECT_FAILURE);
1795 MASKEQ_TEST(2, 0x0000000300000000, EXPECT_FAILURE);
1796 MASKEQ_TEST(2, 0x0000010000000000, EXPECT_FAILURE);
1797 MASKEQ_TEST(2, 0x0000030000000000, EXPECT_FAILURE);
1798 MASKEQ_TEST(2, 0x00000000005500aa, EXPECT_FAILURE);
1799 MASKEQ_TEST(2, 0x005500aa00000000, EXPECT_FAILURE);
1800 MASKEQ_TEST(2, 0x005500aa005500aa, EXPECT_SUCCESS);
1801 MASKEQ_TEST(2, 0x005500aa005700aa, EXPECT_FAILURE);
1802 MASKEQ_TEST(2, 0x005700aa005500aa, EXPECT_FAILURE);
1803 MASKEQ_TEST(2, 0x005500aa004500aa, EXPECT_FAILURE);
1804 MASKEQ_TEST(2, 0x004500aa005500aa, EXPECT_FAILURE);
1805 MASKEQ_TEST(2, 0x005512aa005500aa, EXPECT_SUCCESS);
1806 MASKEQ_TEST(2, 0x005500aa005534aa, EXPECT_SUCCESS);
1807 MASKEQ_TEST(2, 0xff5500aa0055ffaa, EXPECT_SUCCESS);
1811 intptr_t PthreadTrapHandler(const struct arch_seccomp_data& args, void* aux) {
1812 if (args.args[0] != (CLONE_CHILD_CLEARTID | CLONE_CHILD_SETTID | SIGCHLD)) {
1813 // We expect to get called for an attempt to fork(). No need to log that
1814 // call. But if we ever get called for anything else, we want to verbosely
1815 // print as much information as possible.
1816 const char* msg = (const char*)aux;
1818 "Clone() was called with unexpected arguments\n"
1828 (long long)args.args[0],
1829 (long long)args.args[1],
1830 (long long)args.args[2],
1831 (long long)args.args[3],
1832 (long long)args.args[4],
1833 (long long)args.args[5],
1839 class PthreadPolicyEquality : public Policy {
1841 PthreadPolicyEquality() {}
1842 ~PthreadPolicyEquality() override {}
1844 ResultExpr EvaluateSyscall(int sysno) const override;
1847 DISALLOW_COPY_AND_ASSIGN(PthreadPolicyEquality);
1850 ResultExpr PthreadPolicyEquality::EvaluateSyscall(int sysno) const {
1851 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
1852 // This policy allows creating threads with pthread_create(). But it
1853 // doesn't allow any other uses of clone(). Most notably, it does not
1854 // allow callers to implement fork() or vfork() by passing suitable flags
1855 // to the clone() system call.
1856 if (sysno == __NR_clone) {
1857 // We have seen two different valid combinations of flags. Glibc
1858 // uses the more modern flags, sets the TLS from the call to clone(), and
1859 // uses futexes to monitor threads. Android's C run-time library, doesn't
1860 // do any of this, but it sets the obsolete (and no-op) CLONE_DETACHED.
1861 // More recent versions of Android don't set CLONE_DETACHED anymore, so
1862 // the last case accounts for that.
1863 // The following policy is very strict. It only allows the exact masks
1864 // that we have seen in known implementations. It is probably somewhat
1865 // stricter than what we would want to do.
1866 const uint64_t kGlibcCloneMask = CLONE_VM | CLONE_FS | CLONE_FILES |
1867 CLONE_SIGHAND | CLONE_THREAD |
1868 CLONE_SYSVSEM | CLONE_SETTLS |
1869 CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID;
1870 const uint64_t kBaseAndroidCloneMask = CLONE_VM | CLONE_FS | CLONE_FILES |
1871 CLONE_SIGHAND | CLONE_THREAD |
1873 const Arg<unsigned long> flags(0);
1874 return If(flags == kGlibcCloneMask ||
1875 flags == (kBaseAndroidCloneMask | CLONE_DETACHED) ||
1876 flags == kBaseAndroidCloneMask,
1877 Allow()).Else(Trap(PthreadTrapHandler, "Unknown mask"));
1883 class PthreadPolicyBitMask : public Policy {
1885 PthreadPolicyBitMask() {}
1886 ~PthreadPolicyBitMask() override {}
1888 ResultExpr EvaluateSyscall(int sysno) const override;
1891 static BoolExpr HasAnyBits(const Arg<unsigned long>& arg, unsigned long bits);
1892 static BoolExpr HasAllBits(const Arg<unsigned long>& arg, unsigned long bits);
1894 DISALLOW_COPY_AND_ASSIGN(PthreadPolicyBitMask);
1897 BoolExpr PthreadPolicyBitMask::HasAnyBits(const Arg<unsigned long>& arg,
1898 unsigned long bits) {
1899 return (arg & bits) != 0;
1902 BoolExpr PthreadPolicyBitMask::HasAllBits(const Arg<unsigned long>& arg,
1903 unsigned long bits) {
1904 return (arg & bits) == bits;
1907 ResultExpr PthreadPolicyBitMask::EvaluateSyscall(int sysno) const {
1908 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
1909 // This policy allows creating threads with pthread_create(). But it
1910 // doesn't allow any other uses of clone(). Most notably, it does not
1911 // allow callers to implement fork() or vfork() by passing suitable flags
1912 // to the clone() system call.
1913 if (sysno == __NR_clone) {
1914 // We have seen two different valid combinations of flags. Glibc
1915 // uses the more modern flags, sets the TLS from the call to clone(), and
1916 // uses futexes to monitor threads. Android's C run-time library, doesn't
1917 // do any of this, but it sets the obsolete (and no-op) CLONE_DETACHED.
1918 // The following policy allows for either combination of flags, but it
1919 // is generally a little more conservative than strictly necessary. We
1920 // err on the side of rather safe than sorry.
1921 // Very noticeably though, we disallow fork() (which is often just a
1922 // wrapper around clone()).
1923 const unsigned long kMandatoryFlags = CLONE_VM | CLONE_FS | CLONE_FILES |
1924 CLONE_SIGHAND | CLONE_THREAD |
1926 const unsigned long kFutexFlags =
1927 CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID;
1928 const unsigned long kNoopFlags = CLONE_DETACHED;
1929 const unsigned long kKnownFlags =
1930 kMandatoryFlags | kFutexFlags | kNoopFlags;
1932 const Arg<unsigned long> flags(0);
1933 return If(HasAnyBits(flags, ~kKnownFlags),
1934 Trap(PthreadTrapHandler, "Unexpected CLONE_XXX flag found"))
1935 .ElseIf(!HasAllBits(flags, kMandatoryFlags),
1936 Trap(PthreadTrapHandler,
1937 "Missing mandatory CLONE_XXX flags "
1938 "when creating new thread"))
1940 !HasAllBits(flags, kFutexFlags) && HasAnyBits(flags, kFutexFlags),
1941 Trap(PthreadTrapHandler,
1942 "Must set either all or none of the TLS and futex bits in "
1950 static void* ThreadFnc(void* arg) {
1951 ++*reinterpret_cast<int*>(arg);
1952 Syscall::Call(__NR_futex, arg, FUTEX_WAKE, 1, 0, 0, 0);
1956 static void PthreadTest() {
1957 // Attempt to start a joinable thread. This should succeed.
1960 BPF_ASSERT(!pthread_create(&thread, NULL, ThreadFnc, &thread_ran));
1961 BPF_ASSERT(!pthread_join(thread, NULL));
1962 BPF_ASSERT(thread_ran);
1964 // Attempt to start a detached thread. This should succeed.
1966 pthread_attr_t attr;
1967 BPF_ASSERT(!pthread_attr_init(&attr));
1968 BPF_ASSERT(!pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
1969 BPF_ASSERT(!pthread_create(&thread, &attr, ThreadFnc, &thread_ran));
1970 BPF_ASSERT(!pthread_attr_destroy(&attr));
1971 while (Syscall::Call(__NR_futex, &thread_ran, FUTEX_WAIT, 0, 0, 0, 0) ==
1974 BPF_ASSERT(thread_ran);
1976 // Attempt to fork() a process using clone(). This should fail. We use the
1977 // same flags that glibc uses when calling fork(). But we don't actually
1978 // try calling the fork() implementation in the C run-time library, as
1979 // run-time libraries other than glibc might call __NR_fork instead of
1980 // __NR_clone, and that would introduce a bogus test failure.
1982 BPF_ASSERT(Syscall::Call(__NR_clone,
1983 CLONE_CHILD_CLEARTID | CLONE_CHILD_SETTID | SIGCHLD,
1989 BPF_TEST_C(SandboxBPF, PthreadEquality, PthreadPolicyEquality) {
1993 BPF_TEST_C(SandboxBPF, PthreadBitMask, PthreadPolicyBitMask) {
1997 // libc might not define these even though the kernel supports it.
1998 #ifndef PTRACE_O_TRACESECCOMP
1999 #define PTRACE_O_TRACESECCOMP 0x00000080
2002 #ifdef PTRACE_EVENT_SECCOMP
2003 #define IS_SECCOMP_EVENT(status) ((status >> 16) == PTRACE_EVENT_SECCOMP)
2005 // When Debian/Ubuntu backported seccomp-bpf support into earlier kernels, they
2006 // changed the value of PTRACE_EVENT_SECCOMP from 7 to 8, since 7 was taken by
2007 // PTRACE_EVENT_STOP (upstream chose to renumber PTRACE_EVENT_STOP to 128). If
2008 // PTRACE_EVENT_SECCOMP isn't defined, we have no choice but to consider both
2010 #define IS_SECCOMP_EVENT(status) ((status >> 16) == 7 || (status >> 16) == 8)
2013 #if defined(__arm__)
2014 #ifndef PTRACE_SET_SYSCALL
2015 #define PTRACE_SET_SYSCALL 23
2019 #if defined(__aarch64__)
2020 #ifndef PTRACE_GETREGS
2021 #define PTRACE_GETREGS 12
2025 #if defined(__aarch64__)
2026 #ifndef PTRACE_SETREGS
2027 #define PTRACE_SETREGS 13
2031 // Changes the syscall to run for a child being sandboxed using seccomp-bpf with
2032 // PTRACE_O_TRACESECCOMP. Should only be called when the child is stopped on
2033 // PTRACE_EVENT_SECCOMP.
2035 // regs should contain the current set of registers of the child, obtained using
2038 // Depending on the architecture, this may modify regs, so the caller is
2039 // responsible for committing these changes using PTRACE_SETREGS.
2040 long SetSyscall(pid_t pid, regs_struct* regs, int syscall_number) {
2041 #if defined(__arm__)
2042 // On ARM, the syscall is changed using PTRACE_SET_SYSCALL. We cannot use the
2043 // libc ptrace call as the request parameter is an enum, and
2044 // PTRACE_SET_SYSCALL may not be in the enum.
2045 return syscall(__NR_ptrace, PTRACE_SET_SYSCALL, pid, NULL, syscall_number);
2048 SECCOMP_PT_SYSCALL(*regs) = syscall_number;
2052 const uint16_t kTraceData = 0xcc;
2054 class TraceAllPolicy : public Policy {
2057 ~TraceAllPolicy() override {}
2059 ResultExpr EvaluateSyscall(int system_call_number) const override {
2060 return Trace(kTraceData);
2064 DISALLOW_COPY_AND_ASSIGN(TraceAllPolicy);
2067 SANDBOX_TEST(SandboxBPF, DISABLE_ON_TSAN(SeccompRetTrace)) {
2068 if (SandboxBPF::SupportsSeccompSandbox(-1) !=
2069 sandbox::SandboxBPF::STATUS_AVAILABLE) {
2073 // This test is disabled on arm due to a kernel bug.
2074 // See https://code.google.com/p/chromium/issues/detail?id=383977
2075 #if defined(__arm__) || defined(__aarch64__)
2076 printf("This test is currently disabled on ARM32/64 due to a kernel bug.");
2080 #if defined(__mips__)
2081 // TODO: Figure out how to support specificity of handling indirect syscalls
2082 // in this test and enable it.
2083 printf("This test is currently disabled on MIPS.");
2088 BPF_ASSERT_NE(-1, pid);
2090 pid_t my_pid = getpid();
2091 BPF_ASSERT_NE(-1, ptrace(PTRACE_TRACEME, -1, NULL, NULL));
2092 BPF_ASSERT_EQ(0, raise(SIGSTOP));
2094 sandbox.SetSandboxPolicy(new TraceAllPolicy);
2095 BPF_ASSERT(sandbox.StartSandbox(SandboxBPF::PROCESS_SINGLE_THREADED));
2097 // getpid is allowed.
2098 BPF_ASSERT_EQ(my_pid, syscall(__NR_getpid));
2100 // write to stdout is skipped and returns a fake value.
2101 BPF_ASSERT_EQ(kExpectedReturnValue,
2102 syscall(__NR_write, STDOUT_FILENO, "A", 1));
2104 // kill is rewritten to exit(kExpectedReturnValue).
2105 syscall(__NR_kill, my_pid, SIGKILL);
2107 // Should not be reached.
2112 BPF_ASSERT(HANDLE_EINTR(waitpid(pid, &status, WUNTRACED)) != -1);
2113 BPF_ASSERT(WIFSTOPPED(status));
2116 ptrace(PTRACE_SETOPTIONS,
2119 reinterpret_cast<void*>(PTRACE_O_TRACESECCOMP)));
2120 BPF_ASSERT_NE(-1, ptrace(PTRACE_CONT, pid, NULL, NULL));
2122 BPF_ASSERT(HANDLE_EINTR(waitpid(pid, &status, 0)) != -1);
2123 if (WIFEXITED(status) || WIFSIGNALED(status)) {
2124 BPF_ASSERT(WIFEXITED(status));
2125 BPF_ASSERT_EQ(kExpectedReturnValue, WEXITSTATUS(status));
2129 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGTRAP ||
2130 !IS_SECCOMP_EVENT(status)) {
2131 BPF_ASSERT_NE(-1, ptrace(PTRACE_CONT, pid, NULL, NULL));
2136 BPF_ASSERT_NE(-1, ptrace(PTRACE_GETEVENTMSG, pid, NULL, &data));
2137 BPF_ASSERT_EQ(kTraceData, data);
2140 BPF_ASSERT_NE(-1, ptrace(PTRACE_GETREGS, pid, NULL, ®s));
2141 switch (SECCOMP_PT_SYSCALL(regs)) {
2143 // Skip writes to stdout, make it return kExpectedReturnValue. Allow
2144 // writes to stderr so that BPF_ASSERT messages show up.
2145 if (SECCOMP_PT_PARM1(regs) == STDOUT_FILENO) {
2146 BPF_ASSERT_NE(-1, SetSyscall(pid, ®s, -1));
2147 SECCOMP_PT_RESULT(regs) = kExpectedReturnValue;
2148 BPF_ASSERT_NE(-1, ptrace(PTRACE_SETREGS, pid, NULL, ®s));
2153 // Rewrite to exit(kExpectedReturnValue).
2154 BPF_ASSERT_NE(-1, SetSyscall(pid, ®s, __NR_exit));
2155 SECCOMP_PT_PARM1(regs) = kExpectedReturnValue;
2156 BPF_ASSERT_NE(-1, ptrace(PTRACE_SETREGS, pid, NULL, ®s));
2160 // Allow all other syscalls.
2164 BPF_ASSERT_NE(-1, ptrace(PTRACE_CONT, pid, NULL, NULL));
2168 // Android does not expose pread64 nor pwrite64.
2169 #if !defined(OS_ANDROID)
2171 bool FullPwrite64(int fd, const char* buffer, size_t count, off64_t offset) {
2173 const ssize_t transfered =
2174 HANDLE_EINTR(pwrite64(fd, buffer, count, offset));
2175 if (transfered <= 0 || static_cast<size_t>(transfered) > count) {
2178 count -= transfered;
2179 buffer += transfered;
2180 offset += transfered;
2185 bool FullPread64(int fd, char* buffer, size_t count, off64_t offset) {
2187 const ssize_t transfered = HANDLE_EINTR(pread64(fd, buffer, count, offset));
2188 if (transfered <= 0 || static_cast<size_t>(transfered) > count) {
2191 count -= transfered;
2192 buffer += transfered;
2193 offset += transfered;
2198 bool pread_64_was_forwarded = false;
2200 class TrapPread64Policy : public Policy {
2202 TrapPread64Policy() {}
2203 ~TrapPread64Policy() override {}
2205 ResultExpr EvaluateSyscall(int system_call_number) const override {
2206 // Set the global environment for unsafe traps once.
2207 if (system_call_number == MIN_SYSCALL) {
2208 EnableUnsafeTraps();
2211 if (system_call_number == __NR_pread64) {
2212 return UnsafeTrap(ForwardPreadHandler, NULL);
2218 static intptr_t ForwardPreadHandler(const struct arch_seccomp_data& args,
2220 BPF_ASSERT(args.nr == __NR_pread64);
2221 pread_64_was_forwarded = true;
2223 return SandboxBPF::ForwardSyscall(args);
2226 DISALLOW_COPY_AND_ASSIGN(TrapPread64Policy);
2229 // pread(2) takes a 64 bits offset. On 32 bits systems, it will be split
2230 // between two arguments. In this test, we make sure that ForwardSyscall() can
2231 // forward it properly.
2232 BPF_TEST_C(SandboxBPF, Pread64, TrapPread64Policy) {
2233 ScopedTemporaryFile temp_file;
2234 const uint64_t kLargeOffset = (static_cast<uint64_t>(1) << 32) | 0xBEEF;
2235 const char kTestString[] = "This is a test!";
2236 BPF_ASSERT(FullPwrite64(
2237 temp_file.fd(), kTestString, sizeof(kTestString), kLargeOffset));
2239 char read_test_string[sizeof(kTestString)] = {0};
2240 BPF_ASSERT(FullPread64(temp_file.fd(),
2242 sizeof(read_test_string),
2244 BPF_ASSERT_EQ(0, memcmp(kTestString, read_test_string, sizeof(kTestString)));
2245 BPF_ASSERT(pread_64_was_forwarded);
2248 #endif // !defined(OS_ANDROID)
2250 void* TsyncApplyToTwoThreadsFunc(void* cond_ptr) {
2251 base::WaitableEvent* event = static_cast<base::WaitableEvent*>(cond_ptr);
2253 // Wait for the main thread to signal that the filter has been applied.
2254 if (!event->IsSignaled()) {
2258 BPF_ASSERT(event->IsSignaled());
2260 BlacklistNanosleepPolicy::AssertNanosleepFails();
2265 SANDBOX_TEST(SandboxBPF, Tsync) {
2266 if (SandboxBPF::SupportsSeccompThreadFilterSynchronization() !=
2267 SandboxBPF::STATUS_AVAILABLE) {
2271 base::WaitableEvent event(true, false);
2273 // Create a thread on which to invoke the blocked syscall.
2276 0, pthread_create(&thread, NULL, &TsyncApplyToTwoThreadsFunc, &event));
2278 // Test that nanoseelp success.
2279 const struct timespec ts = {0, 0};
2280 BPF_ASSERT_EQ(0, HANDLE_EINTR(syscall(__NR_nanosleep, &ts, NULL)));
2282 // Engage the sandbox.
2284 sandbox.SetSandboxPolicy(new BlacklistNanosleepPolicy());
2285 BPF_ASSERT(sandbox.StartSandbox(SandboxBPF::PROCESS_MULTI_THREADED));
2287 // This thread should have the filter applied as well.
2288 BlacklistNanosleepPolicy::AssertNanosleepFails();
2290 // Signal the condition to invoke the system call.
2293 // Wait for the thread to finish.
2294 BPF_ASSERT_EQ(0, pthread_join(thread, NULL));
2297 class AllowAllPolicy : public Policy {
2300 ~AllowAllPolicy() override {}
2302 ResultExpr EvaluateSyscall(int sysno) const override { return Allow(); }
2305 DISALLOW_COPY_AND_ASSIGN(AllowAllPolicy);
2310 StartMultiThreadedAsSingleThreaded,
2311 DEATH_MESSAGE("Cannot start sandbox; process is already multi-threaded")) {
2312 base::Thread thread("sandbox.linux.StartMultiThreadedAsSingleThreaded");
2313 BPF_ASSERT(thread.Start());
2316 sandbox.SetSandboxPolicy(new AllowAllPolicy());
2317 BPF_ASSERT(!sandbox.StartSandbox(SandboxBPF::PROCESS_SINGLE_THREADED));
2320 // http://crbug.com/407357
2321 #if !defined(THREAD_SANITIZER)
2324 StartSingleThreadedAsMultiThreaded,
2326 "Cannot start sandbox; process may be single-threaded when "
2327 "reported as not")) {
2329 sandbox.SetSandboxPolicy(new AllowAllPolicy());
2330 BPF_ASSERT(!sandbox.StartSandbox(SandboxBPF::PROCESS_MULTI_THREADED));
2332 #endif // !defined(THREAD_SANITIZER)
2334 // A stub handler for the UnsafeTrap. Never called.
2335 intptr_t NoOpHandler(const struct arch_seccomp_data& args, void*) {
2339 class UnsafeTrapWithCondPolicy : public Policy {
2341 UnsafeTrapWithCondPolicy() {}
2342 ~UnsafeTrapWithCondPolicy() override {}
2344 ResultExpr EvaluateSyscall(int sysno) const override {
2345 DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
2346 setenv(kSandboxDebuggingEnv, "t", 0);
2347 Die::SuppressInfoMessages(true);
2349 if (SandboxBPF::IsRequiredForUnsafeTrap(sysno))
2354 const Arg<uint32_t> arg(0);
2355 return If(arg == 0, Allow()).Else(Error(EPERM));
2358 const Arg<uint32_t> arg(0);
2360 .Case(100, Error(ENOMEM))
2361 .Case(200, Error(ENOSYS))
2362 .Default(Error(EPERM));
2365 case __NR_exit_group:
2369 return UnsafeTrap(NoOpHandler, NULL);
2371 return Error(EPERM);
2376 DISALLOW_COPY_AND_ASSIGN(UnsafeTrapWithCondPolicy);
2379 BPF_TEST_C(SandboxBPF, UnsafeTrapWithCond, UnsafeTrapWithCondPolicy) {
2380 BPF_ASSERT_EQ(-1, syscall(__NR_uname, 0));
2381 BPF_ASSERT_EQ(EFAULT, errno);
2383 BPF_ASSERT_EQ(-1, syscall(__NR_uname, 1));
2384 BPF_ASSERT_EQ(EPERM, errno);
2386 BPF_ASSERT_EQ(-1, syscall(__NR_setgid, 100));
2387 BPF_ASSERT_EQ(ENOMEM, errno);
2389 BPF_ASSERT_EQ(-1, syscall(__NR_setgid, 200));
2390 BPF_ASSERT_EQ(ENOSYS, errno);
2392 BPF_ASSERT_EQ(-1, syscall(__NR_setgid, 300));
2393 BPF_ASSERT_EQ(EPERM, errno);
2398 } // namespace bpf_dsl
2399 } // namespace sandbox