container security

Detecting Container Escape Attempts

Container escape is a critical attack technique where an adversary breaks out of container isolation to access the host system or other containers. Detection involves monitoring for escape indicators such as namespace manipulation, capability abuse, kernel exploits, mounted sensitive paths, and anomalous syscall patterns using runtime security tools like Falco, Sysdig, and custom seccomp/audit rules.

containersdockerescape-detectionkubernetesruntime-securitysecurity
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Overview

Container escape is a critical attack technique where an adversary breaks out of container isolation to access the host system or other containers. Detection involves monitoring for escape indicators such as namespace manipulation, capability abuse, kernel exploits, mounted sensitive paths, and anomalous syscall patterns using runtime security tools like Falco, Sysdig, and custom seccomp/audit rules.

When to Use

  • When investigating security incidents that require detecting container escape attempts
  • When building detection rules or threat hunting queries for this domain
  • When SOC analysts need structured procedures for this analysis type
  • When validating security monitoring coverage for related attack techniques

Prerequisites

  • Linux host with kernel 5.10+ (eBPF support)
  • Falco 0.37+ installed (kernel module or eBPF probe)
  • Docker Engine or containerd runtime
  • auditd configured
  • Root access for eBPF/kernel module loading

Core Concepts

Common Container Escape Vectors

Vector Technique MITRE ID
Privileged containers Mount host filesystem, load kernel modules T1611
Docker socket mount Create privileged container from within T1610
Kernel exploits CVE-2022-0185 (fsconfig), Dirty Pipe, runc CVEs T1068
Capability abuse CAP_SYS_ADMIN, CAP_SYS_PTRACE, CAP_NET_ADMIN T1548
Sensitive mounts /proc/sysrq-trigger, /proc/kcore, cgroup release_agent T1611
Namespace escape nsenter, unshare to host namespaces T1611
Symlink/bind mount Escape through /proc/self/root T1611

Detection Layers

  1. Syscall monitoring - eBPF/kernel module captures syscalls in real-time
  2. File integrity - Detect modification of escape-enabling paths
  3. Process monitoring - Track process creation, namespace changes
  4. Network monitoring - Detect container-to-host connections
  5. Audit logging - Linux auditd for capability and mount operations

Workflow

Step 1: Deploy Falco for Runtime Detection

# falco-values.yaml for Helm deployment
falco:
  driver:
    kind: ebpf   # or modern_ebpf for kernel 5.8+
  rules_files:
    - /etc/falco/falco_rules.yaml
    - /etc/falco/falco_rules.local.yaml
    - /etc/falco/rules.d
  json_output: true
  json_include_output_property: true
  http_output:
    enabled: true
    url: "http://falcosidekick:2801"
  grpc:
    enabled: true
  priority: warning
# Install Falco via Helm
helm repo add falcosecurity https://falcosecurity.github.io/charts
helm install falco falcosecurity/falco \
  --namespace falco-system --create-namespace \
  -f falco-values.yaml

Step 2: Custom Falco Rules for Escape Detection

# /etc/falco/rules.d/container_escape.yaml
 
# Detect container escape via privileged container
- rule: Container Escape via Privileged Mode
  desc: Detect attempts to escape container using privileged capabilities
  condition: >
    spawned_process and container and
    (proc.name in (nsenter, unshare, mount, umount, modprobe, insmod) or
     (proc.name = chroot and proc.args contains "/host"))
  output: >
    Container escape attempt via privileged operation
    (user=%user.name container=%container.name image=%container.image.repository
     command=%proc.cmdline pid=%proc.pid %container.info)
  priority: CRITICAL
  tags: [container, escape, T1611]
 
# Detect Docker socket access from container
- rule: Container Access to Docker Socket
  desc: Detect container reading/writing to Docker socket
  condition: >
    (open_read or open_write) and container and
    fd.name = /var/run/docker.sock
  output: >
    Docker socket accessed from container
    (user=%user.name container=%container.name image=%container.image.repository
     fd=%fd.name command=%proc.cmdline %container.info)
  priority: CRITICAL
  tags: [container, escape, docker_socket]
 
# Detect sensitive proc filesystem access
- rule: Container Access to Sensitive Proc Paths
  desc: Detect container accessing host-sensitive proc paths
  condition: >
    open_read and container and
    (fd.name startswith /proc/sysrq-trigger or
     fd.name startswith /proc/kcore or
     fd.name startswith /proc/kmsg or
     fd.name startswith /proc/kallsyms or
     fd.name startswith /sys/kernel)
  output: >
    Sensitive proc/sys access from container
    (user=%user.name container=%container.name path=%fd.name
     command=%proc.cmdline %container.info)
  priority: CRITICAL
  tags: [container, escape, proc_access]
 
