ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / sandbox / linux / bpf_dsl / policy_compiler.cc
blob18ed7be582a363367c23a39c10230aa42b4acd39
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "sandbox/linux/bpf_dsl/policy_compiler.h"
7 #include <errno.h>
8 #include <linux/filter.h>
9 #include <sys/syscall.h>
11 #include <limits>
13 #include "base/logging.h"
14 #include "base/macros.h"
15 #include "sandbox/linux/bpf_dsl/bpf_dsl.h"
16 #include "sandbox/linux/bpf_dsl/bpf_dsl_impl.h"
17 #include "sandbox/linux/bpf_dsl/codegen.h"
18 #include "sandbox/linux/bpf_dsl/policy.h"
19 #include "sandbox/linux/bpf_dsl/seccomp_macros.h"
20 #include "sandbox/linux/bpf_dsl/syscall_set.h"
21 #include "sandbox/linux/seccomp-bpf/die.h"
22 #include "sandbox/linux/seccomp-bpf/errorcode.h"
23 #include "sandbox/linux/seccomp-bpf/syscall.h"
24 #include "sandbox/linux/system_headers/linux_seccomp.h"
26 namespace sandbox {
27 namespace bpf_dsl {
29 namespace {
31 #if defined(__i386__) || defined(__x86_64__)
32 const bool kIsIntel = true;
33 #else
34 const bool kIsIntel = false;
35 #endif
36 #if defined(__x86_64__) && defined(__ILP32__)
37 const bool kIsX32 = true;
38 #else
39 const bool kIsX32 = false;
40 #endif
42 const int kSyscallsRequiredForUnsafeTraps[] = {
43 __NR_rt_sigprocmask,
44 __NR_rt_sigreturn,
45 #if defined(__NR_sigprocmask)
46 __NR_sigprocmask,
47 #endif
48 #if defined(__NR_sigreturn)
49 __NR_sigreturn,
50 #endif
53 bool HasExactlyOneBit(uint64_t x) {
54 // Common trick; e.g., see http://stackoverflow.com/a/108329.
55 return x != 0 && (x & (x - 1)) == 0;
58 // A Trap() handler that returns an "errno" value. The value is encoded
59 // in the "aux" parameter.
60 intptr_t ReturnErrno(const struct arch_seccomp_data&, void* aux) {
61 // TrapFnc functions report error by following the native kernel convention
62 // of returning an exit code in the range of -1..-4096. They do not try to
63 // set errno themselves. The glibc wrapper that triggered the SIGSYS will
64 // ultimately do so for us.
65 int err = reinterpret_cast<intptr_t>(aux) & SECCOMP_RET_DATA;
66 return -err;
69 bool HasUnsafeTraps(const Policy* policy) {
70 DCHECK(policy);
71 for (uint32_t sysnum : SyscallSet::ValidOnly()) {
72 if (policy->EvaluateSyscall(sysnum)->HasUnsafeTraps()) {
73 return true;
76 return policy->InvalidSyscall()->HasUnsafeTraps();
79 } // namespace
81 struct PolicyCompiler::Range {
82 uint32_t from;
83 CodeGen::Node node;
86 PolicyCompiler::PolicyCompiler(const Policy* policy, TrapRegistry* registry)
87 : policy_(policy),
88 registry_(registry),
89 conds_(),
90 gen_(),
91 has_unsafe_traps_(HasUnsafeTraps(policy_)) {
92 DCHECK(policy);
95 PolicyCompiler::~PolicyCompiler() {
98 scoped_ptr<CodeGen::Program> PolicyCompiler::Compile() {
99 if (!policy_->InvalidSyscall()->IsDeny()) {
100 SANDBOX_DIE("Policies should deny invalid system calls.");
103 // If our BPF program has unsafe traps, enable support for them.
104 if (has_unsafe_traps_) {
105 // As support for unsafe jumps essentially defeats all the security
106 // measures that the sandbox provides, we print a big warning message --
107 // and of course, we make sure to only ever enable this feature if it
108 // is actually requested by the sandbox policy.
109 if (Syscall::Call(-1) == -1 && errno == ENOSYS) {
110 SANDBOX_DIE(
111 "Support for UnsafeTrap() has not yet been ported to this "
112 "architecture");
115 for (int sysnum : kSyscallsRequiredForUnsafeTraps) {
116 if (!policy_->EvaluateSyscall(sysnum)->IsAllow()) {
117 SANDBOX_DIE(
118 "Policies that use UnsafeTrap() must unconditionally allow all "
119 "required system calls");
123 if (!registry_->EnableUnsafeTraps()) {
124 // We should never be able to get here, as UnsafeTrap() should never
125 // actually return a valid ErrorCode object unless the user set the
126 // CHROME_SANDBOX_DEBUGGING environment variable; and therefore,
127 // "has_unsafe_traps" would always be false. But better double-check
128 // than enabling dangerous code.
129 SANDBOX_DIE("We'd rather die than enable unsafe traps");
133 // Assemble the BPF filter program.
134 scoped_ptr<CodeGen::Program> program(new CodeGen::Program());
135 gen_.Compile(AssemblePolicy(), program.get());
136 return program.Pass();
139 CodeGen::Node PolicyCompiler::AssemblePolicy() {
140 // A compiled policy consists of three logical parts:
141 // 1. Check that the "arch" field matches the expected architecture.
142 // 2. If the policy involves unsafe traps, check if the syscall was
143 // invoked by Syscall::Call, and then allow it unconditionally.
144 // 3. Check the system call number and jump to the appropriate compiled
145 // system call policy number.
146 return CheckArch(MaybeAddEscapeHatch(DispatchSyscall()));
149 CodeGen::Node PolicyCompiler::CheckArch(CodeGen::Node passed) {
150 // If the architecture doesn't match SECCOMP_ARCH, disallow the
151 // system call.
152 return gen_.MakeInstruction(
153 BPF_LD + BPF_W + BPF_ABS, SECCOMP_ARCH_IDX,
154 gen_.MakeInstruction(
155 BPF_JMP + BPF_JEQ + BPF_K, SECCOMP_ARCH, passed,
156 CompileResult(Kill("Invalid audit architecture in BPF filter"))));
159 CodeGen::Node PolicyCompiler::MaybeAddEscapeHatch(CodeGen::Node rest) {
160 // If no unsafe traps, then simply return |rest|.
161 if (!has_unsafe_traps_) {
162 return rest;
165 // Allow system calls, if they originate from our magic return address
166 // (which we can query by calling Syscall::Call(-1)).
167 uint64_t syscall_entry_point =
168 static_cast<uint64_t>(static_cast<uintptr_t>(Syscall::Call(-1)));
169 uint32_t low = static_cast<uint32_t>(syscall_entry_point);
170 uint32_t hi = static_cast<uint32_t>(syscall_entry_point >> 32);
172 // BPF cannot do native 64-bit comparisons, so we have to compare
173 // both 32-bit halves of the instruction pointer. If they match what
174 // we expect, we return ERR_ALLOWED. If either or both don't match,
175 // we continue evalutating the rest of the sandbox policy.
177 // For simplicity, we check the full 64-bit instruction pointer even
178 // on 32-bit architectures.
179 return gen_.MakeInstruction(
180 BPF_LD + BPF_W + BPF_ABS, SECCOMP_IP_LSB_IDX,
181 gen_.MakeInstruction(
182 BPF_JMP + BPF_JEQ + BPF_K, low,
183 gen_.MakeInstruction(
184 BPF_LD + BPF_W + BPF_ABS, SECCOMP_IP_MSB_IDX,
185 gen_.MakeInstruction(BPF_JMP + BPF_JEQ + BPF_K, hi,
186 CompileResult(Allow()), rest)),
187 rest));
190 CodeGen::Node PolicyCompiler::DispatchSyscall() {
191 // Evaluate all possible system calls and group their ErrorCodes into
192 // ranges of identical codes.
193 Ranges ranges;
194 FindRanges(&ranges);
196 // Compile the system call ranges to an optimized BPF jumptable
197 CodeGen::Node jumptable = AssembleJumpTable(ranges.begin(), ranges.end());
199 // Grab the system call number, so that we can check it and then
200 // execute the jump table.
201 return gen_.MakeInstruction(
202 BPF_LD + BPF_W + BPF_ABS, SECCOMP_NR_IDX, CheckSyscallNumber(jumptable));
205 CodeGen::Node PolicyCompiler::CheckSyscallNumber(CodeGen::Node passed) {
206 if (kIsIntel) {
207 // On Intel architectures, verify that system call numbers are in the
208 // expected number range.
209 CodeGen::Node invalidX32 =
210 CompileResult(Kill("Illegal mixing of system call ABIs"));
211 if (kIsX32) {
212 // The newer x32 API always sets bit 30.
213 return gen_.MakeInstruction(
214 BPF_JMP + BPF_JSET + BPF_K, 0x40000000, passed, invalidX32);
215 } else {
216 // The older i386 and x86-64 APIs clear bit 30 on all system calls.
217 return gen_.MakeInstruction(
218 BPF_JMP + BPF_JSET + BPF_K, 0x40000000, invalidX32, passed);
222 // TODO(mdempsky): Similar validation for other architectures?
223 return passed;
226 void PolicyCompiler::FindRanges(Ranges* ranges) {
227 // Please note that "struct seccomp_data" defines system calls as a signed
228 // int32_t, but BPF instructions always operate on unsigned quantities. We
229 // deal with this disparity by enumerating from MIN_SYSCALL to MAX_SYSCALL,
230 // and then verifying that the rest of the number range (both positive and
231 // negative) all return the same ErrorCode.
232 const CodeGen::Node invalid_node = CompileResult(policy_->InvalidSyscall());
233 uint32_t old_sysnum = 0;
234 CodeGen::Node old_node =
235 SyscallSet::IsValid(old_sysnum)
236 ? CompileResult(policy_->EvaluateSyscall(old_sysnum))
237 : invalid_node;
239 for (uint32_t sysnum : SyscallSet::All()) {
240 CodeGen::Node node =
241 SyscallSet::IsValid(sysnum)
242 ? CompileResult(policy_->EvaluateSyscall(static_cast<int>(sysnum)))
243 : invalid_node;
244 // N.B., here we rely on CodeGen folding (i.e., returning the same
245 // node value for) identical code sequences, otherwise our jump
246 // table will blow up in size.
247 if (node != old_node) {
248 ranges->push_back(Range{old_sysnum, old_node});
249 old_sysnum = sysnum;
250 old_node = node;
253 ranges->push_back(Range{old_sysnum, old_node});
256 CodeGen::Node PolicyCompiler::AssembleJumpTable(Ranges::const_iterator start,
257 Ranges::const_iterator stop) {
258 // We convert the list of system call ranges into jump table that performs
259 // a binary search over the ranges.
260 // As a sanity check, we need to have at least one distinct ranges for us
261 // to be able to build a jump table.
262 if (stop - start <= 0) {
263 SANDBOX_DIE("Invalid set of system call ranges");
264 } else if (stop - start == 1) {
265 // If we have narrowed things down to a single range object, we can
266 // return from the BPF filter program.
267 return start->node;
270 // Pick the range object that is located at the mid point of our list.
271 // We compare our system call number against the lowest valid system call
272 // number in this range object. If our number is lower, it is outside of
273 // this range object. If it is greater or equal, it might be inside.
274 Ranges::const_iterator mid = start + (stop - start) / 2;
276 // Sub-divide the list of ranges and continue recursively.
277 CodeGen::Node jf = AssembleJumpTable(start, mid);
278 CodeGen::Node jt = AssembleJumpTable(mid, stop);
279 return gen_.MakeInstruction(BPF_JMP + BPF_JGE + BPF_K, mid->from, jt, jf);
282 CodeGen::Node PolicyCompiler::CompileResult(const ResultExpr& res) {
283 return RetExpression(res->Compile(this));
286 CodeGen::Node PolicyCompiler::RetExpression(const ErrorCode& err) {
287 switch (err.error_type()) {
288 case ErrorCode::ET_COND:
289 return CondExpression(err);
290 case ErrorCode::ET_SIMPLE:
291 case ErrorCode::ET_TRAP:
292 return gen_.MakeInstruction(BPF_RET + BPF_K, err.err());
293 default:
294 SANDBOX_DIE("ErrorCode is not suitable for returning from a BPF program");
298 CodeGen::Node PolicyCompiler::CondExpression(const ErrorCode& cond) {
299 // Sanity check that |cond| makes sense.
300 if (cond.argno_ < 0 || cond.argno_ >= 6) {
301 SANDBOX_DIE("sandbox_bpf: invalid argument number");
303 if (cond.width_ != ErrorCode::TP_32BIT &&
304 cond.width_ != ErrorCode::TP_64BIT) {
305 SANDBOX_DIE("sandbox_bpf: invalid argument width");
307 if (cond.mask_ == 0) {
308 SANDBOX_DIE("sandbox_bpf: zero mask is invalid");
310 if ((cond.value_ & cond.mask_) != cond.value_) {
311 SANDBOX_DIE("sandbox_bpf: value contains masked out bits");
313 if (cond.width_ == ErrorCode::TP_32BIT &&
314 ((cond.mask_ >> 32) != 0 || (cond.value_ >> 32) != 0)) {
315 SANDBOX_DIE("sandbox_bpf: test exceeds argument size");
317 // TODO(mdempsky): Reject TP_64BIT on 32-bit platforms. For now we allow it
318 // because some SandboxBPF unit tests exercise it.
320 CodeGen::Node passed = RetExpression(*cond.passed_);
321 CodeGen::Node failed = RetExpression(*cond.failed_);
323 // We want to emit code to check "(arg & mask) == value" where arg, mask, and
324 // value are 64-bit values, but the BPF machine is only 32-bit. We implement
325 // this by independently testing the upper and lower 32-bits and continuing to
326 // |passed| if both evaluate true, or to |failed| if either evaluate false.
327 return CondExpressionHalf(cond,
328 UpperHalf,
329 CondExpressionHalf(cond, LowerHalf, passed, failed),
330 failed);
333 CodeGen::Node PolicyCompiler::CondExpressionHalf(const ErrorCode& cond,
334 ArgHalf half,
335 CodeGen::Node passed,
336 CodeGen::Node failed) {
337 if (cond.width_ == ErrorCode::TP_32BIT && half == UpperHalf) {
338 // Special logic for sanity checking the upper 32-bits of 32-bit system
339 // call arguments.
341 // TODO(mdempsky): Compile Unexpected64bitArgument() just per program.
342 CodeGen::Node invalid_64bit = RetExpression(Unexpected64bitArgument());
344 const uint32_t upper = SECCOMP_ARG_MSB_IDX(cond.argno_);
345 const uint32_t lower = SECCOMP_ARG_LSB_IDX(cond.argno_);
347 if (sizeof(void*) == 4) {
348 // On 32-bit platforms, the upper 32-bits should always be 0:
349 // LDW [upper]
350 // JEQ 0, passed, invalid
351 return gen_.MakeInstruction(
352 BPF_LD + BPF_W + BPF_ABS,
353 upper,
354 gen_.MakeInstruction(
355 BPF_JMP + BPF_JEQ + BPF_K, 0, passed, invalid_64bit));
358 // On 64-bit platforms, the upper 32-bits may be 0 or ~0; but we only allow
359 // ~0 if the sign bit of the lower 32-bits is set too:
360 // LDW [upper]
361 // JEQ 0, passed, (next)
362 // JEQ ~0, (next), invalid
363 // LDW [lower]
364 // JSET (1<<31), passed, invalid
366 // TODO(mdempsky): The JSET instruction could perhaps jump to passed->next
367 // instead, as the first instruction of passed should be "LDW [lower]".
368 return gen_.MakeInstruction(
369 BPF_LD + BPF_W + BPF_ABS,
370 upper,
371 gen_.MakeInstruction(
372 BPF_JMP + BPF_JEQ + BPF_K,
374 passed,
375 gen_.MakeInstruction(
376 BPF_JMP + BPF_JEQ + BPF_K,
377 std::numeric_limits<uint32_t>::max(),
378 gen_.MakeInstruction(
379 BPF_LD + BPF_W + BPF_ABS,
380 lower,
381 gen_.MakeInstruction(BPF_JMP + BPF_JSET + BPF_K,
382 1U << 31,
383 passed,
384 invalid_64bit)),
385 invalid_64bit)));
388 const uint32_t idx = (half == UpperHalf) ? SECCOMP_ARG_MSB_IDX(cond.argno_)
389 : SECCOMP_ARG_LSB_IDX(cond.argno_);
390 const uint32_t mask = (half == UpperHalf) ? cond.mask_ >> 32 : cond.mask_;
391 const uint32_t value = (half == UpperHalf) ? cond.value_ >> 32 : cond.value_;
393 // Emit a suitable instruction sequence for (arg & mask) == value.
395 // For (arg & 0) == 0, just return passed.
396 if (mask == 0) {
397 CHECK_EQ(0U, value);
398 return passed;
401 // For (arg & ~0) == value, emit:
402 // LDW [idx]
403 // JEQ value, passed, failed
404 if (mask == std::numeric_limits<uint32_t>::max()) {
405 return gen_.MakeInstruction(
406 BPF_LD + BPF_W + BPF_ABS,
407 idx,
408 gen_.MakeInstruction(BPF_JMP + BPF_JEQ + BPF_K, value, passed, failed));
411 // For (arg & mask) == 0, emit:
412 // LDW [idx]
413 // JSET mask, failed, passed
414 // (Note: failed and passed are intentionally swapped.)
415 if (value == 0) {
416 return gen_.MakeInstruction(
417 BPF_LD + BPF_W + BPF_ABS,
418 idx,
419 gen_.MakeInstruction(BPF_JMP + BPF_JSET + BPF_K, mask, failed, passed));
422 // For (arg & x) == x where x is a single-bit value, emit:
423 // LDW [idx]
424 // JSET mask, passed, failed
425 if (mask == value && HasExactlyOneBit(mask)) {
426 return gen_.MakeInstruction(
427 BPF_LD + BPF_W + BPF_ABS,
428 idx,
429 gen_.MakeInstruction(BPF_JMP + BPF_JSET + BPF_K, mask, passed, failed));
432 // Generic fallback:
433 // LDW [idx]
434 // AND mask
435 // JEQ value, passed, failed
436 return gen_.MakeInstruction(
437 BPF_LD + BPF_W + BPF_ABS,
438 idx,
439 gen_.MakeInstruction(
440 BPF_ALU + BPF_AND + BPF_K,
441 mask,
442 gen_.MakeInstruction(
443 BPF_JMP + BPF_JEQ + BPF_K, value, passed, failed)));
446 ErrorCode PolicyCompiler::Unexpected64bitArgument() {
447 return Kill("Unexpected 64bit argument detected")->Compile(this);
450 ErrorCode PolicyCompiler::Error(int err) {
451 if (has_unsafe_traps_) {
452 // When inside an UnsafeTrap() callback, we want to allow all system calls.
453 // This means, we must conditionally disable the sandbox -- and that's not
454 // something that kernel-side BPF filters can do, as they cannot inspect
455 // any state other than the syscall arguments.
456 // But if we redirect all error handlers to user-space, then we can easily
457 // make this decision.
458 // The performance penalty for this extra round-trip to user-space is not
459 // actually that bad, as we only ever pay it for denied system calls; and a
460 // typical program has very few of these.
461 return Trap(ReturnErrno, reinterpret_cast<void*>(err), true);
464 return ErrorCode(err);
467 ErrorCode PolicyCompiler::Trap(TrapRegistry::TrapFnc fnc,
468 const void* aux,
469 bool safe) {
470 uint16_t trap_id = registry_->Add(fnc, aux, safe);
471 return ErrorCode(trap_id, fnc, aux, safe);
474 bool PolicyCompiler::IsRequiredForUnsafeTrap(int sysno) {
475 for (size_t i = 0; i < arraysize(kSyscallsRequiredForUnsafeTraps); ++i) {
476 if (sysno == kSyscallsRequiredForUnsafeTraps[i]) {
477 return true;
480 return false;
483 ErrorCode PolicyCompiler::CondMaskedEqual(int argno,
484 ErrorCode::ArgType width,
485 uint64_t mask,
486 uint64_t value,
487 const ErrorCode& passed,
488 const ErrorCode& failed) {
489 return ErrorCode(argno,
490 width,
491 mask,
492 value,
493 &*conds_.insert(passed).first,
494 &*conds_.insert(failed).first);
497 } // namespace bpf_dsl
498 } // namespace sandbox