container security

Hardening Docker Containers for Production

Hardening Docker containers for production involves applying security best practices aligned with CIS Docker Benchmark v1.8.0 to minimize attack surface, prevent privilege escalation, and enforce least-privilege principles across Docker daemon, images, containers, and runtime configurations.

cis-benchmarkcontainersdockerhardeningsecurity
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Overview

Hardening Docker containers for production involves applying security best practices aligned with CIS Docker Benchmark v1.8.0 to minimize attack surface, prevent privilege escalation, and enforce least-privilege principles across Docker daemon, images, containers, and runtime configurations.

When to Use

  • When deploying or configuring hardening docker containers for production capabilities in your environment
  • When establishing security controls aligned to compliance requirements
  • When building or improving security architecture for this domain
  • When conducting security assessments that require this implementation

Prerequisites

  • Docker Engine 24.0+ installed
  • Docker Compose v2
  • Linux host with kernel 5.10+
  • Root or sudo access on Docker host
  • docker-bench-security tool
  • Hadolint for Dockerfile linting
  • Dockle for image linting

Core Concepts

CIS Docker Benchmark Sections

  1. Host Configuration - Audit Docker daemon files, restrict access to /var/run/docker.sock
  2. Docker Daemon Configuration - Enable TLS, restrict inter-container communication, configure logging
  3. Docker Daemon Configuration Files - Set ownership and permissions on daemon.json
  4. Container Images and Build File - Use trusted base images, scan for vulnerabilities, multi-stage builds
  5. Container Runtime - Drop capabilities, read-only rootfs, restrict syscalls
  6. Docker Security Operations - Monitor, audit, and rotate credentials

Key Hardening Principles

  • Least Privilege: Run containers as non-root, drop all capabilities except required
  • Immutability: Use read-only root filesystem, tmpfs for writable directories
  • Minimalism: Use distroless or Alpine base images, multi-stage builds
  • Isolation: Apply seccomp profiles, AppArmor/SELinux, namespace restrictions
  • Auditability: Enable content trust, log all container activity

Workflow

Step 1: Harden the Dockerfile

# Use specific digest for reproducibility
FROM python:3.12-slim@sha256:abc123... AS builder
 
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir --user -r requirements.txt
 
# Production stage - minimal image
FROM gcr.io/distroless/python3-debian12
 
# Copy only necessary artifacts
COPY --from=builder /root/.local /root/.local
COPY --from=builder /app /app
 
WORKDIR /app
 
# Create non-root user
USER 65534:65534
 
# Set read-only filesystem expectation
LABEL org.opencontainers.image.source="https://github.com/org/app"
 
ENTRYPOINT ["python", "app.py"]

Step 2: Harden Docker Daemon Configuration

{
  "icc": false,
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
  },
  "live-restore": true,
  "userland-proxy": false,
  "no-new-privileges": true,
  "default-ulimits": {
    "nofile": {
      "Name": "nofile",
      "Hard": 64000,
      "Soft": 64000
    },
    "nproc": {
      "Name": "nproc",
      "Hard": 1024,
      "Soft": 1024
    }
  },
  "seccomp-profile": "/etc/docker/seccomp-default.json",
  "tls": true,
  "tlscacert": "/etc/docker/tls/ca.pem",
  "tlscert": "/etc/docker/tls/server-cert.pem",
  "tlskey": "/etc/docker/tls/server-key.pem",
  "tlsverify": true
}

Step 3: Harden Container Runtime

docker run -d \
  --name production-app \
  --read-only \
  --tmpfs /tmp:rw,noexec,nosuid,size=100m \
  --tmpfs /var/run:rw,noexec,nosuid,size=10m \
  --cap-drop ALL \
  --cap-add NET_BIND_SERVICE \
  --security-opt no-new-privileges:true \
  --security-opt seccomp=/etc/docker/seccomp-default.json \
  --security-opt apparmor=docker-default \
  --pids-limit 100 \
  --memory 512m \
  --memory-swap 512m \
  --cpus 1.0 \
  --user 65534:65534 \
  --network custom-bridge \
  --restart on-failure:3 \
  --health-cmd "curl -f http://localhost:8080/health || exit 1" \
  --health-interval 30s \
  --health-timeout 10s \
  --health-retries 3 \
  myapp:latest

Step 4: Enable Docker Content Trust

export DOCKER_CONTENT_TRUST=1
export DOCKER_CONTENT_TRUST_SERVER=https://notary.example.com
 