# Detect cgroup escape technique
- rule: Container Cgroup Escape Attempt
  desc: Detect writing to cgroup release_agent (escape technique)
  condition: >
    open_write and container and
    (fd.name contains release_agent or
     fd.name contains notify_on_release)
  output: >
    Cgroup escape attempt detected
    (user=%user.name container=%container.name path=%fd.name
     command=%proc.cmdline %container.info)
  priority: CRITICAL
  tags: [container, escape, cgroup]
 
# Detect kernel module loading from container
- rule: Container Loading Kernel Module
  desc: Detect container attempting to load kernel modules
  condition: >
    spawned_process and container and
    (proc.name in (modprobe, insmod, rmmod) or
     (evt.type = init_module or evt.type = finit_module))
  output: >
    Kernel module load attempt from container
    (user=%user.name container=%container.name command=%proc.cmdline
     %container.info)
  priority: CRITICAL
  tags: [container, escape, kernel_module]
 
# Detect namespace manipulation
- rule: Container Namespace Manipulation
  desc: Detect setns/unshare syscalls from container
  condition: >
    container and (evt.type = setns or evt.type = unshare) and
    not proc.name in (containerd-shim, runc)
  output: >
    Namespace manipulation from container
    (user=%user.name container=%container.name syscall=%evt.type
     command=%proc.cmdline %container.info)
  priority: CRITICAL
  tags: [container, escape, namespace]
 
# Detect mount operations from container
- rule: Container Mount Sensitive Filesystem
  desc: Detect container mounting host filesystems
  condition: >
    spawned_process and container and proc.name = mount and
    (proc.args contains "/dev/" or proc.args contains "proc" or
     proc.args contains "sysfs")
  output: >
    Sensitive mount operation from container
    (user=%user.name container=%container.name command=%proc.cmdline
     %container.info)
  priority: HIGH
  tags: [container, escape, mount]

Step 3: Configure Seccomp Profile for Escape Prevention

{
  "defaultAction": "SCMP_ACT_ERRNO",
  "archMap": [
    { "architecture": "SCMP_ARCH_X86_64", "subArchitectures": ["SCMP_ARCH_X86", "SCMP_ARCH_X32"] }
  ],
  "syscalls": [
    {
      "names": [
        "read", "write", "open", "close", "stat", "fstat", "lstat",
        "poll", "lseek", "mmap", "mprotect", "munmap", "brk",
        "rt_sigaction", "rt_sigprocmask", "ioctl", "access",
        "pipe", "select", "sched_yield", "dup", "dup2",
        "nanosleep", "getpid", "socket", "connect", "accept",
        "sendto", "recvfrom", "bind", "listen", "getsockname",
        "getpeername", "socketpair", "setsockopt", "getsockopt",
        "clone", "fork", "vfork", "execve", "exit", "wait4",
        "kill", "getuid", "getgid", "geteuid", "getegid",
        "epoll_create", "epoll_wait", "epoll_ctl", "epoll_create1",
        "futex", "set_tid_address", "set_robust_list",
        "openat", "newfstatat", "readlinkat", "fchownat",
        "clock_gettime", "clock_getres", "clock_nanosleep",
        "getrandom", "memfd_create", "statx", "rseq"
      ],
      "action": "SCMP_ACT_ALLOW"
    },
    {
      "names": ["unshare", "setns", "mount", "umount2", "pivot_root",
                "init_module", "finit_module", "delete_module",
                "kexec_load", "kexec_file_load", "ptrace",
                "reboot", "swapon", "swapoff", "sethostname",
                "setdomainname", "keyctl", "bpf"],
      "action": "SCMP_ACT_LOG",
      "comment": "Log escape-relevant syscalls for detection"
    }
  ]
}

Step 4: Audit Rules for Container Escape

# /etc/audit/rules.d/container-escape.rules
 
# Monitor namespace operations
-a always,exit -F arch=b64 -S setns -S unshare -k container_escape
-a always,exit -F arch=b64 -S mount -S umount2 -k container_mount
-a always,exit -F arch=b64 -S init_module -S finit_module -S delete_module -k kernel_module
-a always,exit -F arch=b64 -S ptrace -k process_trace
 
