seccomp (short for "secure computing mode") is a security feature in the Linux kernel that allows restricting the system calls that a process can make. seccomp filters can be used to provide a sandboxed environment for untrusted code or to implement privilege separation between components of a trusted application.
seccomp works by intercepting the system calls made by a process and comparing them against a set of rules. If a system call is not allowed by the rules, it will be denied and the process will receive an error code. The rules are defined by a BPF (Berkeley Packet Filter) program that runs in kernel space.
The seccomp feature was introduced in Linux kernel version 2.6.12 and has been improved and expanded over time. seccomp can be used in conjunction with other security features in Linux, such as namespaces and cgroups, to create a more secure and isolated environment for running applications.
Here is an example of how to use seccomp to limit the system calls that a process can make:
#include <stddef.h>
#include <linux/seccomp.h>
#include <sys/prctl.h>
#include <unistd.h>
int main() {
// Define the set of allowed system calls
scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_ALLOW);
seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EPERM), SCMP_SYS(execve), 0);
seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EPERM), SCMP_SYS(open), 0);
seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EPERM), SCMP_SYS(write), 0);
seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EPERM), SCMP_SYS(read), 0);
// Load the filter into the kernel
if (seccomp_load(ctx) < 0) {
perror("seccomp_load");
return 1;
}
// Apply the filter to the current process
if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER) < 0) {
perror("prctl");
return 1;
}
// Perform some restricted operations
int fd = open("/etc/passwd", O_RDONLY); // Will fail with EPERM
write(fd, "hello", 5); // Will also fail with EPERM
return 0;
}
In this example, we create a seccomp filter that allows only a few system calls (execve, open, read, and write) and denies all others. We then load the filter into the kernel and apply it to the current process using the prctl system call. Finally, we attempt to open a file and write to it, but both operations will fail with the EPERM error code because they are not allowed by the seccomp filter.