# Sign and push image
docker trust sign myregistry.com/myapp:v1.0.0
 
# Verify image signature before pull
docker trust inspect --pretty myregistry.com/myapp:v1.0.0

Step 5: Configure Host-Level Auditing

# Add audit rules for Docker files and directories
cat >> /etc/audit/rules.d/docker.rules << 'EOF'
-w /usr/bin/docker -k docker
-w /var/lib/docker -k docker
-w /etc/docker -k docker
-w /lib/systemd/system/docker.service -k docker
-w /lib/systemd/system/docker.socket -k docker
-w /etc/default/docker -k docker
-w /etc/docker/daemon.json -k docker
-w /usr/bin/containerd -k docker
-w /usr/bin/runc -k docker
EOF
 
systemctl restart auditd

Validation Commands

# Run Docker Bench Security
docker run --rm --net host --pid host \
  --userns host --cap-add audit_control \
  -e DOCKER_CONTENT_TRUST=$DOCKER_CONTENT_TRUST \
  -v /etc:/etc:ro \
  -v /usr/bin/containerd:/usr/bin/containerd:ro \
  -v /usr/bin/runc:/usr/bin/runc:ro \
  -v /usr/lib/systemd:/usr/lib/systemd:ro \
  -v /var/lib:/var/lib:ro \
  -v /var/run/docker.sock:/var/run/docker.sock:ro \
  docker/docker-bench-security
 
# Lint Dockerfile
hadolint Dockerfile
 
# Lint built image
dockle myapp:latest
 
# Verify no containers running as root
docker ps -q | xargs docker inspect --format '{{.Id}}: User={{.Config.User}}'

Key Security Controls

Control Implementation CIS Section
Non-root user USER instruction in Dockerfile 4.1
Read-only rootfs --read-only flag 5.12
Drop capabilities --cap-drop ALL 5.3
Resource limits --memory, --cpus, --pids-limit 5.10
No new privileges --security-opt no-new-privileges 5.25
Content trust DOCKER_CONTENT_TRUST=1 4.5
TLS for daemon daemon.json TLS config 2.6
Audit logging auditd rules 1.1

References

Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 3

api-reference.md1.8 KB

API Reference: Docker Container Hardening

Docker CLI

List Containers

docker ps --format '{{json .}}'

Inspect Container

docker inspect <container_id>

Key Inspect Fields

Path Description
.HostConfig.Privileged Privileged mode
.HostConfig.NetworkMode Network namespace
.HostConfig.CapAdd Added capabilities
.HostConfig.ReadonlyRootfs Read-only filesystem
.HostConfig.Memory Memory limit (bytes)
.Config.User Container user

CIS Docker Benchmark Checks

Check Description Severity
4.1 Non-root user HIGH
5.3 Restrict capabilities HIGH
5.4 No privileged containers CRITICAL
5.5 No sensitive host mounts HIGH
5.10 No host network HIGH
5.12 Read-only root FS MEDIUM
5.13 CPU limits set LOW
5.14 Memory limits set MEDIUM

Secure Dockerfile Practices

Non-Root User

FROM alpine:3.18
RUN adduser -D appuser
USER appuser

Read-Only Filesystem

docker run --read-only --tmpfs /tmp:rw,noexec,nosuid myimage

Drop Capabilities

docker run --cap-drop ALL --cap-add NET_BIND_SERVICE myimage

Resource Limits

docker run --memory=512m --cpus=1.0 myimage

Docker Bench Security

Run Audit

docker run --rm --net host --pid host --userns host \
    --cap-add audit_control \
    -v /var/lib:/var/lib \
    -v /var/run/docker.sock:/var/run/docker.sock \
    -v /etc:/etc \
    docker/docker-bench-security

Seccomp and AppArmor

Custom Seccomp Profile

docker run --security-opt seccomp=profile.json myimage

AppArmor Profile

docker run --security-opt apparmor=docker-default myimage
standards.md3.6 KB

Standards Reference - Docker Container Hardening

CIS Docker Benchmark v1.8.0

Section 1: Host Configuration

  • 1.1.1: Ensure a separate partition for containers has been created
  • 1.1.2: Ensure only trusted users are allowed to control Docker daemon
  • 1.1.3-1.1.18: Ensure Docker daemon audit configuration