# Monitor sensitive paths
-w /var/run/docker.sock -p rwxa -k docker_socket
-w /proc/sysrq-trigger -p w -k sysrq
-w /proc/kcore -p r -k kcore_read
 
# Monitor container runtime
-w /usr/bin/runc -p x -k container_runtime
-w /usr/bin/containerd -p x -k container_runtime
-w /usr/bin/docker -p x -k container_runtime

Step 5: Real-Time Alert Pipeline

# Falcosidekick configuration for alert routing
config:
  slack:
    webhookurl: "https://hooks.slack.com/services/xxx"
    minimumpriority: "critical"
    messageformat: |
      *Container Escape Alert*
      Rule: {{ .Rule }}
      Priority: {{ .Priority }}
      Output: {{ .Output }}
 
  elasticsearch:
    hostport: "https://elasticsearch:9200"
    index: "falco-alerts"
    minimumpriority: "warning"
 
  pagerduty:
    routingkey: "xxxx"
    minimumpriority: "critical"

Validation Commands

# Test Falco rules with event generator
kubectl run falco-event-generator \
  --image=falcosecurity/event-generator \
  --restart=Never \
  -- run syscall --action PtraceAttachContainer
 
# Check Falco alerts
kubectl logs -n falco-system -l app.kubernetes.io/name=falco --tail=50
 
# Verify seccomp profile is loaded
docker inspect --format '{{.HostConfig.SecurityOpt}}' <container-id>
 
# Check audit logs for escape-related events
ausearch -k container_escape --interpret

References

Source materials

References and resources

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

References 3

api-reference.md2.2 KB

API Reference: Detecting Container Escape Attempts

Common Escape Vectors (MITRE ATT&CK)

Vector Technique MITRE ID
Privileged container Mount host FS, load modules T1611
Docker socket mount Create privileged container T1610
Kernel exploits CVE-2022-0185, Dirty Pipe T1068
Capability abuse SYS_ADMIN, SYS_PTRACE T1548
Sensitive mounts /proc/sysrq-trigger, cgroup release_agent T1611
Namespace escape nsenter, unshare T1611

Docker CLI Inspection

# Check if container is privileged
docker inspect --format='{{.HostConfig.Privileged}}' <container>
 
# Check added capabilities
docker inspect --format='{{.HostConfig.CapAdd}}' <container>
 
# Check PID namespace mode
docker inspect --format='{{.HostConfig.PidMode}}' <container>
 
# Check volume mounts
docker inspect --format='{{range .Mounts}}{{.Source}}:{{.Destination}} {{end}}' <container>

Falco JSON Alert Format

{
  "time": "2024-01-15T10:30:00.000Z",
  "rule": "Container Escape via Privileged Mode",
  "priority": "Critical",
  "output": "Container escape attempt...",
  "output_fields": {
    "container.name": "attacker-pod",
    "container.image.repository": "alpine",
    "proc.cmdline": "nsenter -t 1 -m -u -i -n"
  },
  "tags": ["container", "escape", "T1611"]
}

Linux Audit Rules for Escape Detection

# /etc/audit/rules.d/container-escape.rules
-a always,exit -F arch=b64 -S setns -S unshare -k container_escape
-a always,exit -F arch=b64 -S mount -S umount2 -k container_mount
-a always,exit -F arch=b64 -S init_module -S finit_module -k kernel_module
-w /var/run/docker.sock -p rwxa -k docker_socket

Dangerous Linux Capabilities

Capability Escape Risk
CAP_SYS_ADMIN Mount filesystems, manage cgroups
CAP_SYS_PTRACE Trace/debug any process
CAP_NET_ADMIN Network namespace manipulation
CAP_SYS_MODULE Load/unload kernel modules
CAP_DAC_READ_SEARCH Bypass file read permissions

CLI Usage

python agent.py --falco-log /var/log/falco/events.json
python agent.py --audit-log /var/log/audit/audit.log
python agent.py --check-containers
python agent.py --container-id abc123
standards.md2.3 KB

Standards Reference - Container Escape Detection

MITRE ATT&CK for Containers

T1611 - Escape to Host

  • Tactic: Privilege Escalation
  • Description: Adversaries may escape container isolation and gain access to the host
  • Sub-techniques: Privileged container, nsenter, cgroup escape, kernel exploit
  • Detection: Monitor for namespace manipulation, sensitive path access, privilege changes

