seccomp, AppArmor, SELinux and Rootless Containers
Namespaces decide what a container can see and capabilities decide what root inside it may do. Three more layers decide what happens when those two aren't enough: seccomp filters the system calls a process can make at all, Linux security modules (AppArmor on Debian/Ubuntu families, SELinux on Red Hat families) confine file and resource access by policy, and user namespaces make root in the container an unprivileged user on the host. Each has stopped real container escapes on its own: many kernel exploits need a syscall that the default seccomp profile blocks, and a process that is root only inside a user namespace gains much less when it breaks out. This lesson shows each layer working, and what turning it off costs.
seccomp: the syscall filter
A seccomp filter is a small program the kernel runs on every system call of the process. Docker, containerd and CRI-O ship a default profile that allows the few hundred syscalls ordinary software uses and refuses several dozen (Docker's documentation says around 44) that are rarely needed and often abused: loading kernel modules, kexec, mount, bpf, keyctl, open_by_handle_at, perf_event_open, userfaultfd, and creating user namespaces without CAP_SYS_ADMIN. Kubernetes doesn't apply it unless asked (seccompProfile: {type: RuntimeDefault}), which is why Pod Security's restricted level requires it.
Your sandbox runs under Docker's default profile. Creating a user namespace is a common first step of kernel exploits, and the filter refuses it; the session also shows no_new_privs, the flag that stops setuid binaries from raising privileges. It only touches the sandbox itself.
grep -E '^(Seccomp|Seccomp_filters|NoNewPrivs):' /proc/self/status
echo "--- try to create a user namespace (a common exploit primitive)"
unshare --user --map-root-user id 2>&1; echo "exit $?"
echo "--- the same process with no_new_privs set"
setpriv --no-new-privs grep NoNewPrivs /proc/self/statusNoNewPrivs: 0
Seccomp: 2
Seccomp_filters: 1
--- try to create a user namespace (a common exploit primitive)
unshare: unshare failed: Operation not permitted
exit 1
--- the same process with no_new_privs set
NoNewPrivs: 1
For comparison, the same unshare with the filter switched off. This is a lab session recorded on the course's build machine, not something your sandbox can run:
# lab session: the sandbox image started with --security-opt seccomp=unconfined (don't do this in production)
$ unshare --user --map-root-user id
uid=0(root) gid=0(root) groups=0(root)With the filter off, an unprivileged process becomes "root" in a new user namespace and gains access to kernel code paths (network, filesystem and namespace syscalls) that are only reachable with capabilities, which is where many kernel privilege-escalation bugs live. One configuration flag decides whether that attack surface exists.
A seccomp profile, evaluated
Profiles are JSON: a default action plus rules for named syscalls. The program applies a cut-down profile in the style of the runtime default to two syscall traces: an ordinary web application, and the sequence typical of an escape attempt (reduced to names; no exploit is involved).
profile = {
"defaultAction": "SCMP_ACT_ERRNO",
"allow": {"read", "write", "openat", "close", "fstat", "mmap", "mprotect", "brk", "rt_sigaction", "futex",
"epoll_wait", "accept4", "recvfrom", "sendto", "socket", "connect", "clone", "execve", "exit_group",
"getrandom", "clock_gettime", "setuid", "setgid"},
"allow_if_cap": {"unshare": "CAP_SYS_ADMIN", "mount": "CAP_SYS_ADMIN", "bpf": "CAP_SYS_ADMIN"},
# never allowed, whatever the capabilities
"deny": {"init_module", "finit_module", "kexec_load", "open_by_handle_at", "keyctl", "userfaultfd"},
}
def check(syscall, caps):
if syscall in profile["deny"]:
return "EPERM (blocked)"
if syscall in profile["allow"]:
return "allowed"
need = profile["allow_if_cap"].get(syscall)
if need:
return "allowed" if need in caps else f"EPERM (needs {need})"
return "EPERM (default action)"
traces = {
"web app": ["openat", "read", "socket", "connect", "sendto", "recvfrom", "epoll_wait", "futex", "write"],
"escape attempt": ["unshare", "mount", "open_by_handle_at", "keyctl", "init_module"],
}
for caps_label, caps in [("default caps", set()), ("with CAP_SYS_ADMIN", {"CAP_SYS_ADMIN"})]:
for name, trace in traces.items():
results = [f"{s}={check(s, caps).split(' ')[0]}" for s in trace]
blocked = sum(1 for s in trace if check(s, caps) != "allowed")
print(f"{caps_label:18} {name:15} blocked {blocked}/{len(trace)}: {' '.join(results)}")default caps web app blocked 0/9: openat=allowed read=allowed socket=allowed connect=allowed sendto=allowed recvfrom=allowed epoll_wait=allowed futex=allowed write=allowed
default caps escape attempt blocked 5/5: unshare=EPERM mount=EPERM open_by_handle_at=EPERM keyctl=EPERM init_module=EPERM
with CAP_SYS_ADMIN web app blocked 0/9: openat=allowed read=allowed socket=allowed connect=allowed sendto=allowed recvfrom=allowed epoll_wait=allowed futex=allowed write=allowed
with CAP_SYS_ADMIN escape attempt blocked 3/5: unshare=allowed mount=allowed open_by_handle_at=EPERM keyctl=EPERM init_module=EPERM
The ordinary application never notices the filter. The escape sequence is blocked at every step with default capabilities; adding CAP_SYS_ADMIN reopens unshare and mount, the first two steps. (The real profile goes further in the same direction: it also unlocks init_module for CAP_SYS_MODULE and open_by_handle_at for CAP_DAC_READ_SEARCH; the model keeps those blocked for brevity.) Capabilities and seccomp interact, which is one more reason SYS_ADMIN is a red flag.
AppArmor and SELinux
Both are mandatory access control systems: rules that even root can't override.
- AppArmor uses per-program profiles naming files, capabilities and operations. Docker's
docker-defaultprofile, for example, denies writes to most of/procand/sysand deniesmount. Kubernetes sets profiles withsecurityContext.appArmorProfile(older clusters used annotations). - SELinux labels every process and file with a type and, for containers, MCS categories. Container processes run as
container_tand may only touch files labelledcontainer_file_t; each container gets a unique category pair (for examples0:c123,c456), so even two containers of the same type can't read each other's files. Host files keep host types (etc_t,shadow_t…), which a container process can't read even when they are mounted into it.
The SELinux category rule is simple enough to model: access requires a matching type rule and the process's categories must include the file's.
TYPE_RULES = {("container_t", "container_file_t"): {"read", "write"}}
def mcs_ok(proc_cats, file_cats):
return file_cats <= proc_cats
def access(proc, file, op):
if op not in TYPE_RULES.get((proc["type"], file["type"]), set()):
return f"denied (no {proc['type']} -> {file['type']} rule)"
if not mcs_ok(proc["cats"], file["cats"]):
return f"denied (categories {sorted(file['cats'])} not in {sorted(proc['cats'])})"
return "allowed"
web = {"type": "container_t", "cats": {"c123", "c456"}}
worker = {"type": "container_t", "cats": {"c7", "c901"}}
files = {
"web's own /data/app.db": {"type": "container_file_t", "cats": {"c123", "c456"}},
"worker's /data/queue.db": {"type": "container_file_t", "cats": {"c7", "c901"}},
"host /etc/shadow (bind-mounted)": {"type": "shadow_t", "cats": set()},
}
for fname, f in files.items():
print(f"web read {fname:33} {access(web, f, 'read')}")
app_db = "web's own /data/app.db"
print(f"worker read {app_db:33} {access(worker, files[app_db], 'read')}")web read web's own /data/app.db allowed
web read worker's /data/queue.db denied (categories ['c7', 'c901'] not in ['c123', 'c456'])
web read host /etc/shadow (bind-mounted) denied (no container_t -> shadow_t rule)
worker read web's own /data/app.db denied (categories ['c123', 'c456'] not in ['c7', 'c901'])
Even a bind mount of /etc/shadow into the container doesn't make it readable: the type rule is missing. That is why SELinux-enforcing hosts have been immune to several published escapes that relied on reading or writing host files, and why "just set SELinux to permissive" during a container incident is the wrong move.
Rootless containers and user namespaces
In a rootless setup (rootless Docker or Podman, or Kubernetes pods with user namespaces via hostUsers: false, stable since Kubernetes 1.36 on Linux nodes with a recent kernel and runtime), UID 0 inside the container maps to an unprivileged UID range on the host (for example 100000–165535). A process that escapes is then an ordinary user on the host: no access to other users' files, no capabilities on host resources. The cost is compatibility: some networking modes, privileged ports below 1024 without extra configuration, and certain storage drivers behave differently.
How missing layers are detected
docker inspect:SecurityOptcontainingseccomp=unconfined,apparmor=unconfinedorlabel=disable;Privileged: true(which disables all three).- Kubernetes: pods without
seccompProfileRuntimeDefaultorLocalhost, withappArmorProfile: Unconfined, withseLinuxOptionsoverriding the type, withhostUserstrue where user namespaces are available. Pod Security admission'srestrictedlevel flags most of these (Pod Security). - Hosts: SELinux in permissive mode (
getenforce), AppArmor profiles in complain mode (aa-status). - Runtime: kernel audit logs of seccomp kills and AppArmor/SELinux denials (
type=SECCOMP,apparmor="DENIED",avc: denied) are high-value signals: legitimate software rarely hits them.
How it is fixed
RuntimeDefaultseccomp on every pod (Kubernetes can make it the default for the kubelet), custom tighter profiles for sensitive workloads (record the syscalls in testing, then enforce).- Keep AppArmor or SELinux enforcing on nodes; use the runtime's default profiles.
- Use user namespaces or rootless runtimes where the workload allows; set
allowPrivilegeEscalation: falseeverywhere.
Pitfalls
- Fixing a failing container by setting
seccomp=unconfinedinstead of finding the one syscall it needs. - Assuming Kubernetes pods get the runtime's seccomp profile by default: they run
Unconfinedunless the profile is set. - Treating SELinux denials as noise: on a container host, an
avc: deniedfrom a container process touching host files is an incident lead.
Practice
1. Add "ptrace" to the escape trace. What does the model answer, and what does the real default profile do?
EPERM (default action): it is in no list. Docker's real profile allows ptrace on kernels 4.8 and later (older kernels had a seccomp bypass through ptrace), still limited by capabilities and the PID namespace.
2. In the SELinux model, give the worker the categories {"c123", "c456", "c7", "c901"}. What changes, and why is it a bad idea?
The worker can read the web container's files: categories are a superset. Runtimes assign unique pairs precisely so no container dominates another; overlapping categories reconnect containers that should be isolated.
3. A developer says "the container works with --privileged but not without". What do you ask for?
The exact error. It is usually one capability (NET_ADMIN for a VPN client, SYS_PTRACE for a profiler), one device, or one syscall; grant exactly that, on that workload only, and record why.
Test yourself
What happened when the sandbox tried to create a user namespace?
- It became root on the host
- The default seccomp profile refused it (Operation not permitted)
- It crashed the container
- It worked
Do Kubernetes pods get the container runtime's default seccomp profile automatically?
- Yes, always
- No: they run Unconfined unless seccompProfile RuntimeDefault (or a kubelet default) is set
- Only on GKE
- Only privileged pods
Why couldn't the web container read the bind-mounted /etc/shadow under SELinux?
- The file was empty
- No type rule lets container_t read shadow_t
- MCS categories matched
- It was encrypted
What does a rootless runtime change for a container escape?
- Nothing
- Root in the container maps to an unprivileged host UID, so an escapee is an ordinary user
- It disables networking
- It removes the kernel