Section 2: Docker Daemon Configuration

  • 2.1: Run the Docker daemon as non-root user (rootless mode)
  • 2.2: Ensure network traffic is restricted between containers (--icc=false)
  • 2.3: Ensure logging level is set to info
  • 2.4: Ensure Docker is allowed to make changes to iptables
  • 2.5: Ensure insecure registries are not used
  • 2.6: Ensure aufs storage driver is not used
  • 2.7: Ensure TLS authentication for Docker daemon is configured
  • 2.8: Ensure default ulimit is configured appropriately
  • 2.9: Enable user namespace support
  • 2.10: Ensure default cgroup usage has been confirmed
  • 2.11: Ensure base device size is not changed until needed
  • 2.12: Ensure centralized and remote logging is configured
  • 2.13: Ensure live restore is enabled
  • 2.14: Ensure Userland Proxy is disabled
  • 2.15: Ensure daemon-wide custom seccomp profile is applied
  • 2.16: Ensure experimental features are not used in production
  • 2.17: Ensure containers are restricted from acquiring new privileges

Section 4: Container Images and Build Files

  • 4.1: Ensure that a user for the container has been created
  • 4.2: Ensure containers use trusted base images
  • 4.3: Ensure unnecessary packages are not installed
  • 4.4: Ensure images are scanned for vulnerabilities
  • 4.5: Ensure Content trust for Docker is enabled
  • 4.6: Ensure HEALTHCHECK instructions have been added to container images
  • 4.7: Ensure update instructions are not used alone in the Dockerfile
  • 4.8: Ensure setuid and setgid permissions are removed
  • 4.9: Ensure COPY is used instead of ADD
  • 4.10: Ensure secrets are not stored in Dockerfiles
  • 4.11: Ensure only verified packages are installed

Section 5: Container Runtime

  • 5.1: Ensure AppArmor profile is enabled
  • 5.2: Ensure SELinux security options are set
  • 5.3: Ensure Linux kernel capabilities are restricted
  • 5.4: Ensure privileged containers are not used
  • 5.5: Ensure sensitive host system directories are not mounted
  • 5.6: Ensure sshd is not running within containers
  • 5.7: Ensure privileged ports are not mapped within containers
  • 5.8: Ensure only needed ports are open on the container
  • 5.9: Ensure host network mode is not used
  • 5.10: Ensure memory usage for container is limited
  • 5.11: Ensure CPU priority is set appropriately
  • 5.12: Ensure container root filesystem is mounted as read only
  • 5.13: Ensure incoming container traffic is bound to a specific host interface
  • 5.25: Ensure container is restricted from acquiring additional privileges

NIST SP 800-190 - Application Container Security Guide

Key Recommendations

  • Use container-specific host OS (CoreOS, Flatcar, Bottlerocket)
  • Segment container networks by sensitivity level
  • Use container runtime with minimal attack surface
  • Implement image signing and verification
  • Harden container registries with access controls
  • Monitor container runtime behavior for anomalies

OWASP Docker Security Cheat Sheet

Top Docker Security Risks

  1. Unrestricted container access to host resources
  2. Running containers in privileged mode
  3. Running as root inside containers
  4. Unverified or unscanned container images
  5. Exposed Docker daemon socket
  6. Insecure container networking
  7. Secrets stored in images or environment variables
  8. Missing resource limits
  9. Outdated base images with known vulnerabilities
  10. Insufficient logging and monitoring
workflows.md4.2 KB

Workflows - Docker Container Hardening

Workflow 1: New Container Hardening Pipeline

[Dockerfile Created] --> [Hadolint Lint] --> [Build Image] --> [Dockle Scan]
        |                      |                    |               |
        v                      v                    v               v
  Use multi-stage        Fix warnings         Tag with digest   Fix findings
  Non-root USER          No ADD, use COPY     Sign image        Remove setuid
  Minimal base           Pin versions         Push to registry  Drop caps
        |                      |                    |               |
        +----------+-----------+--------------------+               |
                   |                                                |
                   v                                                v
          [Trivy Vulnerability Scan] -----> [Docker Bench Assessment]
                   |                                    |
                   v                                    v
          Fix HIGH/CRITICAL CVEs              Remediate CIS failures
                   |                                    |
                   +------------------------------------+
                   |
                   v
          [Deploy to Production with Hardened Runtime Flags]
                   |
                   v
          [Continuous Monitoring with Falco]

Workflow 2: Existing Container Remediation