T1610 - Deploy Container

  • Tactic: Execution
  • Description: Deploy a new container using Docker socket access from within a container

T1068 - Exploitation for Privilege Escalation

  • Tactic: Privilege Escalation
  • Description: Exploit kernel vulnerabilities for container escape (Dirty Pipe, runc CVEs)

T1548 - Abuse Elevation Control Mechanism

  • Sub-technique: T1548.004 - Elevated Execution with Prompt
  • Description: Abuse Linux capabilities like CAP_SYS_ADMIN for escape

Known Container Escape CVEs

CVE Component Description CVSS
CVE-2024-21626 runc Working directory escape via /proc/self/fd leak 8.6
CVE-2022-0185 Linux kernel fsconfig heap overflow, namespace escape 8.4
CVE-2022-0847 Linux kernel Dirty Pipe - arbitrary file overwrite 7.8
CVE-2021-22555 Linux kernel Netfilter heap OOB, container escape 7.8
CVE-2020-15257 containerd Abstract socket namespace escape 5.2
CVE-2019-5736 runc Binary overwrite, host code execution 8.6

NIST SP 800-190 - Application Container Security Guide

Container Runtime Security

  • Monitor containers for anomalous behavior
  • Detect attempts to access host namespaces
  • Alert on kernel module loading from containers
  • Implement syscall filtering with seccomp

Linux Capabilities Required for Escape

Capability Escape Risk Description
CAP_SYS_ADMIN Critical Mount filesystems, namespace manipulation
CAP_SYS_PTRACE Critical ptrace processes, inspect memory
CAP_NET_ADMIN High Network namespace manipulation
CAP_SYS_MODULE Critical Load kernel modules
CAP_SYS_RAWIO High Raw I/O access, iopl/ioperm
CAP_DAC_OVERRIDE High Bypass file read/write permission
CAP_DAC_READ_SEARCH Medium Bypass file read permission
CAP_MKNOD Medium Create device files
workflows.md3.0 KB

Workflows - Container Escape Detection

Workflow 1: Real-Time Detection Pipeline

[Container Syscall] --> [eBPF/Kernel Module] --> [Falco Engine]
        |                                             |
        v                                             v
  Syscall captured                          Rule evaluation
  (setns, mount,                                  |
   ptrace, etc.)                    +-------------+-------------+
                                    |                           |
                                    v                           v
                              Match found                No match
                                    |                     (normal)
                                    v
                          [Alert Generated]
                                    |
                          +---------+---------+
                          |         |         |
                          v         v         v
                       Slack    SIEM     PagerDuty
                       Alert    Log      Incident

Workflow 2: Escape Attempt Investigation

Step 1: Triage alert
  - Identify container, image, namespace
  - Check if container is privileged
  - Determine escape vector attempted
 
Step 2: Immediate containment
  - kubectl delete pod <pod-name> -n <namespace> (if active escape)
  - kubectl cordon <node> (if node compromised)
  - Network isolate the node
 
Step 3: Forensic collection
  - Capture container filesystem: docker export <id> > container.tar
  - Collect Falco events for timeline
  - Dump process tree: ps auxf
  - Check for new processes on host
  - Audit logs: ausearch -k container_escape
 
Step 4: Root cause analysis
  - Was the container privileged?
  - What capabilities were granted?
  - Was Docker socket mounted?
  - Which vulnerability was exploited?
 
Step 5: Remediation
  - Patch kernel/runtime vulnerability
  - Remove excessive capabilities
  - Apply PSS restricted profile
  - Update seccomp profiles

Workflow 3: Proactive Escape Surface Audit

[Inventory all containers] --> [Check for escape risk factors]
                                        |
                            +-----------+-----------+
                            |           |           |
                            v           v           v
                     Privileged?   Docker sock?  Host NS?
                     CAP_SYS_ADMIN? mounted?     hostPID?
                            |           |           |
                            +-----------+-----------+
                                        |
                                        v
                            [Risk Score per container]
                                        |
                              +---------+---------+
                              |                   |
                              v                   v
                        HIGH risk            LOW risk
                        Remediate            Monitor
                        immediately          continuously

Scripts 2

agent.py6.6 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Container escape detection agent using Falco output parsing and audit log analysis.

