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"
8 #include <sys/syscall.h>
12 #include "base/logging.h"
13 #include "base/macros.h"
14 #include "sandbox/linux/bpf_dsl/bpf_dsl.h"
15 #include "sandbox/linux/bpf_dsl/bpf_dsl_impl.h"
16 #include "sandbox/linux/bpf_dsl/codegen.h"
17 #include "sandbox/linux/bpf_dsl/dump_bpf.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/bpf_dsl/verifier.h"
22 #include "sandbox/linux/seccomp-bpf/errorcode.h"
23 #include "sandbox/linux/system_headers/linux_filter.h"
24 #include "sandbox/linux/system_headers/linux_seccomp.h"
31 #if defined(__i386__) || defined(__x86_64__)
32 const bool kIsIntel
= true;
34 const bool kIsIntel
= false;
36 #if defined(__x86_64__) && defined(__ILP32__)
37 const bool kIsX32
= true;
39 const bool kIsX32
= false;
42 const int kSyscallsRequiredForUnsafeTraps
[] = {
45 #if defined(__NR_sigprocmask)
48 #if defined(__NR_sigreturn)
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
;
69 bool HasUnsafeTraps(const Policy
* policy
) {
71 for (uint32_t sysnum
: SyscallSet::ValidOnly()) {
72 if (policy
->EvaluateSyscall(sysnum
)->HasUnsafeTraps()) {
76 return policy
->InvalidSyscall()->HasUnsafeTraps();
81 struct PolicyCompiler::Range
{
86 PolicyCompiler::PolicyCompiler(const Policy
* policy
, TrapRegistry
* registry
)
92 has_unsafe_traps_(HasUnsafeTraps(policy_
)) {
96 PolicyCompiler::~PolicyCompiler() {
99 scoped_ptr
<CodeGen::Program
> PolicyCompiler::Compile(bool verify
) {
100 CHECK(policy_
->InvalidSyscall()->IsDeny())
101 << "Policies should deny invalid system calls";
103 // If our BPF program has unsafe traps, enable support for them.
104 if (has_unsafe_traps_
) {
105 CHECK_NE(0U, escapepc_
) << "UnsafeTrap() requires a valid escape PC";
107 for (int sysnum
: kSyscallsRequiredForUnsafeTraps
) {
108 CHECK(policy_
->EvaluateSyscall(sysnum
)->IsAllow())
109 << "Policies that use UnsafeTrap() must unconditionally allow all "
110 "required system calls";
113 CHECK(registry_
->EnableUnsafeTraps())
114 << "We'd rather die than enable unsafe traps";
117 // Assemble the BPF filter program.
118 scoped_ptr
<CodeGen::Program
> program(new CodeGen::Program());
119 gen_
.Compile(AssemblePolicy(), program
.get());
121 // Make sure compilation resulted in a BPF program that executes
122 // correctly. Otherwise, there is an internal error in our BPF compiler.
123 // There is really nothing the caller can do until the bug is fixed.
125 const char* err
= nullptr;
126 if (!Verifier::VerifyBPF(this, *program
, *policy_
, &err
)) {
127 DumpBPF::PrintProgram(*program
);
132 return program
.Pass();
135 void PolicyCompiler::DangerousSetEscapePC(uint64_t escapepc
) {
136 escapepc_
= escapepc
;
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
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_
) {
165 // We already enabled unsafe traps in Compile, but enable them again to give
166 // the trap registry a second chance to complain before we add the backdoor.
167 CHECK(registry_
->EnableUnsafeTraps());
169 // Allow system calls, if they originate from our magic return address.
170 const uint32_t lopc
= static_cast<uint32_t>(escapepc_
);
171 const uint32_t hipc
= static_cast<uint32_t>(escapepc_
>> 32);
173 // BPF cannot do native 64-bit comparisons, so we have to compare
174 // both 32-bit halves of the instruction pointer. If they match what
175 // we expect, we return ERR_ALLOWED. If either or both don't match,
176 // we continue evalutating the rest of the sandbox policy.
178 // For simplicity, we check the full 64-bit instruction pointer even
179 // on 32-bit architectures.
180 return gen_
.MakeInstruction(
181 BPF_LD
+ BPF_W
+ BPF_ABS
, SECCOMP_IP_LSB_IDX
,
182 gen_
.MakeInstruction(
183 BPF_JMP
+ BPF_JEQ
+ BPF_K
, lopc
,
184 gen_
.MakeInstruction(
185 BPF_LD
+ BPF_W
+ BPF_ABS
, SECCOMP_IP_MSB_IDX
,
186 gen_
.MakeInstruction(BPF_JMP
+ BPF_JEQ
+ BPF_K
, hipc
,
187 CompileResult(Allow()), rest
)),
191 CodeGen::Node
PolicyCompiler::DispatchSyscall() {
192 // Evaluate all possible system calls and group their ErrorCodes into
193 // ranges of identical codes.
197 // Compile the system call ranges to an optimized BPF jumptable
198 CodeGen::Node jumptable
= AssembleJumpTable(ranges
.begin(), ranges
.end());
200 // Grab the system call number, so that we can check it and then
201 // execute the jump table.
202 return gen_
.MakeInstruction(
203 BPF_LD
+ BPF_W
+ BPF_ABS
, SECCOMP_NR_IDX
, CheckSyscallNumber(jumptable
));
206 CodeGen::Node
PolicyCompiler::CheckSyscallNumber(CodeGen::Node passed
) {
208 // On Intel architectures, verify that system call numbers are in the
209 // expected number range.
210 CodeGen::Node invalidX32
=
211 CompileResult(Kill("Illegal mixing of system call ABIs"));
213 // The newer x32 API always sets bit 30.
214 return gen_
.MakeInstruction(
215 BPF_JMP
+ BPF_JSET
+ BPF_K
, 0x40000000, passed
, invalidX32
);
217 // The older i386 and x86-64 APIs clear bit 30 on all system calls.
218 return gen_
.MakeInstruction(
219 BPF_JMP
+ BPF_JSET
+ BPF_K
, 0x40000000, invalidX32
, passed
);
223 // TODO(mdempsky): Similar validation for other architectures?
227 void PolicyCompiler::FindRanges(Ranges
* ranges
) {
228 // Please note that "struct seccomp_data" defines system calls as a signed
229 // int32_t, but BPF instructions always operate on unsigned quantities. We
230 // deal with this disparity by enumerating from MIN_SYSCALL to MAX_SYSCALL,
231 // and then verifying that the rest of the number range (both positive and
232 // negative) all return the same ErrorCode.
233 const CodeGen::Node invalid_node
= CompileResult(policy_
->InvalidSyscall());
234 uint32_t old_sysnum
= 0;
235 CodeGen::Node old_node
=
236 SyscallSet::IsValid(old_sysnum
)
237 ? CompileResult(policy_
->EvaluateSyscall(old_sysnum
))
240 for (uint32_t sysnum
: SyscallSet::All()) {
242 SyscallSet::IsValid(sysnum
)
243 ? CompileResult(policy_
->EvaluateSyscall(static_cast<int>(sysnum
)))
245 // N.B., here we rely on CodeGen folding (i.e., returning the same
246 // node value for) identical code sequences, otherwise our jump
247 // table will blow up in size.
248 if (node
!= old_node
) {
249 ranges
->push_back(Range
{old_sysnum
, old_node
});
254 ranges
->push_back(Range
{old_sysnum
, old_node
});
257 CodeGen::Node
PolicyCompiler::AssembleJumpTable(Ranges::const_iterator start
,
258 Ranges::const_iterator stop
) {
259 // We convert the list of system call ranges into jump table that performs
260 // a binary search over the ranges.
261 // As a sanity check, we need to have at least one distinct ranges for us
262 // to be able to build a jump table.
263 CHECK(start
< stop
) << "Invalid iterator range";
264 const auto n
= stop
- start
;
266 // If we have narrowed things down to a single range object, we can
267 // return from the BPF filter program.
271 // Pick the range object that is located at the mid point of our list.
272 // We compare our system call number against the lowest valid system call
273 // number in this range object. If our number is lower, it is outside of
274 // this range object. If it is greater or equal, it might be inside.
275 Ranges::const_iterator mid
= start
+ n
/ 2;
277 // Sub-divide the list of ranges and continue recursively.
278 CodeGen::Node jf
= AssembleJumpTable(start
, mid
);
279 CodeGen::Node jt
= AssembleJumpTable(mid
, stop
);
280 return gen_
.MakeInstruction(BPF_JMP
+ BPF_JGE
+ BPF_K
, mid
->from
, jt
, jf
);
283 CodeGen::Node
PolicyCompiler::CompileResult(const ResultExpr
& res
) {
284 return RetExpression(res
->Compile(this));
287 CodeGen::Node
PolicyCompiler::RetExpression(const ErrorCode
& err
) {
288 switch (err
.error_type()) {
289 case ErrorCode::ET_COND
:
290 return CondExpression(err
);
291 case ErrorCode::ET_SIMPLE
:
292 case ErrorCode::ET_TRAP
:
293 return gen_
.MakeInstruction(BPF_RET
+ BPF_K
, err
.err());
296 << "ErrorCode is not suitable for returning from a BPF program";
297 return CodeGen::kNullNode
;
301 CodeGen::Node
PolicyCompiler::CondExpression(const ErrorCode
& cond
) {
302 // Sanity check that |cond| makes sense.
303 CHECK(cond
.argno_
>= 0 && cond
.argno_
< 6) << "Invalid argument number "
305 CHECK(cond
.width_
== ErrorCode::TP_32BIT
||
306 cond
.width_
== ErrorCode::TP_64BIT
)
307 << "Invalid argument width " << cond
.width_
;
308 CHECK_NE(0U, cond
.mask_
) << "Zero mask is invalid";
309 CHECK_EQ(cond
.value_
, cond
.value_
& cond
.mask_
)
310 << "Value contains masked out bits";
311 if (sizeof(void*) == 4) {
312 CHECK_EQ(ErrorCode::TP_32BIT
, cond
.width_
)
313 << "Invalid width on 32-bit platform";
315 if (cond
.width_
== ErrorCode::TP_32BIT
) {
316 CHECK_EQ(0U, cond
.mask_
>> 32) << "Mask exceeds argument size";
317 CHECK_EQ(0U, cond
.value_
>> 32) << "Value exceeds argument size";
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
,
329 CondExpressionHalf(cond
, LowerHalf
, passed
, failed
),
333 CodeGen::Node
PolicyCompiler::CondExpressionHalf(const ErrorCode
& cond
,
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
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:
350 // JEQ 0, passed, invalid
351 return gen_
.MakeInstruction(
352 BPF_LD
+ BPF_W
+ BPF_ABS
,
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:
361 // JEQ 0, passed, (next)
362 // JEQ ~0, (next), invalid
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
,
371 gen_
.MakeInstruction(
372 BPF_JMP
+ BPF_JEQ
+ BPF_K
,
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
,
381 gen_
.MakeInstruction(BPF_JMP
+ BPF_JSET
+ BPF_K
,
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.
401 // For (arg & ~0) == value, emit:
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
,
408 gen_
.MakeInstruction(BPF_JMP
+ BPF_JEQ
+ BPF_K
, value
, passed
, failed
));
411 // For (arg & mask) == 0, emit:
413 // JSET mask, failed, passed
414 // (Note: failed and passed are intentionally swapped.)
416 return gen_
.MakeInstruction(
417 BPF_LD
+ BPF_W
+ BPF_ABS
,
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:
424 // JSET mask, passed, failed
425 if (mask
== value
&& HasExactlyOneBit(mask
)) {
426 return gen_
.MakeInstruction(
427 BPF_LD
+ BPF_W
+ BPF_ABS
,
429 gen_
.MakeInstruction(BPF_JMP
+ BPF_JSET
+ BPF_K
, mask
, passed
, failed
));
435 // JEQ value, passed, failed
436 return gen_
.MakeInstruction(
437 BPF_LD
+ BPF_W
+ BPF_ABS
,
439 gen_
.MakeInstruction(
440 BPF_ALU
+ BPF_AND
+ BPF_K
,
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
,
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
]) {
483 ErrorCode
PolicyCompiler::CondMaskedEqual(int argno
,
484 ErrorCode::ArgType width
,
487 const ErrorCode
& passed
,
488 const ErrorCode
& failed
) {
489 return ErrorCode(argno
,
493 &*conds_
.insert(passed
).first
,
494 &*conds_
.insert(failed
).first
);
497 } // namespace bpf_dsl
498 } // namespace sandbox