Step 1: Assess Current State
  - Run docker-bench-security against host
  - Run Trivy scan against all running images
  - Audit all running containers for root users
  - Check daemon.json configuration
 
Step 2: Prioritize Remediation
  - Critical: Privileged containers, root users, exposed daemon socket
  - High: Missing seccomp profiles, no resource limits, capability escalation
  - Medium: Missing health checks, no content trust, excessive open ports
  - Low: Missing labels, audit rules, log rotation
 
Step 3: Apply Fixes
  - Update Dockerfiles with non-root users
  - Rebuild images with multi-stage builds
  - Update docker-compose or orchestrator configs
  - Configure daemon.json with TLS and security options
 
Step 4: Validate
  - Re-run docker-bench-security
  - Confirm score improvement
  - Document remaining accepted risks

Workflow 3: CI/CD Integration

# GitHub Actions hardening pipeline
name: Container Hardening Pipeline
on: [push]
 
jobs:
  lint-dockerfile:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: hadolint/hadolint-action@v3.1.0
        with:
          dockerfile: Dockerfile
 
  build-and-scan:
    needs: lint-dockerfile
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Build image
        run: docker build -t myapp:${{ github.sha }} .
 
      - name: Dockle lint
        uses: erzz/dockle-action@v1
        with:
          image: myapp:${{ github.sha }}
          failure-threshold: WARN
 
      - name: Trivy scan
        uses: aquasecurity/trivy-action@master
        with:
          image-ref: myapp:${{ github.sha }}
          format: table
          exit-code: 1
          severity: CRITICAL,HIGH
 
      - name: Sign image with Cosign
        if: github.ref == 'refs/heads/main'
        uses: sigstore/cosign-installer@v3
        run: cosign sign --yes myapp:${{ github.sha }}

Workflow 4: Runtime Hardening Checklist

Pre-deployment:
  [ ] Image built from minimal base (distroless/Alpine)
  [ ] Non-root USER specified in Dockerfile
  [ ] No secrets in image layers
  [ ] Image signed and verified
  [ ] Vulnerability scan shows no CRITICAL/HIGH CVEs
  [ ] Hadolint and Dockle pass with zero errors
 
Runtime configuration:
  [ ] --read-only flag enabled
  [ ] --cap-drop ALL with minimum cap-add
  [ ] --security-opt no-new-privileges:true
  [ ] --security-opt seccomp=<profile>
  [ ] --memory and --cpus limits set
  [ ] --pids-limit configured
  [ ] --user flag set to non-root UID
  [ ] --tmpfs for writable directories only
  [ ] Health check configured
  [ ] Restart policy set (on-failure with max retries)
 
Host configuration:
  [ ] Docker daemon TLS enabled
  [ ] Inter-container communication disabled (icc=false)
  [ ] User namespace remapping enabled
  [ ] Audit rules for Docker binaries and directories
  [ ] Docker socket not exposed to containers

Scripts 2