Monitors for container escape indicators by parsing Falco JSON alerts,
auditd logs, and Docker inspect data for privileged/vulnerable containers.
"""

import argparse
import json
import re
import subprocess
import sys
from datetime import datetime
from pathlib import Path

ESCAPE_VECTORS = {
    "nsenter": {"severity": "CRITICAL", "mitre": "T1611", "desc": "Namespace escape via nsenter"},
    "unshare": {"severity": "CRITICAL", "mitre": "T1611", "desc": "Namespace manipulation"},
    "mount": {"severity": "HIGH", "mitre": "T1611", "desc": "Host filesystem mount"},
    "modprobe": {"severity": "CRITICAL", "mitre": "T1611", "desc": "Kernel module loading"},
    "insmod": {"severity": "CRITICAL", "mitre": "T1611", "desc": "Kernel module insertion"},
    "chroot": {"severity": "HIGH", "mitre": "T1611", "desc": "Chroot escape attempt"},
}

SENSITIVE_PATHS = [
    "/var/run/docker.sock", "/proc/sysrq-trigger", "/proc/kcore",
    "/proc/kmsg", "/proc/kallsyms", "/sys/kernel",
    "/etc/shadow", "/etc/kubernetes/admin.conf",
]


def parse_falco_json(filepath):
    alerts = []
    with open(filepath, "r") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            try:
                evt = json.loads(line)
                if any(tag in evt.get("tags", []) for tag in ["escape", "container"]):
                    alerts.append({
                        "time": evt.get("time", ""),
                        "rule": evt.get("rule", ""),
                        "priority": evt.get("priority", ""),
                        "output": evt.get("output", ""),
                        "output_fields": evt.get("output_fields", {}),
                    })
            except json.JSONDecodeError:
                continue
    return alerts


def parse_auditd_escape_events(filepath):
    findings = []
    escape_keys = {"container_escape", "container_mount", "kernel_module",
                   "docker_socket", "process_trace"}
    with open(filepath, "r") as f:
        for line in f:
            for key in escape_keys:
                if f'key="{key}"' in line or f"key={key}" in line:
                    timestamp = re.search(r'msg=audit\((\d+\.\d+):', line)
                    syscall = re.search(r'syscall=(\w+)', line)
                    exe = re.search(r'exe="([^"]+)"', line)
                    findings.append({
                        "timestamp": timestamp.group(1) if timestamp else "",
                        "key": key,
                        "syscall": syscall.group(1) if syscall else "",
                        "exe": exe.group(1) if exe else "",
                        "severity": "CRITICAL",
                        "raw": line.strip()[:200],
                    })
    return findings


def check_privileged_containers():
    containers = []
    try:
        result = subprocess.run(
            ["docker", "ps", "--format", "{{.ID}} {{.Names}} {{.Image}}"],
            capture_output=True, text=True, timeout=10)
        if result.returncode != 0:
            return containers
        for line in result.stdout.strip().split("\n"):
            if not line.strip():
                continue
            parts = line.split(None, 2)
            cid = parts[0]
            inspect = subprocess.run(
                ["docker", "inspect", "--format",
                 "{{.HostConfig.Privileged}} {{.HostConfig.PidMode}} "
                 "{{range .HostConfig.Binds}}{{.}} {{end}}"],
                capture_output=True, text=True, timeout=10)
            if inspect.returncode == 0:
                info = inspect.stdout.strip()
                findings = []
                if "true" in info.split()[0:1]:
                    findings.append("privileged_mode")
                if "host" in info:
                    findings.append("host_pid_namespace")
                if "/var/run/docker.sock" in info:
                    findings.append("docker_socket_mounted")
                if findings:
                    containers.append({
                        "container_id": cid,
                        "name": parts[1] if len(parts) > 1 else "",
                        "image": parts[2] if len(parts) > 2 else "",
                        "escape_risks": findings,
                        "severity": "CRITICAL" if "privileged_mode" in findings else "HIGH",
                    })
    except (subprocess.TimeoutExpired, FileNotFoundError):
        pass
    return containers


def check_dangerous_capabilities(container_id):
    dangerous_caps = {"SYS_ADMIN", "SYS_PTRACE", "NET_ADMIN", "SYS_RAWIO",
                      "SYS_MODULE", "DAC_READ_SEARCH"}
    try:
        result = subprocess.run(
            ["docker", "inspect", "--format", "{{.HostConfig.CapAdd}}", container_id],
            capture_output=True, text=True, timeout=10)
        if result.returncode == 0:
            caps = set(re.findall(r'\b([A-Z_]+)\b', result.stdout))
            found = caps & dangerous_caps
            return [{"capability": c, "severity": "CRITICAL"} for c in found]
    except (subprocess.TimeoutExpired, FileNotFoundError):
        pass
    return []


def main():
    parser = argparse.ArgumentParser(description="Container Escape Detector")
    parser.add_argument("--falco-log", help="Path to Falco JSON output log")
    parser.add_argument("--audit-log", help="Path to auditd log file")
    parser.add_argument("--check-containers", action="store_true",
                        help="Check running containers for escape risks")
    parser.add_argument("--container-id", help="Check specific container capabilities")
    args = parser.parse_args()

    results = {"timestamp": datetime.utcnow().isoformat() + "Z", "findings": []}

    if args.falco_log:
        alerts = parse_falco_json(args.falco_log)
        results["falco_alerts"] = alerts
        results["findings"].extend([{"source": "falco", **a} for a in alerts])

    if args.audit_log:
        audit = parse_auditd_escape_events(args.audit_log)
        results["audit_events"] = audit
        results["findings"].extend([{"source": "auditd", **a} for a in audit])

    if args.check_containers:
        priv = check_privileged_containers()
        results["privileged_containers"] = priv
        results["findings"].extend([{"source": "docker_inspect", **c} for c in priv])

    if args.container_id:
        caps = check_dangerous_capabilities(args.container_id)
        results["dangerous_capabilities"] = caps
        results["findings"].extend([{"source": "capabilities", **c} for c in caps])

    results["total_findings"] = len(results["findings"])
    print(json.dumps(results, indent=2))


if __name__ == "__main__":
    main()
process.py12.2 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
Container Escape Detection Scanner

Analyzes running containers for escape risk factors including
privileged mode, dangerous capabilities, sensitive mounts,
and Docker socket exposure.
"""

