TExcelTAD
Home › Cloud & Container Security › Container Escape Classes, Detection and Fixes

Container Escape Classes, Detection and Fixes

A container escape is code in a container gaining control outside it: over the host, the container runtime or other containers. For an attacker it is the step from "I own one application" to "I own the node", and on Kubernetes the node often holds credentials for much more. Escapes come in a small number of classes, and almost all of them are enabled by configuration rather than by exotic bugs: a privileged flag, a mounted socket, a host path, a shared namespace. This lesson describes each class by its mechanism (what isolation layer is missing), how it is detected, and how it is prevented. It deliberately contains no escape procedures: knowing the class is enough to find and remove it.

The classes

Class Missing layer Typical cause
Privileged container capabilities, seccomp, LSM and device isolation all at once --privileged, privileged: true "to make it work"
Container runtime socket the runtime API itself /var/run/docker.sock or the containerd socket mounted for a CI agent, dashboard or log shipper; whoever talks to it can start new containers with any settings
Sensitive host mounts the filesystem boundary hostPath of /, /etc, /root, /var/lib/kubelet, /var/log (with symlink tricks), /proc or /sys writable
Host namespaces the view boundary hostPID (see and signal host processes), hostNetwork (node-local services, the node's metadata access), hostIPC
Dangerous capabilities part of the privilege boundary SYS_ADMIN, SYS_MODULE, SYS_PTRACE + hostPID, DAC_READ_SEARCH, NET_ADMIN
Kernel vulnerabilities the shared kernel itself a local privilege-escalation bug reachable through allowed syscalls (Dirty COW, CVE-2016-5195; Dirty Pipe, CVE-2022-0847)
Runtime vulnerabilities the runtime's own code bugs in runc and similar (CVE-2019-5736, overwriting the host's runc binary; CVE-2024-21626, a leaked file descriptor letting a container start with a host working directory)

The first five are configuration; they are found by reading specs. The last two are vulnerabilities; they are found by patch level, and their impact is reduced by the same layers: seccomp blocks many syscalls kernel exploits need, user namespaces make "root" after the escape an unprivileged user, and Red Hat reported that SELinux in enforcing mode mitigated both runc CVEs on its default setups (a mitigation, not a substitute for the patch).

An escape-class auditor

The program reads a list of container configurations in the shape of docker inspect output (trimmed to the relevant fields) and reports, for each container, which escape classes its configuration enables. The containers are from the lab's CI and application hosts.

python · try it yourself
SENSITIVE_MOUNTS = {"/": "host root filesystem", "/etc": "host configuration", "/root": "root's home",
                    "/var/run/docker.sock": "Docker API socket", "/run/containerd/containerd.sock": "containerd API socket",
                    "/var/lib/kubelet": "kubelet credentials and pod volumes", "/proc": "host /proc", "/var/log": "host logs"}
DANGEROUS_CAPS = {"SYS_ADMIN", "SYS_MODULE", "SYS_PTRACE", "DAC_READ_SEARCH", "SYS_RAWIO", "NET_ADMIN", "BPF"}

containers = [
    {"Name": "shop-web", "HostConfig": {"Privileged": False, "CapAdd": [], "CapDrop": ["ALL"], "PidMode": "", "NetworkMode": "bridge",
     "SecurityOpt": ["no-new-privileges"], "Binds": ["/srv/shop/static:/app/static:ro"]}, "Config": {"User": "10001"}},
    {"Name": "ci-runner", "HostConfig": {"Privileged": False, "CapAdd": [], "CapDrop": [], "PidMode": "", "NetworkMode": "bridge",
     "SecurityOpt": [], "Binds": ["/var/run/docker.sock:/var/run/docker.sock"]}, "Config": {"User": ""}},
    {"Name": "node-debug", "HostConfig": {"Privileged": True, "CapAdd": [], "CapDrop": [], "PidMode": "host", "NetworkMode": "host",
     "SecurityOpt": [], "Binds": ["/:/host"]}, "Config": {"User": "0"}},
    {"Name": "log-shipper", "HostConfig": {"Privileged": False, "CapAdd": ["DAC_READ_SEARCH"], "CapDrop": [], "PidMode": "",
     "NetworkMode": "bridge", "SecurityOpt": ["apparmor=unconfined"], "Binds": ["/var/log:/host/var/log:ro"]}, "Config": {"User": ""}},
    {"Name": "profiler", "HostConfig": {"Privileged": False, "CapAdd": ["SYS_PTRACE"], "CapDrop": [], "PidMode": "host",
     "NetworkMode": "bridge", "SecurityOpt": ["seccomp=unconfined"], "Binds": []}, "Config": {"User": "1000"}},
]

