blob: b305d38b4f8b2e53d1fb1cff09e6c8ff36232078 [file] [log] [blame]
Dmitry V. Levin35701992015-02-06 01:52:59 +00001#include <stddef.h>
2#include <unistd.h>
3#include <errno.h>
4#include <sys/prctl.h>
5#include <sys/syscall.h>
6#include <linux/audit.h>
7#include <linux/filter.h>
8#include <linux/seccomp.h>
9
10#if defined __i386__
11# define SECCOMP_ARCH AUDIT_ARCH_I386
12#elif defined __x86_64__
13# define SECCOMP_ARCH AUDIT_ARCH_X86_64
14#elif defined __arm__
15# define SECCOMP_ARCH AUDIT_ARCH_ARM
16#elif defined __arm64__ || defined __aarch64__
17# define SECCOMP_ARCH AUDIT_ARCH_AARCH64
18#else
19# error unsupported architecture
20#endif
21
22#define SOCK_FILTER_KILL_PROCESS \
23 BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL)
24
25#define SOCK_FILTER_DENY_SYSCALL(nr, err) \
26 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_ ## nr, 0, 1), \
27 BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | (SECCOMP_RET_DATA & (err)))
28
29#define SOCK_FILTER_ALLOW_SYSCALL(nr) \
30 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_ ## nr, 0, 1), \
31 BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW)
32
33static const struct sock_filter filter[] = {
34 /* load architecture */
35 BPF_STMT(BPF_LD | BPF_W | BPF_ABS, (offsetof (struct seccomp_data, arch))),
36 /* jump forward 1 instruction if architecture matches */
37 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SECCOMP_ARCH, 1, 0),
38 /* kill process */
39 SOCK_FILTER_KILL_PROCESS,
40
41 /* load syscall number */
42 BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)),
43
44 /* allow syscalls */
45 SOCK_FILTER_ALLOW_SYSCALL(close),
46 SOCK_FILTER_ALLOW_SYSCALL(exit),
47 SOCK_FILTER_ALLOW_SYSCALL(exit_group),
48
49 /* deny syscalls */
50 SOCK_FILTER_DENY_SYSCALL(sync, EBUSY),
51 SOCK_FILTER_DENY_SYSCALL(setsid, EACCES),
52 SOCK_FILTER_DENY_SYSCALL(getpid, EPERM),
53 SOCK_FILTER_DENY_SYSCALL(munlockall, SECCOMP_RET_DATA),
54
55 /* kill process */
56 SOCK_FILTER_KILL_PROCESS
57};
58
59static const struct sock_fprog prog = {
60 .len = sizeof(filter) / sizeof(filter[0]),
61 .filter = (struct sock_filter *) filter,
62};
63
64int
65main(void)
66{
67 int fds[2];
68
69 close(0);
70 close(1);
71 if (pipe(fds))
72 return 77;
73
74 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0))
75 return 77;
76
77 if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog))
78 return 77;
79
80 if (close(0) || close(1))
81 _exit(1);
82
83#define TEST_DENIED_SYSCALL(nr, err, fail) \
84 if (errno = 0, syscall(__NR_ ## nr, 0xbad, 0xf00d, 0xdead, 0xbeef, err, fail) != -1 || err != errno) \
85 close(-fail)
86
87 TEST_DENIED_SYSCALL(sync, EBUSY, 2);
88 TEST_DENIED_SYSCALL(setsid, EACCES, 3);
89 TEST_DENIED_SYSCALL(getpid, EPERM, 4);
90 TEST_DENIED_SYSCALL(munlockall, SECCOMP_RET_DATA, 5);
91
92 _exit(0);
93}