import subprocess
import json
import sys
from dataclasses import dataclass, field


DANGEROUS_CAPABILITIES = {
    "SYS_ADMIN": 10,
    "SYS_PTRACE": 9,
    "SYS_MODULE": 10,
    "SYS_RAWIO": 8,
    "NET_ADMIN": 7,
    "DAC_OVERRIDE": 6,
    "DAC_READ_SEARCH": 5,
    "MKNOD": 4,
    "NET_RAW": 4,
    "SYS_CHROOT": 3,
}

SENSITIVE_MOUNT_PATHS = [
    "/var/run/docker.sock",
    "/run/containerd/containerd.sock",
    "/proc/sysrq-trigger",
    "/proc/kcore",
    "/proc/kmsg",
    "/proc/kallsyms",
    "/sys/kernel",
    "/sys/fs/cgroup",
    "/dev",
    "/etc/shadow",
    "/etc/passwd",
    "/root",
]


@dataclass
class EscapeRisk:
    container_name: str
    container_id: str
    image: str
    risk_score: int = 0
    risk_factors: list = field(default_factory=list)

    @property
    def risk_level(self) -> str:
        if self.risk_score >= 8:
            return "CRITICAL"
        elif self.risk_score >= 5:
            return "HIGH"
        elif self.risk_score >= 3:
            return "MEDIUM"
        return "LOW"


def run_command(cmd: list, timeout: int = 30) -> tuple:
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
        return result.returncode, result.stdout.strip(), result.stderr.strip()
    except (subprocess.TimeoutExpired, FileNotFoundError) as e:
        return -1, "", str(e)


def get_running_containers() -> list:
    """Get list of running container IDs."""
    rc, out, _ = run_command(["docker", "ps", "-q"])
    if rc != 0 or not out:
        return []
    return out.split("\n")


def inspect_container(container_id: str) -> dict:
    """Get container inspection data."""
    rc, out, _ = run_command(["docker", "inspect", container_id])
    if rc != 0:
        return {}
    try:
        return json.loads(out)[0]
    except (json.JSONDecodeError, IndexError):
        return {}


