1 // seccomp example for x86 (32-bit and 64-bit) with BPF macros
2 //
3 // Copyright (c) 2012 The Chromium OS Authors <chromium-os-dev@chromium.org>
4 // Authors:
5 //  Will Drewry <wad@chromium.org>
6 //  Kees Cook <keescook@chromium.org>
7 //
8 // The code may be used by anyone for any purpose, and can serve as a
9 // starting point for developing applications using mode 2 seccomp.
10 
11 #ifndef _SECCOMP_BPF_H_
12 #define _SECCOMP_BPF_H_
13 
14 #define _GNU_SOURCE 1
15 #include <stdio.h>
16 #include <stddef.h>
17 #include <stdlib.h>
18 #include <errno.h>
19 #include <signal.h>
20 #include <string.h>
21 #include <unistd.h>
22 
23 #include <sys/prctl.h>
24 #ifndef PR_SET_NO_NEW_PRIVS
25 # define PR_SET_NO_NEW_PRIVS 38
26 #endif
27 
28 #include <linux/unistd.h>
29 #include <linux/audit.h>
30 #include <linux/filter.h>
31 #ifdef HAVE_LINUX_SECCOMP_H
32 # include <linux/seccomp.h>
33 #endif
34 #ifndef SECCOMP_MODE_FILTER
35 # define SECCOMP_MODE_FILTER	2 /* uses user-supplied filter. */
36 # define SECCOMP_RET_KILL	0x00000000U /* kill the task immediately */
37 # define SECCOMP_RET_TRAP	0x00030000U /* disallow and force a SIGSYS */
38 # define SECCOMP_RET_ALLOW	0x7fff0000U /* allow */
39 struct seccomp_data {
40     int nr;
41     __u32 arch;
42     __u64 instruction_pointer;
43     __u64 args[6];
44 };
45 #endif
46 #ifndef SYS_SECCOMP
47 # define SYS_SECCOMP 1
48 #endif
49 
50 #define syscall_nr (offsetof(struct seccomp_data, nr))
51 #define arch_nr (offsetof(struct seccomp_data, arch))
52 
53 #if defined(__i386__)
54 # define REG_SYSCALL	REG_EAX
55 # define ARCH_NR	AUDIT_ARCH_I386
56 #elif defined(__x86_64__)
57 # define REG_SYSCALL	REG_RAX
58 # define ARCH_NR	AUDIT_ARCH_X86_64
59 #else
60 # warning "Platform does not support seccomp filter yet"
61 # define REG_SYSCALL	0
62 # define ARCH_NR	0
63 #endif
64 
65 #define VALIDATE_ARCHITECTURE \
66 	BPF_STMT(BPF_LD+BPF_W+BPF_ABS, arch_nr), \
67 	BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, ARCH_NR, 1, 0), \
68 	BPF_STMT(BPF_RET+BPF_K, SECCOMP_RET_KILL)
69 
70 #define EXAMINE_SYSCALL \
71 	BPF_STMT(BPF_LD+BPF_W+BPF_ABS, syscall_nr)
72 
73 #define ALLOW_SYSCALL(name) \
74 	BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, __NR_##name, 0, 1), \
75 	BPF_STMT(BPF_RET+BPF_K, SECCOMP_RET_ALLOW)
76 
77 #define KILL_PROCESS \
78 	BPF_STMT(BPF_RET+BPF_K, SECCOMP_RET_KILL)
79 
80 int seccomp_sandbox_strict_init();
81 int seccomp_sandbox_filter_init();
82 
83 #endif /* _SECCOMP_BPF_H_ */
84