agent.py4.9 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Agent for auditing Docker container security and applying CIS hardening."""

import argparse
import json
import subprocess
import sys
from datetime import datetime, timezone


def get_running_containers():
    """List running Docker containers with details."""
    try:
        result = subprocess.check_output(
            ["docker", "ps", "--format", "{{json .}}"],
            text=True, errors="replace", timeout=10
        )
        containers = []
        for line in result.strip().splitlines():
            if line:
                containers.append(json.loads(line))
        return containers
    except (subprocess.SubprocessError, json.JSONDecodeError):
        return []


def inspect_container(container_id):
    """Get detailed container configuration."""
    try:
        result = subprocess.check_output(
            ["docker", "inspect", container_id],
            text=True, errors="replace", timeout=10
        )
        return json.loads(result)[0]
    except (subprocess.SubprocessError, json.JSONDecodeError):
        return {}


def audit_container(container_id):
    """Audit a container against CIS Docker Benchmark checks."""
    findings = []
    config = inspect_container(container_id)
    if not config:
        return findings
    host_config = config.get("HostConfig", {})
    name = config.get("Name", container_id)

    if host_config.get("Privileged"):
        findings.append({"check": "CIS 5.4", "issue": "Container runs privileged", "severity": "CRITICAL"})
    if host_config.get("NetworkMode") == "host":
        findings.append({"check": "CIS 5.10", "issue": "Uses host network", "severity": "HIGH"})
    if host_config.get("PidMode") == "host":
        findings.append({"check": "CIS 5.15", "issue": "Shares host PID namespace", "severity": "HIGH"})
    if host_config.get("IpcMode") == "host":
        findings.append({"check": "CIS 5.16", "issue": "Shares host IPC namespace", "severity": "HIGH"})

    user = config.get("Config", {}).get("User", "")
    if not user or user == "root" or user == "0":
        findings.append({"check": "CIS 4.1", "issue": "Container runs as root", "severity": "HIGH"})

    cap_add = host_config.get("CapAdd") or []
    if "SYS_ADMIN" in cap_add:
        findings.append({"check": "CIS 5.3", "issue": "SYS_ADMIN capability added", "severity": "CRITICAL"})
    if "NET_ADMIN" in cap_add:
        findings.append({"check": "CIS 5.3", "issue": "NET_ADMIN capability added", "severity": "HIGH"})

    if not host_config.get("ReadonlyRootfs"):
        findings.append({"check": "CIS 5.12", "issue": "Root filesystem not read-only", "severity": "MEDIUM"})

    memory = host_config.get("Memory", 0)
    if memory == 0:
        findings.append({"check": "CIS 5.14", "issue": "No memory limit set", "severity": "MEDIUM"})

    cpu_shares = host_config.get("CpuShares", 0)
    if cpu_shares == 0:
        findings.append({"check": "CIS 5.13", "issue": "No CPU limit set", "severity": "LOW"})

    restart = host_config.get("RestartPolicy", {}).get("Name", "")
    if restart == "always":
        findings.append({"check": "CIS 5.14", "issue": "RestartPolicy=always (use on-failure)", "severity": "LOW"})

    mounts = host_config.get("Binds") or []
    sensitive = ["/", "/etc", "/var/run/docker.sock", "/proc", "/sys"]
    for mount in mounts:
        src = mount.split(":")[0]
        if src in sensitive:
            findings.append({"check": "CIS 5.5", "issue": f"Sensitive host mount: {src}", "severity": "HIGH"})

    return findings


def main():
    parser = argparse.ArgumentParser(
        description="Audit Docker containers against CIS benchmarks"
    )
    parser.add_argument("--container", help="Specific container ID to audit")
    parser.add_argument("--all", action="store_true", help="Audit all running containers")
    parser.add_argument("--output", "-o", help="Output JSON report")
    args = parser.parse_args()

    print("[*] Docker Container Hardening Audit Agent")
    report = {"timestamp": datetime.now(timezone.utc).isoformat(), "audits": []}

    if args.all:
        containers = get_running_containers()
        print(f"[*] Found {len(containers)} running containers")
        for c in containers:
            cid = c.get("ID", "")
            findings = audit_container(cid)
            report["audits"].append({"container": c.get("Names", cid), "findings": findings})
    elif args.container:
        findings = audit_container(args.container)
        report["audits"].append({"container": args.container, "findings": findings})

    total = sum(len(a["findings"]) for a in report["audits"])
    critical = sum(1 for a in report["audits"] for f in a["findings"] if f["severity"] == "CRITICAL")
    print(f"[*] Total findings: {total} (CRITICAL: {critical})")

    if args.output:
        with open(args.output, "w") as f:
            json.dump(report, f, indent=2)
        print(f"[*] Report saved to {args.output}")
    else:
        print(json.dumps(report, indent=2))


if __name__ == "__main__":
    main()
process.py14.8 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
Docker Container Hardening Assessment Tool

Audits Docker daemon configuration, running containers, and images
against CIS Docker Benchmark v1.8.0 hardening requirements.
"""

import subprocess
import json
import sys
import os
import re
from dataclasses import dataclass, field
from typing import Optional


@dataclass
class Finding:
    check_id: str
    title: str
    severity: str  # CRITICAL, HIGH, MEDIUM, LOW, INFO
    status: str    # PASS, FAIL, WARN, INFO
    details: str
    remediation: str


@dataclass
class HardeningReport:
    findings: list = field(default_factory=list)
    total_pass: int = 0
    total_fail: int = 0
    total_warn: int = 0

    def add(self, finding: Finding):
        self.findings.append(finding)
        if finding.status == "PASS":
            self.total_pass += 1
        elif finding.status == "FAIL":
            self.total_fail += 1
        elif finding.status == "WARN":
            self.total_warn += 1