def assess_escape_risk(container_data: dict) -> EscapeRisk:
    """Assess container escape risk based on configuration."""
    name = container_data.get("Name", "unknown").lstrip("/")
    cid = container_data.get("Id", "")[:12]
    image = container_data.get("Config", {}).get("Image", "unknown")

    risk = EscapeRisk(container_name=name, container_id=cid, image=image)
    host_config = container_data.get("HostConfig", {})
    config = container_data.get("Config", {})
    mounts = container_data.get("Mounts", [])

    # Check privileged mode
    if host_config.get("Privileged", False):
        risk.risk_score += 10
        risk.risk_factors.append({
            "factor": "Privileged mode enabled",
            "severity": "CRITICAL",
            "score": 10,
            "description": "Container has full host access, trivial escape",
            "remediation": "Remove --privileged flag, use specific --cap-add"
        })

    # Check 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]

    for cap in cap_add:
        cap_upper = cap.upper()
        if cap_upper in DANGEROUS_CAPABILITIES:
            score = DANGEROUS_CAPABILITIES[cap_upper]
            risk.risk_score += score
            risk.risk_factors.append({
                "factor": f"Dangerous capability: {cap_upper}",
                "severity": "CRITICAL" if score >= 8 else "HIGH",
                "score": score,
                "description": f"CAP_{cap_upper} can be used for container escape",
                "remediation": f"Remove CAP_{cap_upper} unless absolutely required"
            })

    if not all_dropped and not host_config.get("Privileged", False):
        risk.risk_score += 2
        risk.risk_factors.append({
            "factor": "Default capabilities not dropped",
            "severity": "MEDIUM",
            "score": 2,
            "description": "Container retains default Linux capabilities",
            "remediation": "Use --cap-drop ALL and add only required capabilities"
        })

    # Check host namespaces
    for ns in ["NetworkMode", "PidMode", "IpcMode"]:
        value = host_config.get(ns, "")
        if value == "host":
            risk.risk_score += 7
            risk.risk_factors.append({
                "factor": f"Host namespace: {ns}={value}",
                "severity": "CRITICAL",
                "score": 7,
                "description": f"Container shares host {ns}, enabling escape",
                "remediation": f"Remove host {ns} configuration"
            })

    # Check sensitive mounts
    for mount in mounts:
        source = mount.get("Source", "")
        for sensitive_path in SENSITIVE_MOUNT_PATHS:
            if source == sensitive_path or source.startswith(sensitive_path):
                score = 9 if "docker.sock" in source else 6
                risk.risk_score += score
                risk.risk_factors.append({
                    "factor": f"Sensitive mount: {source}",
                    "severity": "CRITICAL" if score >= 8 else "HIGH",
                    "score": score,
                    "description": f"Container has access to {source}",
                    "remediation": f"Remove mount of {source}, use alternative access method"
                })
                break

    # Check user
    user = config.get("User", "")
    if not user or user == "0" or user == "root":
        risk.risk_score += 3
        risk.risk_factors.append({
            "factor": "Running as root",
            "severity": "HIGH",
            "score": 3,
            "description": "Container process runs as root (UID 0)",
            "remediation": "Set USER in Dockerfile or use --user flag"
        })

    # Check security options
    security_opts = host_config.get("SecurityOpt") or []
    has_seccomp = any("seccomp" in opt for opt in security_opts)
    has_apparmor = any("apparmor" in opt for opt in security_opts)
    no_new_privs = any("no-new-privileges" in opt for opt in security_opts)

    if not has_seccomp:
        risk.risk_score += 2
        risk.risk_factors.append({
            "factor": "No custom seccomp profile",
            "severity": "MEDIUM",
            "score": 2,
            "description": "Container uses default seccomp profile or none",
            "remediation": "Apply restrictive custom seccomp profile"
        })

    if not no_new_privs:
        risk.risk_score += 2
        risk.risk_factors.append({
            "factor": "No new-privileges restriction missing",
            "severity": "MEDIUM",
            "score": 2,
            "description": "Container can acquire new privileges via setuid binaries",
            "remediation": "Add --security-opt no-new-privileges:true"
        })

    # Check read-only filesystem
    if not host_config.get("ReadonlyRootfs", False):
        risk.risk_score += 1
        risk.risk_factors.append({
            "factor": "Writable root filesystem",
            "severity": "LOW",
            "score": 1,
            "description": "Container filesystem is writable, allowing tool download",
            "remediation": "Use --read-only with --tmpfs for writable directories"
        })

    # Cap score at 10
    risk.risk_score = min(risk.risk_score, 10)
    return risk


