Upstream version 8.37.180.0
[platform/framework/web/crosswalk.git] / src / sandbox / linux / seccomp-bpf / sandbox_bpf.h
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 #ifndef SANDBOX_LINUX_SECCOMP_BPF_SANDBOX_BPF_H__
6 #define SANDBOX_LINUX_SECCOMP_BPF_SANDBOX_BPF_H__
7
8 #include <stddef.h>
9 #include <sys/types.h>
10 #include <sys/wait.h>
11
12 #include <algorithm>
13 #include <limits>
14 #include <map>
15 #include <set>
16 #include <utility>
17 #include <vector>
18
19 #include "base/compiler_specific.h"
20 #include "base/memory/scoped_ptr.h"
21 #include "sandbox/linux/seccomp-bpf/die.h"
22 #include "sandbox/linux/seccomp-bpf/errorcode.h"
23 #include "sandbox/linux/seccomp-bpf/linux_seccomp.h"
24 #include "sandbox/sandbox_export.h"
25
26 namespace sandbox {
27
28 // This must match the kernel's seccomp_data structure.
29 struct arch_seccomp_data {
30   int nr;
31   uint32_t arch;
32   uint64_t instruction_pointer;
33   uint64_t args[6];
34 };
35
36 struct arch_sigsys {
37   void* ip;
38   int nr;
39   unsigned int arch;
40 };
41
42 class CodeGen;
43 class SandboxBPFPolicy;
44 class SandboxUnittestHelper;
45 struct Instruction;
46
47 class SANDBOX_EXPORT SandboxBPF {
48  public:
49   enum SandboxStatus {
50     STATUS_UNKNOWN,      // Status prior to calling supportsSeccompSandbox()
51     STATUS_UNSUPPORTED,  // The kernel does not appear to support sandboxing
52     STATUS_UNAVAILABLE,  // Currently unavailable but might work again later
53     STATUS_AVAILABLE,    // Sandboxing is available but not currently active
54     STATUS_ENABLED       // The sandbox is now active
55   };
56
57   // Depending on the level of kernel support, seccomp-bpf may require the
58   // process to be single-threaded in order to enable it. When calling
59   // StartSandbox(), the program should indicate whether or not the sandbox
60   // should try and engage with multi-thread support.
61   enum SandboxThreadState {
62     PROCESS_INVALID,
63     PROCESS_SINGLE_THREADED,  // The program is currently single-threaded.
64     // Note: PROCESS_MULTI_THREADED requires experimental kernel support that
65     // has not been contributed to upstream Linux.
66     PROCESS_MULTI_THREADED,   // The program may be multi-threaded.
67   };
68
69   // A vector of BPF instructions that need to be installed as a filter
70   // program in the kernel.
71   typedef std::vector<struct sock_filter> Program;
72
73   // Constructors and destructors.
74   // NOTE: Setting a policy and starting the sandbox is a one-way operation.
75   //       The kernel does not provide any option for unloading a loaded
76   //       sandbox. Strictly speaking, that means we should disallow calling
77   //       the destructor, if StartSandbox() has ever been called. In practice,
78   //       this makes it needlessly complicated to operate on "Sandbox"
79   //       objects. So, we instead opted to allow object destruction. But it
80   //       should be noted that during its lifetime, the object probably made
81   //       irreversible state changes to the runtime environment. These changes
82   //       stay in effect even after the destructor has been run.
83   SandboxBPF();
84   ~SandboxBPF();
85
86   // Checks whether a particular system call number is valid on the current
87   // architecture. E.g. on ARM there's a non-contiguous range of private
88   // system calls.
89   static bool IsValidSyscallNumber(int sysnum);
90
91   // There are a lot of reasons why the Seccomp sandbox might not be available.
92   // This could be because the kernel does not support Seccomp mode, or it
93   // could be because another sandbox is already active.
94   // "proc_fd" should be a file descriptor for "/proc", or -1 if not
95   // provided by the caller.
96   static SandboxStatus SupportsSeccompSandbox(int proc_fd);
97
98   // The sandbox needs to be able to access files in "/proc/self". If this
99   // directory is not accessible when "startSandbox()" gets called, the caller
100   // can provide an already opened file descriptor by calling "set_proc_fd()".
101   // The sandbox becomes the new owner of this file descriptor and will
102   // eventually close it when "StartSandbox()" executes.
103   void set_proc_fd(int proc_fd);
104
105   // Set the BPF policy as |policy|. Ownership of |policy| is transfered here
106   // to the sandbox object.
107   void SetSandboxPolicy(SandboxBPFPolicy* policy);
108
109   // We can use ErrorCode to request calling of a trap handler. This method
110   // performs the required wrapping of the callback function into an
111   // ErrorCode object.
112   // The "aux" field can carry a pointer to arbitrary data. See EvaluateSyscall
113   // for a description of how to pass data from SetSandboxPolicy() to a Trap()
114   // handler.
115   ErrorCode Trap(Trap::TrapFnc fnc, const void* aux);
116
117   // Calls a user-space trap handler and disables all sandboxing for system
118   // calls made from this trap handler.
119   // This feature is available only if explicitly enabled by the user having
120   // set the CHROME_SANDBOX_DEBUGGING environment variable.
121   // Returns an ET_INVALID ErrorCode, if called when not enabled.
122   // NOTE: This feature, by definition, disables all security features of
123   //   the sandbox. It should never be used in production, but it can be
124   //   very useful to diagnose code that is incompatible with the sandbox.
125   //   If even a single system call returns "UnsafeTrap", the security of
126   //   entire sandbox should be considered compromised.
127   ErrorCode UnsafeTrap(Trap::TrapFnc fnc, const void* aux);
128
129   // From within an UnsafeTrap() it is often useful to be able to execute
130   // the system call that triggered the trap. The ForwardSyscall() method
131   // makes this easy. It is more efficient than calling glibc's syscall()
132   // function, as it avoid the extra round-trip to the signal handler. And
133   // it automatically does the correct thing to report kernel-style error
134   // conditions, rather than setting errno. See the comments for TrapFnc for
135   // details. In other words, the return value from ForwardSyscall() is
136   // directly suitable as a return value for a trap handler.
137   static intptr_t ForwardSyscall(const struct arch_seccomp_data& args);
138
139   // We can also use ErrorCode to request evaluation of a conditional
140   // statement based on inspection of system call parameters.
141   // This method wrap an ErrorCode object around the conditional statement.
142   // Argument "argno" (1..6) will be compared to "value" using comparator
143   // "op". If the condition is true "passed" will be returned, otherwise
144   // "failed".
145   // If "is32bit" is set, the argument must in the range of 0x0..(1u << 32 - 1)
146   // If it is outside this range, the sandbox treats the system call just
147   // the same as any other ABI violation (i.e. it aborts with an error
148   // message).
149   ErrorCode Cond(int argno,
150                  ErrorCode::ArgType is_32bit,
151                  ErrorCode::Operation op,
152                  uint64_t value,
153                  const ErrorCode& passed,
154                  const ErrorCode& failed);
155
156   // Kill the program and print an error message.
157   ErrorCode Kill(const char* msg);
158
159   // This is the main public entry point. It finds all system calls that
160   // need rewriting, sets up the resources needed by the sandbox, and
161   // enters Seccomp mode.
162   // The calling process must specify its current SandboxThreadState, as a way
163   // to tell the sandbox which type of kernel support it should engage.
164   // It is possible to stack multiple sandboxes by creating separate "Sandbox"
165   // objects and calling "StartSandbox()" on each of them. Please note, that
166   // this requires special care, though, as newly stacked sandboxes can never
167   // relax restrictions imposed by earlier sandboxes. Furthermore, installing
168   // a new policy requires making system calls, that might already be
169   // disallowed.
170   // Finally, stacking does add more kernel overhead than having a single
171   // combined policy. So, it should only be used if there are no alternatives.
172   bool StartSandbox(SandboxThreadState thread_state) WARN_UNUSED_RESULT;
173
174   // Assembles a BPF filter program from the current policy. After calling this
175   // function, you must not call any other sandboxing function.
176   // Typically, AssembleFilter() is only used by unit tests and by sandbox
177   // internals. It should not be used by production code.
178   // For performance reasons, we normally only run the assembled BPF program
179   // through the verifier, iff the program was built in debug mode.
180   // But by setting "force_verification", the caller can request that the
181   // verifier is run unconditionally. This is useful for unittests.
182   Program* AssembleFilter(bool force_verification);
183
184   // Returns the fatal ErrorCode that is used to indicate that somebody
185   // attempted to pass a 64bit value in a 32bit system call argument.
186   // This method is primarily needed for testing purposes.
187   ErrorCode Unexpected64bitArgument();
188
189  private:
190   friend class CodeGen;
191   friend class SandboxUnittestHelper;
192   friend class ErrorCode;
193
194   struct Range {
195     Range(uint32_t f, uint32_t t, const ErrorCode& e)
196         : from(f), to(t), err(e) {}
197     uint32_t from, to;
198     ErrorCode err;
199   };
200   typedef std::vector<Range> Ranges;
201   typedef std::map<uint32_t, ErrorCode> ErrMap;
202   typedef std::set<ErrorCode, struct ErrorCode::LessThan> Conds;
203
204   // Get a file descriptor pointing to "/proc", if currently available.
205   int proc_fd() { return proc_fd_; }
206
207   // Creates a subprocess and runs "code_in_sandbox" inside of the specified
208   // policy. The caller has to make sure that "this" has not yet been
209   // initialized with any other policies.
210   bool RunFunctionInPolicy(void (*code_in_sandbox)(),
211                            scoped_ptr<SandboxBPFPolicy> policy);
212
213   // Performs a couple of sanity checks to verify that the kernel supports the
214   // features that we need for successful sandboxing.
215   // The caller has to make sure that "this" has not yet been initialized with
216   // any other policies.
217   bool KernelSupportSeccompBPF();
218
219   // Verify that the current policy passes some basic sanity checks.
220   void PolicySanityChecks(SandboxBPFPolicy* policy);
221
222   // Assembles and installs a filter based on the policy that has previously
223   // been configured with SetSandboxPolicy().
224   void InstallFilter(SandboxThreadState thread_state);
225
226   // Verify the correctness of a compiled program by comparing it against the
227   // current policy. This function should only ever be called by unit tests and
228   // by the sandbox internals. It should not be used by production code.
229   void VerifyProgram(const Program& program, bool has_unsafe_traps);
230
231   // Finds all the ranges of system calls that need to be handled. Ranges are
232   // sorted in ascending order of system call numbers. There are no gaps in the
233   // ranges. System calls with identical ErrorCodes are coalesced into a single
234   // range.
235   void FindRanges(Ranges* ranges);
236
237   // Returns a BPF program snippet that implements a jump table for the
238   // given range of system call numbers. This function runs recursively.
239   Instruction* AssembleJumpTable(CodeGen* gen,
240                                  Ranges::const_iterator start,
241                                  Ranges::const_iterator stop);
242
243   // Returns a BPF program snippet that makes the BPF filter program exit
244   // with the given ErrorCode "err". N.B. the ErrorCode may very well be a
245   // conditional expression; if so, this function will recursively call
246   // CondExpression() and possibly RetExpression() to build a complex set of
247   // instructions.
248   Instruction* RetExpression(CodeGen* gen, const ErrorCode& err);
249
250   // Returns a BPF program that evaluates the conditional expression in
251   // "cond" and returns the appropriate value from the BPF filter program.
252   // This function recursively calls RetExpression(); it should only ever be
253   // called from RetExpression().
254   Instruction* CondExpression(CodeGen* gen, const ErrorCode& cond);
255
256   static SandboxStatus status_;
257
258   bool quiet_;
259   int proc_fd_;
260   scoped_ptr<const SandboxBPFPolicy> policy_;
261   Conds* conds_;
262   bool sandbox_has_started_;
263
264   DISALLOW_COPY_AND_ASSIGN(SandboxBPF);
265 };
266
267 }  // namespace sandbox
268
269 #endif  // SANDBOX_LINUX_SECCOMP_BPF_SANDBOX_BPF_H__