Block privilege gain across exec with PR_SET_NO_NEW_PRIVS
Call prctl(PR_SET_NO_NEW_PRIVS) on Linux 3.5 or later so execve can never grant more privilege, which also lets unprivileged code install seccomp filters.
Setuid binaries, file capabilities and sudo all work because execve can raise privilege. Setting the no_new_privs bit tells the kernel to stop doing that for this process and everything it creates. It cannot be cleared, it survives fork and execve, and it is the precondition for installing a seccomp filter without CAP_SYS_ADMIN.
#include <stdio.h>
#include <sys/prctl.h>
#include <unistd.h>
int main(void)
{
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
perror("prctl");
return 1;
}
printf("no_new_privs=%d\n", prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0));
fflush(stdout);
execl("/usr/bin/sudo", "sudo", "-n", "id", (char *)NULL);
perror("execl");
return 1;
}no_new_privs=1
sudo: The "no new privileges" flag is set, which prevents sudo from running as root.The second line comes from sudo itself, which notices the flag and refuses. The flag does not drop privileges you already hold, so a root process that sets it still runs as root, and it only blocks gains made at execve. Container runtimes set it with an option such as no-new-privileges, and systemd offers it as NoNewPrivileges=yes. See PR_SET_NO_NEW_PRIVS in prctl(2) and the kernel documentation.