Upstream version 10.38.222.0
[platform/framework/web/crosswalk.git] / src / sandbox / linux / seccomp-bpf / sandbox_bpf_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 <errno.h>
6 #include <pthread.h>
7 #include <sched.h>
8 #include <signal.h>
9 #include <sys/prctl.h>
10 #include <sys/ptrace.h>
11 #include <sys/syscall.h>
12 #include <sys/time.h>
13 #include <sys/types.h>
14 #include <sys/utsname.h>
15 #include <unistd.h>
16 #include <sys/socket.h>
17
18 #if defined(ANDROID)
19 // Work-around for buggy headers in Android's NDK
20 #define __user
21 #endif
22 #include <linux/futex.h>
23
24 #include <ostream>
25
26 #include "base/bind.h"
27 #include "base/logging.h"
28 #include "base/macros.h"
29 #include "base/memory/scoped_ptr.h"
30 #include "base/posix/eintr_wrapper.h"
31 #include "build/build_config.h"
32 #include "sandbox/linux/seccomp-bpf/bpf_tests.h"
33 #include "sandbox/linux/seccomp-bpf/syscall.h"
34 #include "sandbox/linux/seccomp-bpf/trap.h"
35 #include "sandbox/linux/seccomp-bpf/verifier.h"
36 #include "sandbox/linux/services/broker_process.h"
37 #include "sandbox/linux/services/linux_syscalls.h"
38 #include "sandbox/linux/tests/scoped_temporary_file.h"
39 #include "sandbox/linux/tests/unit_tests.h"
40 #include "testing/gtest/include/gtest/gtest.h"
41
42 // Workaround for Android's prctl.h file.
43 #ifndef PR_GET_ENDIAN
44 #define PR_GET_ENDIAN 19
45 #endif
46 #ifndef PR_CAPBSET_READ
47 #define PR_CAPBSET_READ 23
48 #define PR_CAPBSET_DROP 24
49 #endif
50
51 namespace sandbox {
52
53 namespace {
54
55 const int kExpectedReturnValue = 42;
56 const char kSandboxDebuggingEnv[] = "CHROME_SANDBOX_DEBUGGING";
57
58 // Set the global environment to allow the use of UnsafeTrap() policies.
59 void EnableUnsafeTraps() {
60   // The use of UnsafeTrap() causes us to print a warning message. This is
61   // generally desirable, but it results in the unittest failing, as it doesn't
62   // expect any messages on "stderr". So, temporarily disable messages. The
63   // BPF_TEST() is guaranteed to turn messages back on, after the policy
64   // function has completed.
65   setenv(kSandboxDebuggingEnv, "t", 0);
66   Die::SuppressInfoMessages(true);
67 }
68
69 // This test should execute no matter whether we have kernel support. So,
70 // we make it a TEST() instead of a BPF_TEST().
71 TEST(SandboxBPF, DISABLE_ON_TSAN(CallSupports)) {
72   // We check that we don't crash, but it's ok if the kernel doesn't
73   // support it.
74   bool seccomp_bpf_supported =
75       SandboxBPF::SupportsSeccompSandbox(-1) == SandboxBPF::STATUS_AVAILABLE;
76   // We want to log whether or not seccomp BPF is actually supported
77   // since actual test coverage depends on it.
78   RecordProperty("SeccompBPFSupported",
79                  seccomp_bpf_supported ? "true." : "false.");
80   std::cout << "Seccomp BPF supported: "
81             << (seccomp_bpf_supported ? "true." : "false.") << "\n";
82   RecordProperty("PointerSize", sizeof(void*));
83   std::cout << "Pointer size: " << sizeof(void*) << "\n";
84 }
85
86 SANDBOX_TEST(SandboxBPF, DISABLE_ON_TSAN(CallSupportsTwice)) {
87   SandboxBPF::SupportsSeccompSandbox(-1);
88   SandboxBPF::SupportsSeccompSandbox(-1);
89 }
90
91 // BPF_TEST does a lot of the boiler-plate code around setting up a
92 // policy and optional passing data between the caller, the policy and
93 // any Trap() handlers. This is great for writing short and concise tests,
94 // and it helps us accidentally forgetting any of the crucial steps in
95 // setting up the sandbox. But it wouldn't hurt to have at least one test
96 // that explicitly walks through all these steps.
97
98 intptr_t IncreaseCounter(const struct arch_seccomp_data& args, void* aux) {
99   BPF_ASSERT(aux);
100   int* counter = static_cast<int*>(aux);
101   return (*counter)++;
102 }
103
104 class VerboseAPITestingPolicy : public SandboxBPFPolicy {
105  public:
106   VerboseAPITestingPolicy(int* counter_ptr) : counter_ptr_(counter_ptr) {}
107
108   virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
109                                     int sysno) const OVERRIDE {
110     DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
111     if (sysno == __NR_uname) {
112       return sandbox->Trap(IncreaseCounter, counter_ptr_);
113     }
114     return ErrorCode(ErrorCode::ERR_ALLOWED);
115   }
116
117  private:
118   int* counter_ptr_;
119   DISALLOW_COPY_AND_ASSIGN(VerboseAPITestingPolicy);
120 };
121
122 SANDBOX_TEST(SandboxBPF, DISABLE_ON_TSAN(VerboseAPITesting)) {
123   if (SandboxBPF::SupportsSeccompSandbox(-1) ==
124       sandbox::SandboxBPF::STATUS_AVAILABLE) {
125     static int counter = 0;
126
127     SandboxBPF sandbox;
128     sandbox.SetSandboxPolicy(new VerboseAPITestingPolicy(&counter));
129     BPF_ASSERT(sandbox.StartSandbox(SandboxBPF::PROCESS_SINGLE_THREADED));
130
131     BPF_ASSERT_EQ(0, counter);
132     BPF_ASSERT_EQ(0, syscall(__NR_uname, 0));
133     BPF_ASSERT_EQ(1, counter);
134     BPF_ASSERT_EQ(1, syscall(__NR_uname, 0));
135     BPF_ASSERT_EQ(2, counter);
136   }
137 }
138
139 // A simple blacklist test
140
141 class BlacklistNanosleepPolicy : public SandboxBPFPolicy {
142  public:
143   BlacklistNanosleepPolicy() {}
144   virtual ErrorCode EvaluateSyscall(SandboxBPF*, int sysno) const OVERRIDE {
145     DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
146     switch (sysno) {
147       case __NR_nanosleep:
148         return ErrorCode(EACCES);
149       default:
150         return ErrorCode(ErrorCode::ERR_ALLOWED);
151     }
152   }
153
154  private:
155   DISALLOW_COPY_AND_ASSIGN(BlacklistNanosleepPolicy);
156 };
157
158 BPF_TEST_C(SandboxBPF, ApplyBasicBlacklistPolicy, BlacklistNanosleepPolicy) {
159   // nanosleep() should be denied
160   const struct timespec ts = {0, 0};
161   errno = 0;
162   BPF_ASSERT(syscall(__NR_nanosleep, &ts, NULL) == -1);
163   BPF_ASSERT(errno == EACCES);
164 }
165
166 // Now do a simple whitelist test
167
168 class WhitelistGetpidPolicy : public SandboxBPFPolicy {
169  public:
170   WhitelistGetpidPolicy() {}
171   virtual ErrorCode EvaluateSyscall(SandboxBPF*, int sysno) const OVERRIDE {
172     DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
173     switch (sysno) {
174       case __NR_getpid:
175       case __NR_exit_group:
176         return ErrorCode(ErrorCode::ERR_ALLOWED);
177       default:
178         return ErrorCode(ENOMEM);
179     }
180   }
181
182  private:
183   DISALLOW_COPY_AND_ASSIGN(WhitelistGetpidPolicy);
184 };
185
186 BPF_TEST_C(SandboxBPF, ApplyBasicWhitelistPolicy, WhitelistGetpidPolicy) {
187   // getpid() should be allowed
188   errno = 0;
189   BPF_ASSERT(syscall(__NR_getpid) > 0);
190   BPF_ASSERT(errno == 0);
191
192   // getpgid() should be denied
193   BPF_ASSERT(getpgid(0) == -1);
194   BPF_ASSERT(errno == ENOMEM);
195 }
196
197 // A simple blacklist policy, with a SIGSYS handler
198 intptr_t EnomemHandler(const struct arch_seccomp_data& args, void* aux) {
199   // We also check that the auxiliary data is correct
200   SANDBOX_ASSERT(aux);
201   *(static_cast<int*>(aux)) = kExpectedReturnValue;
202   return -ENOMEM;
203 }
204
205 ErrorCode BlacklistNanosleepPolicySigsys(SandboxBPF* sandbox,
206                                          int sysno,
207                                          int* aux) {
208   DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
209   switch (sysno) {
210     case __NR_nanosleep:
211       return sandbox->Trap(EnomemHandler, aux);
212     default:
213       return ErrorCode(ErrorCode::ERR_ALLOWED);
214   }
215 }
216
217 BPF_TEST(SandboxBPF,
218          BasicBlacklistWithSigsys,
219          BlacklistNanosleepPolicySigsys,
220          int /* (*BPF_AUX) */) {
221   // getpid() should work properly
222   errno = 0;
223   BPF_ASSERT(syscall(__NR_getpid) > 0);
224   BPF_ASSERT(errno == 0);
225
226   // Our Auxiliary Data, should be reset by the signal handler
227   *BPF_AUX = -1;
228   const struct timespec ts = {0, 0};
229   BPF_ASSERT(syscall(__NR_nanosleep, &ts, NULL) == -1);
230   BPF_ASSERT(errno == ENOMEM);
231
232   // We expect the signal handler to modify AuxData
233   BPF_ASSERT(*BPF_AUX == kExpectedReturnValue);
234 }
235
236 // A simple test that verifies we can return arbitrary errno values.
237
238 class ErrnoTestPolicy : public SandboxBPFPolicy {
239  public:
240   ErrnoTestPolicy() {}
241   virtual ErrorCode EvaluateSyscall(SandboxBPF*, int sysno) const OVERRIDE;
242
243  private:
244   DISALLOW_COPY_AND_ASSIGN(ErrnoTestPolicy);
245 };
246
247 ErrorCode ErrnoTestPolicy::EvaluateSyscall(SandboxBPF*, int sysno) const {
248   DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
249   switch (sysno) {
250     case __NR_dup3:    // dup2 is a wrapper of dup3 in android
251     case __NR_dup2:
252       // Pretend that dup2() worked, but don't actually do anything.
253       return ErrorCode(0);
254     case __NR_setuid:
255 #if defined(__NR_setuid32)
256     case __NR_setuid32:
257 #endif
258       // Return errno = 1.
259       return ErrorCode(1);
260     case __NR_setgid:
261 #if defined(__NR_setgid32)
262     case __NR_setgid32:
263 #endif
264       // Return maximum errno value (typically 4095).
265       return ErrorCode(ErrorCode::ERR_MAX_ERRNO);
266     case __NR_uname:
267       // Return errno = 42;
268       return ErrorCode(42);
269     default:
270       return ErrorCode(ErrorCode::ERR_ALLOWED);
271   }
272 }
273
274 BPF_TEST_C(SandboxBPF, ErrnoTest, ErrnoTestPolicy) {
275   // Verify that dup2() returns success, but doesn't actually run.
276   int fds[4];
277   BPF_ASSERT(pipe(fds) == 0);
278   BPF_ASSERT(pipe(fds + 2) == 0);
279   BPF_ASSERT(dup2(fds[2], fds[0]) == 0);
280   char buf[1] = {};
281   BPF_ASSERT(write(fds[1], "\x55", 1) == 1);
282   BPF_ASSERT(write(fds[3], "\xAA", 1) == 1);
283   BPF_ASSERT(read(fds[0], buf, 1) == 1);
284
285   // If dup2() executed, we will read \xAA, but it dup2() has been turned
286   // into a no-op by our policy, then we will read \x55.
287   BPF_ASSERT(buf[0] == '\x55');
288
289   // Verify that we can return the minimum and maximum errno values.
290   errno = 0;
291   BPF_ASSERT(setuid(0) == -1);
292   BPF_ASSERT(errno == 1);
293
294   // On Android, errno is only supported up to 255, otherwise errno
295   // processing is skipped.
296   // We work around this (crbug.com/181647).
297   if (sandbox::IsAndroid() && setgid(0) != -1) {
298     errno = 0;
299     BPF_ASSERT(setgid(0) == -ErrorCode::ERR_MAX_ERRNO);
300     BPF_ASSERT(errno == 0);
301   } else {
302     errno = 0;
303     BPF_ASSERT(setgid(0) == -1);
304     BPF_ASSERT(errno == ErrorCode::ERR_MAX_ERRNO);
305   }
306
307   // Finally, test an errno in between the minimum and maximum.
308   errno = 0;
309   struct utsname uts_buf;
310   BPF_ASSERT(uname(&uts_buf) == -1);
311   BPF_ASSERT(errno == 42);
312 }
313
314 // Testing the stacking of two sandboxes
315
316 class StackingPolicyPartOne : public SandboxBPFPolicy {
317  public:
318   StackingPolicyPartOne() {}
319   virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
320                                     int sysno) const OVERRIDE {
321     DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
322     switch (sysno) {
323       case __NR_getppid:
324         return sandbox->Cond(0,
325                              ErrorCode::TP_32BIT,
326                              ErrorCode::OP_EQUAL,
327                              0,
328                              ErrorCode(ErrorCode::ERR_ALLOWED),
329                              ErrorCode(EPERM));
330       default:
331         return ErrorCode(ErrorCode::ERR_ALLOWED);
332     }
333   }
334
335  private:
336   DISALLOW_COPY_AND_ASSIGN(StackingPolicyPartOne);
337 };
338
339 class StackingPolicyPartTwo : public SandboxBPFPolicy {
340  public:
341   StackingPolicyPartTwo() {}
342   virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
343                                     int sysno) const OVERRIDE {
344     DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
345     switch (sysno) {
346       case __NR_getppid:
347         return sandbox->Cond(0,
348                              ErrorCode::TP_32BIT,
349                              ErrorCode::OP_EQUAL,
350                              0,
351                              ErrorCode(EINVAL),
352                              ErrorCode(ErrorCode::ERR_ALLOWED));
353       default:
354         return ErrorCode(ErrorCode::ERR_ALLOWED);
355     }
356   }
357
358  private:
359   DISALLOW_COPY_AND_ASSIGN(StackingPolicyPartTwo);
360 };
361
362 BPF_TEST_C(SandboxBPF, StackingPolicy, StackingPolicyPartOne) {
363   errno = 0;
364   BPF_ASSERT(syscall(__NR_getppid, 0) > 0);
365   BPF_ASSERT(errno == 0);
366
367   BPF_ASSERT(syscall(__NR_getppid, 1) == -1);
368   BPF_ASSERT(errno == EPERM);
369
370   // Stack a second sandbox with its own policy. Verify that we can further
371   // restrict filters, but we cannot relax existing filters.
372   SandboxBPF sandbox;
373   sandbox.SetSandboxPolicy(new StackingPolicyPartTwo());
374   BPF_ASSERT(sandbox.StartSandbox(SandboxBPF::PROCESS_SINGLE_THREADED));
375
376   errno = 0;
377   BPF_ASSERT(syscall(__NR_getppid, 0) == -1);
378   BPF_ASSERT(errno == EINVAL);
379
380   BPF_ASSERT(syscall(__NR_getppid, 1) == -1);
381   BPF_ASSERT(errno == EPERM);
382 }
383
384 // A more complex, but synthetic policy. This tests the correctness of the BPF
385 // program by iterating through all syscalls and checking for an errno that
386 // depends on the syscall number. Unlike the Verifier, this exercises the BPF
387 // interpreter in the kernel.
388
389 // We try to make sure we exercise optimizations in the BPF compiler. We make
390 // sure that the compiler can have an opportunity to coalesce syscalls with
391 // contiguous numbers and we also make sure that disjoint sets can return the
392 // same errno.
393 int SysnoToRandomErrno(int sysno) {
394   // Small contiguous sets of 3 system calls return an errno equal to the
395   // index of that set + 1 (so that we never return a NUL errno).
396   return ((sysno & ~3) >> 2) % 29 + 1;
397 }
398
399 class SyntheticPolicy : public SandboxBPFPolicy {
400  public:
401   SyntheticPolicy() {}
402   virtual ErrorCode EvaluateSyscall(SandboxBPF*, int sysno) const OVERRIDE {
403     DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
404     if (sysno == __NR_exit_group || sysno == __NR_write) {
405       // exit_group() is special, we really need it to work.
406       // write() is needed for BPF_ASSERT() to report a useful error message.
407       return ErrorCode(ErrorCode::ERR_ALLOWED);
408     }
409     return ErrorCode(SysnoToRandomErrno(sysno));
410   }
411
412  private:
413   DISALLOW_COPY_AND_ASSIGN(SyntheticPolicy);
414 };
415
416 BPF_TEST_C(SandboxBPF, SyntheticPolicy, SyntheticPolicy) {
417   // Ensure that that kExpectedReturnValue + syscallnumber + 1 does not int
418   // overflow.
419   BPF_ASSERT(std::numeric_limits<int>::max() - kExpectedReturnValue - 1 >=
420              static_cast<int>(MAX_PUBLIC_SYSCALL));
421
422   for (int syscall_number = static_cast<int>(MIN_SYSCALL);
423        syscall_number <= static_cast<int>(MAX_PUBLIC_SYSCALL);
424        ++syscall_number) {
425     if (syscall_number == __NR_exit_group || syscall_number == __NR_write) {
426       // exit_group() is special
427       continue;
428     }
429     errno = 0;
430     BPF_ASSERT(syscall(syscall_number) == -1);
431     BPF_ASSERT(errno == SysnoToRandomErrno(syscall_number));
432   }
433 }
434
435 #if defined(__arm__)
436 // A simple policy that tests whether ARM private system calls are supported
437 // by our BPF compiler and by the BPF interpreter in the kernel.
438
439 // For ARM private system calls, return an errno equal to their offset from
440 // MIN_PRIVATE_SYSCALL plus 1 (to avoid NUL errno).
441 int ArmPrivateSysnoToErrno(int sysno) {
442   if (sysno >= static_cast<int>(MIN_PRIVATE_SYSCALL) &&
443       sysno <= static_cast<int>(MAX_PRIVATE_SYSCALL)) {
444     return (sysno - MIN_PRIVATE_SYSCALL) + 1;
445   } else {
446     return ENOSYS;
447   }
448 }
449
450 class ArmPrivatePolicy : public SandboxBPFPolicy {
451  public:
452   ArmPrivatePolicy() {}
453   virtual ErrorCode EvaluateSyscall(SandboxBPF*, int sysno) const OVERRIDE {
454     DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
455     // Start from |__ARM_NR_set_tls + 1| so as not to mess with actual
456     // ARM private system calls.
457     if (sysno >= static_cast<int>(__ARM_NR_set_tls + 1) &&
458         sysno <= static_cast<int>(MAX_PRIVATE_SYSCALL)) {
459       return ErrorCode(ArmPrivateSysnoToErrno(sysno));
460     }
461     return ErrorCode(ErrorCode::ERR_ALLOWED);
462   }
463
464  private:
465   DISALLOW_COPY_AND_ASSIGN(ArmPrivatePolicy);
466 };
467
468 BPF_TEST_C(SandboxBPF, ArmPrivatePolicy, ArmPrivatePolicy) {
469   for (int syscall_number = static_cast<int>(__ARM_NR_set_tls + 1);
470        syscall_number <= static_cast<int>(MAX_PRIVATE_SYSCALL);
471        ++syscall_number) {
472     errno = 0;
473     BPF_ASSERT(syscall(syscall_number) == -1);
474     BPF_ASSERT(errno == ArmPrivateSysnoToErrno(syscall_number));
475   }
476 }
477 #endif  // defined(__arm__)
478
479 intptr_t CountSyscalls(const struct arch_seccomp_data& args, void* aux) {
480   // Count all invocations of our callback function.
481   ++*reinterpret_cast<int*>(aux);
482
483   // Verify that within the callback function all filtering is temporarily
484   // disabled.
485   BPF_ASSERT(syscall(__NR_getpid) > 1);
486
487   // Verify that we can now call the underlying system call without causing
488   // infinite recursion.
489   return SandboxBPF::ForwardSyscall(args);
490 }
491
492 ErrorCode GreyListedPolicy(SandboxBPF* sandbox, int sysno, int* aux) {
493   // Set the global environment for unsafe traps once.
494   if (sysno == MIN_SYSCALL) {
495     EnableUnsafeTraps();
496   }
497
498   // Some system calls must always be allowed, if our policy wants to make
499   // use of UnsafeTrap()
500   if (sysno == __NR_rt_sigprocmask || sysno == __NR_rt_sigreturn
501 #if defined(__NR_sigprocmask)
502       ||
503       sysno == __NR_sigprocmask
504 #endif
505 #if defined(__NR_sigreturn)
506       ||
507       sysno == __NR_sigreturn
508 #endif
509       ) {
510     return ErrorCode(ErrorCode::ERR_ALLOWED);
511   } else if (sysno == __NR_getpid) {
512     // Disallow getpid()
513     return ErrorCode(EPERM);
514   } else if (SandboxBPF::IsValidSyscallNumber(sysno)) {
515     // Allow (and count) all other system calls.
516     return sandbox->UnsafeTrap(CountSyscalls, aux);
517   } else {
518     return ErrorCode(ENOSYS);
519   }
520 }
521
522 BPF_TEST(SandboxBPF, GreyListedPolicy, GreyListedPolicy, int /* (*BPF_AUX) */) {
523   BPF_ASSERT(syscall(__NR_getpid) == -1);
524   BPF_ASSERT(errno == EPERM);
525   BPF_ASSERT(*BPF_AUX == 0);
526   BPF_ASSERT(syscall(__NR_geteuid) == syscall(__NR_getuid));
527   BPF_ASSERT(*BPF_AUX == 2);
528   char name[17] = {};
529   BPF_ASSERT(!syscall(__NR_prctl,
530                       PR_GET_NAME,
531                       name,
532                       (void*)NULL,
533                       (void*)NULL,
534                       (void*)NULL));
535   BPF_ASSERT(*BPF_AUX == 3);
536   BPF_ASSERT(*name);
537 }
538
539 SANDBOX_TEST(SandboxBPF, EnableUnsafeTrapsInSigSysHandler) {
540   // Disabling warning messages that could confuse our test framework.
541   setenv(kSandboxDebuggingEnv, "t", 0);
542   Die::SuppressInfoMessages(true);
543
544   unsetenv(kSandboxDebuggingEnv);
545   SANDBOX_ASSERT(Trap::EnableUnsafeTrapsInSigSysHandler() == false);
546   setenv(kSandboxDebuggingEnv, "", 1);
547   SANDBOX_ASSERT(Trap::EnableUnsafeTrapsInSigSysHandler() == false);
548   setenv(kSandboxDebuggingEnv, "t", 1);
549   SANDBOX_ASSERT(Trap::EnableUnsafeTrapsInSigSysHandler() == true);
550 }
551
552 intptr_t PrctlHandler(const struct arch_seccomp_data& args, void*) {
553   if (args.args[0] == PR_CAPBSET_DROP && static_cast<int>(args.args[1]) == -1) {
554     // prctl(PR_CAPBSET_DROP, -1) is never valid. The kernel will always
555     // return an error. But our handler allows this call.
556     return 0;
557   } else {
558     return SandboxBPF::ForwardSyscall(args);
559   }
560 }
561
562 class PrctlPolicy : public SandboxBPFPolicy {
563  public:
564   PrctlPolicy() {}
565   virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
566                                     int sysno) const OVERRIDE {
567     DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
568     setenv(kSandboxDebuggingEnv, "t", 0);
569     Die::SuppressInfoMessages(true);
570
571     if (sysno == __NR_prctl) {
572       // Handle prctl() inside an UnsafeTrap()
573       return sandbox->UnsafeTrap(PrctlHandler, NULL);
574     }
575
576     // Allow all other system calls.
577     return ErrorCode(ErrorCode::ERR_ALLOWED);
578   }
579
580  private:
581   DISALLOW_COPY_AND_ASSIGN(PrctlPolicy);
582 };
583
584 BPF_TEST_C(SandboxBPF, ForwardSyscall, PrctlPolicy) {
585   // This call should never be allowed. But our policy will intercept it and
586   // let it pass successfully.
587   BPF_ASSERT(
588       !prctl(PR_CAPBSET_DROP, -1, (void*)NULL, (void*)NULL, (void*)NULL));
589
590   // Verify that the call will fail, if it makes it all the way to the kernel.
591   BPF_ASSERT(
592       prctl(PR_CAPBSET_DROP, -2, (void*)NULL, (void*)NULL, (void*)NULL) == -1);
593
594   // And verify that other uses of prctl() work just fine.
595   char name[17] = {};
596   BPF_ASSERT(!syscall(__NR_prctl,
597                       PR_GET_NAME,
598                       name,
599                       (void*)NULL,
600                       (void*)NULL,
601                       (void*)NULL));
602   BPF_ASSERT(*name);
603
604   // Finally, verify that system calls other than prctl() are completely
605   // unaffected by our policy.
606   struct utsname uts = {};
607   BPF_ASSERT(!uname(&uts));
608   BPF_ASSERT(!strcmp(uts.sysname, "Linux"));
609 }
610
611 intptr_t AllowRedirectedSyscall(const struct arch_seccomp_data& args, void*) {
612   return SandboxBPF::ForwardSyscall(args);
613 }
614
615 class RedirectAllSyscallsPolicy : public SandboxBPFPolicy {
616  public:
617   RedirectAllSyscallsPolicy() {}
618   virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
619                                     int sysno) const OVERRIDE;
620
621  private:
622   DISALLOW_COPY_AND_ASSIGN(RedirectAllSyscallsPolicy);
623 };
624
625 ErrorCode RedirectAllSyscallsPolicy::EvaluateSyscall(SandboxBPF* sandbox,
626                                                      int sysno) const {
627   DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
628   setenv(kSandboxDebuggingEnv, "t", 0);
629   Die::SuppressInfoMessages(true);
630
631   // Some system calls must always be allowed, if our policy wants to make
632   // use of UnsafeTrap()
633   if (sysno == __NR_rt_sigprocmask || sysno == __NR_rt_sigreturn
634 #if defined(__NR_sigprocmask)
635       ||
636       sysno == __NR_sigprocmask
637 #endif
638 #if defined(__NR_sigreturn)
639       ||
640       sysno == __NR_sigreturn
641 #endif
642       ) {
643     return ErrorCode(ErrorCode::ERR_ALLOWED);
644   }
645   return sandbox->UnsafeTrap(AllowRedirectedSyscall, NULL);
646 }
647
648 int bus_handler_fd_ = -1;
649
650 void SigBusHandler(int, siginfo_t* info, void* void_context) {
651   BPF_ASSERT(write(bus_handler_fd_, "\x55", 1) == 1);
652 }
653
654 BPF_TEST_C(SandboxBPF, SigBus, RedirectAllSyscallsPolicy) {
655   // We use the SIGBUS bit in the signal mask as a thread-local boolean
656   // value in the implementation of UnsafeTrap(). This is obviously a bit
657   // of a hack that could conceivably interfere with code that uses SIGBUS
658   // in more traditional ways. This test verifies that basic functionality
659   // of SIGBUS is not impacted, but it is certainly possibly to construe
660   // more complex uses of signals where our use of the SIGBUS mask is not
661   // 100% transparent. This is expected behavior.
662   int fds[2];
663   BPF_ASSERT(socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == 0);
664   bus_handler_fd_ = fds[1];
665   struct sigaction sa = {};
666   sa.sa_sigaction = SigBusHandler;
667   sa.sa_flags = SA_SIGINFO;
668   BPF_ASSERT(sigaction(SIGBUS, &sa, NULL) == 0);
669   raise(SIGBUS);
670   char c = '\000';
671   BPF_ASSERT(read(fds[0], &c, 1) == 1);
672   BPF_ASSERT(close(fds[0]) == 0);
673   BPF_ASSERT(close(fds[1]) == 0);
674   BPF_ASSERT(c == 0x55);
675 }
676
677 BPF_TEST_C(SandboxBPF, SigMask, RedirectAllSyscallsPolicy) {
678   // Signal masks are potentially tricky to handle. For instance, if we
679   // ever tried to update them from inside a Trap() or UnsafeTrap() handler,
680   // the call to sigreturn() at the end of the signal handler would undo
681   // all of our efforts. So, it makes sense to test that sigprocmask()
682   // works, even if we have a policy in place that makes use of UnsafeTrap().
683   // In practice, this works because we force sigprocmask() to be handled
684   // entirely in the kernel.
685   sigset_t mask0, mask1, mask2;
686
687   // Call sigprocmask() to verify that SIGUSR2 wasn't blocked, if we didn't
688   // change the mask (it shouldn't have been, as it isn't blocked by default
689   // in POSIX).
690   //
691   // Use SIGUSR2 because Android seems to use SIGUSR1 for some purpose.
692   sigemptyset(&mask0);
693   BPF_ASSERT(!sigprocmask(SIG_BLOCK, &mask0, &mask1));
694   BPF_ASSERT(!sigismember(&mask1, SIGUSR2));
695
696   // Try again, and this time we verify that we can block it. This
697   // requires a second call to sigprocmask().
698   sigaddset(&mask0, SIGUSR2);
699   BPF_ASSERT(!sigprocmask(SIG_BLOCK, &mask0, NULL));
700   BPF_ASSERT(!sigprocmask(SIG_BLOCK, NULL, &mask2));
701   BPF_ASSERT(sigismember(&mask2, SIGUSR2));
702 }
703
704 BPF_TEST_C(SandboxBPF, UnsafeTrapWithErrno, RedirectAllSyscallsPolicy) {
705   // An UnsafeTrap() (or for that matter, a Trap()) has to report error
706   // conditions by returning an exit code in the range -1..-4096. This
707   // should happen automatically if using ForwardSyscall(). If the TrapFnc()
708   // uses some other method to make system calls, then it is responsible
709   // for computing the correct return code.
710   // This test verifies that ForwardSyscall() does the correct thing.
711
712   // The glibc system wrapper will ultimately set errno for us. So, from normal
713   // userspace, all of this should be completely transparent.
714   errno = 0;
715   BPF_ASSERT(close(-1) == -1);
716   BPF_ASSERT(errno == EBADF);
717
718   // Explicitly avoid the glibc wrapper. This is not normally the way anybody
719   // would make system calls, but it allows us to verify that we don't
720   // accidentally mess with errno, when we shouldn't.
721   errno = 0;
722   struct arch_seccomp_data args = {};
723   args.nr = __NR_close;
724   args.args[0] = -1;
725   BPF_ASSERT(SandboxBPF::ForwardSyscall(args) == -EBADF);
726   BPF_ASSERT(errno == 0);
727 }
728
729 bool NoOpCallback() { return true; }
730
731 // Test a trap handler that makes use of a broker process to open().
732
733 class InitializedOpenBroker {
734  public:
735   InitializedOpenBroker() : initialized_(false) {
736     std::vector<std::string> allowed_files;
737     allowed_files.push_back("/proc/allowed");
738     allowed_files.push_back("/proc/cpuinfo");
739
740     broker_process_.reset(
741         new BrokerProcess(EPERM, allowed_files, std::vector<std::string>()));
742     BPF_ASSERT(broker_process() != NULL);
743     BPF_ASSERT(broker_process_->Init(base::Bind(&NoOpCallback)));
744
745     initialized_ = true;
746   }
747   bool initialized() { return initialized_; }
748   class BrokerProcess* broker_process() { return broker_process_.get(); }
749
750  private:
751   bool initialized_;
752   scoped_ptr<class BrokerProcess> broker_process_;
753   DISALLOW_COPY_AND_ASSIGN(InitializedOpenBroker);
754 };
755
756 intptr_t BrokerOpenTrapHandler(const struct arch_seccomp_data& args,
757                                void* aux) {
758   BPF_ASSERT(aux);
759   BrokerProcess* broker_process = static_cast<BrokerProcess*>(aux);
760   switch (args.nr) {
761     case __NR_faccessat:    // access is a wrapper of faccessat in android
762       BPF_ASSERT(static_cast<int>(args.args[0]) == AT_FDCWD);
763       return broker_process->Access(reinterpret_cast<const char*>(args.args[1]),
764                                     static_cast<int>(args.args[2]));
765     case __NR_access:
766       return broker_process->Access(reinterpret_cast<const char*>(args.args[0]),
767                                     static_cast<int>(args.args[1]));
768     case __NR_open:
769       return broker_process->Open(reinterpret_cast<const char*>(args.args[0]),
770                                   static_cast<int>(args.args[1]));
771     case __NR_openat:
772       // We only call open() so if we arrive here, it's because glibc uses
773       // the openat() system call.
774       BPF_ASSERT(static_cast<int>(args.args[0]) == AT_FDCWD);
775       return broker_process->Open(reinterpret_cast<const char*>(args.args[1]),
776                                   static_cast<int>(args.args[2]));
777     default:
778       BPF_ASSERT(false);
779       return -ENOSYS;
780   }
781 }
782
783 ErrorCode DenyOpenPolicy(SandboxBPF* sandbox,
784                          int sysno,
785                          InitializedOpenBroker* iob) {
786   if (!SandboxBPF::IsValidSyscallNumber(sysno)) {
787     return ErrorCode(ENOSYS);
788   }
789
790   switch (sysno) {
791     case __NR_faccessat:
792     case __NR_access:
793     case __NR_open:
794     case __NR_openat:
795       // We get a InitializedOpenBroker class, but our trap handler wants
796       // the BrokerProcess object.
797       return ErrorCode(
798           sandbox->Trap(BrokerOpenTrapHandler, iob->broker_process()));
799     default:
800       return ErrorCode(ErrorCode::ERR_ALLOWED);
801   }
802 }
803
804 // We use a InitializedOpenBroker class, so that we can run unsandboxed
805 // code in its constructor, which is the only way to do so in a BPF_TEST.
806 BPF_TEST(SandboxBPF,
807          UseOpenBroker,
808          DenyOpenPolicy,
809          InitializedOpenBroker /* (*BPF_AUX) */) {
810   BPF_ASSERT(BPF_AUX->initialized());
811   BrokerProcess* broker_process = BPF_AUX->broker_process();
812   BPF_ASSERT(broker_process != NULL);
813
814   // First, use the broker "manually"
815   BPF_ASSERT(broker_process->Open("/proc/denied", O_RDONLY) == -EPERM);
816   BPF_ASSERT(broker_process->Access("/proc/denied", R_OK) == -EPERM);
817   BPF_ASSERT(broker_process->Open("/proc/allowed", O_RDONLY) == -ENOENT);
818   BPF_ASSERT(broker_process->Access("/proc/allowed", R_OK) == -ENOENT);
819
820   // Now use glibc's open() as an external library would.
821   BPF_ASSERT(open("/proc/denied", O_RDONLY) == -1);
822   BPF_ASSERT(errno == EPERM);
823
824   BPF_ASSERT(open("/proc/allowed", O_RDONLY) == -1);
825   BPF_ASSERT(errno == ENOENT);
826
827   // Also test glibc's openat(), some versions of libc use it transparently
828   // instead of open().
829   BPF_ASSERT(openat(AT_FDCWD, "/proc/denied", O_RDONLY) == -1);
830   BPF_ASSERT(errno == EPERM);
831
832   BPF_ASSERT(openat(AT_FDCWD, "/proc/allowed", O_RDONLY) == -1);
833   BPF_ASSERT(errno == ENOENT);
834
835   // And test glibc's access().
836   BPF_ASSERT(access("/proc/denied", R_OK) == -1);
837   BPF_ASSERT(errno == EPERM);
838
839   BPF_ASSERT(access("/proc/allowed", R_OK) == -1);
840   BPF_ASSERT(errno == ENOENT);
841
842   // This is also white listed and does exist.
843   int cpu_info_access = access("/proc/cpuinfo", R_OK);
844   BPF_ASSERT(cpu_info_access == 0);
845   int cpu_info_fd = open("/proc/cpuinfo", O_RDONLY);
846   BPF_ASSERT(cpu_info_fd >= 0);
847   char buf[1024];
848   BPF_ASSERT(read(cpu_info_fd, buf, sizeof(buf)) > 0);
849 }
850
851 // Simple test demonstrating how to use SandboxBPF::Cond()
852
853 class SimpleCondTestPolicy : public SandboxBPFPolicy {
854  public:
855   SimpleCondTestPolicy() {}
856   virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
857                                     int sysno) const OVERRIDE;
858
859  private:
860   DISALLOW_COPY_AND_ASSIGN(SimpleCondTestPolicy);
861 };
862
863 ErrorCode SimpleCondTestPolicy::EvaluateSyscall(SandboxBPF* sandbox,
864                                                 int sysno) const {
865   DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
866
867   // We deliberately return unusual errno values upon failure, so that we
868   // can uniquely test for these values. In a "real" policy, you would want
869   // to return more traditional values.
870   int flags_argument_position = -1;
871   switch (sysno) {
872     case __NR_open:
873     case __NR_openat:  // open can be a wrapper for openat(2).
874       if (sysno == __NR_open) {
875         flags_argument_position = 1;
876       } else if (sysno == __NR_openat) {
877         flags_argument_position = 2;
878       }
879       // Allow opening files for reading, but don't allow writing.
880       COMPILE_ASSERT(O_RDONLY == 0, O_RDONLY_must_be_all_zero_bits);
881       return sandbox->Cond(flags_argument_position,
882                            ErrorCode::TP_32BIT,
883                            ErrorCode::OP_HAS_ANY_BITS,
884                            O_ACCMODE /* 0x3 */,
885                            ErrorCode(EROFS),
886                            ErrorCode(ErrorCode::ERR_ALLOWED));
887     case __NR_prctl:
888       // Allow prctl(PR_SET_DUMPABLE) and prctl(PR_GET_DUMPABLE), but
889       // disallow everything else.
890       return sandbox->Cond(0,
891                            ErrorCode::TP_32BIT,
892                            ErrorCode::OP_EQUAL,
893                            PR_SET_DUMPABLE,
894                            ErrorCode(ErrorCode::ERR_ALLOWED),
895                            sandbox->Cond(0,
896                                          ErrorCode::TP_32BIT,
897                                          ErrorCode::OP_EQUAL,
898                                          PR_GET_DUMPABLE,
899                                          ErrorCode(ErrorCode::ERR_ALLOWED),
900                                          ErrorCode(ENOMEM)));
901     default:
902       return ErrorCode(ErrorCode::ERR_ALLOWED);
903   }
904 }
905
906 BPF_TEST_C(SandboxBPF, SimpleCondTest, SimpleCondTestPolicy) {
907   int fd;
908   BPF_ASSERT((fd = open("/proc/self/comm", O_RDWR)) == -1);
909   BPF_ASSERT(errno == EROFS);
910   BPF_ASSERT((fd = open("/proc/self/comm", O_RDONLY)) >= 0);
911   close(fd);
912
913   int ret;
914   BPF_ASSERT((ret = prctl(PR_GET_DUMPABLE)) >= 0);
915   BPF_ASSERT(prctl(PR_SET_DUMPABLE, 1 - ret) == 0);
916   BPF_ASSERT(prctl(PR_GET_ENDIAN, &ret) == -1);
917   BPF_ASSERT(errno == ENOMEM);
918 }
919
920 // This test exercises the SandboxBPF::Cond() method by building a complex
921 // tree of conditional equality operations. It then makes system calls and
922 // verifies that they return the values that we expected from our BPF
923 // program.
924 class EqualityStressTest {
925  public:
926   EqualityStressTest() {
927     // We want a deterministic test
928     srand(0);
929
930     // Iterates over system call numbers and builds a random tree of
931     // equality tests.
932     // We are actually constructing a graph of ArgValue objects. This
933     // graph will later be used to a) compute our sandbox policy, and
934     // b) drive the code that verifies the output from the BPF program.
935     COMPILE_ASSERT(
936         kNumTestCases < (int)(MAX_PUBLIC_SYSCALL - MIN_SYSCALL - 10),
937         num_test_cases_must_be_significantly_smaller_than_num_system_calls);
938     for (int sysno = MIN_SYSCALL, end = kNumTestCases; sysno < end; ++sysno) {
939       if (IsReservedSyscall(sysno)) {
940         // Skip reserved system calls. This ensures that our test frame
941         // work isn't impacted by the fact that we are overriding
942         // a lot of different system calls.
943         ++end;
944         arg_values_.push_back(NULL);
945       } else {
946         arg_values_.push_back(
947             RandomArgValue(rand() % kMaxArgs, 0, rand() % kMaxArgs));
948       }
949     }
950   }
951
952   ~EqualityStressTest() {
953     for (std::vector<ArgValue*>::iterator iter = arg_values_.begin();
954          iter != arg_values_.end();
955          ++iter) {
956       DeleteArgValue(*iter);
957     }
958   }
959
960   ErrorCode Policy(SandboxBPF* sandbox, int sysno) {
961     if (!SandboxBPF::IsValidSyscallNumber(sysno)) {
962       // FIXME: we should really not have to do that in a trivial policy
963       return ErrorCode(ENOSYS);
964     } else if (sysno < 0 || sysno >= (int)arg_values_.size() ||
965                IsReservedSyscall(sysno)) {
966       // We only return ErrorCode values for the system calls that
967       // are part of our test data. Every other system call remains
968       // allowed.
969       return ErrorCode(ErrorCode::ERR_ALLOWED);
970     } else {
971       // ToErrorCode() turns an ArgValue object into an ErrorCode that is
972       // suitable for use by a sandbox policy.
973       return ToErrorCode(sandbox, arg_values_[sysno]);
974     }
975   }
976
977   void VerifyFilter() {
978     // Iterate over all system calls. Skip the system calls that have
979     // previously been determined as being reserved.
980     for (int sysno = 0; sysno < (int)arg_values_.size(); ++sysno) {
981       if (!arg_values_[sysno]) {
982         // Skip reserved system calls.
983         continue;
984       }
985       // Verify that system calls return the values that we expect them to
986       // return. This involves passing different combinations of system call
987       // parameters in order to exercise all possible code paths through the
988       // BPF filter program.
989       // We arbitrarily start by setting all six system call arguments to
990       // zero. And we then recursive traverse our tree of ArgValues to
991       // determine the necessary combinations of parameters.
992       intptr_t args[6] = {};
993       Verify(sysno, args, *arg_values_[sysno]);
994     }
995   }
996
997  private:
998   struct ArgValue {
999     int argno;  // Argument number to inspect.
1000     int size;   // Number of test cases (must be > 0).
1001     struct Tests {
1002       uint32_t k_value;            // Value to compare syscall arg against.
1003       int err;                     // If non-zero, errno value to return.
1004       struct ArgValue* arg_value;  // Otherwise, more args needs inspecting.
1005     }* tests;
1006     int err;                     // If none of the tests passed, this is what
1007     struct ArgValue* arg_value;  // we'll return (this is the "else" branch).
1008   };
1009
1010   bool IsReservedSyscall(int sysno) {
1011     // There are a handful of system calls that we should never use in our
1012     // test cases. These system calls are needed to allow the test framework
1013     // to run properly.
1014     // If we wanted to write fully generic code, there are more system calls
1015     // that could be listed here, and it is quite difficult to come up with a
1016     // truly comprehensive list. After all, we are deliberately making system
1017     // calls unavailable. In practice, we have a pretty good idea of the system
1018     // calls that will be made by this particular test. So, this small list is
1019     // sufficient. But if anybody copy'n'pasted this code for other uses, they
1020     // would have to review that the list.
1021     return sysno == __NR_read || sysno == __NR_write || sysno == __NR_exit ||
1022            sysno == __NR_exit_group || sysno == __NR_restart_syscall;
1023   }
1024
1025   ArgValue* RandomArgValue(int argno, int args_mask, int remaining_args) {
1026     // Create a new ArgValue and fill it with random data. We use as bit mask
1027     // to keep track of the system call parameters that have previously been
1028     // set; this ensures that we won't accidentally define a contradictory
1029     // set of equality tests.
1030     struct ArgValue* arg_value = new ArgValue();
1031     args_mask |= 1 << argno;
1032     arg_value->argno = argno;
1033
1034     // Apply some restrictions on just how complex our tests can be.
1035     // Otherwise, we end up with a BPF program that is too complicated for
1036     // the kernel to load.
1037     int fan_out = kMaxFanOut;
1038     if (remaining_args > 3) {
1039       fan_out = 1;
1040     } else if (remaining_args > 2) {
1041       fan_out = 2;
1042     }
1043
1044     // Create a couple of different test cases with randomized values that
1045     // we want to use when comparing system call parameter number "argno".
1046     arg_value->size = rand() % fan_out + 1;
1047     arg_value->tests = new ArgValue::Tests[arg_value->size];
1048
1049     uint32_t k_value = rand();
1050     for (int n = 0; n < arg_value->size; ++n) {
1051       // Ensure that we have unique values
1052       k_value += rand() % (RAND_MAX / (kMaxFanOut + 1)) + 1;
1053
1054       // There are two possible types of nodes. Either this is a leaf node;
1055       // in that case, we have completed all the equality tests that we
1056       // wanted to perform, and we can now compute a random "errno" value that
1057       // we should return. Or this is part of a more complex boolean
1058       // expression; in that case, we have to recursively add tests for some
1059       // of system call parameters that we have not yet included in our
1060       // tests.
1061       arg_value->tests[n].k_value = k_value;
1062       if (!remaining_args || (rand() & 1)) {
1063         arg_value->tests[n].err = (rand() % 1000) + 1;
1064         arg_value->tests[n].arg_value = NULL;
1065       } else {
1066         arg_value->tests[n].err = 0;
1067         arg_value->tests[n].arg_value =
1068             RandomArgValue(RandomArg(args_mask), args_mask, remaining_args - 1);
1069       }
1070     }
1071     // Finally, we have to define what we should return if none of the
1072     // previous equality tests pass. Again, we can either deal with a leaf
1073     // node, or we can randomly add another couple of tests.
1074     if (!remaining_args || (rand() & 1)) {
1075       arg_value->err = (rand() % 1000) + 1;
1076       arg_value->arg_value = NULL;
1077     } else {
1078       arg_value->err = 0;
1079       arg_value->arg_value =
1080           RandomArgValue(RandomArg(args_mask), args_mask, remaining_args - 1);
1081     }
1082     // We have now built a new (sub-)tree of ArgValues defining a set of
1083     // boolean expressions for testing random system call arguments against
1084     // random values. Return this tree to our caller.
1085     return arg_value;
1086   }
1087
1088   int RandomArg(int args_mask) {
1089     // Compute a random system call parameter number.
1090     int argno = rand() % kMaxArgs;
1091
1092     // Make sure that this same parameter number has not previously been
1093     // used. Otherwise, we could end up with a test that is impossible to
1094     // satisfy (e.g. args[0] == 1 && args[0] == 2).
1095     while (args_mask & (1 << argno)) {
1096       argno = (argno + 1) % kMaxArgs;
1097     }
1098     return argno;
1099   }
1100
1101   void DeleteArgValue(ArgValue* arg_value) {
1102     // Delete an ArgValue and all of its child nodes. This requires
1103     // recursively descending into the tree.
1104     if (arg_value) {
1105       if (arg_value->size) {
1106         for (int n = 0; n < arg_value->size; ++n) {
1107           if (!arg_value->tests[n].err) {
1108             DeleteArgValue(arg_value->tests[n].arg_value);
1109           }
1110         }
1111         delete[] arg_value->tests;
1112       }
1113       if (!arg_value->err) {
1114         DeleteArgValue(arg_value->arg_value);
1115       }
1116       delete arg_value;
1117     }
1118   }
1119
1120   ErrorCode ToErrorCode(SandboxBPF* sandbox, ArgValue* arg_value) {
1121     // Compute the ErrorCode that should be returned, if none of our
1122     // tests succeed (i.e. the system call parameter doesn't match any
1123     // of the values in arg_value->tests[].k_value).
1124     ErrorCode err;
1125     if (arg_value->err) {
1126       // If this was a leaf node, return the errno value that we expect to
1127       // return from the BPF filter program.
1128       err = ErrorCode(arg_value->err);
1129     } else {
1130       // If this wasn't a leaf node yet, recursively descend into the rest
1131       // of the tree. This will end up adding a few more SandboxBPF::Cond()
1132       // tests to our ErrorCode.
1133       err = ToErrorCode(sandbox, arg_value->arg_value);
1134     }
1135
1136     // Now, iterate over all the test cases that we want to compare against.
1137     // This builds a chain of SandboxBPF::Cond() tests
1138     // (aka "if ... elif ... elif ... elif ... fi")
1139     for (int n = arg_value->size; n-- > 0;) {
1140       ErrorCode matched;
1141       // Again, we distinguish between leaf nodes and subtrees.
1142       if (arg_value->tests[n].err) {
1143         matched = ErrorCode(arg_value->tests[n].err);
1144       } else {
1145         matched = ToErrorCode(sandbox, arg_value->tests[n].arg_value);
1146       }
1147       // For now, all of our tests are limited to 32bit.
1148       // We have separate tests that check the behavior of 32bit vs. 64bit
1149       // conditional expressions.
1150       err = sandbox->Cond(arg_value->argno,
1151                           ErrorCode::TP_32BIT,
1152                           ErrorCode::OP_EQUAL,
1153                           arg_value->tests[n].k_value,
1154                           matched,
1155                           err);
1156     }
1157     return err;
1158   }
1159
1160   void Verify(int sysno, intptr_t* args, const ArgValue& arg_value) {
1161     uint32_t mismatched = 0;
1162     // Iterate over all the k_values in arg_value.tests[] and verify that
1163     // we see the expected return values from system calls, when we pass
1164     // the k_value as a parameter in a system call.
1165     for (int n = arg_value.size; n-- > 0;) {
1166       mismatched += arg_value.tests[n].k_value;
1167       args[arg_value.argno] = arg_value.tests[n].k_value;
1168       if (arg_value.tests[n].err) {
1169         VerifyErrno(sysno, args, arg_value.tests[n].err);
1170       } else {
1171         Verify(sysno, args, *arg_value.tests[n].arg_value);
1172       }
1173     }
1174   // Find a k_value that doesn't match any of the k_values in
1175   // arg_value.tests[]. In most cases, the current value of "mismatched"
1176   // would fit this requirement. But on the off-chance that it happens
1177   // to collide, we double-check.
1178   try_again:
1179     for (int n = arg_value.size; n-- > 0;) {
1180       if (mismatched == arg_value.tests[n].k_value) {
1181         ++mismatched;
1182         goto try_again;
1183       }
1184     }
1185     // Now verify that we see the expected return value from system calls,
1186     // if we pass a value that doesn't match any of the conditions (i.e. this
1187     // is testing the "else" clause of the conditions).
1188     args[arg_value.argno] = mismatched;
1189     if (arg_value.err) {
1190       VerifyErrno(sysno, args, arg_value.err);
1191     } else {
1192       Verify(sysno, args, *arg_value.arg_value);
1193     }
1194     // Reset args[arg_value.argno]. This is not technically needed, but it
1195     // makes it easier to reason about the correctness of our tests.
1196     args[arg_value.argno] = 0;
1197   }
1198
1199   void VerifyErrno(int sysno, intptr_t* args, int err) {
1200     // We installed BPF filters that return different errno values
1201     // based on the system call number and the parameters that we decided
1202     // to pass in. Verify that this condition holds true.
1203     BPF_ASSERT(
1204         Syscall::Call(
1205             sysno, args[0], args[1], args[2], args[3], args[4], args[5]) ==
1206         -err);
1207   }
1208
1209   // Vector of ArgValue trees. These trees define all the possible boolean
1210   // expressions that we want to turn into a BPF filter program.
1211   std::vector<ArgValue*> arg_values_;
1212
1213   // Don't increase these values. We are pushing the limits of the maximum
1214   // BPF program that the kernel will allow us to load. If the values are
1215   // increased too much, the test will start failing.
1216   static const int kNumTestCases = 40;
1217   static const int kMaxFanOut = 3;
1218   static const int kMaxArgs = 6;
1219 };
1220
1221 ErrorCode EqualityStressTestPolicy(SandboxBPF* sandbox,
1222                                    int sysno,
1223                                    EqualityStressTest* aux) {
1224   DCHECK(aux);
1225   return aux->Policy(sandbox, sysno);
1226 }
1227
1228 BPF_TEST(SandboxBPF,
1229          EqualityTests,
1230          EqualityStressTestPolicy,
1231          EqualityStressTest /* (*BPF_AUX) */) {
1232   BPF_AUX->VerifyFilter();
1233 }
1234
1235 class EqualityArgumentWidthPolicy : public SandboxBPFPolicy {
1236  public:
1237   EqualityArgumentWidthPolicy() {}
1238   virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
1239                                     int sysno) const OVERRIDE;
1240
1241  private:
1242   DISALLOW_COPY_AND_ASSIGN(EqualityArgumentWidthPolicy);
1243 };
1244
1245 ErrorCode EqualityArgumentWidthPolicy::EvaluateSyscall(SandboxBPF* sandbox,
1246                                                        int sysno) const {
1247   DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
1248   if (sysno == __NR_uname) {
1249     return sandbox->Cond(
1250         0,
1251         ErrorCode::TP_32BIT,
1252         ErrorCode::OP_EQUAL,
1253         0,
1254         sandbox->Cond(1,
1255                       ErrorCode::TP_32BIT,
1256                       ErrorCode::OP_EQUAL,
1257                       0x55555555,
1258                       ErrorCode(1),
1259                       ErrorCode(2)),
1260         // The BPF compiler and the BPF interpreter in the kernel are
1261         // (mostly) agnostic of the host platform's word size. The compiler
1262         // will happily generate code that tests a 64bit value, and the
1263         // interpreter will happily perform this test.
1264         // But unless there is a kernel bug, there is no way for us to pass
1265         // in a 64bit quantity on a 32bit platform. The upper 32bits should
1266         // always be zero. So, this test should always evaluate as false on
1267         // 32bit systems.
1268         sandbox->Cond(1,
1269                       ErrorCode::TP_64BIT,
1270                       ErrorCode::OP_EQUAL,
1271                       0x55555555AAAAAAAAULL,
1272                       ErrorCode(1),
1273                       ErrorCode(2)));
1274   }
1275   return ErrorCode(ErrorCode::ERR_ALLOWED);
1276 }
1277
1278 BPF_TEST_C(SandboxBPF, EqualityArgumentWidth, EqualityArgumentWidthPolicy) {
1279   BPF_ASSERT(Syscall::Call(__NR_uname, 0, 0x55555555) == -1);
1280   BPF_ASSERT(Syscall::Call(__NR_uname, 0, 0xAAAAAAAA) == -2);
1281 #if __SIZEOF_POINTER__ > 4
1282   // On 32bit machines, there is no way to pass a 64bit argument through the
1283   // syscall interface. So, we have to skip the part of the test that requires
1284   // 64bit arguments.
1285   BPF_ASSERT(Syscall::Call(__NR_uname, 1, 0x55555555AAAAAAAAULL) == -1);
1286   BPF_ASSERT(Syscall::Call(__NR_uname, 1, 0x5555555500000000ULL) == -2);
1287   BPF_ASSERT(Syscall::Call(__NR_uname, 1, 0x5555555511111111ULL) == -2);
1288   BPF_ASSERT(Syscall::Call(__NR_uname, 1, 0x11111111AAAAAAAAULL) == -2);
1289 #else
1290   BPF_ASSERT(Syscall::Call(__NR_uname, 1, 0x55555555) == -2);
1291 #endif
1292 }
1293
1294 #if __SIZEOF_POINTER__ > 4
1295 // On 32bit machines, there is no way to pass a 64bit argument through the
1296 // syscall interface. So, we have to skip the part of the test that requires
1297 // 64bit arguments.
1298 BPF_DEATH_TEST_C(SandboxBPF,
1299                  EqualityArgumentUnallowed64bit,
1300                  DEATH_MESSAGE("Unexpected 64bit argument detected"),
1301                  EqualityArgumentWidthPolicy) {
1302   Syscall::Call(__NR_uname, 0, 0x5555555555555555ULL);
1303 }
1304 #endif
1305
1306 class EqualityWithNegativeArgumentsPolicy : public SandboxBPFPolicy {
1307  public:
1308   EqualityWithNegativeArgumentsPolicy() {}
1309   virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
1310                                     int sysno) const OVERRIDE {
1311     DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
1312     if (sysno == __NR_uname) {
1313       return sandbox->Cond(0,
1314                            ErrorCode::TP_32BIT,
1315                            ErrorCode::OP_EQUAL,
1316                            0xFFFFFFFF,
1317                            ErrorCode(1),
1318                            ErrorCode(2));
1319     }
1320     return ErrorCode(ErrorCode::ERR_ALLOWED);
1321   }
1322
1323  private:
1324   DISALLOW_COPY_AND_ASSIGN(EqualityWithNegativeArgumentsPolicy);
1325 };
1326
1327 BPF_TEST_C(SandboxBPF,
1328            EqualityWithNegativeArguments,
1329            EqualityWithNegativeArgumentsPolicy) {
1330   BPF_ASSERT(Syscall::Call(__NR_uname, 0xFFFFFFFF) == -1);
1331   BPF_ASSERT(Syscall::Call(__NR_uname, -1) == -1);
1332   BPF_ASSERT(Syscall::Call(__NR_uname, -1LL) == -1);
1333 }
1334
1335 #if __SIZEOF_POINTER__ > 4
1336 BPF_DEATH_TEST_C(SandboxBPF,
1337                  EqualityWithNegative64bitArguments,
1338                  DEATH_MESSAGE("Unexpected 64bit argument detected"),
1339                  EqualityWithNegativeArgumentsPolicy) {
1340   // When expecting a 32bit system call argument, we look at the MSB of the
1341   // 64bit value and allow both "0" and "-1". But the latter is allowed only
1342   // iff the LSB was negative. So, this death test should error out.
1343   BPF_ASSERT(Syscall::Call(__NR_uname, 0xFFFFFFFF00000000LL) == -1);
1344 }
1345 #endif
1346 class AllBitTestPolicy : public SandboxBPFPolicy {
1347  public:
1348   AllBitTestPolicy() {}
1349   virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
1350                                     int sysno) const OVERRIDE;
1351
1352  private:
1353   DISALLOW_COPY_AND_ASSIGN(AllBitTestPolicy);
1354 };
1355
1356 ErrorCode AllBitTestPolicy::EvaluateSyscall(SandboxBPF* sandbox,
1357                                             int sysno) const {
1358   DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
1359   // Test the OP_HAS_ALL_BITS conditional test operator with a couple of
1360   // different bitmasks. We try to find bitmasks that could conceivably
1361   // touch corner cases.
1362   // For all of these tests, we override the uname(). We can make use with
1363   // a single system call number, as we use the first system call argument to
1364   // select the different bit masks that we want to test against.
1365   if (sysno == __NR_uname) {
1366     return sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 0,
1367            sandbox->Cond(1, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ALL_BITS,
1368                          0x0,
1369                          ErrorCode(1), ErrorCode(0)),
1370
1371            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 1,
1372            sandbox->Cond(1, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ALL_BITS,
1373                          0x1,
1374                          ErrorCode(1), ErrorCode(0)),
1375
1376            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 2,
1377            sandbox->Cond(1, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ALL_BITS,
1378                          0x3,
1379                          ErrorCode(1), ErrorCode(0)),
1380
1381            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 3,
1382            sandbox->Cond(1, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ALL_BITS,
1383                          0x80000000,
1384                          ErrorCode(1), ErrorCode(0)),
1385            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 4,
1386            sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ALL_BITS,
1387                          0x0,
1388                          ErrorCode(1), ErrorCode(0)),
1389
1390            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 5,
1391            sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ALL_BITS,
1392                          0x1,
1393                          ErrorCode(1), ErrorCode(0)),
1394
1395            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 6,
1396            sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ALL_BITS,
1397                          0x3,
1398                          ErrorCode(1), ErrorCode(0)),
1399
1400            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 7,
1401            sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ALL_BITS,
1402                          0x80000000,
1403                          ErrorCode(1), ErrorCode(0)),
1404
1405            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 8,
1406            sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ALL_BITS,
1407                          0x100000000ULL,
1408                          ErrorCode(1), ErrorCode(0)),
1409
1410            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 9,
1411            sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ALL_BITS,
1412                          0x300000000ULL,
1413                          ErrorCode(1), ErrorCode(0)),
1414
1415            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 10,
1416            sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ALL_BITS,
1417                          0x100000001ULL,
1418                          ErrorCode(1), ErrorCode(0)),
1419
1420                          sandbox->Kill("Invalid test case number"))))))))))));
1421   }
1422   return ErrorCode(ErrorCode::ERR_ALLOWED);
1423 }
1424
1425 // Define a macro that performs tests using our test policy.
1426 // NOTE: Not all of the arguments in this macro are actually used!
1427 //       They are here just to serve as documentation of the conditions
1428 //       implemented in the test policy.
1429 //       Most notably, "op" and "mask" are unused by the macro. If you want
1430 //       to make changes to these values, you will have to edit the
1431 //       test policy instead.
1432 #define BITMASK_TEST(testcase, arg, op, mask, expected_value) \
1433   BPF_ASSERT(Syscall::Call(__NR_uname, (testcase), (arg)) == (expected_value))
1434
1435 // Our uname() system call returns ErrorCode(1) for success and
1436 // ErrorCode(0) for failure. Syscall::Call() turns this into an
1437 // exit code of -1 or 0.
1438 #define EXPECT_FAILURE 0
1439 #define EXPECT_SUCCESS -1
1440
1441 // A couple of our tests behave differently on 32bit and 64bit systems, as
1442 // there is no way for a 32bit system call to pass in a 64bit system call
1443 // argument "arg".
1444 // We expect these tests to succeed on 64bit systems, but to tail on 32bit
1445 // systems.
1446 #define EXPT64_SUCCESS (sizeof(void*) > 4 ? EXPECT_SUCCESS : EXPECT_FAILURE)
1447 BPF_TEST_C(SandboxBPF, AllBitTests, AllBitTestPolicy) {
1448   // 32bit test: all of 0x0 (should always be true)
1449   BITMASK_TEST( 0,                   0, ALLBITS32,          0, EXPECT_SUCCESS);
1450   BITMASK_TEST( 0,                   1, ALLBITS32,          0, EXPECT_SUCCESS);
1451   BITMASK_TEST( 0,                   3, ALLBITS32,          0, EXPECT_SUCCESS);
1452   BITMASK_TEST( 0,         0xFFFFFFFFU, ALLBITS32,          0, EXPECT_SUCCESS);
1453   BITMASK_TEST( 0,                -1LL, ALLBITS32,          0, EXPECT_SUCCESS);
1454
1455   // 32bit test: all of 0x1
1456   BITMASK_TEST( 1,                   0, ALLBITS32,        0x1, EXPECT_FAILURE);
1457   BITMASK_TEST( 1,                   1, ALLBITS32,        0x1, EXPECT_SUCCESS);
1458   BITMASK_TEST( 1,                   2, ALLBITS32,        0x1, EXPECT_FAILURE);
1459   BITMASK_TEST( 1,                   3, ALLBITS32,        0x1, EXPECT_SUCCESS);
1460
1461   // 32bit test: all of 0x3
1462   BITMASK_TEST( 2,                   0, ALLBITS32,        0x3, EXPECT_FAILURE);
1463   BITMASK_TEST( 2,                   1, ALLBITS32,        0x3, EXPECT_FAILURE);
1464   BITMASK_TEST( 2,                   2, ALLBITS32,        0x3, EXPECT_FAILURE);
1465   BITMASK_TEST( 2,                   3, ALLBITS32,        0x3, EXPECT_SUCCESS);
1466   BITMASK_TEST( 2,                   7, ALLBITS32,        0x3, EXPECT_SUCCESS);
1467
1468   // 32bit test: all of 0x80000000
1469   BITMASK_TEST( 3,                   0, ALLBITS32, 0x80000000, EXPECT_FAILURE);
1470   BITMASK_TEST( 3,         0x40000000U, ALLBITS32, 0x80000000, EXPECT_FAILURE);
1471   BITMASK_TEST( 3,         0x80000000U, ALLBITS32, 0x80000000, EXPECT_SUCCESS);
1472   BITMASK_TEST( 3,         0xC0000000U, ALLBITS32, 0x80000000, EXPECT_SUCCESS);
1473   BITMASK_TEST( 3,       -0x80000000LL, ALLBITS32, 0x80000000, EXPECT_SUCCESS);
1474
1475   // 64bit test: all of 0x0 (should always be true)
1476   BITMASK_TEST( 4,                   0, ALLBITS64,          0, EXPECT_SUCCESS);
1477   BITMASK_TEST( 4,                   1, ALLBITS64,          0, EXPECT_SUCCESS);
1478   BITMASK_TEST( 4,                   3, ALLBITS64,          0, EXPECT_SUCCESS);
1479   BITMASK_TEST( 4,         0xFFFFFFFFU, ALLBITS64,          0, EXPECT_SUCCESS);
1480   BITMASK_TEST( 4,       0x100000000LL, ALLBITS64,          0, EXPECT_SUCCESS);
1481   BITMASK_TEST( 4,       0x300000000LL, ALLBITS64,          0, EXPECT_SUCCESS);
1482   BITMASK_TEST( 4,0x8000000000000000LL, ALLBITS64,          0, EXPECT_SUCCESS);
1483   BITMASK_TEST( 4,                -1LL, ALLBITS64,          0, EXPECT_SUCCESS);
1484
1485   // 64bit test: all of 0x1
1486   BITMASK_TEST( 5,                   0, ALLBITS64,          1, EXPECT_FAILURE);
1487   BITMASK_TEST( 5,                   1, ALLBITS64,          1, EXPECT_SUCCESS);
1488   BITMASK_TEST( 5,                   2, ALLBITS64,          1, EXPECT_FAILURE);
1489   BITMASK_TEST( 5,                   3, ALLBITS64,          1, EXPECT_SUCCESS);
1490   BITMASK_TEST( 5,       0x100000000LL, ALLBITS64,          1, EXPECT_FAILURE);
1491   BITMASK_TEST( 5,       0x100000001LL, ALLBITS64,          1, EXPECT_SUCCESS);
1492   BITMASK_TEST( 5,       0x100000002LL, ALLBITS64,          1, EXPECT_FAILURE);
1493   BITMASK_TEST( 5,       0x100000003LL, ALLBITS64,          1, EXPECT_SUCCESS);
1494
1495   // 64bit test: all of 0x3
1496   BITMASK_TEST( 6,                   0, ALLBITS64,          3, EXPECT_FAILURE);
1497   BITMASK_TEST( 6,                   1, ALLBITS64,          3, EXPECT_FAILURE);
1498   BITMASK_TEST( 6,                   2, ALLBITS64,          3, EXPECT_FAILURE);
1499   BITMASK_TEST( 6,                   3, ALLBITS64,          3, EXPECT_SUCCESS);
1500   BITMASK_TEST( 6,                   7, ALLBITS64,          3, EXPECT_SUCCESS);
1501   BITMASK_TEST( 6,       0x100000000LL, ALLBITS64,          3, EXPECT_FAILURE);
1502   BITMASK_TEST( 6,       0x100000001LL, ALLBITS64,          3, EXPECT_FAILURE);
1503   BITMASK_TEST( 6,       0x100000002LL, ALLBITS64,          3, EXPECT_FAILURE);
1504   BITMASK_TEST( 6,       0x100000003LL, ALLBITS64,          3, EXPECT_SUCCESS);
1505   BITMASK_TEST( 6,       0x100000007LL, ALLBITS64,          3, EXPECT_SUCCESS);
1506
1507   // 64bit test: all of 0x80000000
1508   BITMASK_TEST( 7,                   0, ALLBITS64, 0x80000000, EXPECT_FAILURE);
1509   BITMASK_TEST( 7,         0x40000000U, ALLBITS64, 0x80000000, EXPECT_FAILURE);
1510   BITMASK_TEST( 7,         0x80000000U, ALLBITS64, 0x80000000, EXPECT_SUCCESS);
1511   BITMASK_TEST( 7,         0xC0000000U, ALLBITS64, 0x80000000, EXPECT_SUCCESS);
1512   BITMASK_TEST( 7,       -0x80000000LL, ALLBITS64, 0x80000000, EXPECT_SUCCESS);
1513   BITMASK_TEST( 7,       0x100000000LL, ALLBITS64, 0x80000000, EXPECT_FAILURE);
1514   BITMASK_TEST( 7,       0x140000000LL, ALLBITS64, 0x80000000, EXPECT_FAILURE);
1515   BITMASK_TEST( 7,       0x180000000LL, ALLBITS64, 0x80000000, EXPECT_SUCCESS);
1516   BITMASK_TEST( 7,       0x1C0000000LL, ALLBITS64, 0x80000000, EXPECT_SUCCESS);
1517   BITMASK_TEST( 7,      -0x180000000LL, ALLBITS64, 0x80000000, EXPECT_SUCCESS);
1518
1519   // 64bit test: all of 0x100000000
1520   BITMASK_TEST( 8,       0x000000000LL, ALLBITS64,0x100000000, EXPECT_FAILURE);
1521   BITMASK_TEST( 8,       0x100000000LL, ALLBITS64,0x100000000, EXPT64_SUCCESS);
1522   BITMASK_TEST( 8,       0x200000000LL, ALLBITS64,0x100000000, EXPECT_FAILURE);
1523   BITMASK_TEST( 8,       0x300000000LL, ALLBITS64,0x100000000, EXPT64_SUCCESS);
1524   BITMASK_TEST( 8,       0x000000001LL, ALLBITS64,0x100000000, EXPECT_FAILURE);
1525   BITMASK_TEST( 8,       0x100000001LL, ALLBITS64,0x100000000, EXPT64_SUCCESS);
1526   BITMASK_TEST( 8,       0x200000001LL, ALLBITS64,0x100000000, EXPECT_FAILURE);
1527   BITMASK_TEST( 8,       0x300000001LL, ALLBITS64,0x100000000, EXPT64_SUCCESS);
1528
1529   // 64bit test: all of 0x300000000
1530   BITMASK_TEST( 9,       0x000000000LL, ALLBITS64,0x300000000, EXPECT_FAILURE);
1531   BITMASK_TEST( 9,       0x100000000LL, ALLBITS64,0x300000000, EXPECT_FAILURE);
1532   BITMASK_TEST( 9,       0x200000000LL, ALLBITS64,0x300000000, EXPECT_FAILURE);
1533   BITMASK_TEST( 9,       0x300000000LL, ALLBITS64,0x300000000, EXPT64_SUCCESS);
1534   BITMASK_TEST( 9,       0x700000000LL, ALLBITS64,0x300000000, EXPT64_SUCCESS);
1535   BITMASK_TEST( 9,       0x000000001LL, ALLBITS64,0x300000000, EXPECT_FAILURE);
1536   BITMASK_TEST( 9,       0x100000001LL, ALLBITS64,0x300000000, EXPECT_FAILURE);
1537   BITMASK_TEST( 9,       0x200000001LL, ALLBITS64,0x300000000, EXPECT_FAILURE);
1538   BITMASK_TEST( 9,       0x300000001LL, ALLBITS64,0x300000000, EXPT64_SUCCESS);
1539   BITMASK_TEST( 9,       0x700000001LL, ALLBITS64,0x300000000, EXPT64_SUCCESS);
1540
1541   // 64bit test: all of 0x100000001
1542   BITMASK_TEST(10,       0x000000000LL, ALLBITS64,0x100000001, EXPECT_FAILURE);
1543   BITMASK_TEST(10,       0x000000001LL, ALLBITS64,0x100000001, EXPECT_FAILURE);
1544   BITMASK_TEST(10,       0x100000000LL, ALLBITS64,0x100000001, EXPECT_FAILURE);
1545   BITMASK_TEST(10,       0x100000001LL, ALLBITS64,0x100000001, EXPT64_SUCCESS);
1546   BITMASK_TEST(10,         0xFFFFFFFFU, ALLBITS64,0x100000001, EXPECT_FAILURE);
1547   BITMASK_TEST(10,                 -1L, ALLBITS64,0x100000001, EXPT64_SUCCESS);
1548 }
1549
1550 class AnyBitTestPolicy : public SandboxBPFPolicy {
1551  public:
1552   AnyBitTestPolicy() {}
1553   virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
1554                                     int sysno) const OVERRIDE;
1555
1556  private:
1557   DISALLOW_COPY_AND_ASSIGN(AnyBitTestPolicy);
1558 };
1559
1560 ErrorCode AnyBitTestPolicy::EvaluateSyscall(SandboxBPF* sandbox,
1561                                             int sysno) const {
1562   DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
1563   // Test the OP_HAS_ANY_BITS conditional test operator with a couple of
1564   // different bitmasks. We try to find bitmasks that could conceivably
1565   // touch corner cases.
1566   // For all of these tests, we override the uname(). We can make use with
1567   // a single system call number, as we use the first system call argument to
1568   // select the different bit masks that we want to test against.
1569   if (sysno == __NR_uname) {
1570     return sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 0,
1571            sandbox->Cond(1, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ANY_BITS,
1572                          0x0,
1573                          ErrorCode(1), ErrorCode(0)),
1574
1575            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 1,
1576            sandbox->Cond(1, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ANY_BITS,
1577                          0x1,
1578                          ErrorCode(1), ErrorCode(0)),
1579
1580            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 2,
1581            sandbox->Cond(1, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ANY_BITS,
1582                          0x3,
1583                          ErrorCode(1), ErrorCode(0)),
1584
1585            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 3,
1586            sandbox->Cond(1, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ANY_BITS,
1587                          0x80000000,
1588                          ErrorCode(1), ErrorCode(0)),
1589
1590            // All the following tests don't really make much sense on 32bit
1591            // systems. They will always evaluate as false.
1592            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 4,
1593            sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ANY_BITS,
1594                          0x0,
1595                          ErrorCode(1), ErrorCode(0)),
1596
1597            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 5,
1598            sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ANY_BITS,
1599                          0x1,
1600                          ErrorCode(1), ErrorCode(0)),
1601
1602            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 6,
1603            sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ANY_BITS,
1604                          0x3,
1605                          ErrorCode(1), ErrorCode(0)),
1606
1607            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 7,
1608            sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ANY_BITS,
1609                          0x80000000,
1610                          ErrorCode(1), ErrorCode(0)),
1611
1612            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 8,
1613            sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ANY_BITS,
1614                          0x100000000ULL,
1615                          ErrorCode(1), ErrorCode(0)),
1616
1617            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 9,
1618            sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ANY_BITS,
1619                          0x300000000ULL,
1620                          ErrorCode(1), ErrorCode(0)),
1621
1622            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL, 10,
1623            sandbox->Cond(1, ErrorCode::TP_64BIT, ErrorCode::OP_HAS_ANY_BITS,
1624                          0x100000001ULL,
1625                          ErrorCode(1), ErrorCode(0)),
1626
1627                          sandbox->Kill("Invalid test case number"))))))))))));
1628   }
1629   return ErrorCode(ErrorCode::ERR_ALLOWED);
1630 }
1631
1632 BPF_TEST_C(SandboxBPF, AnyBitTests, AnyBitTestPolicy) {
1633   // 32bit test: any of 0x0 (should always be false)
1634   BITMASK_TEST( 0,                   0, ANYBITS32,        0x0, EXPECT_FAILURE);
1635   BITMASK_TEST( 0,                   1, ANYBITS32,        0x0, EXPECT_FAILURE);
1636   BITMASK_TEST( 0,                   3, ANYBITS32,        0x0, EXPECT_FAILURE);
1637   BITMASK_TEST( 0,         0xFFFFFFFFU, ANYBITS32,        0x0, EXPECT_FAILURE);
1638   BITMASK_TEST( 0,                -1LL, ANYBITS32,        0x0, EXPECT_FAILURE);
1639
1640   // 32bit test: any of 0x1
1641   BITMASK_TEST( 1,                   0, ANYBITS32,        0x1, EXPECT_FAILURE);
1642   BITMASK_TEST( 1,                   1, ANYBITS32,        0x1, EXPECT_SUCCESS);
1643   BITMASK_TEST( 1,                   2, ANYBITS32,        0x1, EXPECT_FAILURE);
1644   BITMASK_TEST( 1,                   3, ANYBITS32,        0x1, EXPECT_SUCCESS);
1645
1646   // 32bit test: any of 0x3
1647   BITMASK_TEST( 2,                   0, ANYBITS32,        0x3, EXPECT_FAILURE);
1648   BITMASK_TEST( 2,                   1, ANYBITS32,        0x3, EXPECT_SUCCESS);
1649   BITMASK_TEST( 2,                   2, ANYBITS32,        0x3, EXPECT_SUCCESS);
1650   BITMASK_TEST( 2,                   3, ANYBITS32,        0x3, EXPECT_SUCCESS);
1651   BITMASK_TEST( 2,                   7, ANYBITS32,        0x3, EXPECT_SUCCESS);
1652
1653   // 32bit test: any of 0x80000000
1654   BITMASK_TEST( 3,                   0, ANYBITS32, 0x80000000, EXPECT_FAILURE);
1655   BITMASK_TEST( 3,         0x40000000U, ANYBITS32, 0x80000000, EXPECT_FAILURE);
1656   BITMASK_TEST( 3,         0x80000000U, ANYBITS32, 0x80000000, EXPECT_SUCCESS);
1657   BITMASK_TEST( 3,         0xC0000000U, ANYBITS32, 0x80000000, EXPECT_SUCCESS);
1658   BITMASK_TEST( 3,       -0x80000000LL, ANYBITS32, 0x80000000, EXPECT_SUCCESS);
1659
1660   // 64bit test: any of 0x0 (should always be false)
1661   BITMASK_TEST( 4,                   0, ANYBITS64,        0x0, EXPECT_FAILURE);
1662   BITMASK_TEST( 4,                   1, ANYBITS64,        0x0, EXPECT_FAILURE);
1663   BITMASK_TEST( 4,                   3, ANYBITS64,        0x0, EXPECT_FAILURE);
1664   BITMASK_TEST( 4,         0xFFFFFFFFU, ANYBITS64,        0x0, EXPECT_FAILURE);
1665   BITMASK_TEST( 4,       0x100000000LL, ANYBITS64,        0x0, EXPECT_FAILURE);
1666   BITMASK_TEST( 4,       0x300000000LL, ANYBITS64,        0x0, EXPECT_FAILURE);
1667   BITMASK_TEST( 4,0x8000000000000000LL, ANYBITS64,        0x0, EXPECT_FAILURE);
1668   BITMASK_TEST( 4,                -1LL, ANYBITS64,        0x0, EXPECT_FAILURE);
1669
1670   // 64bit test: any of 0x1
1671   BITMASK_TEST( 5,                   0, ANYBITS64,        0x1, EXPECT_FAILURE);
1672   BITMASK_TEST( 5,                   1, ANYBITS64,        0x1, EXPECT_SUCCESS);
1673   BITMASK_TEST( 5,                   2, ANYBITS64,        0x1, EXPECT_FAILURE);
1674   BITMASK_TEST( 5,                   3, ANYBITS64,        0x1, EXPECT_SUCCESS);
1675   BITMASK_TEST( 5,       0x100000001LL, ANYBITS64,        0x1, EXPECT_SUCCESS);
1676   BITMASK_TEST( 5,       0x100000000LL, ANYBITS64,        0x1, EXPECT_FAILURE);
1677   BITMASK_TEST( 5,       0x100000002LL, ANYBITS64,        0x1, EXPECT_FAILURE);
1678   BITMASK_TEST( 5,       0x100000003LL, ANYBITS64,        0x1, EXPECT_SUCCESS);
1679
1680   // 64bit test: any of 0x3
1681   BITMASK_TEST( 6,                   0, ANYBITS64,        0x3, EXPECT_FAILURE);
1682   BITMASK_TEST( 6,                   1, ANYBITS64,        0x3, EXPECT_SUCCESS);
1683   BITMASK_TEST( 6,                   2, ANYBITS64,        0x3, EXPECT_SUCCESS);
1684   BITMASK_TEST( 6,                   3, ANYBITS64,        0x3, EXPECT_SUCCESS);
1685   BITMASK_TEST( 6,                   7, ANYBITS64,        0x3, EXPECT_SUCCESS);
1686   BITMASK_TEST( 6,       0x100000000LL, ANYBITS64,        0x3, EXPECT_FAILURE);
1687   BITMASK_TEST( 6,       0x100000001LL, ANYBITS64,        0x3, EXPECT_SUCCESS);
1688   BITMASK_TEST( 6,       0x100000002LL, ANYBITS64,        0x3, EXPECT_SUCCESS);
1689   BITMASK_TEST( 6,       0x100000003LL, ANYBITS64,        0x3, EXPECT_SUCCESS);
1690   BITMASK_TEST( 6,       0x100000007LL, ANYBITS64,        0x3, EXPECT_SUCCESS);
1691
1692   // 64bit test: any of 0x80000000
1693   BITMASK_TEST( 7,                   0, ANYBITS64, 0x80000000, EXPECT_FAILURE);
1694   BITMASK_TEST( 7,         0x40000000U, ANYBITS64, 0x80000000, EXPECT_FAILURE);
1695   BITMASK_TEST( 7,         0x80000000U, ANYBITS64, 0x80000000, EXPECT_SUCCESS);
1696   BITMASK_TEST( 7,         0xC0000000U, ANYBITS64, 0x80000000, EXPECT_SUCCESS);
1697   BITMASK_TEST( 7,       -0x80000000LL, ANYBITS64, 0x80000000, EXPECT_SUCCESS);
1698   BITMASK_TEST( 7,       0x100000000LL, ANYBITS64, 0x80000000, EXPECT_FAILURE);
1699   BITMASK_TEST( 7,       0x140000000LL, ANYBITS64, 0x80000000, EXPECT_FAILURE);
1700   BITMASK_TEST( 7,       0x180000000LL, ANYBITS64, 0x80000000, EXPECT_SUCCESS);
1701   BITMASK_TEST( 7,       0x1C0000000LL, ANYBITS64, 0x80000000, EXPECT_SUCCESS);
1702   BITMASK_TEST( 7,      -0x180000000LL, ANYBITS64, 0x80000000, EXPECT_SUCCESS);
1703
1704   // 64bit test: any of 0x100000000
1705   BITMASK_TEST( 8,       0x000000000LL, ANYBITS64,0x100000000, EXPECT_FAILURE);
1706   BITMASK_TEST( 8,       0x100000000LL, ANYBITS64,0x100000000, EXPT64_SUCCESS);
1707   BITMASK_TEST( 8,       0x200000000LL, ANYBITS64,0x100000000, EXPECT_FAILURE);
1708   BITMASK_TEST( 8,       0x300000000LL, ANYBITS64,0x100000000, EXPT64_SUCCESS);
1709   BITMASK_TEST( 8,       0x000000001LL, ANYBITS64,0x100000000, EXPECT_FAILURE);
1710   BITMASK_TEST( 8,       0x100000001LL, ANYBITS64,0x100000000, EXPT64_SUCCESS);
1711   BITMASK_TEST( 8,       0x200000001LL, ANYBITS64,0x100000000, EXPECT_FAILURE);
1712   BITMASK_TEST( 8,       0x300000001LL, ANYBITS64,0x100000000, EXPT64_SUCCESS);
1713
1714   // 64bit test: any of 0x300000000
1715   BITMASK_TEST( 9,       0x000000000LL, ANYBITS64,0x300000000, EXPECT_FAILURE);
1716   BITMASK_TEST( 9,       0x100000000LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1717   BITMASK_TEST( 9,       0x200000000LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1718   BITMASK_TEST( 9,       0x300000000LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1719   BITMASK_TEST( 9,       0x700000000LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1720   BITMASK_TEST( 9,       0x000000001LL, ANYBITS64,0x300000000, EXPECT_FAILURE);
1721   BITMASK_TEST( 9,       0x100000001LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1722   BITMASK_TEST( 9,       0x200000001LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1723   BITMASK_TEST( 9,       0x300000001LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1724   BITMASK_TEST( 9,       0x700000001LL, ANYBITS64,0x300000000, EXPT64_SUCCESS);
1725
1726   // 64bit test: any of 0x100000001
1727   BITMASK_TEST( 10,      0x000000000LL, ANYBITS64,0x100000001, EXPECT_FAILURE);
1728   BITMASK_TEST( 10,      0x000000001LL, ANYBITS64,0x100000001, EXPECT_SUCCESS);
1729   BITMASK_TEST( 10,      0x100000000LL, ANYBITS64,0x100000001, EXPT64_SUCCESS);
1730   BITMASK_TEST( 10,      0x100000001LL, ANYBITS64,0x100000001, EXPECT_SUCCESS);
1731   BITMASK_TEST( 10,        0xFFFFFFFFU, ANYBITS64,0x100000001, EXPECT_SUCCESS);
1732   BITMASK_TEST( 10,                -1L, ANYBITS64,0x100000001, EXPECT_SUCCESS);
1733 }
1734
1735 intptr_t PthreadTrapHandler(const struct arch_seccomp_data& args, void* aux) {
1736   if (args.args[0] != (CLONE_CHILD_CLEARTID | CLONE_CHILD_SETTID | SIGCHLD)) {
1737     // We expect to get called for an attempt to fork(). No need to log that
1738     // call. But if we ever get called for anything else, we want to verbosely
1739     // print as much information as possible.
1740     const char* msg = (const char*)aux;
1741     printf(
1742         "Clone() was called with unexpected arguments\n"
1743         "  nr: %d\n"
1744         "  1: 0x%llX\n"
1745         "  2: 0x%llX\n"
1746         "  3: 0x%llX\n"
1747         "  4: 0x%llX\n"
1748         "  5: 0x%llX\n"
1749         "  6: 0x%llX\n"
1750         "%s\n",
1751         args.nr,
1752         (long long)args.args[0],
1753         (long long)args.args[1],
1754         (long long)args.args[2],
1755         (long long)args.args[3],
1756         (long long)args.args[4],
1757         (long long)args.args[5],
1758         msg);
1759   }
1760   return -EPERM;
1761 }
1762
1763 class PthreadPolicyEquality : public SandboxBPFPolicy {
1764  public:
1765   PthreadPolicyEquality() {}
1766   virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
1767                                     int sysno) const OVERRIDE;
1768
1769  private:
1770   DISALLOW_COPY_AND_ASSIGN(PthreadPolicyEquality);
1771 };
1772
1773 ErrorCode PthreadPolicyEquality::EvaluateSyscall(SandboxBPF* sandbox,
1774                                                  int sysno) const {
1775   DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
1776   // This policy allows creating threads with pthread_create(). But it
1777   // doesn't allow any other uses of clone(). Most notably, it does not
1778   // allow callers to implement fork() or vfork() by passing suitable flags
1779   // to the clone() system call.
1780   if (sysno == __NR_clone) {
1781     // We have seen two different valid combinations of flags. Glibc
1782     // uses the more modern flags, sets the TLS from the call to clone(), and
1783     // uses futexes to monitor threads. Android's C run-time library, doesn't
1784     // do any of this, but it sets the obsolete (and no-op) CLONE_DETACHED.
1785     // More recent versions of Android don't set CLONE_DETACHED anymore, so
1786     // the last case accounts for that.
1787     // The following policy is very strict. It only allows the exact masks
1788     // that we have seen in known implementations. It is probably somewhat
1789     // stricter than what we would want to do.
1790     const uint64_t kGlibcCloneMask =
1791         CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
1792         CLONE_THREAD | CLONE_SYSVSEM | CLONE_SETTLS |
1793         CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID;
1794     const uint64_t kBaseAndroidCloneMask =
1795         CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
1796         CLONE_THREAD | CLONE_SYSVSEM;
1797     return sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL,
1798                          kGlibcCloneMask,
1799                          ErrorCode(ErrorCode::ERR_ALLOWED),
1800            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL,
1801                          kBaseAndroidCloneMask | CLONE_DETACHED,
1802                          ErrorCode(ErrorCode::ERR_ALLOWED),
1803            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_EQUAL,
1804                          kBaseAndroidCloneMask,
1805                          ErrorCode(ErrorCode::ERR_ALLOWED),
1806                          sandbox->Trap(PthreadTrapHandler, "Unknown mask"))));
1807   }
1808   return ErrorCode(ErrorCode::ERR_ALLOWED);
1809 }
1810
1811 class PthreadPolicyBitMask : public SandboxBPFPolicy {
1812  public:
1813   PthreadPolicyBitMask() {}
1814   virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox,
1815                                     int sysno) const OVERRIDE;
1816
1817  private:
1818   DISALLOW_COPY_AND_ASSIGN(PthreadPolicyBitMask);
1819 };
1820
1821 ErrorCode PthreadPolicyBitMask::EvaluateSyscall(SandboxBPF* sandbox,
1822                                                 int sysno) const {
1823   DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
1824   // This policy allows creating threads with pthread_create(). But it
1825   // doesn't allow any other uses of clone(). Most notably, it does not
1826   // allow callers to implement fork() or vfork() by passing suitable flags
1827   // to the clone() system call.
1828   if (sysno == __NR_clone) {
1829     // We have seen two different valid combinations of flags. Glibc
1830     // uses the more modern flags, sets the TLS from the call to clone(), and
1831     // uses futexes to monitor threads. Android's C run-time library, doesn't
1832     // do any of this, but it sets the obsolete (and no-op) CLONE_DETACHED.
1833     // The following policy allows for either combination of flags, but it
1834     // is generally a little more conservative than strictly necessary. We
1835     // err on the side of rather safe than sorry.
1836     // Very noticeably though, we disallow fork() (which is often just a
1837     // wrapper around clone()).
1838     return sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ANY_BITS,
1839                          ~uint32(CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|
1840                                  CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|
1841                                  CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID|
1842                                  CLONE_DETACHED),
1843                          sandbox->Trap(PthreadTrapHandler,
1844                                        "Unexpected CLONE_XXX flag found"),
1845            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ALL_BITS,
1846                          CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|
1847                          CLONE_THREAD|CLONE_SYSVSEM,
1848            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ALL_BITS,
1849                          CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID,
1850                          ErrorCode(ErrorCode::ERR_ALLOWED),
1851            sandbox->Cond(0, ErrorCode::TP_32BIT, ErrorCode::OP_HAS_ANY_BITS,
1852                          CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID,
1853                          sandbox->Trap(PthreadTrapHandler,
1854                                        "Must set either all or none of the TLS"
1855                                        " and futex bits in call to clone()"),
1856                          ErrorCode(ErrorCode::ERR_ALLOWED))),
1857                          sandbox->Trap(PthreadTrapHandler,
1858                                        "Missing mandatory CLONE_XXX flags "
1859                                        "when creating new thread")));
1860   }
1861   return ErrorCode(ErrorCode::ERR_ALLOWED);
1862 }
1863
1864 static void* ThreadFnc(void* arg) {
1865   ++*reinterpret_cast<int*>(arg);
1866   Syscall::Call(__NR_futex, arg, FUTEX_WAKE, 1, 0, 0, 0);
1867   return NULL;
1868 }
1869
1870 static void PthreadTest() {
1871   // Attempt to start a joinable thread. This should succeed.
1872   pthread_t thread;
1873   int thread_ran = 0;
1874   BPF_ASSERT(!pthread_create(&thread, NULL, ThreadFnc, &thread_ran));
1875   BPF_ASSERT(!pthread_join(thread, NULL));
1876   BPF_ASSERT(thread_ran);
1877
1878   // Attempt to start a detached thread. This should succeed.
1879   thread_ran = 0;
1880   pthread_attr_t attr;
1881   BPF_ASSERT(!pthread_attr_init(&attr));
1882   BPF_ASSERT(!pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
1883   BPF_ASSERT(!pthread_create(&thread, &attr, ThreadFnc, &thread_ran));
1884   BPF_ASSERT(!pthread_attr_destroy(&attr));
1885   while (Syscall::Call(__NR_futex, &thread_ran, FUTEX_WAIT, 0, 0, 0, 0) ==
1886          -EINTR) {
1887   }
1888   BPF_ASSERT(thread_ran);
1889
1890   // Attempt to fork() a process using clone(). This should fail. We use the
1891   // same flags that glibc uses when calling fork(). But we don't actually
1892   // try calling the fork() implementation in the C run-time library, as
1893   // run-time libraries other than glibc might call __NR_fork instead of
1894   // __NR_clone, and that would introduce a bogus test failure.
1895   int pid;
1896   BPF_ASSERT(Syscall::Call(__NR_clone,
1897                            CLONE_CHILD_CLEARTID | CLONE_CHILD_SETTID | SIGCHLD,
1898                            0,
1899                            0,
1900                            &pid) == -EPERM);
1901 }
1902
1903 BPF_TEST_C(SandboxBPF, PthreadEquality, PthreadPolicyEquality) {
1904   PthreadTest();
1905 }
1906
1907 BPF_TEST_C(SandboxBPF, PthreadBitMask, PthreadPolicyBitMask) {
1908   PthreadTest();
1909 }
1910
1911 // libc might not define these even though the kernel supports it.
1912 #ifndef PTRACE_O_TRACESECCOMP
1913 #define PTRACE_O_TRACESECCOMP 0x00000080
1914 #endif
1915
1916 #ifdef PTRACE_EVENT_SECCOMP
1917 #define IS_SECCOMP_EVENT(status) ((status >> 16) == PTRACE_EVENT_SECCOMP)
1918 #else
1919 // When Debian/Ubuntu backported seccomp-bpf support into earlier kernels, they
1920 // changed the value of PTRACE_EVENT_SECCOMP from 7 to 8, since 7 was taken by
1921 // PTRACE_EVENT_STOP (upstream chose to renumber PTRACE_EVENT_STOP to 128).  If
1922 // PTRACE_EVENT_SECCOMP isn't defined, we have no choice but to consider both
1923 // values here.
1924 #define IS_SECCOMP_EVENT(status) ((status >> 16) == 7 || (status >> 16) == 8)
1925 #endif
1926
1927 #if defined(__arm__)
1928 #ifndef PTRACE_SET_SYSCALL
1929 #define PTRACE_SET_SYSCALL 23
1930 #endif
1931 #endif
1932
1933 // Changes the syscall to run for a child being sandboxed using seccomp-bpf with
1934 // PTRACE_O_TRACESECCOMP.  Should only be called when the child is stopped on
1935 // PTRACE_EVENT_SECCOMP.
1936 //
1937 // regs should contain the current set of registers of the child, obtained using
1938 // PTRACE_GETREGS.
1939 //
1940 // Depending on the architecture, this may modify regs, so the caller is
1941 // responsible for committing these changes using PTRACE_SETREGS.
1942 long SetSyscall(pid_t pid, regs_struct* regs, int syscall_number) {
1943 #if defined(__arm__)
1944   // On ARM, the syscall is changed using PTRACE_SET_SYSCALL.  We cannot use the
1945   // libc ptrace call as the request parameter is an enum, and
1946   // PTRACE_SET_SYSCALL may not be in the enum.
1947   return syscall(__NR_ptrace, PTRACE_SET_SYSCALL, pid, NULL, syscall_number);
1948 #endif
1949
1950   SECCOMP_PT_SYSCALL(*regs) = syscall_number;
1951   return 0;
1952 }
1953
1954 const uint16_t kTraceData = 0xcc;
1955
1956 class TraceAllPolicy : public SandboxBPFPolicy {
1957  public:
1958   TraceAllPolicy() {}
1959   virtual ~TraceAllPolicy() {}
1960
1961   virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox_compiler,
1962                                     int system_call_number) const OVERRIDE {
1963     return ErrorCode(ErrorCode::ERR_TRACE + kTraceData);
1964   }
1965
1966  private:
1967   DISALLOW_COPY_AND_ASSIGN(TraceAllPolicy);
1968 };
1969
1970 SANDBOX_TEST(SandboxBPF, DISABLE_ON_TSAN(SeccompRetTrace)) {
1971   if (SandboxBPF::SupportsSeccompSandbox(-1) !=
1972       sandbox::SandboxBPF::STATUS_AVAILABLE) {
1973     return;
1974   }
1975
1976 #if defined(__arm__)
1977   printf("This test is currently disabled on ARM due to a kernel bug.");
1978   return;
1979 #endif
1980
1981 #if defined(__mips__)
1982   // TODO: Figure out how to support specificity of handling indirect syscalls
1983   //        in this test and enable it.
1984   printf("This test is currently disabled on MIPS.");
1985   return;
1986 #endif
1987
1988   pid_t pid = fork();
1989   BPF_ASSERT_NE(-1, pid);
1990   if (pid == 0) {
1991     pid_t my_pid = getpid();
1992     BPF_ASSERT_NE(-1, ptrace(PTRACE_TRACEME, -1, NULL, NULL));
1993     BPF_ASSERT_EQ(0, raise(SIGSTOP));
1994     SandboxBPF sandbox;
1995     sandbox.SetSandboxPolicy(new TraceAllPolicy);
1996     BPF_ASSERT(sandbox.StartSandbox(SandboxBPF::PROCESS_SINGLE_THREADED));
1997
1998     // getpid is allowed.
1999     BPF_ASSERT_EQ(my_pid, syscall(__NR_getpid));
2000
2001     // write to stdout is skipped and returns a fake value.
2002     BPF_ASSERT_EQ(kExpectedReturnValue,
2003                   syscall(__NR_write, STDOUT_FILENO, "A", 1));
2004
2005     // kill is rewritten to exit(kExpectedReturnValue).
2006     syscall(__NR_kill, my_pid, SIGKILL);
2007
2008     // Should not be reached.
2009     BPF_ASSERT(false);
2010   }
2011
2012   int status;
2013   BPF_ASSERT(HANDLE_EINTR(waitpid(pid, &status, WUNTRACED)) != -1);
2014   BPF_ASSERT(WIFSTOPPED(status));
2015
2016   BPF_ASSERT_NE(-1, ptrace(PTRACE_SETOPTIONS, pid, NULL,
2017                            reinterpret_cast<void*>(PTRACE_O_TRACESECCOMP)));
2018   BPF_ASSERT_NE(-1, ptrace(PTRACE_CONT, pid, NULL, NULL));
2019   while (true) {
2020     BPF_ASSERT(HANDLE_EINTR(waitpid(pid, &status, 0)) != -1);
2021     if (WIFEXITED(status) || WIFSIGNALED(status)) {
2022       BPF_ASSERT(WIFEXITED(status));
2023       BPF_ASSERT_EQ(kExpectedReturnValue, WEXITSTATUS(status));
2024       break;
2025     }
2026
2027     if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGTRAP ||
2028         !IS_SECCOMP_EVENT(status)) {
2029       BPF_ASSERT_NE(-1, ptrace(PTRACE_CONT, pid, NULL, NULL));
2030       continue;
2031     }
2032
2033     unsigned long data;
2034     BPF_ASSERT_NE(-1, ptrace(PTRACE_GETEVENTMSG, pid, NULL, &data));
2035     BPF_ASSERT_EQ(kTraceData, data);
2036
2037     regs_struct regs;
2038     BPF_ASSERT_NE(-1, ptrace(PTRACE_GETREGS, pid, NULL, &regs));
2039     switch (SECCOMP_PT_SYSCALL(regs)) {
2040       case __NR_write:
2041         // Skip writes to stdout, make it return kExpectedReturnValue.  Allow
2042         // writes to stderr so that BPF_ASSERT messages show up.
2043         if (SECCOMP_PT_PARM1(regs) == STDOUT_FILENO) {
2044           BPF_ASSERT_NE(-1, SetSyscall(pid, &regs, -1));
2045           SECCOMP_PT_RESULT(regs) = kExpectedReturnValue;
2046           BPF_ASSERT_NE(-1, ptrace(PTRACE_SETREGS, pid, NULL, &regs));
2047         }
2048         break;
2049
2050       case __NR_kill:
2051         // Rewrite to exit(kExpectedReturnValue).
2052         BPF_ASSERT_NE(-1, SetSyscall(pid, &regs, __NR_exit));
2053         SECCOMP_PT_PARM1(regs) = kExpectedReturnValue;
2054         BPF_ASSERT_NE(-1, ptrace(PTRACE_SETREGS, pid, NULL, &regs));
2055         break;
2056
2057       default:
2058         // Allow all other syscalls.
2059         break;
2060     }
2061
2062     BPF_ASSERT_NE(-1, ptrace(PTRACE_CONT, pid, NULL, NULL));
2063   }
2064 }
2065
2066 // Android does not expose pread64 nor pwrite64.
2067 #if !defined(OS_ANDROID)
2068
2069 bool FullPwrite64(int fd, const char* buffer, size_t count, off64_t offset) {
2070   while (count > 0) {
2071     const ssize_t transfered =
2072         HANDLE_EINTR(pwrite64(fd, buffer, count, offset));
2073     if (transfered <= 0 || static_cast<size_t>(transfered) > count) {
2074       return false;
2075     }
2076     count -= transfered;
2077     buffer += transfered;
2078     offset += transfered;
2079   }
2080   return true;
2081 }
2082
2083 bool FullPread64(int fd, char* buffer, size_t count, off64_t offset) {
2084   while (count > 0) {
2085     const ssize_t transfered = HANDLE_EINTR(pread64(fd, buffer, count, offset));
2086     if (transfered <= 0 || static_cast<size_t>(transfered) > count) {
2087       return false;
2088     }
2089     count -= transfered;
2090     buffer += transfered;
2091     offset += transfered;
2092   }
2093   return true;
2094 }
2095
2096 bool pread_64_was_forwarded = false;
2097
2098 class TrapPread64Policy : public SandboxBPFPolicy {
2099  public:
2100   TrapPread64Policy() {}
2101   virtual ~TrapPread64Policy() {}
2102
2103   virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox_compiler,
2104                                     int system_call_number) const OVERRIDE {
2105     // Set the global environment for unsafe traps once.
2106     if (system_call_number == MIN_SYSCALL) {
2107       EnableUnsafeTraps();
2108     }
2109
2110     if (system_call_number == __NR_pread64) {
2111       return sandbox_compiler->UnsafeTrap(ForwardPreadHandler, NULL);
2112     }
2113     return ErrorCode(ErrorCode::ERR_ALLOWED);
2114   }
2115
2116  private:
2117   static intptr_t ForwardPreadHandler(const struct arch_seccomp_data& args,
2118                                       void* aux) {
2119     BPF_ASSERT(args.nr == __NR_pread64);
2120     pread_64_was_forwarded = true;
2121
2122     return SandboxBPF::ForwardSyscall(args);
2123   }
2124   DISALLOW_COPY_AND_ASSIGN(TrapPread64Policy);
2125 };
2126
2127 // pread(2) takes a 64 bits offset. On 32 bits systems, it will be split
2128 // between two arguments. In this test, we make sure that ForwardSyscall() can
2129 // forward it properly.
2130 BPF_TEST_C(SandboxBPF, Pread64, TrapPread64Policy) {
2131   ScopedTemporaryFile temp_file;
2132   const uint64_t kLargeOffset = (static_cast<uint64_t>(1) << 32) | 0xBEEF;
2133   const char kTestString[] = "This is a test!";
2134   BPF_ASSERT(FullPwrite64(
2135       temp_file.fd(), kTestString, sizeof(kTestString), kLargeOffset));
2136
2137   char read_test_string[sizeof(kTestString)] = {0};
2138   BPF_ASSERT(FullPread64(temp_file.fd(),
2139                          read_test_string,
2140                          sizeof(read_test_string),
2141                          kLargeOffset));
2142   BPF_ASSERT_EQ(0, memcmp(kTestString, read_test_string, sizeof(kTestString)));
2143   BPF_ASSERT(pread_64_was_forwarded);
2144 }
2145
2146 #endif  // !defined(OS_ANDROID)
2147
2148 }  // namespace
2149
2150 }  // namespace sandbox