def run_command(cmd: list, timeout: int = 30) -> tuple:
    """Execute a shell command and return (returncode, stdout, stderr)."""
    try:
        result = subprocess.run(
            cmd, capture_output=True, text=True, timeout=timeout
        )
        return result.returncode, result.stdout.strip(), result.stderr.strip()
    except subprocess.TimeoutExpired:
        return -1, "", "Command timed out"
    except FileNotFoundError:
        return -1, "", f"Command not found: {cmd[0]}"


def check_docker_available() -> bool:
    """Verify Docker is installed and accessible."""
    rc, out, _ = run_command(["docker", "version", "--format", "{{.Server.Version}}"])
    if rc == 0:
        print(f"[*] Docker version: {out}")
        return True
    print("[!] Docker is not available or not running")
    return False


def check_daemon_config(report: HardeningReport):
    """Check Docker daemon.json configuration against CIS benchmarks."""
    daemon_config_path = "/etc/docker/daemon.json"

    if not os.path.exists(daemon_config_path):
        report.add(Finding(
            check_id="2.0",
            title="Docker daemon configuration file exists",
            severity="HIGH",
            status="FAIL",
            details="daemon.json not found at /etc/docker/daemon.json",
            remediation="Create /etc/docker/daemon.json with security-hardened settings"
        ))
        return

    with open(daemon_config_path, "r") as f:
        try:
            config = json.load(f)
        except json.JSONDecodeError:
            report.add(Finding(
                check_id="2.0",
                title="Docker daemon configuration is valid JSON",
                severity="HIGH",
                status="FAIL",
                details="daemon.json contains invalid JSON",
                remediation="Fix JSON syntax in /etc/docker/daemon.json"
            ))
            return

    # Check 2.2: Inter-container communication
    icc = config.get("icc", True)
    report.add(Finding(
        check_id="2.2",
        title="Network traffic restricted between containers",
        severity="HIGH",
        status="PASS" if icc is False else "FAIL",
        details=f"icc is set to {icc}",
        remediation='Set "icc": false in daemon.json to restrict inter-container communication'
    ))

    # Check 2.7: TLS authentication
    tls_verify = config.get("tlsverify", False)
    report.add(Finding(
        check_id="2.7",
        title="TLS authentication for Docker daemon",
        severity="CRITICAL",
        status="PASS" if tls_verify else "FAIL",
        details=f"tlsverify is {tls_verify}",
        remediation='Enable TLS: set "tls": true, "tlsverify": true with cert paths in daemon.json'
    ))

    # Check 2.13: Live restore
    live_restore = config.get("live-restore", False)
    report.add(Finding(
        check_id="2.13",
        title="Live restore is enabled",
        severity="MEDIUM",
        status="PASS" if live_restore else "WARN",
        details=f"live-restore is {live_restore}",
        remediation='Set "live-restore": true in daemon.json'
    ))

    # Check 2.14: Userland proxy disabled
    userland_proxy = config.get("userland-proxy", True)
    report.add(Finding(
        check_id="2.14",
        title="Userland Proxy is disabled",
        severity="MEDIUM",
        status="PASS" if userland_proxy is False else "WARN",
        details=f"userland-proxy is {userland_proxy}",
        remediation='Set "userland-proxy": false in daemon.json'
    ))

    # Check 2.17: No new privileges
    no_new_privs = config.get("no-new-privileges", False)
    report.add(Finding(
        check_id="2.17",
        title="Containers restricted from acquiring new privileges",
        severity="HIGH",
        status="PASS" if no_new_privs else "FAIL",
        details=f"no-new-privileges is {no_new_privs}",
        remediation='Set "no-new-privileges": true in daemon.json'
    ))

    # Check logging configuration
    log_driver = config.get("log-driver", "json-file")
    log_opts = config.get("log-opts", {})
    has_log_limits = "max-size" in log_opts and "max-file" in log_opts
    report.add(Finding(
        check_id="2.12",
        title="Logging is properly configured with rotation",
        severity="MEDIUM",
        status="PASS" if has_log_limits else "WARN",
        details=f"log-driver={log_driver}, max-size={log_opts.get('max-size', 'not set')}, max-file={log_opts.get('max-file', 'not set')}",
        remediation='Configure log-opts with max-size and max-file in daemon.json'
    ))