def scan_kubernetes_pods() -> list:
    """Scan Kubernetes pods for escape risks."""
    rc, out, _ = run_command(["kubectl", "get", "pods", "-A", "-o", "json"])
    if rc != 0:
        return []

    risks = []
    try:
        pods = json.loads(out)
    except json.JSONDecodeError:
        return []

    for pod in pods.get("items", []):
        pod_name = pod["metadata"]["name"]
        namespace = pod["metadata"]["namespace"]
        spec = pod.get("spec", {})

        risk = EscapeRisk(
            container_name=f"{namespace}/{pod_name}",
            container_id="k8s",
            image=spec.get("containers", [{}])[0].get("image", "unknown")
        )

        # Check host namespaces
        if spec.get("hostNetwork", False):
            risk.risk_score += 7
            risk.risk_factors.append({
                "factor": "hostNetwork enabled",
                "severity": "CRITICAL",
                "score": 7,
                "description": "Pod shares host network namespace",
                "remediation": "Set hostNetwork: false"
            })

        if spec.get("hostPID", False):
            risk.risk_score += 7
            risk.risk_factors.append({
                "factor": "hostPID enabled",
                "severity": "CRITICAL",
                "score": 7,
                "description": "Pod shares host PID namespace",
                "remediation": "Set hostPID: false"
            })

        # Check containers
        for container in spec.get("containers", []):
            sc = container.get("securityContext", {})
            if sc.get("privileged", False):
                risk.risk_score += 10
                risk.risk_factors.append({
                    "factor": f"Privileged container: {container.get('name')}",
                    "severity": "CRITICAL",
                    "score": 10,
                    "description": "Container runs in privileged mode",
                    "remediation": "Set privileged: false"
                })

        # Check volumes
        for vol in spec.get("volumes", []):
            if "hostPath" in vol:
                path = vol["hostPath"].get("path", "")
                if any(path.startswith(p) for p in SENSITIVE_MOUNT_PATHS):
                    risk.risk_score += 8
                    risk.risk_factors.append({
                        "factor": f"Sensitive hostPath: {path}",
                        "severity": "CRITICAL",
                        "score": 8,
                        "description": f"Pod mounts sensitive host path: {path}",
                        "remediation": "Remove hostPath volume"
                    })

        risk.risk_score = min(risk.risk_score, 10)
        if risk.risk_factors:
            risks.append(risk)

    return risks


def main():
    print("[*] Container Escape Risk Scanner")
    print("=" * 70)

    risks = []

    # Scan Docker containers
    containers = get_running_containers()
    if containers:
        print(f"[*] Scanning {len(containers)} Docker containers...")
        for cid in containers:
            data = inspect_container(cid)
            if data:
                risk = assess_escape_risk(data)
                risks.append(risk)
    else:
        print("[*] No Docker containers found, checking Kubernetes...")
        k8s_risks = scan_kubernetes_pods()
        risks.extend(k8s_risks)

    if not risks:
        print("[+] No containers found to scan")
        sys.exit(0)

    # Sort by risk score
    risks.sort(key=lambda r: r.risk_score, reverse=True)

    # Print results
    print(f"\n{'=' * 70}")
    print("CONTAINER ESCAPE RISK ASSESSMENT")
    print(f"{'=' * 70}")

    for risk in risks:
        print(f"\n[{risk.risk_level}] {risk.container_name} (score: {risk.risk_score}/10)")
        print(f"  Image: {risk.image}")
        for factor in risk.risk_factors:
            print(f"  - [{factor['severity']}] {factor['factor']}")
            print(f"    Fix: {factor['remediation']}")

    # Summary
    critical = sum(1 for r in risks if r.risk_level == "CRITICAL")
    high = sum(1 for r in risks if r.risk_level == "HIGH")
    medium = sum(1 for r in risks if r.risk_level == "MEDIUM")
    low = sum(1 for r in risks if r.risk_level == "LOW")

    print(f"\n{'=' * 70}")
    print(f"SUMMARY: {len(risks)} containers scanned")
    print(f"  CRITICAL: {critical}  HIGH: {high}  MEDIUM: {medium}  LOW: {low}")

    # Save report
    report = {
        "scan_type": "container_escape_risk",
        "containers_scanned": len(risks),
        "results": [
            {
                "container": r.container_name,
                "image": r.image,
                "risk_score": r.risk_score,
                "risk_level": r.risk_level,
                "factors": r.risk_factors
            }
            for r in risks
        ]
    }

    with open("escape_risk_report.json", "w") as f:
        json.dump(report, f, indent=2)
    print(f"\n[*] Report saved to escape_risk_report.json")

    if critical > 0:
        print(f"\n[!] {critical} containers with CRITICAL escape risk!")
        sys.exit(1)


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 1.3 KB
Keep exploring