1 // SPDX-License-Identifier: GPL-2.0
3 * Seccomp BPF example using a macro-based generator.
5 * Copyright (c) 2012 The Chromium OS Authors <chromium-os-dev@chromium.org>
6 * Author: Will Drewry <wad@chromium.org>
8 * The code may be used by anyone for any purpose,
9 * and can serve as a starting point for developing
10 * applications using prctl(PR_ATTACH_SECCOMP_FILTER).
13 #include <linux/filter.h>
14 #include <linux/seccomp.h>
15 #include <linux/unistd.h>
18 #include <sys/prctl.h>
21 #include "bpf-helper.h"
23 #ifndef PR_SET_NO_NEW_PRIVS
24 #define PR_SET_NO_NEW_PRIVS 38
27 int main(int argc, char **argv)
29 struct bpf_labels l = {
32 static const char msg1[] = "Please type something: ";
33 static const char msg2[] = "You typed: ";
35 struct sock_filter filter[] = {
36 /* TODO: LOAD_SYSCALL_NR(arch) and enforce an arch */
38 SYSCALL(__NR_exit, ALLOW),
39 SYSCALL(__NR_exit_group, ALLOW),
40 SYSCALL(__NR_write, JUMP(&l, write_fd)),
41 SYSCALL(__NR_read, JUMP(&l, read)),
42 DENY, /* Don't passthrough into a label */
46 JNE(STDIN_FILENO, DENY),
48 JNE((unsigned long)buf, DENY),
50 JGE(sizeof(buf), DENY),
55 JEQ(STDOUT_FILENO, JUMP(&l, write_buf)),
56 JEQ(STDERR_FILENO, JUMP(&l, write_buf)),
61 JEQ((unsigned long)msg1, JUMP(&l, msg1_len)),
62 JEQ((unsigned long)msg2, JUMP(&l, msg2_len)),
63 JEQ((unsigned long)buf, JUMP(&l, buf_len)),
68 JLT(sizeof(msg1), ALLOW),
73 JLT(sizeof(msg2), ALLOW),
78 JLT(sizeof(buf), ALLOW),
81 struct sock_fprog prog = {
83 .len = (unsigned short)(sizeof(filter)/sizeof(filter[0])),
86 bpf_resolve_jumps(&l, filter, sizeof(filter)/sizeof(*filter));
88 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
89 perror("prctl(NO_NEW_PRIVS)");
93 if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)) {
94 perror("prctl(SECCOMP)");
97 syscall(__NR_write, STDOUT_FILENO, msg1, strlen(msg1));
98 bytes = syscall(__NR_read, STDIN_FILENO, buf, sizeof(buf)-1);
99 bytes = (bytes > 0 ? bytes : 0);
100 syscall(__NR_write, STDERR_FILENO, msg2, strlen(msg2));
101 syscall(__NR_write, STDERR_FILENO, buf, bytes);
103 syscall(__NR_write, STDERR_FILENO, msg2, strlen(msg2)+2);