Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / sandbox / linux / seccomp-bpf / sandbox_bpf.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "sandbox/linux/seccomp-bpf/sandbox_bpf.h"
6
7 // Some headers on Android are missing cdefs: crbug.com/172337.
8 // (We can't use OS_ANDROID here since build_config.h is not included).
9 #if defined(ANDROID)
10 #include <sys/cdefs.h>
11 #endif
12
13 #include <errno.h>
14 #include <fcntl.h>
15 #include <linux/filter.h>
16 #include <signal.h>
17 #include <string.h>
18 #include <sys/prctl.h>
19 #include <sys/stat.h>
20 #include <sys/syscall.h>
21 #include <sys/types.h>
22 #include <sys/wait.h>
23 #include <time.h>
24 #include <unistd.h>
25
26 #include <limits>
27
28 #include "base/compiler_specific.h"
29 #include "base/logging.h"
30 #include "base/macros.h"
31 #include "base/memory/scoped_ptr.h"
32 #include "base/posix/eintr_wrapper.h"
33 #include "sandbox/linux/seccomp-bpf/codegen.h"
34 #include "sandbox/linux/seccomp-bpf/die.h"
35 #include "sandbox/linux/seccomp-bpf/errorcode.h"
36 #include "sandbox/linux/seccomp-bpf/instruction.h"
37 #include "sandbox/linux/seccomp-bpf/linux_seccomp.h"
38 #include "sandbox/linux/seccomp-bpf/sandbox_bpf_policy.h"
39 #include "sandbox/linux/seccomp-bpf/syscall.h"
40 #include "sandbox/linux/seccomp-bpf/syscall_iterator.h"
41 #include "sandbox/linux/seccomp-bpf/trap.h"
42 #include "sandbox/linux/seccomp-bpf/verifier.h"
43 #include "sandbox/linux/services/linux_syscalls.h"
44
45 namespace sandbox {
46
47 namespace {
48
49 const int kExpectedExitCode = 100;
50
51 #if defined(__i386__) || defined(__x86_64__)
52 const bool kIsIntel = true;
53 #else
54 const bool kIsIntel = false;
55 #endif
56 #if defined(__x86_64__) && defined(__ILP32__)
57 const bool kIsX32 = true;
58 #else
59 const bool kIsX32 = false;
60 #endif
61
62 const int kSyscallsRequiredForUnsafeTraps[] = {
63   __NR_rt_sigprocmask,
64   __NR_rt_sigreturn,
65 #if defined(__NR_sigprocmask)
66   __NR_sigprocmask,
67 #endif
68 #if defined(__NR_sigreturn)
69   __NR_sigreturn,
70 #endif
71 };
72
73 bool HasExactlyOneBit(uint64_t x) {
74   // Common trick; e.g., see http://stackoverflow.com/a/108329.
75   return x != 0 && (x & (x - 1)) == 0;
76 }
77
78 #if !defined(NDEBUG)
79 void WriteFailedStderrSetupMessage(int out_fd) {
80   const char* error_string = strerror(errno);
81   static const char msg[] =
82       "You have reproduced a puzzling issue.\n"
83       "Please, report to crbug.com/152530!\n"
84       "Failed to set up stderr: ";
85   if (HANDLE_EINTR(write(out_fd, msg, sizeof(msg) - 1)) > 0 && error_string &&
86       HANDLE_EINTR(write(out_fd, error_string, strlen(error_string))) > 0 &&
87       HANDLE_EINTR(write(out_fd, "\n", 1))) {
88   }
89 }
90 #endif  // !defined(NDEBUG)
91
92 // We define a really simple sandbox policy. It is just good enough for us
93 // to tell that the sandbox has actually been activated.
94 class ProbePolicy : public SandboxBPFPolicy {
95  public:
96   ProbePolicy() {}
97   virtual ErrorCode EvaluateSyscall(SandboxBPF*, int sysnum) const OVERRIDE {
98     switch (sysnum) {
99       case __NR_getpid:
100         // Return EPERM so that we can check that the filter actually ran.
101         return ErrorCode(EPERM);
102       case __NR_exit_group:
103         // Allow exit() with a non-default return code.
104         return ErrorCode(ErrorCode::ERR_ALLOWED);
105       default:
106         // Make everything else fail in an easily recognizable way.
107         return ErrorCode(EINVAL);
108     }
109   }
110
111  private:
112   DISALLOW_COPY_AND_ASSIGN(ProbePolicy);
113 };
114
115 void ProbeProcess(void) {
116   if (syscall(__NR_getpid) < 0 && errno == EPERM) {
117     syscall(__NR_exit_group, static_cast<intptr_t>(kExpectedExitCode));
118   }
119 }
120
121 class AllowAllPolicy : public SandboxBPFPolicy {
122  public:
123   AllowAllPolicy() {}
124   virtual ErrorCode EvaluateSyscall(SandboxBPF*, int sysnum) const OVERRIDE {
125     DCHECK(SandboxBPF::IsValidSyscallNumber(sysnum));
126     return ErrorCode(ErrorCode::ERR_ALLOWED);
127   }
128
129  private:
130   DISALLOW_COPY_AND_ASSIGN(AllowAllPolicy);
131 };
132
133 void TryVsyscallProcess(void) {
134   time_t current_time;
135   // time() is implemented as a vsyscall. With an older glibc, with
136   // vsyscall=emulate and some versions of the seccomp BPF patch
137   // we may get SIGKILL-ed. Detect this!
138   if (time(&current_time) != static_cast<time_t>(-1)) {
139     syscall(__NR_exit_group, static_cast<intptr_t>(kExpectedExitCode));
140   }
141 }
142
143 bool IsSingleThreaded(int proc_fd) {
144   if (proc_fd < 0) {
145     // Cannot determine whether program is single-threaded. Hope for
146     // the best...
147     return true;
148   }
149
150   struct stat sb;
151   int task = -1;
152   if ((task = openat(proc_fd, "self/task", O_RDONLY | O_DIRECTORY)) < 0 ||
153       fstat(task, &sb) != 0 || sb.st_nlink != 3 || IGNORE_EINTR(close(task))) {
154     if (task >= 0) {
155       if (IGNORE_EINTR(close(task))) {
156       }
157     }
158     return false;
159   }
160   return true;
161 }
162
163 bool IsDenied(const ErrorCode& code) {
164   return (code.err() & SECCOMP_RET_ACTION) == SECCOMP_RET_TRAP ||
165          (code.err() >= (SECCOMP_RET_ERRNO + ErrorCode::ERR_MIN_ERRNO) &&
166           code.err() <= (SECCOMP_RET_ERRNO + ErrorCode::ERR_MAX_ERRNO));
167 }
168
169 // Function that can be passed as a callback function to CodeGen::Traverse().
170 // Checks whether the "insn" returns an UnsafeTrap() ErrorCode. If so, it
171 // sets the "bool" variable pointed to by "aux".
172 void CheckForUnsafeErrorCodes(Instruction* insn, void* aux) {
173   bool* is_unsafe = static_cast<bool*>(aux);
174   if (!*is_unsafe) {
175     if (BPF_CLASS(insn->code) == BPF_RET && insn->k > SECCOMP_RET_TRAP &&
176         insn->k - SECCOMP_RET_TRAP <= SECCOMP_RET_DATA) {
177       if (!Trap::IsSafeTrapId(insn->k & SECCOMP_RET_DATA)) {
178         *is_unsafe = true;
179       }
180     }
181   }
182 }
183
184 // A Trap() handler that returns an "errno" value. The value is encoded
185 // in the "aux" parameter.
186 intptr_t ReturnErrno(const struct arch_seccomp_data&, void* aux) {
187   // TrapFnc functions report error by following the native kernel convention
188   // of returning an exit code in the range of -1..-4096. They do not try to
189   // set errno themselves. The glibc wrapper that triggered the SIGSYS will
190   // ultimately do so for us.
191   int err = reinterpret_cast<intptr_t>(aux) & SECCOMP_RET_DATA;
192   return -err;
193 }
194
195 // Function that can be passed as a callback function to CodeGen::Traverse().
196 // Checks whether the "insn" returns an errno value from a BPF filter. If so,
197 // it rewrites the instruction to instead call a Trap() handler that does
198 // the same thing. "aux" is ignored.
199 void RedirectToUserspace(Instruction* insn, void* aux) {
200   // When inside an UnsafeTrap() callback, we want to allow all system calls.
201   // This means, we must conditionally disable the sandbox -- and that's not
202   // something that kernel-side BPF filters can do, as they cannot inspect
203   // any state other than the syscall arguments.
204   // But if we redirect all error handlers to user-space, then we can easily
205   // make this decision.
206   // The performance penalty for this extra round-trip to user-space is not
207   // actually that bad, as we only ever pay it for denied system calls; and a
208   // typical program has very few of these.
209   SandboxBPF* sandbox = static_cast<SandboxBPF*>(aux);
210   if (BPF_CLASS(insn->code) == BPF_RET &&
211       (insn->k & SECCOMP_RET_ACTION) == SECCOMP_RET_ERRNO) {
212     insn->k = sandbox->Trap(ReturnErrno,
213         reinterpret_cast<void*>(insn->k & SECCOMP_RET_DATA)).err();
214   }
215 }
216
217 // This wraps an existing policy and changes its behavior to match the changes
218 // made by RedirectToUserspace(). This is part of the framework that allows BPF
219 // evaluation in userland.
220 // TODO(markus): document the code inside better.
221 class RedirectToUserSpacePolicyWrapper : public SandboxBPFPolicy {
222  public:
223   explicit RedirectToUserSpacePolicyWrapper(
224       const SandboxBPFPolicy* wrapped_policy)
225       : wrapped_policy_(wrapped_policy) {
226     DCHECK(wrapped_policy_);
227   }
228
229   virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox_compiler,
230                                     int system_call_number) const OVERRIDE {
231     ErrorCode err =
232         wrapped_policy_->EvaluateSyscall(sandbox_compiler, system_call_number);
233     ChangeErrnoToTraps(&err, sandbox_compiler);
234     return err;
235   }
236
237   virtual ErrorCode InvalidSyscall(
238       SandboxBPF* sandbox_compiler) const OVERRIDE {
239     return ReturnErrnoViaTrap(sandbox_compiler, ENOSYS);
240   }
241
242  private:
243   ErrorCode ReturnErrnoViaTrap(SandboxBPF* sandbox_compiler, int err) const {
244     return sandbox_compiler->Trap(ReturnErrno, reinterpret_cast<void*>(err));
245   }
246
247   // ChangeErrnoToTraps recursivly iterates through the ErrorCode
248   // converting any ERRNO to a userspace trap
249   void ChangeErrnoToTraps(ErrorCode* err, SandboxBPF* sandbox_compiler) const {
250     if (err->error_type() == ErrorCode::ET_SIMPLE &&
251         (err->err() & SECCOMP_RET_ACTION) == SECCOMP_RET_ERRNO) {
252       // Have an errno, need to change this to a trap
253       *err =
254           ReturnErrnoViaTrap(sandbox_compiler, err->err() & SECCOMP_RET_DATA);
255       return;
256     } else if (err->error_type() == ErrorCode::ET_COND) {
257       // Need to explore both paths
258       ChangeErrnoToTraps((ErrorCode*)err->passed(), sandbox_compiler);
259       ChangeErrnoToTraps((ErrorCode*)err->failed(), sandbox_compiler);
260       return;
261     } else if (err->error_type() == ErrorCode::ET_TRAP) {
262       return;
263     } else if (err->error_type() == ErrorCode::ET_SIMPLE &&
264                (err->err() & SECCOMP_RET_ACTION) == SECCOMP_RET_ALLOW) {
265       return;
266     }
267     NOTREACHED();
268   }
269
270   const SandboxBPFPolicy* wrapped_policy_;
271   DISALLOW_COPY_AND_ASSIGN(RedirectToUserSpacePolicyWrapper);
272 };
273
274 intptr_t BPFFailure(const struct arch_seccomp_data&, void* aux) {
275   SANDBOX_DIE(static_cast<char*>(aux));
276 }
277
278 }  // namespace
279
280 SandboxBPF::SandboxBPF()
281     : quiet_(false),
282       proc_fd_(-1),
283       conds_(new Conds),
284       sandbox_has_started_(false) {}
285
286 SandboxBPF::~SandboxBPF() {
287   // It is generally unsafe to call any memory allocator operations or to even
288   // call arbitrary destructors after having installed a new policy. We just
289   // have no way to tell whether this policy would allow the system calls that
290   // the constructors can trigger.
291   // So, we normally destroy all of our complex state prior to starting the
292   // sandbox. But this won't happen, if the Sandbox object was created and
293   // never actually used to set up a sandbox. So, just in case, we are
294   // destroying any remaining state.
295   // The "if ()" statements are technically superfluous. But let's be explicit
296   // that we really don't want to run any code, when we already destroyed
297   // objects before setting up the sandbox.
298   if (conds_) {
299     delete conds_;
300   }
301 }
302
303 bool SandboxBPF::IsValidSyscallNumber(int sysnum) {
304   return SyscallIterator::IsValid(sysnum);
305 }
306
307 bool SandboxBPF::RunFunctionInPolicy(void (*code_in_sandbox)(),
308                                      scoped_ptr<SandboxBPFPolicy> policy) {
309   // Block all signals before forking a child process. This prevents an
310   // attacker from manipulating our test by sending us an unexpected signal.
311   sigset_t old_mask, new_mask;
312   if (sigfillset(&new_mask) || sigprocmask(SIG_BLOCK, &new_mask, &old_mask)) {
313     SANDBOX_DIE("sigprocmask() failed");
314   }
315   int fds[2];
316   if (pipe2(fds, O_NONBLOCK | O_CLOEXEC)) {
317     SANDBOX_DIE("pipe() failed");
318   }
319
320   if (fds[0] <= 2 || fds[1] <= 2) {
321     SANDBOX_DIE("Process started without standard file descriptors");
322   }
323
324   // This code is using fork() and should only ever run single-threaded.
325   // Most of the code below is "async-signal-safe" and only minor changes
326   // would be needed to support threads.
327   DCHECK(IsSingleThreaded(proc_fd_));
328   pid_t pid = fork();
329   if (pid < 0) {
330     // Die if we cannot fork(). We would probably fail a little later
331     // anyway, as the machine is likely very close to running out of
332     // memory.
333     // But what we don't want to do is return "false", as a crafty
334     // attacker might cause fork() to fail at will and could trick us
335     // into running without a sandbox.
336     sigprocmask(SIG_SETMASK, &old_mask, NULL);  // OK, if it fails
337     SANDBOX_DIE("fork() failed unexpectedly");
338   }
339
340   // In the child process
341   if (!pid) {
342     // Test a very simple sandbox policy to verify that we can
343     // successfully turn on sandboxing.
344     Die::EnableSimpleExit();
345
346     errno = 0;
347     if (IGNORE_EINTR(close(fds[0]))) {
348       // This call to close() has been failing in strange ways. See
349       // crbug.com/152530. So we only fail in debug mode now.
350 #if !defined(NDEBUG)
351       WriteFailedStderrSetupMessage(fds[1]);
352       SANDBOX_DIE(NULL);
353 #endif
354     }
355     if (HANDLE_EINTR(dup2(fds[1], 2)) != 2) {
356       // Stderr could very well be a file descriptor to .xsession-errors, or
357       // another file, which could be backed by a file system that could cause
358       // dup2 to fail while trying to close stderr. It's important that we do
359       // not fail on trying to close stderr.
360       // If dup2 fails here, we will continue normally, this means that our
361       // parent won't cause a fatal failure if something writes to stderr in
362       // this child.
363 #if !defined(NDEBUG)
364       // In DEBUG builds, we still want to get a report.
365       WriteFailedStderrSetupMessage(fds[1]);
366       SANDBOX_DIE(NULL);
367 #endif
368     }
369     if (IGNORE_EINTR(close(fds[1]))) {
370       // This call to close() has been failing in strange ways. See
371       // crbug.com/152530. So we only fail in debug mode now.
372 #if !defined(NDEBUG)
373       WriteFailedStderrSetupMessage(fds[1]);
374       SANDBOX_DIE(NULL);
375 #endif
376     }
377
378     SetSandboxPolicy(policy.release());
379     if (!StartSandbox(PROCESS_SINGLE_THREADED)) {
380       SANDBOX_DIE(NULL);
381     }
382
383     // Run our code in the sandbox.
384     code_in_sandbox();
385
386     // code_in_sandbox() is not supposed to return here.
387     SANDBOX_DIE(NULL);
388   }
389
390   // In the parent process.
391   if (IGNORE_EINTR(close(fds[1]))) {
392     SANDBOX_DIE("close() failed");
393   }
394   if (sigprocmask(SIG_SETMASK, &old_mask, NULL)) {
395     SANDBOX_DIE("sigprocmask() failed");
396   }
397   int status;
398   if (HANDLE_EINTR(waitpid(pid, &status, 0)) != pid) {
399     SANDBOX_DIE("waitpid() failed unexpectedly");
400   }
401   bool rc = WIFEXITED(status) && WEXITSTATUS(status) == kExpectedExitCode;
402
403   // If we fail to support sandboxing, there might be an additional
404   // error message. If so, this was an entirely unexpected and fatal
405   // failure. We should report the failure and somebody must fix
406   // things. This is probably a security-critical bug in the sandboxing
407   // code.
408   if (!rc) {
409     char buf[4096];
410     ssize_t len = HANDLE_EINTR(read(fds[0], buf, sizeof(buf) - 1));
411     if (len > 0) {
412       while (len > 1 && buf[len - 1] == '\n') {
413         --len;
414       }
415       buf[len] = '\000';
416       SANDBOX_DIE(buf);
417     }
418   }
419   if (IGNORE_EINTR(close(fds[0]))) {
420     SANDBOX_DIE("close() failed");
421   }
422
423   return rc;
424 }
425
426 bool SandboxBPF::KernelSupportSeccompBPF() {
427   return RunFunctionInPolicy(ProbeProcess,
428                              scoped_ptr<SandboxBPFPolicy>(new ProbePolicy())) &&
429          RunFunctionInPolicy(
430              TryVsyscallProcess,
431              scoped_ptr<SandboxBPFPolicy>(new AllowAllPolicy()));
432 }
433
434 // static
435 SandboxBPF::SandboxStatus SandboxBPF::SupportsSeccompSandbox(int proc_fd) {
436   // It the sandbox is currently active, we clearly must have support for
437   // sandboxing.
438   if (status_ == STATUS_ENABLED) {
439     return status_;
440   }
441
442   // Even if the sandbox was previously available, something might have
443   // changed in our run-time environment. Check one more time.
444   if (status_ == STATUS_AVAILABLE) {
445     if (!IsSingleThreaded(proc_fd)) {
446       status_ = STATUS_UNAVAILABLE;
447     }
448     return status_;
449   }
450
451   if (status_ == STATUS_UNAVAILABLE && IsSingleThreaded(proc_fd)) {
452     // All state transitions resulting in STATUS_UNAVAILABLE are immediately
453     // preceded by STATUS_AVAILABLE. Furthermore, these transitions all
454     // happen, if and only if they are triggered by the process being multi-
455     // threaded.
456     // In other words, if a single-threaded process is currently in the
457     // STATUS_UNAVAILABLE state, it is safe to assume that sandboxing is
458     // actually available.
459     status_ = STATUS_AVAILABLE;
460     return status_;
461   }
462
463   // If we have not previously checked for availability of the sandbox or if
464   // we otherwise don't believe to have a good cached value, we have to
465   // perform a thorough check now.
466   if (status_ == STATUS_UNKNOWN) {
467     // We create our own private copy of a "Sandbox" object. This ensures that
468     // the object does not have any policies configured, that might interfere
469     // with the tests done by "KernelSupportSeccompBPF()".
470     SandboxBPF sandbox;
471
472     // By setting "quiet_ = true" we suppress messages for expected and benign
473     // failures (e.g. if the current kernel lacks support for BPF filters).
474     sandbox.quiet_ = true;
475     sandbox.set_proc_fd(proc_fd);
476     status_ = sandbox.KernelSupportSeccompBPF() ? STATUS_AVAILABLE
477                                                 : STATUS_UNSUPPORTED;
478
479     // As we are performing our tests from a child process, the run-time
480     // environment that is visible to the sandbox is always guaranteed to be
481     // single-threaded. Let's check here whether the caller is single-
482     // threaded. Otherwise, we mark the sandbox as temporarily unavailable.
483     if (status_ == STATUS_AVAILABLE && !IsSingleThreaded(proc_fd)) {
484       status_ = STATUS_UNAVAILABLE;
485     }
486   }
487   return status_;
488 }
489
490 // static
491 SandboxBPF::SandboxStatus
492 SandboxBPF::SupportsSeccompThreadFilterSynchronization() {
493   // Applying NO_NEW_PRIVS, a BPF filter, and synchronizing the filter across
494   // the thread group are all handled atomically by this syscall.
495   const int rv = syscall(
496       __NR_seccomp, SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_TSYNC, NULL);
497
498   if (rv == -1 && errno == EFAULT) {
499     return STATUS_AVAILABLE;
500   } else {
501     // TODO(jln): turn these into DCHECK after 417888 is considered fixed.
502     CHECK_EQ(-1, rv);
503     CHECK(ENOSYS == errno || EINVAL == errno);
504     return STATUS_UNSUPPORTED;
505   }
506 }
507
508 void SandboxBPF::set_proc_fd(int proc_fd) { proc_fd_ = proc_fd; }
509
510 bool SandboxBPF::StartSandbox(SandboxThreadState thread_state) {
511   CHECK(thread_state == PROCESS_SINGLE_THREADED ||
512         thread_state == PROCESS_MULTI_THREADED);
513
514   if (status_ == STATUS_UNSUPPORTED || status_ == STATUS_UNAVAILABLE) {
515     SANDBOX_DIE(
516         "Trying to start sandbox, even though it is known to be "
517         "unavailable");
518     return false;
519   } else if (sandbox_has_started_ || !conds_) {
520     SANDBOX_DIE(
521         "Cannot repeatedly start sandbox. Create a separate Sandbox "
522         "object instead.");
523     return false;
524   }
525   if (proc_fd_ < 0) {
526     proc_fd_ = open("/proc", O_RDONLY | O_DIRECTORY);
527   }
528   if (proc_fd_ < 0) {
529     // For now, continue in degraded mode, if we can't access /proc.
530     // In the future, we might want to tighten this requirement.
531   }
532
533   bool supports_tsync =
534       SupportsSeccompThreadFilterSynchronization() == STATUS_AVAILABLE;
535
536   if (thread_state == PROCESS_SINGLE_THREADED) {
537     if (!IsSingleThreaded(proc_fd_)) {
538       SANDBOX_DIE("Cannot start sandbox; process is already multi-threaded");
539       return false;
540     }
541   } else if (thread_state == PROCESS_MULTI_THREADED) {
542     if (IsSingleThreaded(proc_fd_)) {
543       SANDBOX_DIE("Cannot start sandbox; "
544                   "process may be single-threaded when reported as not");
545       return false;
546     }
547     if (!supports_tsync) {
548       SANDBOX_DIE("Cannot start sandbox; kernel does not support synchronizing "
549                   "filters for a threadgroup");
550       return false;
551     }
552   }
553
554   // We no longer need access to any files in /proc. We want to do this
555   // before installing the filters, just in case that our policy denies
556   // close().
557   if (proc_fd_ >= 0) {
558     if (IGNORE_EINTR(close(proc_fd_))) {
559       SANDBOX_DIE("Failed to close file descriptor for /proc");
560       return false;
561     }
562     proc_fd_ = -1;
563   }
564
565   // Install the filters.
566   InstallFilter(supports_tsync || thread_state == PROCESS_MULTI_THREADED);
567
568   // We are now inside the sandbox.
569   status_ = STATUS_ENABLED;
570
571   return true;
572 }
573
574 void SandboxBPF::PolicySanityChecks(SandboxBPFPolicy* policy) {
575   if (!IsDenied(policy->InvalidSyscall(this))) {
576     SANDBOX_DIE("Policies should deny invalid system calls.");
577   }
578   return;
579 }
580
581 // Don't take a scoped_ptr here, polymorphism make their use awkward.
582 void SandboxBPF::SetSandboxPolicy(SandboxBPFPolicy* policy) {
583   DCHECK(!policy_);
584   if (sandbox_has_started_ || !conds_) {
585     SANDBOX_DIE("Cannot change policy after sandbox has started");
586   }
587   PolicySanityChecks(policy);
588   policy_.reset(policy);
589 }
590
591 void SandboxBPF::InstallFilter(bool must_sync_threads) {
592   // We want to be very careful in not imposing any requirements on the
593   // policies that are set with SetSandboxPolicy(). This means, as soon as
594   // the sandbox is active, we shouldn't be relying on libraries that could
595   // be making system calls. This, for example, means we should avoid
596   // using the heap and we should avoid using STL functions.
597   // Temporarily copy the contents of the "program" vector into a
598   // stack-allocated array; and then explicitly destroy that object.
599   // This makes sure we don't ex- or implicitly call new/delete after we
600   // installed the BPF filter program in the kernel. Depending on the
601   // system memory allocator that is in effect, these operators can result
602   // in system calls to things like munmap() or brk().
603   Program* program = AssembleFilter(false /* force_verification */);
604
605   struct sock_filter bpf[program->size()];
606   const struct sock_fprog prog = {static_cast<unsigned short>(program->size()),
607                                   bpf};
608   memcpy(bpf, &(*program)[0], sizeof(bpf));
609   delete program;
610
611   // Make an attempt to release memory that is no longer needed here, rather
612   // than in the destructor. Try to avoid as much as possible to presume of
613   // what will be possible to do in the new (sandboxed) execution environment.
614   delete conds_;
615   conds_ = NULL;
616   policy_.reset();
617
618   if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
619     SANDBOX_DIE(quiet_ ? NULL : "Kernel refuses to enable no-new-privs");
620   }
621
622   // Install BPF filter program. If the thread state indicates multi-threading
623   // support, then the kernel hass the seccomp system call. Otherwise, fall
624   // back on prctl, which requires the process to be single-threaded.
625   if (must_sync_threads) {
626     int rv = syscall(__NR_seccomp, SECCOMP_SET_MODE_FILTER,
627         SECCOMP_FILTER_FLAG_TSYNC, reinterpret_cast<const char*>(&prog));
628     if (rv) {
629       SANDBOX_DIE(quiet_ ? NULL :
630           "Kernel refuses to turn on and synchronize threads for BPF filters");
631     }
632   } else {
633     if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)) {
634       SANDBOX_DIE(quiet_ ? NULL : "Kernel refuses to turn on BPF filters");
635     }
636   }
637
638   sandbox_has_started_ = true;
639 }
640
641 SandboxBPF::Program* SandboxBPF::AssembleFilter(bool force_verification) {
642 #if !defined(NDEBUG)
643   force_verification = true;
644 #endif
645
646   // Verify that the user pushed a policy.
647   DCHECK(policy_);
648
649   // Assemble the BPF filter program.
650   CodeGen* gen = new CodeGen();
651   if (!gen) {
652     SANDBOX_DIE("Out of memory");
653   }
654
655   bool has_unsafe_traps;
656   Instruction* head = CompilePolicy(gen, &has_unsafe_traps);
657
658   // Turn the DAG into a vector of instructions.
659   Program* program = new Program();
660   gen->Compile(head, program);
661   delete gen;
662
663   // Make sure compilation resulted in BPF program that executes
664   // correctly. Otherwise, there is an internal error in our BPF compiler.
665   // There is really nothing the caller can do until the bug is fixed.
666   if (force_verification) {
667     // Verification is expensive. We only perform this step, if we are
668     // compiled in debug mode, or if the caller explicitly requested
669     // verification.
670     VerifyProgram(*program, has_unsafe_traps);
671   }
672
673   return program;
674 }
675
676 Instruction* SandboxBPF::CompilePolicy(CodeGen* gen, bool* has_unsafe_traps) {
677   // A compiled policy consists of three logical parts:
678   //   1. Check that the "arch" field matches the expected architecture.
679   //   2. If the policy involves unsafe traps, check if the syscall was
680   //      invoked by Syscall::Call, and then allow it unconditionally.
681   //   3. Check the system call number and jump to the appropriate compiled
682   //      system call policy number.
683   return CheckArch(
684       gen, MaybeAddEscapeHatch(gen, has_unsafe_traps, DispatchSyscall(gen)));
685 }
686
687 Instruction* SandboxBPF::CheckArch(CodeGen* gen, Instruction* passed) {
688   // If the architecture doesn't match SECCOMP_ARCH, disallow the
689   // system call.
690   return gen->MakeInstruction(
691       BPF_LD + BPF_W + BPF_ABS,
692       SECCOMP_ARCH_IDX,
693       gen->MakeInstruction(
694           BPF_JMP + BPF_JEQ + BPF_K,
695           SECCOMP_ARCH,
696           passed,
697           RetExpression(gen,
698                         Kill("Invalid audit architecture in BPF filter"))));
699 }
700
701 Instruction* SandboxBPF::MaybeAddEscapeHatch(CodeGen* gen,
702                                              bool* has_unsafe_traps,
703                                              Instruction* rest) {
704   // If there is at least one UnsafeTrap() in our program, the entire sandbox
705   // is unsafe. We need to modify the program so that all non-
706   // SECCOMP_RET_ALLOW ErrorCodes are handled in user-space. This will then
707   // allow us to temporarily disable sandboxing rules inside of callbacks to
708   // UnsafeTrap().
709   *has_unsafe_traps = false;
710   gen->Traverse(rest, CheckForUnsafeErrorCodes, has_unsafe_traps);
711   if (!*has_unsafe_traps) {
712     // If no unsafe traps, then simply return |rest|.
713     return rest;
714   }
715
716   // If our BPF program has unsafe jumps, enable support for them. This
717   // test happens very early in the BPF filter program. Even before we
718   // consider looking at system call numbers.
719   // As support for unsafe jumps essentially defeats all the security
720   // measures that the sandbox provides, we print a big warning message --
721   // and of course, we make sure to only ever enable this feature if it
722   // is actually requested by the sandbox policy.
723   if (Syscall::Call(-1) == -1 && errno == ENOSYS) {
724     SANDBOX_DIE(
725         "Support for UnsafeTrap() has not yet been ported to this "
726         "architecture");
727   }
728
729   for (size_t i = 0; i < arraysize(kSyscallsRequiredForUnsafeTraps); ++i) {
730     if (!policy_->EvaluateSyscall(this, kSyscallsRequiredForUnsafeTraps[i])
731              .Equals(ErrorCode(ErrorCode::ERR_ALLOWED))) {
732       SANDBOX_DIE(
733           "Policies that use UnsafeTrap() must unconditionally allow all "
734           "required system calls");
735     }
736   }
737
738   if (!Trap::EnableUnsafeTrapsInSigSysHandler()) {
739     // We should never be able to get here, as UnsafeTrap() should never
740     // actually return a valid ErrorCode object unless the user set the
741     // CHROME_SANDBOX_DEBUGGING environment variable; and therefore,
742     // "has_unsafe_traps" would always be false. But better double-check
743     // than enabling dangerous code.
744     SANDBOX_DIE("We'd rather die than enable unsafe traps");
745   }
746   gen->Traverse(rest, RedirectToUserspace, this);
747
748   // Allow system calls, if they originate from our magic return address
749   // (which we can query by calling Syscall::Call(-1)).
750   uint64_t syscall_entry_point =
751       static_cast<uint64_t>(static_cast<uintptr_t>(Syscall::Call(-1)));
752   uint32_t low = static_cast<uint32_t>(syscall_entry_point);
753   uint32_t hi = static_cast<uint32_t>(syscall_entry_point >> 32);
754
755   // BPF cannot do native 64-bit comparisons, so we have to compare
756   // both 32-bit halves of the instruction pointer. If they match what
757   // we expect, we return ERR_ALLOWED. If either or both don't match,
758   // we continue evalutating the rest of the sandbox policy.
759   //
760   // For simplicity, we check the full 64-bit instruction pointer even
761   // on 32-bit architectures.
762   return gen->MakeInstruction(
763       BPF_LD + BPF_W + BPF_ABS,
764       SECCOMP_IP_LSB_IDX,
765       gen->MakeInstruction(
766           BPF_JMP + BPF_JEQ + BPF_K,
767           low,
768           gen->MakeInstruction(
769               BPF_LD + BPF_W + BPF_ABS,
770               SECCOMP_IP_MSB_IDX,
771               gen->MakeInstruction(
772                   BPF_JMP + BPF_JEQ + BPF_K,
773                   hi,
774                   RetExpression(gen, ErrorCode(ErrorCode::ERR_ALLOWED)),
775                   rest)),
776           rest));
777 }
778
779 Instruction* SandboxBPF::DispatchSyscall(CodeGen* gen) {
780   // Evaluate all possible system calls and group their ErrorCodes into
781   // ranges of identical codes.
782   Ranges ranges;
783   FindRanges(&ranges);
784
785   // Compile the system call ranges to an optimized BPF jumptable
786   Instruction* jumptable = AssembleJumpTable(gen, ranges.begin(), ranges.end());
787
788   // Grab the system call number, so that we can check it and then
789   // execute the jump table.
790   return gen->MakeInstruction(BPF_LD + BPF_W + BPF_ABS,
791                               SECCOMP_NR_IDX,
792                               CheckSyscallNumber(gen, jumptable));
793 }
794
795 Instruction* SandboxBPF::CheckSyscallNumber(CodeGen* gen, Instruction* passed) {
796   if (kIsIntel) {
797     // On Intel architectures, verify that system call numbers are in the
798     // expected number range.
799     Instruction* invalidX32 =
800         RetExpression(gen, Kill("Illegal mixing of system call ABIs"));
801     if (kIsX32) {
802       // The newer x32 API always sets bit 30.
803       return gen->MakeInstruction(
804           BPF_JMP + BPF_JSET + BPF_K, 0x40000000, passed, invalidX32);
805     } else {
806       // The older i386 and x86-64 APIs clear bit 30 on all system calls.
807       return gen->MakeInstruction(
808           BPF_JMP + BPF_JSET + BPF_K, 0x40000000, invalidX32, passed);
809     }
810   }
811
812   // TODO(mdempsky): Similar validation for other architectures?
813   return passed;
814 }
815
816 void SandboxBPF::VerifyProgram(const Program& program, bool has_unsafe_traps) {
817   // If we previously rewrote the BPF program so that it calls user-space
818   // whenever we return an "errno" value from the filter, then we have to
819   // wrap our system call evaluator to perform the same operation. Otherwise,
820   // the verifier would also report a mismatch in return codes.
821   scoped_ptr<const RedirectToUserSpacePolicyWrapper> redirected_policy(
822       new RedirectToUserSpacePolicyWrapper(policy_.get()));
823
824   const char* err = NULL;
825   if (!Verifier::VerifyBPF(this,
826                            program,
827                            has_unsafe_traps ? *redirected_policy : *policy_,
828                            &err)) {
829     CodeGen::PrintProgram(program);
830     SANDBOX_DIE(err);
831   }
832 }
833
834 void SandboxBPF::FindRanges(Ranges* ranges) {
835   // Please note that "struct seccomp_data" defines system calls as a signed
836   // int32_t, but BPF instructions always operate on unsigned quantities. We
837   // deal with this disparity by enumerating from MIN_SYSCALL to MAX_SYSCALL,
838   // and then verifying that the rest of the number range (both positive and
839   // negative) all return the same ErrorCode.
840   const ErrorCode invalid_err = policy_->InvalidSyscall(this);
841   uint32_t old_sysnum = 0;
842   ErrorCode old_err = IsValidSyscallNumber(old_sysnum)
843                           ? policy_->EvaluateSyscall(this, old_sysnum)
844                           : invalid_err;
845
846   for (SyscallIterator iter(false); !iter.Done();) {
847     uint32_t sysnum = iter.Next();
848     ErrorCode err =
849         IsValidSyscallNumber(sysnum)
850             ? policy_->EvaluateSyscall(this, static_cast<int>(sysnum))
851             : invalid_err;
852     if (!err.Equals(old_err) || iter.Done()) {
853       ranges->push_back(Range(old_sysnum, sysnum - 1, old_err));
854       old_sysnum = sysnum;
855       old_err = err;
856     }
857   }
858 }
859
860 Instruction* SandboxBPF::AssembleJumpTable(CodeGen* gen,
861                                            Ranges::const_iterator start,
862                                            Ranges::const_iterator stop) {
863   // We convert the list of system call ranges into jump table that performs
864   // a binary search over the ranges.
865   // As a sanity check, we need to have at least one distinct ranges for us
866   // to be able to build a jump table.
867   if (stop - start <= 0) {
868     SANDBOX_DIE("Invalid set of system call ranges");
869   } else if (stop - start == 1) {
870     // If we have narrowed things down to a single range object, we can
871     // return from the BPF filter program.
872     return RetExpression(gen, start->err);
873   }
874
875   // Pick the range object that is located at the mid point of our list.
876   // We compare our system call number against the lowest valid system call
877   // number in this range object. If our number is lower, it is outside of
878   // this range object. If it is greater or equal, it might be inside.
879   Ranges::const_iterator mid = start + (stop - start) / 2;
880
881   // Sub-divide the list of ranges and continue recursively.
882   Instruction* jf = AssembleJumpTable(gen, start, mid);
883   Instruction* jt = AssembleJumpTable(gen, mid, stop);
884   return gen->MakeInstruction(BPF_JMP + BPF_JGE + BPF_K, mid->from, jt, jf);
885 }
886
887 Instruction* SandboxBPF::RetExpression(CodeGen* gen, const ErrorCode& err) {
888   switch (err.error_type()) {
889     case ErrorCode::ET_COND:
890       return CondExpression(gen, err);
891     case ErrorCode::ET_SIMPLE:
892     case ErrorCode::ET_TRAP:
893       return gen->MakeInstruction(BPF_RET + BPF_K, err.err());
894     default:
895       SANDBOX_DIE("ErrorCode is not suitable for returning from a BPF program");
896   }
897 }
898
899 Instruction* SandboxBPF::CondExpression(CodeGen* gen, const ErrorCode& cond) {
900   // Sanity check that |cond| makes sense.
901   if (cond.argno_ < 0 || cond.argno_ >= 6) {
902     SANDBOX_DIE("sandbox_bpf: invalid argument number");
903   }
904   if (cond.width_ != ErrorCode::TP_32BIT &&
905       cond.width_ != ErrorCode::TP_64BIT) {
906     SANDBOX_DIE("sandbox_bpf: invalid argument width");
907   }
908   if (cond.mask_ == 0) {
909     SANDBOX_DIE("sandbox_bpf: zero mask is invalid");
910   }
911   if ((cond.value_ & cond.mask_) != cond.value_) {
912     SANDBOX_DIE("sandbox_bpf: value contains masked out bits");
913   }
914   if (cond.width_ == ErrorCode::TP_32BIT &&
915       ((cond.mask_ >> 32) != 0 || (cond.value_ >> 32) != 0)) {
916     SANDBOX_DIE("sandbox_bpf: test exceeds argument size");
917   }
918   // TODO(mdempsky): Reject TP_64BIT on 32-bit platforms. For now we allow it
919   // because some SandboxBPF unit tests exercise it.
920
921   Instruction* passed = RetExpression(gen, *cond.passed_);
922   Instruction* failed = RetExpression(gen, *cond.failed_);
923
924   // We want to emit code to check "(arg & mask) == value" where arg, mask, and
925   // value are 64-bit values, but the BPF machine is only 32-bit. We implement
926   // this by independently testing the upper and lower 32-bits and continuing to
927   // |passed| if both evaluate true, or to |failed| if either evaluate false.
928   return CondExpressionHalf(
929       gen,
930       cond,
931       UpperHalf,
932       CondExpressionHalf(gen, cond, LowerHalf, passed, failed),
933       failed);
934 }
935
936 Instruction* SandboxBPF::CondExpressionHalf(CodeGen* gen,
937                                             const ErrorCode& cond,
938                                             ArgHalf half,
939                                             Instruction* passed,
940                                             Instruction* failed) {
941   if (cond.width_ == ErrorCode::TP_32BIT && half == UpperHalf) {
942     // Special logic for sanity checking the upper 32-bits of 32-bit system
943     // call arguments.
944
945     // TODO(mdempsky): Compile Unexpected64bitArgument() just per program.
946     Instruction* invalid_64bit = RetExpression(gen, Unexpected64bitArgument());
947
948     const uint32_t upper = SECCOMP_ARG_MSB_IDX(cond.argno_);
949     const uint32_t lower = SECCOMP_ARG_LSB_IDX(cond.argno_);
950
951     if (sizeof(void*) == 4) {
952       // On 32-bit platforms, the upper 32-bits should always be 0:
953       //   LDW  [upper]
954       //   JEQ  0, passed, invalid
955       return gen->MakeInstruction(
956           BPF_LD + BPF_W + BPF_ABS,
957           upper,
958           gen->MakeInstruction(
959               BPF_JMP + BPF_JEQ + BPF_K, 0, passed, invalid_64bit));
960     }
961
962     // On 64-bit platforms, the upper 32-bits may be 0 or ~0; but we only allow
963     // ~0 if the sign bit of the lower 32-bits is set too:
964     //   LDW  [upper]
965     //   JEQ  0, passed, (next)
966     //   JEQ  ~0, (next), invalid
967     //   LDW  [lower]
968     //   JSET (1<<31), passed, invalid
969     //
970     // TODO(mdempsky): The JSET instruction could perhaps jump to passed->next
971     // instead, as the first instruction of passed should be "LDW [lower]".
972     return gen->MakeInstruction(
973         BPF_LD + BPF_W + BPF_ABS,
974         upper,
975         gen->MakeInstruction(
976             BPF_JMP + BPF_JEQ + BPF_K,
977             0,
978             passed,
979             gen->MakeInstruction(
980                 BPF_JMP + BPF_JEQ + BPF_K,
981                 std::numeric_limits<uint32_t>::max(),
982                 gen->MakeInstruction(
983                     BPF_LD + BPF_W + BPF_ABS,
984                     lower,
985                     gen->MakeInstruction(BPF_JMP + BPF_JSET + BPF_K,
986                                          1U << 31,
987                                          passed,
988                                          invalid_64bit)),
989                 invalid_64bit)));
990   }
991
992   const uint32_t idx = (half == UpperHalf) ? SECCOMP_ARG_MSB_IDX(cond.argno_)
993                                            : SECCOMP_ARG_LSB_IDX(cond.argno_);
994   const uint32_t mask = (half == UpperHalf) ? cond.mask_ >> 32 : cond.mask_;
995   const uint32_t value = (half == UpperHalf) ? cond.value_ >> 32 : cond.value_;
996
997   // Emit a suitable instruction sequence for (arg & mask) == value.
998
999   // For (arg & 0) == 0, just return passed.
1000   if (mask == 0) {
1001     CHECK_EQ(0U, value);
1002     return passed;
1003   }
1004
1005   // For (arg & ~0) == value, emit:
1006   //   LDW  [idx]
1007   //   JEQ  value, passed, failed
1008   if (mask == std::numeric_limits<uint32_t>::max()) {
1009     return gen->MakeInstruction(
1010         BPF_LD + BPF_W + BPF_ABS,
1011         idx,
1012         gen->MakeInstruction(BPF_JMP + BPF_JEQ + BPF_K, value, passed, failed));
1013   }
1014
1015   // For (arg & mask) == 0, emit:
1016   //   LDW  [idx]
1017   //   JSET mask, failed, passed
1018   // (Note: failed and passed are intentionally swapped.)
1019   if (value == 0) {
1020     return gen->MakeInstruction(
1021         BPF_LD + BPF_W + BPF_ABS,
1022         idx,
1023         gen->MakeInstruction(BPF_JMP + BPF_JSET + BPF_K, mask, failed, passed));
1024   }
1025
1026   // For (arg & x) == x where x is a single-bit value, emit:
1027   //   LDW  [idx]
1028   //   JSET mask, passed, failed
1029   if (mask == value && HasExactlyOneBit(mask)) {
1030     return gen->MakeInstruction(
1031         BPF_LD + BPF_W + BPF_ABS,
1032         idx,
1033         gen->MakeInstruction(BPF_JMP + BPF_JSET + BPF_K, mask, passed, failed));
1034   }
1035
1036   // Generic fallback:
1037   //   LDW  [idx]
1038   //   AND  mask
1039   //   JEQ  value, passed, failed
1040   return gen->MakeInstruction(
1041       BPF_LD + BPF_W + BPF_ABS,
1042       idx,
1043       gen->MakeInstruction(
1044           BPF_ALU + BPF_AND + BPF_K,
1045           mask,
1046           gen->MakeInstruction(
1047               BPF_JMP + BPF_JEQ + BPF_K, value, passed, failed)));
1048 }
1049
1050 ErrorCode SandboxBPF::Unexpected64bitArgument() {
1051   return Kill("Unexpected 64bit argument detected");
1052 }
1053
1054 ErrorCode SandboxBPF::Trap(Trap::TrapFnc fnc, const void* aux) {
1055   return ErrorCode(fnc, aux, true /* Safe Trap */);
1056 }
1057
1058 ErrorCode SandboxBPF::UnsafeTrap(Trap::TrapFnc fnc, const void* aux) {
1059   return ErrorCode(fnc, aux, false /* Unsafe Trap */);
1060 }
1061
1062 bool SandboxBPF::IsRequiredForUnsafeTrap(int sysno) {
1063   for (size_t i = 0; i < arraysize(kSyscallsRequiredForUnsafeTraps); ++i) {
1064     if (sysno == kSyscallsRequiredForUnsafeTraps[i]) {
1065       return true;
1066     }
1067   }
1068   return false;
1069 }
1070
1071 intptr_t SandboxBPF::ForwardSyscall(const struct arch_seccomp_data& args) {
1072   return Syscall::Call(args.nr,
1073                        static_cast<intptr_t>(args.args[0]),
1074                        static_cast<intptr_t>(args.args[1]),
1075                        static_cast<intptr_t>(args.args[2]),
1076                        static_cast<intptr_t>(args.args[3]),
1077                        static_cast<intptr_t>(args.args[4]),
1078                        static_cast<intptr_t>(args.args[5]));
1079 }
1080
1081 ErrorCode SandboxBPF::CondMaskedEqual(int argno,
1082                                       ErrorCode::ArgType width,
1083                                       uint64_t mask,
1084                                       uint64_t value,
1085                                       const ErrorCode& passed,
1086                                       const ErrorCode& failed) {
1087   return ErrorCode(argno,
1088                    width,
1089                    mask,
1090                    value,
1091                    &*conds_->insert(passed).first,
1092                    &*conds_->insert(failed).first);
1093 }
1094
1095 ErrorCode SandboxBPF::Cond(int argno,
1096                            ErrorCode::ArgType width,
1097                            ErrorCode::Operation op,
1098                            uint64_t value,
1099                            const ErrorCode& passed,
1100                            const ErrorCode& failed) {
1101   // CondExpression() currently rejects mask==0 as invalid, but there are
1102   // SandboxBPF unit tests that (questionably) expect OP_HAS_{ANY,ALL}_BITS to
1103   // work with value==0. To keep those tests working for now, we specially
1104   // convert value==0 here.
1105
1106   switch (op) {
1107     case ErrorCode::OP_EQUAL: {
1108       // Convert to "(arg & ~0) == value".
1109       const uint64_t mask = (width == ErrorCode::TP_64BIT)
1110                                 ? std::numeric_limits<uint64_t>::max()
1111                                 : std::numeric_limits<uint32_t>::max();
1112       return CondMaskedEqual(argno, width, mask, value, passed, failed);
1113     }
1114
1115     case ErrorCode::OP_HAS_ALL_BITS:
1116       if (value == 0) {
1117         // Always passes.
1118         return passed;
1119       }
1120       // Convert to "(arg & value) == value".
1121       return CondMaskedEqual(argno, width, value, value, passed, failed);
1122
1123     case ErrorCode::OP_HAS_ANY_BITS:
1124       if (value == 0) {
1125         // Always fails.
1126         return failed;
1127       }
1128       // Convert to "(arg & value) == 0", but swap passed and failed.
1129       return CondMaskedEqual(argno, width, value, 0, failed, passed);
1130
1131     default:
1132       SANDBOX_DIE("Not implemented");
1133   }
1134 }
1135
1136 ErrorCode SandboxBPF::Kill(const char* msg) {
1137   return Trap(BPFFailure, const_cast<char*>(msg));
1138 }
1139
1140 SandboxBPF::SandboxStatus SandboxBPF::status_ = STATUS_UNKNOWN;
1141
1142 }  // namespace sandbox