def check_running_containers(report: HardeningReport):
    """Audit running containers against CIS runtime checks."""
    rc, out, _ = run_command([
        "docker", "ps", "-q"
    ])
    if rc != 0 or not out:
        report.add(Finding(
            check_id="5.0",
            title="Running containers found",
            severity="INFO",
            status="INFO",
            details="No running containers found to audit",
            remediation="N/A"
        ))
        return

    container_ids = out.split("\n")
    print(f"[*] Auditing {len(container_ids)} running containers")

    for cid in container_ids:
        rc, inspect_out, _ = run_command([
            "docker", "inspect", cid
        ])
        if rc != 0:
            continue

        try:
            container = json.loads(inspect_out)[0]
        except (json.JSONDecodeError, IndexError):
            continue

        name = container.get("Name", cid).lstrip("/")
        host_config = container.get("HostConfig", {})
        config = container.get("Config", {})

        # Check 5.4: Privileged mode
        privileged = host_config.get("Privileged", False)
        report.add(Finding(
            check_id="5.4",
            title=f"[{name}] Not running in privileged mode",
            severity="CRITICAL",
            status="PASS" if not privileged else "FAIL",
            details=f"Privileged={privileged}",
            remediation="Remove --privileged flag. Use specific --cap-add instead."
        ))

        # Check 5.3: Capabilities
        cap_add = host_config.get("CapAdd") or []
        cap_drop = host_config.get("CapDrop") or []
        all_dropped = "ALL" in [c.upper() for c in cap_drop] if cap_drop else False
        report.add(Finding(
            check_id="5.3",
            title=f"[{name}] Linux capabilities are restricted",
            severity="HIGH",
            status="PASS" if all_dropped else "FAIL",
            details=f"CapDrop={cap_drop}, CapAdd={cap_add}",
            remediation="Use --cap-drop ALL and only --cap-add specific required capabilities"
        ))

        # Check 5.12: Read-only root filesystem
        read_only = host_config.get("ReadonlyRootfs", False)
        report.add(Finding(
            check_id="5.12",
            title=f"[{name}] Root filesystem is read-only",
            severity="HIGH",
            status="PASS" if read_only else "FAIL",
            details=f"ReadonlyRootfs={read_only}",
            remediation="Run with --read-only and use --tmpfs for writable directories"
        ))

        # Check 4.1: Non-root user
        user = config.get("User", "")
        report.add(Finding(
            check_id="4.1",
            title=f"[{name}] Running as non-root user",
            severity="HIGH",
            status="PASS" if user and user != "0" and user != "root" else "FAIL",
            details=f"User={user if user else 'root (default)'}",
            remediation="Set USER in Dockerfile or use --user flag at runtime"
        ))

        # Check 5.10: Memory limit
        memory = host_config.get("Memory", 0)
        report.add(Finding(
            check_id="5.10",
            title=f"[{name}] Memory usage is limited",
            severity="MEDIUM",
            status="PASS" if memory > 0 else "FAIL",
            details=f"Memory limit={memory} bytes" if memory > 0 else "No memory limit set",
            remediation="Set --memory flag to limit container memory usage"
        ))

        # Check 5.25: No new privileges
        security_opts = host_config.get("SecurityOpt") or []
        no_new_privs = any("no-new-privileges" in opt for opt in security_opts)
        report.add(Finding(
            check_id="5.25",
            title=f"[{name}] No new privileges restriction",
            severity="HIGH",
            status="PASS" if no_new_privs else "FAIL",
            details=f"SecurityOpt={security_opts}",
            remediation="Use --security-opt no-new-privileges:true"
        ))

        # Check 5.28: PID limits
        pids_limit = host_config.get("PidsLimit", 0)
        report.add(Finding(
            check_id="5.28",
            title=f"[{name}] PIDs limit is set",
            severity="MEDIUM",
            status="PASS" if pids_limit and pids_limit > 0 else "WARN",
            details=f"PidsLimit={pids_limit}",
            remediation="Set --pids-limit to prevent fork bomb attacks"
        ))

        # Check health check
        healthcheck = config.get("Healthcheck", {})
        has_healthcheck = bool(healthcheck and healthcheck.get("Test"))
        report.add(Finding(
            check_id="4.6",
            title=f"[{name}] Health check is configured",
            severity="LOW",
            status="PASS" if has_healthcheck else "WARN",
            details=f"Healthcheck configured: {has_healthcheck}",
            remediation="Add HEALTHCHECK instruction in Dockerfile"
        ))


