Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / sandbox / linux / bpf_dsl / bpf_dsl_more_unittest.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "sandbox/linux/bpf_dsl/bpf_dsl.h"
6
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <pthread.h>
10 #include <sched.h>
11 #include <signal.h>
12 #include <sys/prctl.h>
13 #include <sys/ptrace.h>
14 #include <sys/syscall.h>
15 #include <sys/time.h>
16 #include <sys/types.h>
17 #include <sys/utsname.h>
18 #include <unistd.h>
19 #include <sys/socket.h>
20
21 #if defined(ANDROID)
22 // Work-around for buggy headers in Android's NDK
23 #define __user
24 #endif
25 #include <linux/futex.h>
26
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"
48
49 // Workaround for Android's prctl.h file.
50 #ifndef PR_GET_ENDIAN
51 #define PR_GET_ENDIAN 19
52 #endif
53 #ifndef PR_CAPBSET_READ
54 #define PR_CAPBSET_READ 23
55 #define PR_CAPBSET_DROP 24
56 #endif
57
58 namespace sandbox {
59 namespace bpf_dsl {
60
61 namespace {
62
63 const int kExpectedReturnValue = 42;
64 const char kSandboxDebuggingEnv[] = "CHROME_SANDBOX_DEBUGGING";
65
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);
75 }
76
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
81   // support it.
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";
92 }
93
94 SANDBOX_TEST(SandboxBPF, DISABLE_ON_TSAN(CallSupportsTwice)) {
95   SandboxBPF::SupportsSeccompSandbox(-1);
96   SandboxBPF::SupportsSeccompSandbox(-1);
97 }
98
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.
105
106 intptr_t IncreaseCounter(const struct arch_seccomp_data& args, void* aux) {
107   BPF_ASSERT(aux);
108   int* counter = static_cast<int*>(aux);
109   return (*counter)++;
110 }
111
112 class VerboseAPITestingPolicy : public Policy {
113  public:
114   explicit VerboseAPITestingPolicy(int* counter_ptr)
115       : counter_ptr_(counter_ptr) {}
116   ~VerboseAPITestingPolicy() override {}
117
118   ResultExpr EvaluateSyscall(int sysno) const override {
119     DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
120     if (sysno == __NR_uname) {
121       return Trap(IncreaseCounter, counter_ptr_);
122     }
123     return Allow();
124   }
125
126  private:
127   int* counter_ptr_;
128
129   DISALLOW_COPY_AND_ASSIGN(VerboseAPITestingPolicy);
130 };
131
132 SANDBOX_TEST(SandboxBPF, DISABLE_ON_TSAN(VerboseAPITesting)) {
133   if (SandboxBPF::SupportsSeccompSandbox(-1) ==
134       sandbox::SandboxBPF::STATUS_AVAILABLE) {
135     static int counter = 0;
136
137     SandboxBPF sandbox;
138     sandbox.SetSandboxPolicy(new VerboseAPITestingPolicy(&counter));
139     BPF_ASSERT(sandbox.StartSandbox(SandboxBPF::PROCESS_SINGLE_THREADED));
140
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);
146   }
147 }
148
149 // A simple blacklist test
150
151 class BlacklistNanosleepPolicy : public Policy {
152  public:
153   BlacklistNanosleepPolicy() {}
154   ~BlacklistNanosleepPolicy() override {}
155
156   ResultExpr EvaluateSyscall(int sysno) const override {
157     DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
158     switch (sysno) {
159       case __NR_nanosleep:
160         return Error(EACCES);
161       default:
162         return Allow();
163     }
164   }
165
166   static void AssertNanosleepFails() {
167     const struct timespec ts = {0, 0};
168     errno = 0;
169     BPF_ASSERT_EQ(-1, HANDLE_EINTR(syscall(__NR_nanosleep, &ts, NULL)));
170     BPF_ASSERT_EQ(EACCES, errno);
171   }
172
173  private:
174   DISALLOW_COPY_AND_ASSIGN(BlacklistNanosleepPolicy);
175 };
176
177 BPF_TEST_C(SandboxBPF, ApplyBasicBlacklistPolicy, BlacklistNanosleepPolicy) {
178   BlacklistNanosleepPolicy::AssertNanosleepFails();
179 }
180
181 // Now do a simple whitelist test
182
183 class WhitelistGetpidPolicy : public Policy {
184  public:
185   WhitelistGetpidPolicy() {}
186   ~WhitelistGetpidPolicy() override {}
187
188   ResultExpr EvaluateSyscall(int sysno) const override {
189     DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
190     switch (sysno) {
191       case __NR_getpid:
192       case __NR_exit_group:
193         return Allow();
194       default:
195         return Error(ENOMEM);
196     }
197   }
198
199  private:
200   DISALLOW_COPY_AND_ASSIGN(WhitelistGetpidPolicy);
201 };
202
203 BPF_TEST_C(SandboxBPF, ApplyBasicWhitelistPolicy, WhitelistGetpidPolicy) {
204   // getpid() should be allowed
205   errno = 0;
206   BPF_ASSERT(syscall(__NR_getpid) > 0);
207   BPF_ASSERT(errno == 0);
208
209   // getpgid() should be denied
210   BPF_ASSERT(getpgid(0) == -1);
211   BPF_ASSERT(errno == ENOMEM);
212 }
213
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
217   SANDBOX_ASSERT(aux);
218   *(static_cast<int*>(aux)) = kExpectedReturnValue;
219   return -ENOMEM;
220 }
221
222 class BlacklistNanosleepTrapPolicy : public Policy {
223  public:
224   explicit BlacklistNanosleepTrapPolicy(int* aux) : aux_(aux) {}
225   ~BlacklistNanosleepTrapPolicy() override {}
226
227   ResultExpr EvaluateSyscall(int sysno) const override {
228     DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
229     switch (sysno) {
230       case __NR_nanosleep:
231         return Trap(EnomemHandler, aux_);
232       default:
233         return Allow();
234     }
235   }
236
237  private:
238   int* aux_;
239
240   DISALLOW_COPY_AND_ASSIGN(BlacklistNanosleepTrapPolicy);
241 };
242
243 BPF_TEST(SandboxBPF,
244          BasicBlacklistWithSigsys,
245          BlacklistNanosleepTrapPolicy,
246          int /* (*BPF_AUX) */) {
247   // getpid() should work properly
248   errno = 0;
249   BPF_ASSERT(syscall(__NR_getpid) > 0);
250   BPF_ASSERT(errno == 0);
251
252   // Our Auxiliary Data, should be reset by the signal handler
253   *BPF_AUX = -1;
254   const struct timespec ts = {0, 0};
255   BPF_ASSERT(syscall(__NR_nanosleep, &ts, NULL) == -1);
256   BPF_ASSERT(errno == ENOMEM);
257
258   // We expect the signal handler to modify AuxData
259   BPF_ASSERT(*BPF_AUX == kExpectedReturnValue);
260 }
261
262 // A simple test that verifies we can return arbitrary errno values.
263
264 class ErrnoTestPolicy : public Policy {
265  public:
266   ErrnoTestPolicy() {}
267   ~ErrnoTestPolicy() override {}
268
269   ResultExpr EvaluateSyscall(int sysno) const override;
270
271  private:
272   DISALLOW_COPY_AND_ASSIGN(ErrnoTestPolicy);
273 };
274
275 ResultExpr ErrnoTestPolicy::EvaluateSyscall(int sysno) const {
276   DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
277   switch (sysno) {
278     case __NR_dup3:  // dup2 is a wrapper of dup3 in android
279 #if defined(__NR_dup2)
280     case __NR_dup2:
281 #endif
282       // Pretend that dup2() worked, but don't actually do anything.
283       return Error(0);
284     case __NR_setuid:
285 #if defined(__NR_setuid32)
286     case __NR_setuid32:
287 #endif
288       // Return errno = 1.
289       return Error(1);
290     case __NR_setgid:
291 #if defined(__NR_setgid32)
292     case __NR_setgid32:
293 #endif
294       // Return maximum errno value (typically 4095).
295       return Error(ErrorCode::ERR_MAX_ERRNO);
296     case __NR_uname:
297       // Return errno = 42;
298       return Error(42);
299     default:
300       return Allow();
301   }
302 }
303
304 BPF_TEST_C(SandboxBPF, ErrnoTest, ErrnoTestPolicy) {
305   // Verify that dup2() returns success, but doesn't actually run.
306   int fds[4];
307   BPF_ASSERT(pipe(fds) == 0);
308   BPF_ASSERT(pipe(fds + 2) == 0);
309   BPF_ASSERT(dup2(fds[2], fds[0]) == 0);
310   char buf[1] = {};
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);
314
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');
318
319   // Verify that we can return the minimum and maximum errno values.
320   errno = 0;
321   BPF_ASSERT(setuid(0) == -1);
322   BPF_ASSERT(errno == 1);
323
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) {
328     errno = 0;
329     BPF_ASSERT(setgid(0) == -ErrorCode::ERR_MAX_ERRNO);
330     BPF_ASSERT(errno == 0);
331   } else {
332     errno = 0;
333     BPF_ASSERT(setgid(0) == -1);
334     BPF_ASSERT(errno == ErrorCode::ERR_MAX_ERRNO);
335   }
336
337   // Finally, test an errno in between the minimum and maximum.
338   errno = 0;
339   struct utsname uts_buf;
340   BPF_ASSERT(uname(&uts_buf) == -1);
341   BPF_ASSERT(errno == 42);
342 }
343
344 // Testing the stacking of two sandboxes
345
346 class StackingPolicyPartOne : public Policy {
347  public:
348   StackingPolicyPartOne() {}
349   ~StackingPolicyPartOne() override {}
350
351   ResultExpr EvaluateSyscall(int sysno) const override {
352     DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
353     switch (sysno) {
354       case __NR_getppid: {
355         const Arg<int> arg(0);
356         return If(arg == 0, Allow()).Else(Error(EPERM));
357       }
358       default:
359         return Allow();
360     }
361   }
362
363  private:
364   DISALLOW_COPY_AND_ASSIGN(StackingPolicyPartOne);
365 };
366
367 class StackingPolicyPartTwo : public Policy {
368  public:
369   StackingPolicyPartTwo() {}
370   ~StackingPolicyPartTwo() override {}
371
372   ResultExpr EvaluateSyscall(int sysno) const override {
373     DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
374     switch (sysno) {
375       case __NR_getppid: {
376         const Arg<int> arg(0);
377         return If(arg == 0, Error(EINVAL)).Else(Allow());
378       }
379       default:
380         return Allow();
381     }
382   }
383
384  private:
385   DISALLOW_COPY_AND_ASSIGN(StackingPolicyPartTwo);
386 };
387
388 BPF_TEST_C(SandboxBPF, StackingPolicy, StackingPolicyPartOne) {
389   errno = 0;
390   BPF_ASSERT(syscall(__NR_getppid, 0) > 0);
391   BPF_ASSERT(errno == 0);
392
393   BPF_ASSERT(syscall(__NR_getppid, 1) == -1);
394   BPF_ASSERT(errno == EPERM);
395
396   // Stack a second sandbox with its own policy. Verify that we can further
397   // restrict filters, but we cannot relax existing filters.
398   SandboxBPF sandbox;
399   sandbox.SetSandboxPolicy(new StackingPolicyPartTwo());
400   BPF_ASSERT(sandbox.StartSandbox(SandboxBPF::PROCESS_SINGLE_THREADED));
401
402   errno = 0;
403   BPF_ASSERT(syscall(__NR_getppid, 0) == -1);
404   BPF_ASSERT(errno == EINVAL);
405
406   BPF_ASSERT(syscall(__NR_getppid, 1) == -1);
407   BPF_ASSERT(errno == EPERM);
408 }
409
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.
414
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
418 // same errno.
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;
423 }
424
425 class SyntheticPolicy : public Policy {
426  public:
427   SyntheticPolicy() {}
428   ~SyntheticPolicy() override {}
429
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.
435       return Allow();
436     }
437     return Error(SysnoToRandomErrno(sysno));
438   }
439
440  private:
441   DISALLOW_COPY_AND_ASSIGN(SyntheticPolicy);
442 };
443
444 BPF_TEST_C(SandboxBPF, SyntheticPolicy, SyntheticPolicy) {
445   // Ensure that that kExpectedReturnValue + syscallnumber + 1 does not int
446   // overflow.
447   BPF_ASSERT(std::numeric_limits<int>::max() - kExpectedReturnValue - 1 >=
448              static_cast<int>(MAX_PUBLIC_SYSCALL));
449
450   for (int syscall_number = static_cast<int>(MIN_SYSCALL);
451        syscall_number <= static_cast<int>(MAX_PUBLIC_SYSCALL);
452        ++syscall_number) {
453     if (syscall_number == __NR_exit_group || syscall_number == __NR_write) {
454       // exit_group() is special
455       continue;
456     }
457     errno = 0;
458     BPF_ASSERT(syscall(syscall_number) == -1);
459     BPF_ASSERT(errno == SysnoToRandomErrno(syscall_number));
460   }
461 }
462
463 #if defined(__arm__)
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.
466
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;
473   } else {
474     return ENOSYS;
475   }
476 }
477
478 class ArmPrivatePolicy : public Policy {
479  public:
480   ArmPrivatePolicy() {}
481   virtual ~ArmPrivatePolicy() {}
482
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));
490     }
491     return Allow();
492   }
493
494  private:
495   DISALLOW_COPY_AND_ASSIGN(ArmPrivatePolicy);
496 };
497
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);
501        ++syscall_number) {
502     errno = 0;
503     BPF_ASSERT(syscall(syscall_number) == -1);
504     BPF_ASSERT(errno == ArmPrivateSysnoToErrno(syscall_number));
505   }
506 }
507 #endif  // defined(__arm__)
508
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);
512
513   // Verify that within the callback function all filtering is temporarily
514   // disabled.
515   BPF_ASSERT(syscall(__NR_getpid) > 1);
516
517   // Verify that we can now call the underlying system call without causing
518   // infinite recursion.
519   return SandboxBPF::ForwardSyscall(args);
520 }
521
522 class GreyListedPolicy : public Policy {
523  public:
524   explicit GreyListedPolicy(int* aux) : aux_(aux) {
525     // Set the global environment for unsafe traps once.
526     EnableUnsafeTraps();
527   }
528   ~GreyListedPolicy() override {}
529
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)) {
535       return Allow();
536     } else if (sysno == __NR_getpid) {
537       // Disallow getpid()
538       return Error(EPERM);
539     } else {
540       // Allow (and count) all other system calls.
541       return UnsafeTrap(CountSyscalls, aux_);
542     }
543   }
544
545  private:
546   int* aux_;
547
548   DISALLOW_COPY_AND_ASSIGN(GreyListedPolicy);
549 };
550
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);
557   char name[17] = {};
558   BPF_ASSERT(!syscall(__NR_prctl,
559                       PR_GET_NAME,
560                       name,
561                       (void*)NULL,
562                       (void*)NULL,
563                       (void*)NULL));
564   BPF_ASSERT(*BPF_AUX == 3);
565   BPF_ASSERT(*name);
566 }
567
568 SANDBOX_TEST(SandboxBPF, EnableUnsafeTrapsInSigSysHandler) {
569   // Disabling warning messages that could confuse our test framework.
570   setenv(kSandboxDebuggingEnv, "t", 0);
571   Die::SuppressInfoMessages(true);
572
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);
579 }
580
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.
585     return 0;
586   } else {
587     return SandboxBPF::ForwardSyscall(args);
588   }
589 }
590
591 class PrctlPolicy : public Policy {
592  public:
593   PrctlPolicy() {}
594   ~PrctlPolicy() override {}
595
596   ResultExpr EvaluateSyscall(int sysno) const override {
597     DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
598     setenv(kSandboxDebuggingEnv, "t", 0);
599     Die::SuppressInfoMessages(true);
600
601     if (sysno == __NR_prctl) {
602       // Handle prctl() inside an UnsafeTrap()
603       return UnsafeTrap(PrctlHandler, NULL);
604     }
605
606     // Allow all other system calls.
607     return Allow();
608   }
609
610  private:
611   DISALLOW_COPY_AND_ASSIGN(PrctlPolicy);
612 };
613
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.
617   BPF_ASSERT(
618       !prctl(PR_CAPBSET_DROP, -1, (void*)NULL, (void*)NULL, (void*)NULL));
619
620   // Verify that the call will fail, if it makes it all the way to the kernel.
621   BPF_ASSERT(
622       prctl(PR_CAPBSET_DROP, -2, (void*)NULL, (void*)NULL, (void*)NULL) == -1);
623
624   // And verify that other uses of prctl() work just fine.
625   char name[17] = {};
626   BPF_ASSERT(!syscall(__NR_prctl,
627                       PR_GET_NAME,
628                       name,
629                       (void*)NULL,
630                       (void*)NULL,
631                       (void*)NULL));
632   BPF_ASSERT(*name);
633
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"));
639 }
640
641 intptr_t AllowRedirectedSyscall(const struct arch_seccomp_data& args, void*) {
642   return SandboxBPF::ForwardSyscall(args);
643 }
644
645 class RedirectAllSyscallsPolicy : public Policy {
646  public:
647   RedirectAllSyscallsPolicy() {}
648   ~RedirectAllSyscallsPolicy() override {}
649
650   ResultExpr EvaluateSyscall(int sysno) const override;
651
652  private:
653   DISALLOW_COPY_AND_ASSIGN(RedirectAllSyscallsPolicy);
654 };
655
656 ResultExpr RedirectAllSyscallsPolicy::EvaluateSyscall(int sysno) const {
657   DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
658   setenv(kSandboxDebuggingEnv, "t", 0);
659   Die::SuppressInfoMessages(true);
660
661   // Some system calls must always be allowed, if our policy wants to make
662   // use of UnsafeTrap()
663   if (SandboxBPF::IsRequiredForUnsafeTrap(sysno))
664     return Allow();
665   return UnsafeTrap(AllowRedirectedSyscall, NULL);
666 }
667
668 int bus_handler_fd_ = -1;
669
670 void SigBusHandler(int, siginfo_t* info, void* void_context) {
671   BPF_ASSERT(write(bus_handler_fd_, "\x55", 1) == 1);
672 }
673
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.
682   int fds[2];
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);
689   raise(SIGBUS);
690   char c = '\000';
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);
695 }
696
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;
706
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
709   // in POSIX).
710   //
711   // Use SIGUSR2 because Android seems to use SIGUSR1 for some purpose.
712   sigemptyset(&mask0);
713   BPF_ASSERT(!sigprocmask(SIG_BLOCK, &mask0, &mask1));
714   BPF_ASSERT(!sigismember(&mask1, SIGUSR2));
715
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));
722 }
723
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.
731
732   // The glibc system wrapper will ultimately set errno for us. So, from normal
733   // userspace, all of this should be completely transparent.
734   errno = 0;
735   BPF_ASSERT(close(-1) == -1);
736   BPF_ASSERT(errno == EBADF);
737
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.
741   errno = 0;
742   struct arch_seccomp_data args = {};
743   args.nr = __NR_close;
744   args.args[0] = -1;
745   BPF_ASSERT(SandboxBPF::ForwardSyscall(args) == -EBADF);
746   BPF_ASSERT(errno == 0);
747 }
748
749 bool NoOpCallback() {
750   return true;
751 }
752
753 // Test a trap handler that makes use of a broker process to open().
754
755 class InitializedOpenBroker {
756  public:
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");
761
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)));
766
767     initialized_ = true;
768   }
769   bool initialized() { return initialized_; }
770   class BrokerProcess* broker_process() { return broker_process_.get(); }
771
772  private:
773   bool initialized_;
774   scoped_ptr<class BrokerProcess> broker_process_;
775   DISALLOW_COPY_AND_ASSIGN(InitializedOpenBroker);
776 };
777
778 intptr_t BrokerOpenTrapHandler(const struct arch_seccomp_data& args,
779                                void* aux) {
780   BPF_ASSERT(aux);
781   BrokerProcess* broker_process = static_cast<BrokerProcess*>(aux);
782   switch (args.nr) {
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)
788     case __NR_access:
789       return broker_process->Access(reinterpret_cast<const char*>(args.args[0]),
790                                     static_cast<int>(args.args[1]));
791 #endif
792 #if defined(__NR_open)
793     case __NR_open:
794       return broker_process->Open(reinterpret_cast<const char*>(args.args[0]),
795                                   static_cast<int>(args.args[1]));
796 #endif
797     case __NR_openat:
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]));
803     default:
804       BPF_ASSERT(false);
805       return -ENOSYS;
806   }
807 }
808
809 class DenyOpenPolicy : public Policy {
810  public:
811   explicit DenyOpenPolicy(InitializedOpenBroker* iob) : iob_(iob) {}
812   ~DenyOpenPolicy() override {}
813
814   ResultExpr EvaluateSyscall(int sysno) const override {
815     DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
816
817     switch (sysno) {
818       case __NR_faccessat:
819 #if defined(__NR_access)
820       case __NR_access:
821 #endif
822 #if defined(__NR_open)
823       case __NR_open:
824 #endif
825       case __NR_openat:
826         // We get a InitializedOpenBroker class, but our trap handler wants
827         // the BrokerProcess object.
828         return Trap(BrokerOpenTrapHandler, iob_->broker_process());
829       default:
830         return Allow();
831     }
832   }
833
834  private:
835   InitializedOpenBroker* iob_;
836
837   DISALLOW_COPY_AND_ASSIGN(DenyOpenPolicy);
838 };
839
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.
842 BPF_TEST(SandboxBPF,
843          UseOpenBroker,
844          DenyOpenPolicy,
845          InitializedOpenBroker /* (*BPF_AUX) */) {
846   BPF_ASSERT(BPF_AUX->initialized());
847   BrokerProcess* broker_process = BPF_AUX->broker_process();
848   BPF_ASSERT(broker_process != NULL);
849
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);
855
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);
859
860   BPF_ASSERT(open("/proc/allowed", O_RDONLY) == -1);
861   BPF_ASSERT(errno == ENOENT);
862
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);
867
868   BPF_ASSERT(openat(AT_FDCWD, "/proc/allowed", O_RDONLY) == -1);
869   BPF_ASSERT(errno == ENOENT);
870
871   // And test glibc's access().
872   BPF_ASSERT(access("/proc/denied", R_OK) == -1);
873   BPF_ASSERT(errno == EPERM);
874
875   BPF_ASSERT(access("/proc/allowed", R_OK) == -1);
876   BPF_ASSERT(errno == ENOENT);
877
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);
883   char buf[1024];
884   BPF_ASSERT(read(cpu_info_fd, buf, sizeof(buf)) > 0);
885 }
886
887 // Simple test demonstrating how to use SandboxBPF::Cond()
888
889 class SimpleCondTestPolicy : public Policy {
890  public:
891   SimpleCondTestPolicy() {}
892   ~SimpleCondTestPolicy() override {}
893
894   ResultExpr EvaluateSyscall(int sysno) const override;
895
896  private:
897   DISALLOW_COPY_AND_ASSIGN(SimpleCondTestPolicy);
898 };
899
900 ResultExpr SimpleCondTestPolicy::EvaluateSyscall(int sysno) const {
901   DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
902
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;
907   switch (sysno) {
908 #if defined(__NR_open)
909     case __NR_open:
910       flags_argument_position = 1;
911 #endif
912     case __NR_openat: {  // open can be a wrapper for openat(2).
913       if (sysno == __NR_openat)
914         flags_argument_position = 2;
915
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());
920     }
921     case __NR_prctl: {
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));
927     }
928     default:
929       return Allow();
930   }
931 }
932
933 BPF_TEST_C(SandboxBPF, SimpleCondTest, SimpleCondTestPolicy) {
934   int fd;
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);
938   close(fd);
939
940   int ret;
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);
945 }
946
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
950 // program.
951 class EqualityStressTest {
952  public:
953   EqualityStressTest() {
954     // We want a deterministic test
955     srand(0);
956
957     // Iterates over system call numbers and builds a random tree of
958     // equality tests.
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.
962     COMPILE_ASSERT(
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.
970         ++end;
971         arg_values_.push_back(NULL);
972       } else {
973         arg_values_.push_back(
974             RandomArgValue(rand() % kMaxArgs, 0, rand() % kMaxArgs));
975       }
976     }
977   }
978
979   ~EqualityStressTest() {
980     for (std::vector<ArgValue*>::iterator iter = arg_values_.begin();
981          iter != arg_values_.end();
982          ++iter) {
983       DeleteArgValue(*iter);
984     }
985   }
986
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
993       // allowed.
994       return Allow();
995     } else {
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]);
999     }
1000   }
1001
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.
1008         continue;
1009       }
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]);
1019     }
1020   }
1021
1022  private:
1023   struct ArgValue {
1024     int argno;  // Argument number to inspect.
1025     int size;   // Number of test cases (must be > 0).
1026     struct Tests {
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.
1030     }* tests;
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).
1033   };
1034
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
1038     // to run properly.
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;
1048   }
1049
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;
1058
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) {
1064       fan_out = 1;
1065     } else if (remaining_args > 2) {
1066       fan_out = 2;
1067     }
1068
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];
1073
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;
1078
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
1085       // tests.
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;
1090       } else {
1091         arg_value->tests[n].err = 0;
1092         arg_value->tests[n].arg_value =
1093             RandomArgValue(RandomArg(args_mask), args_mask, remaining_args - 1);
1094       }
1095     }
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;
1102     } else {
1103       arg_value->err = 0;
1104       arg_value->arg_value =
1105           RandomArgValue(RandomArg(args_mask), args_mask, remaining_args - 1);
1106     }
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.
1110     return arg_value;
1111   }
1112
1113   int RandomArg(int args_mask) {
1114     // Compute a random system call parameter number.
1115     int argno = rand() % kMaxArgs;
1116
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;
1122     }
1123     return argno;
1124   }
1125
1126   void DeleteArgValue(ArgValue* arg_value) {
1127     // Delete an ArgValue and all of its child nodes. This requires
1128     // recursively descending into the tree.
1129     if (arg_value) {
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);
1134           }
1135         }
1136         delete[] arg_value->tests;
1137       }
1138       if (!arg_value->err) {
1139         DeleteArgValue(arg_value->arg_value);
1140       }
1141       delete arg_value;
1142     }
1143   }
1144
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).
1149     ResultExpr err;
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);
1154     } else {
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);
1159     }
1160
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;) {
1165       ResultExpr matched;
1166       // Again, we distinguish between leaf nodes and subtrees.
1167       if (arg_value->tests[n].err) {
1168         matched = Error(arg_value->tests[n].err);
1169       } else {
1170         matched = ToErrorCode(arg_value->tests[n].arg_value);
1171       }
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);
1177     }
1178     return err;
1179   }
1180
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);
1191       } else {
1192         Verify(sysno, args, *arg_value.tests[n].arg_value);
1193       }
1194     }
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.
1199   try_again:
1200     for (int n = arg_value.size; n-- > 0;) {
1201       if (mismatched == arg_value.tests[n].k_value) {
1202         ++mismatched;
1203         goto try_again;
1204       }
1205     }
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);
1212     } else {
1213       Verify(sysno, args, *arg_value.arg_value);
1214     }
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;
1218   }
1219
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.
1224     BPF_ASSERT(
1225         Syscall::Call(
1226             sysno, args[0], args[1], args[2], args[3], args[4], args[5]) ==
1227         -err);
1228   }
1229
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_;
1233
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;
1239 #else
1240   static const int kNumTestCases = 40;
1241 #endif
1242   static const int kMaxFanOut = 3;
1243   static const int kMaxArgs = 6;
1244 };
1245
1246 class EqualityStressTestPolicy : public Policy {
1247  public:
1248   explicit EqualityStressTestPolicy(EqualityStressTest* aux) : aux_(aux) {}
1249   ~EqualityStressTestPolicy() override {}
1250
1251   ResultExpr EvaluateSyscall(int sysno) const override {
1252     return aux_->Policy(sysno);
1253   }
1254
1255  private:
1256   EqualityStressTest* aux_;
1257
1258   DISALLOW_COPY_AND_ASSIGN(EqualityStressTestPolicy);
1259 };
1260
1261 BPF_TEST(SandboxBPF,
1262          EqualityTests,
1263          EqualityStressTestPolicy,
1264          EqualityStressTest /* (*BPF_AUX) */) {
1265   BPF_AUX->VerifyFilter();
1266 }
1267
1268 class EqualityArgumentWidthPolicy : public Policy {
1269  public:
1270   EqualityArgumentWidthPolicy() {}
1271   ~EqualityArgumentWidthPolicy() override {}
1272
1273   ResultExpr EvaluateSyscall(int sysno) const override;
1274
1275  private:
1276   DISALLOW_COPY_AND_ASSIGN(EqualityArgumentWidthPolicy);
1277 };
1278
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)))
1289 #endif
1290         .Default(Error(3));
1291   }
1292   return Allow();
1293 }
1294
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
1301   // 64bit arguments.
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);
1306 #endif
1307 }
1308
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
1312 // 64bit arguments.
1313 BPF_DEATH_TEST_C(SandboxBPF,
1314                  EqualityArgumentUnallowed64bit,
1315                  DEATH_MESSAGE("Unexpected 64bit argument detected"),
1316                  EqualityArgumentWidthPolicy) {
1317   Syscall::Call(__NR_uname, 0, 0x5555555555555555ULL);
1318 }
1319 #endif
1320
1321 class EqualityWithNegativeArgumentsPolicy : public Policy {
1322  public:
1323   EqualityWithNegativeArgumentsPolicy() {}
1324   ~EqualityWithNegativeArgumentsPolicy() override {}
1325
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));
1334     }
1335     return Allow();
1336   }
1337
1338  private:
1339   DISALLOW_COPY_AND_ASSIGN(EqualityWithNegativeArgumentsPolicy);
1340 };
1341
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);
1348 }
1349
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);
1359 }
1360 #endif
1361
1362 class AllBitTestPolicy : public Policy {
1363  public:
1364   AllBitTestPolicy() {}
1365   ~AllBitTestPolicy() override {}
1366
1367   ResultExpr EvaluateSyscall(int sysno) const override;
1368
1369  private:
1370   static ResultExpr HasAllBits32(uint32_t bits);
1371   static ResultExpr HasAllBits64(uint64_t bits);
1372
1373   DISALLOW_COPY_AND_ASSIGN(AllBitTestPolicy);
1374 };
1375
1376 ResultExpr AllBitTestPolicy::HasAllBits32(uint32_t bits) {
1377   if (bits == 0) {
1378     return Error(1);
1379   }
1380   const Arg<uint32_t> arg(1);
1381   return If((arg & bits) == bits, Error(1)).Else(Error(0));
1382 }
1383
1384 ResultExpr AllBitTestPolicy::HasAllBits64(uint64_t bits) {
1385   if (bits == 0) {
1386     return Error(1);
1387   }
1388   const Arg<uint64_t> arg(1);
1389   return If((arg & bits) == bits, Error(1)).Else(Error(0));
1390 }
1391
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))
1415 #endif
1416         .Default(Kill("Invalid test case number"));
1417   }
1418   return Allow();
1419 }
1420
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))
1430
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
1436
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
1439 // argument "arg".
1440 // We expect these tests to succeed on 64bit systems, but to tail on 32bit
1441 // systems.
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);
1450
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);
1456
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);
1463
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);
1470
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);
1481
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);
1491
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);
1503
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);
1515
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);
1525
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);
1537
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);
1545 #endif
1546 }
1547
1548 class AnyBitTestPolicy : public Policy {
1549  public:
1550   AnyBitTestPolicy() {}
1551   ~AnyBitTestPolicy() override {}
1552
1553   ResultExpr EvaluateSyscall(int sysno) const override;
1554
1555  private:
1556   static ResultExpr HasAnyBits32(uint32_t);
1557   static ResultExpr HasAnyBits64(uint64_t);
1558
1559   DISALLOW_COPY_AND_ASSIGN(AnyBitTestPolicy);
1560 };
1561
1562 ResultExpr AnyBitTestPolicy::HasAnyBits32(uint32_t bits) {
1563   if (bits == 0) {
1564     return Error(0);
1565   }
1566   const Arg<uint32_t> arg(1);
1567   return If((arg & bits) != 0, Error(1)).Else(Error(0));
1568 }
1569
1570 ResultExpr AnyBitTestPolicy::HasAnyBits64(uint64_t bits) {
1571   if (bits == 0) {
1572     return Error(0);
1573   }
1574   const Arg<uint64_t> arg(1);
1575   return If((arg & bits) != 0, Error(1)).Else(Error(0));
1576 }
1577
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))
1601 #endif
1602         .Default(Kill("Invalid test case number"));
1603   }
1604   return Allow();
1605 }
1606
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);
1614
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);
1620
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);
1627
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);
1634
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);
1645
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);
1655
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);
1667
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);
1679
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);
1689
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);
1701
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);
1709 #endif
1710 }
1711
1712 class MaskedEqualTestPolicy : public Policy {
1713  public:
1714   MaskedEqualTestPolicy() {}
1715   ~MaskedEqualTestPolicy() override {}
1716
1717   ResultExpr EvaluateSyscall(int sysno) const override;
1718
1719  private:
1720   static ResultExpr MaskedEqual32(uint32_t mask, uint32_t value);
1721   static ResultExpr MaskedEqual64(uint64_t mask, uint64_t value);
1722
1723   DISALLOW_COPY_AND_ASSIGN(MaskedEqualTestPolicy);
1724 };
1725
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));
1729 }
1730
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));
1734 }
1735
1736 ResultExpr MaskedEqualTestPolicy::EvaluateSyscall(int sysno) const {
1737   DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
1738
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))
1746 #endif
1747         .Default(Kill("Invalid test case number"));
1748   }
1749
1750   return Allow();
1751 }
1752
1753 #define MASKEQ_TEST(rulenum, arg, expected_result) \
1754   BPF_ASSERT(Syscall::Call(__NR_uname, (rulenum), (arg)) == (expected_result))
1755
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);
1770
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);
1789
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);
1808 #endif
1809 }
1810
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;
1817     printf(
1818         "Clone() was called with unexpected arguments\n"
1819         "  nr: %d\n"
1820         "  1: 0x%llX\n"
1821         "  2: 0x%llX\n"
1822         "  3: 0x%llX\n"
1823         "  4: 0x%llX\n"
1824         "  5: 0x%llX\n"
1825         "  6: 0x%llX\n"
1826         "%s\n",
1827         args.nr,
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],
1834         msg);
1835   }
1836   return -EPERM;
1837 }
1838
1839 class PthreadPolicyEquality : public Policy {
1840  public:
1841   PthreadPolicyEquality() {}
1842   ~PthreadPolicyEquality() override {}
1843
1844   ResultExpr EvaluateSyscall(int sysno) const override;
1845
1846  private:
1847   DISALLOW_COPY_AND_ASSIGN(PthreadPolicyEquality);
1848 };
1849
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 |
1872                                            CLONE_SYSVSEM;
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"));
1878   }
1879
1880   return Allow();
1881 }
1882
1883 class PthreadPolicyBitMask : public Policy {
1884  public:
1885   PthreadPolicyBitMask() {}
1886   ~PthreadPolicyBitMask() override {}
1887
1888   ResultExpr EvaluateSyscall(int sysno) const override;
1889
1890  private:
1891   static BoolExpr HasAnyBits(const Arg<unsigned long>& arg, unsigned long bits);
1892   static BoolExpr HasAllBits(const Arg<unsigned long>& arg, unsigned long bits);
1893
1894   DISALLOW_COPY_AND_ASSIGN(PthreadPolicyBitMask);
1895 };
1896
1897 BoolExpr PthreadPolicyBitMask::HasAnyBits(const Arg<unsigned long>& arg,
1898                                           unsigned long bits) {
1899   return (arg & bits) != 0;
1900 }
1901
1902 BoolExpr PthreadPolicyBitMask::HasAllBits(const Arg<unsigned long>& arg,
1903                                           unsigned long bits) {
1904   return (arg & bits) == bits;
1905 }
1906
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 |
1925                                           CLONE_SYSVSEM;
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;
1931
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"))
1939         .ElseIf(
1940              !HasAllBits(flags, kFutexFlags) && HasAnyBits(flags, kFutexFlags),
1941              Trap(PthreadTrapHandler,
1942                   "Must set either all or none of the TLS and futex bits in "
1943                   "call to clone()"))
1944         .Else(Allow());
1945   }
1946
1947   return Allow();
1948 }
1949
1950 static void* ThreadFnc(void* arg) {
1951   ++*reinterpret_cast<int*>(arg);
1952   Syscall::Call(__NR_futex, arg, FUTEX_WAKE, 1, 0, 0, 0);
1953   return NULL;
1954 }
1955
1956 static void PthreadTest() {
1957   // Attempt to start a joinable thread. This should succeed.
1958   pthread_t thread;
1959   int thread_ran = 0;
1960   BPF_ASSERT(!pthread_create(&thread, NULL, ThreadFnc, &thread_ran));
1961   BPF_ASSERT(!pthread_join(thread, NULL));
1962   BPF_ASSERT(thread_ran);
1963
1964   // Attempt to start a detached thread. This should succeed.
1965   thread_ran = 0;
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) ==
1972          -EINTR) {
1973   }
1974   BPF_ASSERT(thread_ran);
1975
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.
1981   int pid;
1982   BPF_ASSERT(Syscall::Call(__NR_clone,
1983                            CLONE_CHILD_CLEARTID | CLONE_CHILD_SETTID | SIGCHLD,
1984                            0,
1985                            0,
1986                            &pid) == -EPERM);
1987 }
1988
1989 BPF_TEST_C(SandboxBPF, PthreadEquality, PthreadPolicyEquality) {
1990   PthreadTest();
1991 }
1992
1993 BPF_TEST_C(SandboxBPF, PthreadBitMask, PthreadPolicyBitMask) {
1994   PthreadTest();
1995 }
1996
1997 // libc might not define these even though the kernel supports it.
1998 #ifndef PTRACE_O_TRACESECCOMP
1999 #define PTRACE_O_TRACESECCOMP 0x00000080
2000 #endif
2001
2002 #ifdef PTRACE_EVENT_SECCOMP
2003 #define IS_SECCOMP_EVENT(status) ((status >> 16) == PTRACE_EVENT_SECCOMP)
2004 #else
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
2009 // values here.
2010 #define IS_SECCOMP_EVENT(status) ((status >> 16) == 7 || (status >> 16) == 8)
2011 #endif
2012
2013 #if defined(__arm__)
2014 #ifndef PTRACE_SET_SYSCALL
2015 #define PTRACE_SET_SYSCALL 23
2016 #endif
2017 #endif
2018
2019 #if defined(__aarch64__)
2020 #ifndef PTRACE_GETREGS
2021 #define PTRACE_GETREGS 12
2022 #endif
2023 #endif
2024
2025 #if defined(__aarch64__)
2026 #ifndef PTRACE_SETREGS
2027 #define PTRACE_SETREGS 13
2028 #endif
2029 #endif
2030
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.
2034 //
2035 // regs should contain the current set of registers of the child, obtained using
2036 // PTRACE_GETREGS.
2037 //
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);
2046 #endif
2047
2048   SECCOMP_PT_SYSCALL(*regs) = syscall_number;
2049   return 0;
2050 }
2051
2052 const uint16_t kTraceData = 0xcc;
2053
2054 class TraceAllPolicy : public Policy {
2055  public:
2056   TraceAllPolicy() {}
2057   ~TraceAllPolicy() override {}
2058
2059   ResultExpr EvaluateSyscall(int system_call_number) const override {
2060     return Trace(kTraceData);
2061   }
2062
2063  private:
2064   DISALLOW_COPY_AND_ASSIGN(TraceAllPolicy);
2065 };
2066
2067 SANDBOX_TEST(SandboxBPF, DISABLE_ON_TSAN(SeccompRetTrace)) {
2068   if (SandboxBPF::SupportsSeccompSandbox(-1) !=
2069       sandbox::SandboxBPF::STATUS_AVAILABLE) {
2070     return;
2071   }
2072
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.");
2077   return;
2078 #endif
2079
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.");
2084   return;
2085 #endif
2086
2087   pid_t pid = fork();
2088   BPF_ASSERT_NE(-1, pid);
2089   if (pid == 0) {
2090     pid_t my_pid = getpid();
2091     BPF_ASSERT_NE(-1, ptrace(PTRACE_TRACEME, -1, NULL, NULL));
2092     BPF_ASSERT_EQ(0, raise(SIGSTOP));
2093     SandboxBPF sandbox;
2094     sandbox.SetSandboxPolicy(new TraceAllPolicy);
2095     BPF_ASSERT(sandbox.StartSandbox(SandboxBPF::PROCESS_SINGLE_THREADED));
2096
2097     // getpid is allowed.
2098     BPF_ASSERT_EQ(my_pid, syscall(__NR_getpid));
2099
2100     // write to stdout is skipped and returns a fake value.
2101     BPF_ASSERT_EQ(kExpectedReturnValue,
2102                   syscall(__NR_write, STDOUT_FILENO, "A", 1));
2103
2104     // kill is rewritten to exit(kExpectedReturnValue).
2105     syscall(__NR_kill, my_pid, SIGKILL);
2106
2107     // Should not be reached.
2108     BPF_ASSERT(false);
2109   }
2110
2111   int status;
2112   BPF_ASSERT(HANDLE_EINTR(waitpid(pid, &status, WUNTRACED)) != -1);
2113   BPF_ASSERT(WIFSTOPPED(status));
2114
2115   BPF_ASSERT_NE(-1,
2116                 ptrace(PTRACE_SETOPTIONS,
2117                        pid,
2118                        NULL,
2119                        reinterpret_cast<void*>(PTRACE_O_TRACESECCOMP)));
2120   BPF_ASSERT_NE(-1, ptrace(PTRACE_CONT, pid, NULL, NULL));
2121   while (true) {
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));
2126       break;
2127     }
2128
2129     if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGTRAP ||
2130         !IS_SECCOMP_EVENT(status)) {
2131       BPF_ASSERT_NE(-1, ptrace(PTRACE_CONT, pid, NULL, NULL));
2132       continue;
2133     }
2134
2135     unsigned long data;
2136     BPF_ASSERT_NE(-1, ptrace(PTRACE_GETEVENTMSG, pid, NULL, &data));
2137     BPF_ASSERT_EQ(kTraceData, data);
2138
2139     regs_struct regs;
2140     BPF_ASSERT_NE(-1, ptrace(PTRACE_GETREGS, pid, NULL, &regs));
2141     switch (SECCOMP_PT_SYSCALL(regs)) {
2142       case __NR_write:
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, &regs, -1));
2147           SECCOMP_PT_RESULT(regs) = kExpectedReturnValue;
2148           BPF_ASSERT_NE(-1, ptrace(PTRACE_SETREGS, pid, NULL, &regs));
2149         }
2150         break;
2151
2152       case __NR_kill:
2153         // Rewrite to exit(kExpectedReturnValue).
2154         BPF_ASSERT_NE(-1, SetSyscall(pid, &regs, __NR_exit));
2155         SECCOMP_PT_PARM1(regs) = kExpectedReturnValue;
2156         BPF_ASSERT_NE(-1, ptrace(PTRACE_SETREGS, pid, NULL, &regs));
2157         break;
2158
2159       default:
2160         // Allow all other syscalls.
2161         break;
2162     }
2163
2164     BPF_ASSERT_NE(-1, ptrace(PTRACE_CONT, pid, NULL, NULL));
2165   }
2166 }
2167
2168 // Android does not expose pread64 nor pwrite64.
2169 #if !defined(OS_ANDROID)
2170
2171 bool FullPwrite64(int fd, const char* buffer, size_t count, off64_t offset) {
2172   while (count > 0) {
2173     const ssize_t transfered =
2174         HANDLE_EINTR(pwrite64(fd, buffer, count, offset));
2175     if (transfered <= 0 || static_cast<size_t>(transfered) > count) {
2176       return false;
2177     }
2178     count -= transfered;
2179     buffer += transfered;
2180     offset += transfered;
2181   }
2182   return true;
2183 }
2184
2185 bool FullPread64(int fd, char* buffer, size_t count, off64_t offset) {
2186   while (count > 0) {
2187     const ssize_t transfered = HANDLE_EINTR(pread64(fd, buffer, count, offset));
2188     if (transfered <= 0 || static_cast<size_t>(transfered) > count) {
2189       return false;
2190     }
2191     count -= transfered;
2192     buffer += transfered;
2193     offset += transfered;
2194   }
2195   return true;
2196 }
2197
2198 bool pread_64_was_forwarded = false;
2199
2200 class TrapPread64Policy : public Policy {
2201  public:
2202   TrapPread64Policy() {}
2203   ~TrapPread64Policy() override {}
2204
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();
2209     }
2210
2211     if (system_call_number == __NR_pread64) {
2212       return UnsafeTrap(ForwardPreadHandler, NULL);
2213     }
2214     return Allow();
2215   }
2216
2217  private:
2218   static intptr_t ForwardPreadHandler(const struct arch_seccomp_data& args,
2219                                       void* aux) {
2220     BPF_ASSERT(args.nr == __NR_pread64);
2221     pread_64_was_forwarded = true;
2222
2223     return SandboxBPF::ForwardSyscall(args);
2224   }
2225
2226   DISALLOW_COPY_AND_ASSIGN(TrapPread64Policy);
2227 };
2228
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));
2238
2239   char read_test_string[sizeof(kTestString)] = {0};
2240   BPF_ASSERT(FullPread64(temp_file.fd(),
2241                          read_test_string,
2242                          sizeof(read_test_string),
2243                          kLargeOffset));
2244   BPF_ASSERT_EQ(0, memcmp(kTestString, read_test_string, sizeof(kTestString)));
2245   BPF_ASSERT(pread_64_was_forwarded);
2246 }
2247
2248 #endif  // !defined(OS_ANDROID)
2249
2250 void* TsyncApplyToTwoThreadsFunc(void* cond_ptr) {
2251   base::WaitableEvent* event = static_cast<base::WaitableEvent*>(cond_ptr);
2252
2253   // Wait for the main thread to signal that the filter has been applied.
2254   if (!event->IsSignaled()) {
2255     event->Wait();
2256   }
2257
2258   BPF_ASSERT(event->IsSignaled());
2259
2260   BlacklistNanosleepPolicy::AssertNanosleepFails();
2261
2262   return NULL;
2263 }
2264
2265 SANDBOX_TEST(SandboxBPF, Tsync) {
2266   if (SandboxBPF::SupportsSeccompThreadFilterSynchronization() !=
2267       SandboxBPF::STATUS_AVAILABLE) {
2268     return;
2269   }
2270
2271   base::WaitableEvent event(true, false);
2272
2273   // Create a thread on which to invoke the blocked syscall.
2274   pthread_t thread;
2275   BPF_ASSERT_EQ(
2276       0, pthread_create(&thread, NULL, &TsyncApplyToTwoThreadsFunc, &event));
2277
2278   // Test that nanoseelp success.
2279   const struct timespec ts = {0, 0};
2280   BPF_ASSERT_EQ(0, HANDLE_EINTR(syscall(__NR_nanosleep, &ts, NULL)));
2281
2282   // Engage the sandbox.
2283   SandboxBPF sandbox;
2284   sandbox.SetSandboxPolicy(new BlacklistNanosleepPolicy());
2285   BPF_ASSERT(sandbox.StartSandbox(SandboxBPF::PROCESS_MULTI_THREADED));
2286
2287   // This thread should have the filter applied as well.
2288   BlacklistNanosleepPolicy::AssertNanosleepFails();
2289
2290   // Signal the condition to invoke the system call.
2291   event.Signal();
2292
2293   // Wait for the thread to finish.
2294   BPF_ASSERT_EQ(0, pthread_join(thread, NULL));
2295 }
2296
2297 class AllowAllPolicy : public Policy {
2298  public:
2299   AllowAllPolicy() {}
2300   ~AllowAllPolicy() override {}
2301
2302   ResultExpr EvaluateSyscall(int sysno) const override { return Allow(); }
2303
2304  private:
2305   DISALLOW_COPY_AND_ASSIGN(AllowAllPolicy);
2306 };
2307
2308 SANDBOX_DEATH_TEST(
2309     SandboxBPF,
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());
2314
2315   SandboxBPF sandbox;
2316   sandbox.SetSandboxPolicy(new AllowAllPolicy());
2317   BPF_ASSERT(!sandbox.StartSandbox(SandboxBPF::PROCESS_SINGLE_THREADED));
2318 }
2319
2320 // http://crbug.com/407357
2321 #if !defined(THREAD_SANITIZER)
2322 SANDBOX_DEATH_TEST(
2323     SandboxBPF,
2324     StartSingleThreadedAsMultiThreaded,
2325     DEATH_MESSAGE(
2326         "Cannot start sandbox; process may be single-threaded when "
2327         "reported as not")) {
2328   SandboxBPF sandbox;
2329   sandbox.SetSandboxPolicy(new AllowAllPolicy());
2330   BPF_ASSERT(!sandbox.StartSandbox(SandboxBPF::PROCESS_MULTI_THREADED));
2331 }
2332 #endif  // !defined(THREAD_SANITIZER)
2333
2334 // A stub handler for the UnsafeTrap. Never called.
2335 intptr_t NoOpHandler(const struct arch_seccomp_data& args, void*) {
2336   return -1;
2337 }
2338
2339 class UnsafeTrapWithCondPolicy : public Policy {
2340  public:
2341   UnsafeTrapWithCondPolicy() {}
2342   ~UnsafeTrapWithCondPolicy() override {}
2343
2344   ResultExpr EvaluateSyscall(int sysno) const override {
2345     DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
2346     setenv(kSandboxDebuggingEnv, "t", 0);
2347     Die::SuppressInfoMessages(true);
2348
2349     if (SandboxBPF::IsRequiredForUnsafeTrap(sysno))
2350       return Allow();
2351
2352     switch (sysno) {
2353       case __NR_uname: {
2354         const Arg<uint32_t> arg(0);
2355         return If(arg == 0, Allow()).Else(Error(EPERM));
2356       }
2357       case __NR_setgid: {
2358         const Arg<uint32_t> arg(0);
2359         return Switch(arg)
2360             .Case(100, Error(ENOMEM))
2361             .Case(200, Error(ENOSYS))
2362             .Default(Error(EPERM));
2363       }
2364       case __NR_close:
2365       case __NR_exit_group:
2366       case __NR_write:
2367         return Allow();
2368       case __NR_getppid:
2369         return UnsafeTrap(NoOpHandler, NULL);
2370       default:
2371         return Error(EPERM);
2372     }
2373   }
2374
2375  private:
2376   DISALLOW_COPY_AND_ASSIGN(UnsafeTrapWithCondPolicy);
2377 };
2378
2379 BPF_TEST_C(SandboxBPF, UnsafeTrapWithCond, UnsafeTrapWithCondPolicy) {
2380   BPF_ASSERT_EQ(-1, syscall(__NR_uname, 0));
2381   BPF_ASSERT_EQ(EFAULT, errno);
2382
2383   BPF_ASSERT_EQ(-1, syscall(__NR_uname, 1));
2384   BPF_ASSERT_EQ(EPERM, errno);
2385
2386   BPF_ASSERT_EQ(-1, syscall(__NR_setgid, 100));
2387   BPF_ASSERT_EQ(ENOMEM, errno);
2388
2389   BPF_ASSERT_EQ(-1, syscall(__NR_setgid, 200));
2390   BPF_ASSERT_EQ(ENOSYS, errno);
2391
2392   BPF_ASSERT_EQ(-1, syscall(__NR_setgid, 300));
2393   BPF_ASSERT_EQ(EPERM, errno);
2394 }
2395
2396 }  // namespace
2397
2398 }  // namespace bpf_dsl
2399 }  // namespace sandbox