PROBLEM: I'm trying to play with seccomp but I can't understand why gcc tells me that seccomp() function call has an implicit declaration.
#define _GNU_SOURCE
#include <stddef.h> // offsetof
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/audit.h> // arch
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <sys/prctl.h>
#include <sys/syscall.h> // syscall numbers
struct sock_filter bpfcode[] = {
/* validate the architecture */
BPF_STMT(BPF_LD+BPF_W+BPF_ABS, (offsetof(struct seccomp_data, arch))),
BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, AUDIT_ARCH_X86_64, 0, 7),
/* load syscall number in the accumulator */
BPF_STMT(BPF_LD+BPF_W+BPF_ABS, (offsetof (struct seccomp_data, nr))),
/* check if the syscall number is allowed */
BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, SYS_nanosleep, 5, 0), // for sleep
BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, SYS_exit, 4, 0),
BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, SYS_exit_group, 3, 0),
BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, SYS_write, 2, 0),
BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, SYS_read, 1, 0),
BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, SYS_rt_sigreturn, 0, 1),
/* allow the sys call */
BPF_STMT(BPF_RET+BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_RET+BPF_K, SECCOMP_RET_TRAP)
};
struct sock_fprog bpf = {
.len = (unsigned short)( sizeof bpfcode / sizeof bpfcode[0] ),
.filter = bpfcode
};
int main(int argc, char **argv)
{
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) == -1) {
printf("prctl no_new_privs\n");
_exit(EXIT_FAILURE);
}
if (seccomp(SECCOMP_SET_MODE_FILTER, 0, &bpf)) {
printf("seccomp");
exit(EXIT_FAILURE);
}
sleep(2);
return 0;
}
WARNING/ERROR: this is the gcc output when I try to compile the program.
s.c: In function ‘main’:
s.c:45:6: warning: implicit declaration of function ‘seccomp’ [-Wimplicit-function-declaration]
if (seccomp(SECCOMP_SET_MODE_FILTER, 0, &bpf)) {
^~~~~~~
/tmp/ccYo4APk.o: In function `main':
s.c:(.text+0x65): undefined reference to `seccomp'
collect2: error: ld returned 1 exit status
QUESTION: what else should I include to make it work?
EDIT: why this works and the first didn't?
syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER, 0, &bpf)
It's a known issue: there is no glibc wrapper for the seccomp syscall.
You might want to use prctl(2) instead to load the BPF program, for two reasons:
Here's how to:
prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &bpf);