def audit(c):
    hc, out = c["HostConfig"], []
    if hc["Privileged"]:
        out.append(("CRITICAL", "privileged: no capability, seccomp, LSM or device isolation"))
    for b in hc["Binds"]:
        src, dst = b.split(":")[:2]
        if src in SENSITIVE_MOUNTS:
            ro = b.endswith(":ro")
            sev = "CRITICAL" if src.endswith(".sock") or (src == "/" and not ro) else "HIGH"
            out.append((sev, f"host mount {src} -> {dst} ({SENSITIVE_MOUNTS[src]}){' read-only' if ro else ''}"))
    caps = set(hc["CapAdd"]) & DANGEROUS_CAPS
    if caps:
        out.append(("HIGH", f"dangerous capabilities added: {sorted(caps)}"))
    if hc["PidMode"] == "host":
        sev = "CRITICAL" if "SYS_PTRACE" in hc["CapAdd"] or hc["Privileged"] else "HIGH"
        out.append((sev, "host PID namespace" + (" + SYS_PTRACE" if "SYS_PTRACE" in hc["CapAdd"] else "")))
    if hc["NetworkMode"] == "host":
        out.append(("HIGH", "host network namespace (node-local services, metadata endpoint)"))
    for opt in hc["SecurityOpt"]:
        if "unconfined" in opt:
            out.append(("MEDIUM", f"{opt}: a protection layer is off"))
    if c["Config"]["User"] in ("", "0", "root"):
        out.append(("MEDIUM", "runs as root (escape impact is host root without user namespaces)"))
    if "ALL" not in hc["CapDrop"] and not hc["Privileged"]:
        out.append(("LOW", "default capability set kept (no cap-drop ALL)"))
    return out

for c in containers:
    findings = audit(c)
    worst = min((f[0] for f in findings), key=["CRITICAL", "HIGH", "MEDIUM", "LOW"].index, default="none")
    print(f"{c['Name']}: worst {worst}")
    for sev, text in findings:
        print(f"   {sev:8} {text}")
shop-web: worst none
ci-runner: worst CRITICAL
   CRITICAL host mount /var/run/docker.sock -> /var/run/docker.sock (Docker API socket)
   MEDIUM   runs as root (escape impact is host root without user namespaces)
   LOW      default capability set kept (no cap-drop ALL)
node-debug: worst CRITICAL
   CRITICAL privileged: no capability, seccomp, LSM or device isolation
   CRITICAL host mount / -> /host (host root filesystem)
   CRITICAL host PID namespace
   HIGH     host network namespace (node-local services, metadata endpoint)
   MEDIUM   runs as root (escape impact is host root without user namespaces)
log-shipper: worst HIGH
   HIGH     host mount /var/log -> /host/var/log (host logs) read-only
   HIGH     dangerous capabilities added: ['DAC_READ_SEARCH']
   MEDIUM   apparmor=unconfined: a protection layer is off
   MEDIUM   runs as root (escape impact is host root without user namespaces)
   LOW      default capability set kept (no cap-drop ALL)
profiler: worst CRITICAL
   HIGH     dangerous capabilities added: ['SYS_PTRACE']
   CRITICAL host PID namespace + SYS_PTRACE
   MEDIUM   seccomp=unconfined: a protection layer is off
   LOW      default capability set kept (no cap-drop ALL)

