ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.
Python active-directorycloud-securitydefensive-validationfastapigood-first-issuemitre-attackopsecreactred-teamreportingsecurity
"""
Container Escape Module
Docker socket, privileged containers, K8s RBAC misconfigs.
"""
from __future__ import annotations
import os
from typing import Any
from ares.core.logger import get_logger
logger = get_logger("ares.modules.linux.container")
from ares.core.campaign import Finding, Severity
from ares.core.errors import ModuleValidationError
from ares.core.tracing import trace_module
from ares.modules.params import ContainerEscapeParams
from ares.sdk import (
BaseModule,
EvidenceRecord,
FilesystemPermission,
LockoutCircuitBreaker,
ModuleResult,
NetworkPermission,
OpsecLevel,
ProcessPermission,
module_contract,
)
@module_contract(
permissions=[
FilesystemPermission(allowed_subdirs=["loot", "artifacts"], read_only=True),
NetworkPermission(ports=[80, 443, 2375, 6443], protocols=["tcp"]),
ProcessPermission(allow_subprocesses=False),
],
circuit_breaker=LockoutCircuitBreaker(),
params_model=ContainerEscapeParams,
)
class ContainerEscapeModule(BaseModule[ContainerEscapeParams, ModuleResult]):
"""
linux.container - Docker socket abuse, privileged escape, K8s RBAC misconfigs
OPSEC: MEDIUM
MITRE: "T1611", "T1552.007", "T1613"
OUTPUTS: "container_escape_vectors", "k8s_rbac_findings"
"""
MODULE_ID = "linux.container"
MODULE_NAME = "Container Escape"
MODULE_CATEGORY = "linux"
MODULE_DESCRIPTION = "Docker socket abuse, privileged escape, K8s RBAC misconfigs"
MODULE_AUTHOR = "ARES Team <[email protected]>"
OPSEC_LEVEL = OpsecLevel.MEDIUM
REQUIRES = []
OUTPUTS = ["container_escape_vectors", "k8s_rbac_findings"]
MITRE_TECHNIQUES = ["T1611", "T1552.007", "T1613"]
PARAMS_MODEL = ContainerEscapeParams
async def validate(self, ctx: "Any") -> None:
"""Pre-flight param checks before any network call."""
from ares.core.context import ExecutionContext
if isinstance(ctx, ExecutionContext):
target = getattr(ctx, "target", "")
if not target and hasattr(ctx, "params") and isinstance(ctx.params, dict):
target = ctx.params.get("target") or ctx.params.get("host", "")
if not target:
raise ModuleValidationError(
"linux.container requires 'target' - IP or hostname of container host.",
module_id=self.MODULE_ID, field="target",
)
if isinstance(ctx.params, dict):
if "target" not in ctx.params and target:
ctx.params["target"] = target
if "username" not in ctx.params:
ctx.params["username"] = ctx.params.get("ssh_user", "root")
await super().validate(ctx)
async def execute(self, ctx: "Any") -> "ModuleResult":
"""ExecutionContext-based entry point (v0.9.0+)."""
from ares.modules.base import ModuleResult
if getattr(ctx, "dry_run", False):
return ModuleResult(status="dry_run", module_id=self.MODULE_ID,
raw={"dry_run": True})
params = getattr(ctx, "params", {})
if isinstance(params, ContainerEscapeParams):
kwargs = params.model_dump()
elif isinstance(params, dict):
kwargs = params
else:
kwargs = {}
findings, raw = await self.run(**kwargs)
# Cryptographic Evidence Records with SHA-256 Merkle Provenance
evidence_chain: list[EvidenceRecord] = []
for finding in findings:
ev = EvidenceRecord(
artifact_id=f"cntr-{finding.title[:20].lower().replace(' ', '-')}",
source_target=getattr(ctx, "target", "container-host"),
collected_by=self.MODULE_ID,
data={
"title": finding.title,
"severity": str(finding.severity),
"description": finding.description,
"mitre": finding.mitre_technique,
},
tags=["linux", "container", "container_escape"],
)
evidence_chain.append(ev)
raw["evidence_chain"] = [e.data for e in evidence_chain]
raw["evidence_integrity"] = [e.record_hash for e in evidence_chain]
# Closed-Loop Purple Telemetry: KQL & Sigma rule synthesis
container_target = getattr(ctx, "target", "") or "ContainerHost"
kql_query = (
"// ARES Closed-Loop Telemetry: Detect Linux Container Escape & Docker Socket Abuse\n"
"// Monitors Syslog / auditd for Docker daemon socket access or privileged container creation\n"
"Syslog\n"
"| where SyslogMessage has \"/var/run/docker.sock\" or SyslogMessage has \"--privileged\" or SyslogMessage has \"cgroup.procs\"\n"
"| project TimeGenerated, Computer, ProcessName, SyslogMessage\n"
)
sigma_rule = (
f"title: Linux Container Escape / Docker Socket Manipulation ({container_target})\n"
f"id: 2b3c4d5e-ares-contescape-{abs(hash(str(container_target))) % 1000000:06d}\n"
f"status: experimental\n"
f"description: Detects command-line or container runtime events accessing docker.sock or mounting host root.\n"
f"logsource:\n"
f" product: linux\n"
f" service: auditd\n"
f"detection:\n"
f" selection:\n"
f" comm:\n"
f" - 'docker'\n"
f" - 'crictl'\n"
f" CommandLine|contains:\n"
f" - 'docker.sock'\n"
f" - '--privileged'\n"
f" condition: selection\n"
f"level: critical\n"
f"tags:\n"
f" - attack.privilege_escalation\n"
f" - attack.t1611\n"
)
loot_items: list[dict[str, Any]] = raw.get("loot", [])
if not any(l.get("loot_type") == "detection_rule_kql" for l in loot_items):
loot_items.extend([
{
"name": f"Detection Rule (KQL): Container Escape ({container_target})",
"loot_type": "detection_rule_kql",
"description": "Microsoft Sentinel KQL query for detecting Docker socket abuse and container escapes",
"content": {"kql": kql_query, "target": container_target},
"tags": ["detection", "kql", "sentinel", "blue_team"],
},
{
"name": f"Detection Rule (Sigma): Container Escape ({container_target})",
"loot_type": "detection_rule_sigma",
"description": "Sigma detection rule for Docker socket abuse and container escapes",
"content": {"sigma": sigma_rule, "target": container_target},
"tags": ["detection", "sigma", "blue_team"],
},
])
raw["loot"] = loot_items
raw["docker_socket_risk_evaluated"] = True
raw["container_escape_vectors_mapped"] = True
return ModuleResult(
status="success" if (findings or any(raw.get(_k) for _k in self.OUTPUTS)) else "partial", # AUDIT run-1 H14
findings=findings, raw=raw, module_id=self.MODULE_ID,
execution_id=getattr(ctx, "execution_id", ""),
)
@trace_module("linux.container")
async def run(self, **kwargs: Any) -> tuple[list[Finding], dict[str, Any]]:
# Note: before_request() intentionally not called - this module runs
# entirely locally inside the container (no remote network calls to a target host).
# Scope/jitter checks apply to remote targets, not local filesystem/socket reads.
raw: dict[str, Any] = {
"docker_socket": await self._check_docker_socket(),
"privileged": await self._check_privileged(),
"host_mounts": await self._check_host_mounts(),
"k8s_token": await self._check_k8s_service_account(),
"host_network": await self._check_host_network(),
}
raw["container_escape_vectors"] = self._findings # OUTPUTS key
raw["k8s_rbac_findings"] = [] # OUTPUTS key
return self._findings, raw
async def _check_docker_socket(self) -> dict[str, Any]:
socket_path = "/var/run/docker.sock"
exists = os.path.exists(socket_path)
writable = exists and os.access(socket_path, os.W_OK)
if writable:
self.finding(
title="Docker Socket Mounted and Writable",
description=(
"The Docker daemon socket is mounted and writable inside this container. "
"An attacker can create a privileged container mounting the host filesystem, "
"achieving full host OS compromise in seconds."
),
severity=Severity.CRITICAL,
mitre_technique="T1611",
mitre_tactic="Privilege Escalation",
evidence={"socket": socket_path, "writable": writable},
remediation=(
"Never mount /var/run/docker.sock in containers. "
"Use rootless Docker, Podman, or Docker-in-Docker alternatives. "
"If CI/CD requires it, use a socket proxy like Tecnativa/docker-socket-proxy."
),
)
elif exists:
self.finding(
title="Docker Socket Mounted (Read-Only)",
description="Docker socket mounted but not writable - limited exploitation.",
severity=Severity.MEDIUM,
mitre_technique="T1611",
mitre_tactic="Privilege Escalation",
evidence={"socket": socket_path, "writable": False},
remediation="Remove Docker socket mount entirely.",
)
return {"exists": exists, "writable": writable}
async def _check_privileged(self) -> dict[str, Any]:
"""Detect --privileged via CapEff in /proc/self/status."""
try:
with open("/proc/self/status") as f:
caps = {
line.split(":")[0].strip(): line.split(":")[1].strip()
for line in f if ":" in line
}
cap_eff = caps.get("CapEff", "0")
privileged = int(cap_eff, 16) == 0x3FFFFFFFFF # Full capability set
if privileged:
self.finding(
title="Container Running in Privileged Mode",
description=(
"This container has the full Linux capability set (--privileged). "
"Host breakout is trivial via /proc/sysrq-trigger, device mounts, "
"or cgroup release_agent exploit."
),
severity=Severity.CRITICAL,
mitre_technique="T1611",
mitre_tactic="Privilege Escalation",
evidence={"CapEff": cap_eff},
remediation=(
"Remove --privileged. Use specific --cap-add for required capabilities. "
"Principle of least privilege - no container should be privileged in prod."
),
)
return {"privileged": privileged, "CapEff": cap_eff}
except OSError as e:
return {"error": str(e)}
async def _check_host_mounts(self) -> dict[str, Any]:
"""Detect sensitive host paths mounted inside the container."""
HIGH_RISK = ["/etc", "/root", "/var/lib/docker", "/proc/sysrq-trigger", "/sys/kernel"]
MEDIUM_RISK = ["/var/log", "/home", "/tmp"]
found: dict[str, list[str]] = {"high": [], "medium": []}
try:
with open("/proc/mounts") as f:
mounts_content = f.read()
for path in HIGH_RISK:
if f" {path} " in mounts_content or f" {path}/" in mounts_content:
found["high"].append(path)
for path in MEDIUM_RISK:
if f" {path} " in mounts_content:
found["medium"].append(path)
except OSError:
pass
if found["high"]:
self.finding(
title="High-Risk Host Paths Mounted in Container",
description=f"Host paths accessible: {found['high']}",
severity=Severity.CRITICAL,
mitre_technique="T1552.007",
mitre_tactic="Credential Access",
evidence={"mounts": found},
remediation="Review all volume mounts. Use :ro (read-only) where possible.",
)
return found
async def _check_k8s_service_account(self) -> dict[str, Any]:
"""Check if K8s service account token is accessible and over-privileged."""
token_path = "/var/run/secrets/kubernetes.io/serviceaccount/token"
if not os.path.exists(token_path):
return {"k8s_detected": False}
try:
with open(token_path) as f:
token = f.read().strip()
logger.info("[container] K8s service account token found - checking RBAC")
# Production:
# from kubernetes import client, config
# config.load_incluster_config()
# v1 = client.AuthorizationV1Api()
# Check: can-i list pods, create pods, exec into pods, etc.
self.finding(
title="Kubernetes Service Account Token Accessible",
description=(
"A K8s service account token is mounted in this pod. "
"If the SA has broad permissions, cluster-level compromise may be possible."
),
severity=Severity.MEDIUM,
mitre_technique="T1552.007",
mitre_tactic="Credential Access",
evidence={"token_path": token_path, "token_length": len(token)},
remediation=(
"Use automountServiceAccountToken: false unless required. "
"Scope SA roles to minimum needed (RBAC least-privilege). "
"Audit with: kubectl auth can-i --list --as=system:serviceaccount:<ns>:<sa>"
),
)
return {"k8s_detected": True, "token_found": True}
except OSError as e:
return {"k8s_detected": True, "error": str(e)}
async def _check_host_network(self) -> dict[str, Any]:
"""
Detect --net=host which exposes all host network interfaces.
Uses network namespace inode comparison and host network interface detection
instead of naive open socket count heuristics.
"""
try:
is_host_net = False
verified = False
evidence: dict[str, Any] = {}
# Check 1: Inode comparison between PID 1 and self network namespace
try:
self_net = os.stat("/proc/self/ns/net").st_ino
init_net = os.stat("/proc/1/ns/net").st_ino
if self_net == init_net:
is_host_net = True
verified = True
evidence["net_ns_inode_match"] = True
evidence["net_ns_inode"] = self_net
except (OSError, PermissionError):
pass
# Check 2: Inspect network interfaces via /proc/net/dev or /sys/class/net
interfaces: list[str] = []
try:
if os.path.exists("/proc/net/dev"):
with open("/proc/net/dev") as f:
for line in f:
if ":" in line:
iface = line.split(":")[0].strip()
interfaces.append(iface)
elif os.path.exists("/sys/class/net"):
interfaces = os.listdir("/sys/class/net")
except OSError:
pass
evidence["interfaces"] = interfaces
# Standard Docker/K8s container netns typically only has 'lo' and 'eth0'
# Host netns typically exposes 'docker0', 'cni0', physical NICs ('ens*', 'enp*', 'eno*', 'wlan*')
host_nic_prefixes = ("ens", "enp", "eno", "eth1", "wlan", "docker0", "cni0", "flannel", "virbr", "bond")
host_ifaces_found = [i for i in interfaces if any(i.startswith(p) for p in host_nic_prefixes)]
if host_ifaces_found:
is_host_net = True
evidence["host_interfaces_detected"] = host_ifaces_found
if is_host_net:
conf = 0.95 if verified else 0.45
title = (
"Container Using Host Network Namespace (--net=host)"
if verified else
"Potential Container Host Network Namespace Detected"
)
self.finding(
title=title,
description=(
"Container shares or may share the host network namespace (--net=host). "
"This allows sniffing host traffic, binding to privileged ports, and reaching host-local services."
),
severity=Severity.HIGH if verified else Severity.LOW,
confidence=conf,
mitre_technique="T1611",
mitre_tactic="Privilege Escalation",
evidence=evidence,
remediation="Remove --net=host. Use CNI plugins or user-defined bridge networks for network isolation.",
)
return {"host_network_detected": True, "verified": verified, "evidence": evidence}
return {"host_network_detected": False, "interfaces": interfaces}
except Exception as e:
return {"error": str(e)}