def check_docker_socket(report: HardeningReport):
    """Check if Docker socket is exposed to any container."""
    rc, out, _ = run_command([
        "docker", "ps", "-q"
    ])
    if rc != 0 or not out:
        return

    for cid in out.split("\n"):
        rc, inspect_out, _ = run_command(["docker", "inspect", cid])
        if rc != 0:
            continue

        try:
            container = json.loads(inspect_out)[0]
        except (json.JSONDecodeError, IndexError):
            continue

        name = container.get("Name", cid).lstrip("/")
        mounts = container.get("Mounts", [])

        for mount in mounts:
            source = mount.get("Source", "")
            if "docker.sock" in source:
                report.add(Finding(
                    check_id="5.31",
                    title=f"[{name}] Docker socket mounted",
                    severity="CRITICAL",
                    status="FAIL",
                    details=f"Docker socket mounted from {source}",
                    remediation="Remove Docker socket mount. Use Docker API proxy with restricted access."
                ))
                break


def check_content_trust(report: HardeningReport):
    """Check if Docker Content Trust is enabled."""
    dct = os.environ.get("DOCKER_CONTENT_TRUST", "0")
    report.add(Finding(
        check_id="4.5",
        title="Docker Content Trust is enabled",
        severity="HIGH",
        status="PASS" if dct == "1" else "FAIL",
        details=f"DOCKER_CONTENT_TRUST={dct}",
        remediation="Set DOCKER_CONTENT_TRUST=1 environment variable"
    ))


def generate_report(report: HardeningReport) -> dict:
    """Generate JSON report from findings."""
    score = (report.total_pass / max(len(report.findings), 1)) * 100

    output = {
        "tool": "Docker Hardening Assessment",
        "framework": "CIS Docker Benchmark v1.8.0",
        "summary": {
            "total_checks": len(report.findings),
            "passed": report.total_pass,
            "failed": report.total_fail,
            "warnings": report.total_warn,
            "score_percent": round(score, 1)
        },
        "findings": []
    }

    for f in report.findings:
        output["findings"].append({
            "check_id": f.check_id,
            "title": f.title,
            "severity": f.severity,
            "status": f.status,
            "details": f.details,
            "remediation": f.remediation
        })

    return output


def print_summary(report_data: dict):
    """Print human-readable summary."""
    summary = report_data["summary"]
    print("\n" + "=" * 70)
    print("DOCKER HARDENING ASSESSMENT REPORT")
    print(f"Framework: {report_data['framework']}")
    print("=" * 70)
    print(f"Total Checks:  {summary['total_checks']}")
    print(f"Passed:        {summary['passed']}")
    print(f"Failed:        {summary['failed']}")
    print(f"Warnings:      {summary['warnings']}")
    print(f"Score:         {summary['score_percent']}%")
    print("=" * 70)

    # Print failures
    failures = [f for f in report_data["findings"] if f["status"] == "FAIL"]
    if failures:
        print("\nFAILED CHECKS:")
        print("-" * 70)
        for f in sorted(failures, key=lambda x: {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "LOW": 3}.get(x["severity"], 4)):
            print(f"  [{f['severity']}] {f['check_id']}: {f['title']}")
            print(f"    Details: {f['details']}")
            print(f"    Fix: {f['remediation']}")
            print()


def main():
    print("[*] Docker Container Hardening Assessment Tool")
    print("[*] Based on CIS Docker Benchmark v1.8.0\n")

    if not check_docker_available():
        sys.exit(1)

    report = HardeningReport()

    print("[*] Checking daemon configuration...")
    check_daemon_config(report)

    print("[*] Checking Docker Content Trust...")
    check_content_trust(report)

    print("[*] Auditing running containers...")
    check_running_containers(report)

    print("[*] Checking Docker socket exposure...")
    check_docker_socket(report)

    report_data = generate_report(report)
    print_summary(report_data)

    # Save JSON report
    output_file = "docker_hardening_report.json"
    with open(output_file, "w") as f:
        json.dump(report_data, f, indent=2)
    print(f"\n[*] Full report saved to {output_file}")

    # Exit with failure if critical/high findings
    critical_high_failures = [
        f for f in report_data["findings"]
        if f["status"] == "FAIL" and f["severity"] in ("CRITICAL", "HIGH")
    ]
    if critical_high_failures:
        print(f"\n[!] {len(critical_high_failures)} CRITICAL/HIGH failures found")
        sys.exit(1)

    print("\n[+] Assessment complete")


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 2.8 KB
Keep exploring