Only shop-web is clean. The CI runner shows the most common real-world escape enabler: a container that can talk to the Docker daemon can ask it for a new container with any settings, including privileged with the host's root mounted, so the socket mount is equivalent to root on the host. node-debug is a debugging container that is the host in all but name; such containers exist for good reasons, and the finding is that it runs permanently instead of on demand. The log shipper combines a host mount with DAC_READ_SEARCH (the capability behind the well-known "shocker" class of escapes, which open host files by handle) and no AppArmor. The profiler can attach to every process on the host.

How escapes and their preconditions are detected

  • Before deployment: the auditor above as a policy; Pod Security baseline already forbids privileged pods, host namespaces, hostPath volumes and adding dangerous capabilities (Pod Security); IaC and manifest scanners flag the same (Trivy's KSV-0006 "hostPath volume mounted with docker.sock", KSV-0017 "Privileged", KSV-0010 "Access to host PID").
  • At runtime: events that legitimate containers rarely produce: a process in a container opening the runtime socket, mount or unshare syscalls, writes under /proc/sys or to host paths, a process whose namespace changes to the host's (setns), new privileged containers being created. These are exactly the default rules of runtime detectors like Falco (the next lesson).
  • On the host: kernel and runtime versions against known CVEs; audit logs of new containers with privileged settings (docker events, Kubernetes audit logs for pods with privileged: true).

How they are prevented

  1. Enforce Pod Security restricted (or baseline at minimum) in every application namespace; put the few system agents that need host access in dedicated namespaces with explicit exceptions.
  2. Never mount runtime sockets into application or CI containers. CI builds use rootless builders (BuildKit rootless, Kaniko-style builders) or dedicated build VMs.
  3. Mount host paths only when unavoidable, as specific files, read-only, and never /, /etc, /proc, /sys or kubelet directories.
  4. Keep the kernel and runtime patched (node image updates on managed Kubernetes are the customer's job, Shared Responsibility), and keep seccomp, LSMs and non-root users so the next kernel bug has less to work with.
  5. For untrusted code, use sandboxed runtimes with their own kernel (gVisor, Kata Containers, Firecracker-based microVMs): the shared-kernel class then largely disappears.

Pitfalls

  • "Read-only" host mounts of sensitive paths: reading /var/lib/kubelet or /etc/kubernetes yields credentials, and read-only sockets still accept API calls.
  • Treating debug containers as temporary while they run for months.
  • Believing patches remove the class: the next kernel bug will look the same; the layered defences are what turn it from "host compromise" into "failed attempt".

Practice

1. Change ci-runner's bind to /var/run/docker.sock:/var/run/docker.sock:ro. Does the auditor lower the severity? Should it?

No, it stays CRITICAL (the rule treats sockets as critical regardless), and that is right: :ro only stops writing to the socket file; connecting and sending API requests still works.

2. Add a container with "CapAdd": ["SYS_ADMIN"] and no other changes. What does the auditor report, and which escape class does it enable?

HIGH dangerous capabilities added: ['SYS_ADMIN'], plus the root and default-capability findings. SYS_ADMIN allows mount operations and much more; combined with missing seccomp/AppArmor, it opens mount-based escape classes.

3. Which runtime events would you alert on to catch the CI runner being abused?

A process in the CI container connecting to /var/run/docker.sock outside a build step, and new containers created by the Docker daemon with Privileged: true or a bind of /. Better still: remove the socket and the alert has nothing to catch.

Test yourself

Why is mounting /var/run/docker.sock into a container equivalent to host root?

  1. The socket file contains passwords
  2. Whoever can talk to the Docker API can start a new privileged container with the host's filesystem mounted
  3. It disables seccomp
  4. It doesn't matter if mounted read-only

Which escape classes are vulnerabilities rather than configuration?

  1. Privileged containers and host mounts
  2. Kernel and runtime bugs such as Dirty Pipe or runc CVE-2019-5736
  3. hostPID
  4. Dangerous capabilities

Which Pod Security level already forbids privileged pods, host namespaces and hostPath volumes?

  1. privileged
  2. baseline
  3. none
  4. unrestricted

What reduces the shared-kernel escape class for untrusted code?

  1. Bigger nodes
  2. Sandboxed runtimes with their own kernel (gVisor, Kata, microVMs)
  3. More CPU limits
  4. Using the latest tag