Fully autonomous AI Agents system capable of performing complex penetration testing tasks
Go ai-agentsai-security-toolanthropicautonomous-agentsgolanggptgraphqlmulti-agent-systemoffensive-securityopen-sourceopenaipenetration-testingpenetration-testing-toolsreactsecurity-automationsecurity-testingsecurity-toolsself-hosted
feat(worker_node): enhance Docker-in-Docker setup with security and cleanup features
Dmitry Ng464dca890356
diff --git a/examples/guides/worker_node.md b/examples/guides/worker_node.mdindex 85aee481..97bdbbaa 100644--- a/examples/guides/worker_node.md+++ b/examples/guides/worker_node.md@@ -1,6 +1,6 @@# PentAGI Worker Node Setup-This guide configures a distributed PentAGI deployment where worker node operations are isolated on a separate server for enhanced security. The worker node runs both host Docker and Docker-in-Docker (dind) to provide secure container execution environments.+This guide configures a distributed PentAGI deployment where worker node operations are isolated on a separate server for enhanced security. The worker node runs both host Docker and a hardened Docker-in-Docker (dind) daemon, which gives agents a sandboxed Docker environment of their own.## Architecture Overview@@ -12,19 +12,22 @@ graph TBsubgraph "Worker Node"HD[Host Docker<br/>:2376 TLS]- DIND[Docker-in-Docker<br/>:3376 TLS]+ DIND[Docker-in-Docker<br/>:3376 TLS<br/>OPA authz + seccomp]subgraph "Worker Containers"WC1[pentagi-terminal-1]WC2[pentagi-terminal-N]end++ NC[Nested Containers<br/>agent 'docker run']endPA -.->|"TLS Connection<br/>Create Workers"| HDHD --> WC1HD --> WC2- WC1 -.->|"docker.sock<br/>mapping"| DIND- WC2 -.->|"docker.sock<br/>mapping"| DIND+ WC1 -.->|"TLS :3376<br/>DOCKER_INSIDE_*"| DIND+ WC2 -.->|"TLS :3376<br/>DOCKER_INSIDE_*"| DIND+ DIND --> NCPA -.->|"Alternative:<br/>Direct TLS"| DIND@@ -34,19 +37,49 @@ graph TBclass PA mainclass HD,DIND worker- class WC1,WC2 container+ class WC1,WC2,NC container```**Connection Modes:**-- **Standard**: PentAGI → Host Docker (creates workers) → Workers use dind via socket mapping-- **Direct**: PentAGI → dind (creates workers directly, socket mapping disabled)+- **Standard** (recommended): PentAGI → Host Docker (creates workers) → Workers reach dind over its **TLS endpoint**, configured through `DOCKER_INSIDE_HOST` / `DOCKER_INSIDE_TLS_VERIFY` / `DOCKER_INSIDE_CERT_PATH`. Agents keep full Docker access, and every container they create is policed by the dind authorization policy.+- **Direct**: PentAGI → dind (creates workers directly). Worker containers become nested containers, so the policy applies to them too: host bind-mounts are denied, which means **Docker Access must be disabled** and the work directory must be left empty (PentAGI then uses a Docker volume). Agents get no nested Docker in this mode.++### Why workers reach dind over TLS instead of a mounted socket++Earlier revisions of this guide mounted `/var/run/docker-dind/docker.sock` into+each worker container. That works while everything is already running, but it has+two failure modes that the TLS endpoint does not.++**Boot-order race.** A bind-mount whose source does not exist is created by Docker+as a **directory**. Worker containers carry a `on-failure` restart policy, so after+a worker-node reboot one of them can start before dind has recreated its socket.+Docker then materialises a *directory* at `/var/run/docker-dind/docker.sock`, and+dind cannot bind its socket at that path any more — the daemon fails to start until+someone removes the directory by hand, and every agent in the meantime has a+useless mount.++**Blast radius.** The race is only reliably avoided when the mounted socket belongs+to the **host** daemon, because that one exists before anything else starts. But+that hands an autonomous agent the host daemon: it can launch a privileged+container, mount `/`, and take over the node — PentAGI, the other flows'+containers, and the certificates on it included. That is precisely the risk this+two-node architecture exists to remove.++Pointing workers at `tcp://${PRIVATE_IP}:3376` avoids both: there is no mount to+race on, and every request the agent makes passes through the dind authorization+policy. Client certificates are mounted read-only, so an agent can use them but not+rewrite them.++`DOCKER_SOCKET` remains supported for single-node setups where the host daemon is+already trusted, but it is not recommended here.## Prerequisites-Set the private IP address that will be used throughout this setup:+Set the private IP address that will be used throughout this setup, and the location of the configuration files shipped with this guide:```bashexport PRIVATE_IP=192.168.10.10 # Replace with your worker node IP+export GUIDE_URL=https://raw.githubusercontent.com/vxcontrol/pentagi/main/examples/guides/worker_node```## Install Docker on Both Nodes@@ -98,9 +131,8 @@ DNS.1 = localhostDNS.2 = dockerDNS.3 = docker-hostIP.1 = 127.0.0.1-IP.2 = 0.0.0.0-IP.3 = ${PRIVATE_IP}"-sudo /usr/share/easy-rsa/easyrsa build-server-full server nopass # Confirm with 'yes'+IP.2 = ${PRIVATE_IP}"+sudo -E /usr/share/easy-rsa/easyrsa build-server-full server nopass # Confirm with 'yes'unset EASYRSA_EXTRA_EXTS# Generate client certificate@@ -108,24 +140,26 @@ sudo /usr/share/easy-rsa/easyrsa build-client-full client nopass # Confirm with# Copy server certificates to Docker directorysudo mkdir -p /etc/docker/certs/server-sudo cp pki/ca.crt /etc/docker/certs/server/ca.pem-sudo cp pki/issued/server.crt /etc/docker/certs/server/cert.pem-sudo cp pki/private/server.key /etc/docker/certs/server/key.pem+sudo install -m 0444 pki/ca.crt /etc/docker/certs/server/ca.pem+sudo install -m 0444 pki/issued/server.crt /etc/docker/certs/server/cert.pem+sudo install -m 0400 pki/private/server.key /etc/docker/certs/server/key.pem# Copy client certificates for remote accesssudo mkdir -p /etc/docker/certs/client-sudo cp pki/ca.crt /etc/docker/certs/client/ca.pem-sudo cp pki/issued/client.crt /etc/docker/certs/client/cert.pem-sudo cp pki/private/client.key /etc/docker/certs/client/key.pem+sudo install -m 0444 pki/ca.crt /etc/docker/certs/client/ca.pem+sudo install -m 0444 pki/issued/client.crt /etc/docker/certs/client/cert.pem+sudo install -m 0400 pki/private/client.key /etc/docker/certs/client/key.pem```+> `sudo -E` is required so that `EASYRSA_EXTRA_EXTS` survives into the easy-rsa call; without it the server certificate is issued without SANs and every TLS client rejects it.+### Configure Docker Daemon with TLSEnable TLS authentication and remote access for the Docker daemon:```bash# Configure Docker daemon with TLS settings-sudo cat > /etc/docker/daemon.json << EOF+sudo tee /etc/docker/daemon.json > /dev/null << EOF{"log-driver": "json-file","log-opts": {@@ -158,7 +192,7 @@ sudo systemctl restart dockerCreate a utility script to test secure Docker API access:```bash-sudo cat > /usr/local/bin/docker-host-tls << EOF+sudo tee /usr/local/bin/docker-host-tls > /dev/null << EOF#!/bin/bash# Docker API client wrapper for TLS connections# Usage: docker-host-tls [docker-commands]@@ -192,13 +226,21 @@ sudo chmod +x /usr/local/bin/docker-host-tlsdocker-host-tls ps && docker-host-tls info```-## Configure Docker-in-Docker (dind) on Worker Node+## Configure Hardened Docker-in-Docker (dind) on Worker Node++The dind daemon is the Docker endpoint agents actually talk to, so it is treated as hostile-input-facing and hardened on three independent layers:-Docker-in-Docker provides an isolated environment for worker containers to execute Docker commands securely.+| Layer | Control | Purpose |+|---|---|---|+| Container | explicit capability set instead of `--privileged` | dind itself runs with the minimum `dockerd` needs |+| Daemon API | OPA authorization plugin (`authz.rego`), fail-closed | denies escape primitives in every nested `containers/create` and `exec` |+| Kernel | daemon-wide seccomp profile (`seccomp.json`) | blocks block-device `mknod`, the primary confirmed escape vector |++The files referenced below ship with this guide in [`examples/guides/worker_node/`](https://github.com/vxcontrol/pentagi/tree/main/examples/guides/worker_node).### Generate TLS Certificates for dind-Create separate certificates for the dind daemon:+Create a separate PKI for the dind daemon — it must not share a CA with host Docker:```bash# Create PKI infrastructure for dind@@ -212,160 +254,200 @@ export EASYRSA_EXTRA_EXTS="subjectAltName = @alt_names[alt_names]DNS.1 = localhost-DNS.2 = docker-DNS.3 = docker-dind+DNS.2 = docker-dindIP.1 = 127.0.0.1-IP.2 = 0.0.0.0-IP.3 = ${PRIVATE_IP}"-sudo /usr/share/easy-rsa/easyrsa build-server-full server nopass # Confirm with 'yes'+IP.2 = ${PRIVATE_IP}"+sudo -E /usr/share/easy-rsa/easyrsa build-server-full server nopass # Confirm with 'yes'unset EASYRSA_EXTRA_EXTS# Generate client certificatesudo /usr/share/easy-rsa/easyrsa build-client-full client nopass # Confirm with 'yes'-# Create certificate directories-sudo mkdir -p /etc/docker/certs/dind/{ca,client,server}+# Create the directory layout dind expects+sudo mkdir -p /etc/docker/dind/{scripts,authz,certs/{ca,server,client}} \+ /var/lib/docker-dind /var/run/docker-dind++# Publish certificates (the CA private key stays in the PKI, never in /certs)+sudo install -m 0444 pki/ca.crt /etc/docker/dind/certs/ca/cert.pem+sudo install -m 0444 pki/ca.crt /etc/docker/dind/certs/server/ca.pem+sudo install -m 0444 pki/issued/server.crt /etc/docker/dind/certs/server/cert.pem+sudo install -m 0400 pki/private/server.key /etc/docker/dind/certs/server/key.pem+sudo install -m 0444 pki/ca.crt /etc/docker/dind/certs/client/ca.pem+sudo install -m 0444 pki/issued/client.crt /etc/docker/dind/certs/client/cert.pem+sudo install -m 0400 pki/private/client.key /etc/docker/dind/certs/client/key.pem+```++The dind entrypoint detects this complete set and uses it as-is instead of generating self-signed certificates on every start.++### Deploy Configuration Files-# Copy CA certificates-sudo cp pki/ca.crt /etc/docker/certs/dind/ca/cert.pem-sudo cp pki/private/ca.key /etc/docker/certs/dind/ca/key.pem+```bash+cd /tmp+for f in authz.rego daemon.json seccomp.json dockerd-entrypoint.sh \+ run-dind.sh docker-dind-tls.sh docker-dind-sock.sh \+ dind-cleanup.sh dind-cleanup.service dind-cleanup.timer policy-tests.sh; do+ curl -fsSL -o "$f" "${GUIDE_URL}/${f}"+done++# Daemon policy files — mounted read-only as /etc/docker inside dind+sudo install -m 0644 authz.rego daemon.json seccomp.json /etc/docker/dind/authz/++# Custom entrypoint (adds DOCKER_API_HOST and DOCKER_DNS_SERVERS support)+sudo install -m 0755 dockerd-entrypoint.sh /etc/docker/dind/scripts/++# Management, wrapper, and maintenance scripts+sudo install -m 0755 run-dind.sh /usr/local/bin/run-dind+sudo install -m 0755 docker-dind-tls.sh /usr/local/bin/docker-dind-tls+sudo install -m 0755 docker-dind-sock.sh /usr/local/bin/docker-dind-sock+sudo install -m 0755 dind-cleanup.sh /usr/local/bin/dind-cleanup+sudo install -m 0755 policy-tests.sh /usr/local/bin/dind-policy-tests+sudo install -m 0644 dind-cleanup.service dind-cleanup.timer /etc/systemd/system/+```-# Copy server certificates-sudo cp pki/ca.crt /etc/docker/certs/dind/server/ca.pem-sudo cp pki/issued/server.crt /etc/docker/certs/dind/server/cert.pem-sudo cp pki/private/server.key /etc/docker/certs/dind/server/key.pem+All scripts read their settings from `/etc/docker/dind/dind.env`, which is the only file you need to edit per host:-# Copy client certificates-sudo cp pki/ca.crt /etc/docker/certs/dind/client/ca.pem-sudo cp pki/issued/client.crt /etc/docker/certs/dind/client/cert.pem-sudo cp pki/private/client.key /etc/docker/certs/dind/client/key.pem+```bash+sudo tee /etc/docker/dind/dind.env > /dev/null << EOF+API_ADDRESS=${PRIVATE_IP}+DOCKER_PORT=3376+METRICS_ADDRESS=${PRIVATE_IP}+METRICS_PORT=9324+CPU_LIMIT=2+MEMORY_LIMIT=4G+MAX_AGE_HOURS=24+EOF```-### Create dind Management Script+| Variable | Default | Description |+|---|---|---|+| `API_ADDRESS` / `DOCKER_PORT` | `0.0.0.0` / `3376` | dind TLS API bind address and port |+| `METRICS_ADDRESS` / `METRICS_PORT` | `0.0.0.0` / `9324` | Prometheus metrics endpoint |+| `NETWORK` | `host` | `host` binds directly on `API_ADDRESS`; `bridge` publishes ports instead |+| `CPU_LIMIT` / `MEMORY_LIMIT` / `PIDS_LIMIT` | `2` / `4G` / `2048` | dind container resource limits |+| `DNS_SERVERS` | empty | Comma-separated DNS servers for all nested containers |+| `MAX_AGE_HOURS` | `24` | Age threshold used by the cleanup timer |++> dind runs with `--network host` by default, so its port **must differ** from the host Docker daemon's `2376`. Keep `3376` unless you also change the host daemon.-Create a script to manage the dind container lifecycle:+### Start dind```bash-sudo cat > /usr/local/bin/run-dind << EOF-#!/bin/bash+sudo run-dind+```-# Check if dind container exists-if docker ps -a --format '{{.Names}}' | grep -q "^docker-dind$"; then- if ! docker ps --format '{{.Names}}' | grep -q "^docker-dind$"; then- echo "Starting existing docker-dind container..."- docker start docker-dind- else- echo "docker-dind container is already running."- fi-else- echo "Creating new docker-dind container..."- docker run -d \- --privileged \- -v /etc/docker/certs/dind/server:/certs/server:ro \- -v /var/lib/docker-dind:/var/lib/docker \- -v /var/run/docker-dind:/var/run/dind \- -p ${PRIVATE_IP}:3376:2376 \- -p ${PRIVATE_IP}:9324:9324 \- --cpus 2 --memory 2G \- --name docker-dind \- --restart always \- --log-opt max-size=50m \- --log-opt max-file=7 \- docker:dind \- --host=unix:///var/run/dind/docker.sock \- --host=tcp://0.0.0.0:2376 \- --tls=true \- --tlscert=/certs/server/cert.pem \- --tlskey=/certs/server/key.pem \- --tlscacert=/certs/server/ca.pem \- --tlsverify=true \- --metrics-addr=0.0.0.0:9324- echo "docker-dind container created and started."-fi-EOF+The first run performs a two-phase bootstrap: dind starts without authorization, the managed OPA plugin is downloaded and installed into the dind daemon, then dind restarts with `--authorization-plugin` enabled (fail-closed). The plugin persists in `/var/lib/docker-dind`, so later starts come up with the policy active immediately.-sudo chmod +x /usr/local/bin/run-dind+Verify the daemon, the policy plugin, and both access paths:-# Start dind container and verify-run-dind && docker ps+```bash+docker ps | grep docker-dind # dind container is up+docker-dind-sock plugin ls # opa-docker-authz is enabled+docker-dind-sock run --rm hello-world # nested containers work+docker-dind-tls version # TLS endpoint answers+curl -s http://${PRIVATE_IP}:9324/metrics | head -5```-### Create dind Access Test Scripts+### Security Model-Create utilities to test dind access via TLS and Unix socket:+**dind container.** It runs without `--privileged`: every capability is dropped, then only what `dockerd` needs is added back — `SYS_ADMIN`, `NET_ADMIN`, `NET_RAW`, `SETUID`, `SETGID`, `MKNOD`, `FOWNER`, `DAC_OVERRIDE`, `CHOWN`, `AUDIT_WRITE`, `KILL`, `SYS_CHROOT`, `FSETID`, `SETFCAP`, `SETPCAP`, `NET_BIND_SERVICE`.-**TLS Access Script:**+**Nested containers.** The OPA policy defaults to `allow = false` and inspects `containers/create` and `exec`; other request types are either allowed untouched or denied outright:-```bash-sudo cat > /usr/local/bin/docker-dind-tls << EOF-#!/bin/bash-# Docker API client wrapper for dind TLS connections-# Usage: docker-dind-tls [docker-commands]+| Denied for nested containers | Covers |+|---|---|+| `--privileged` | container create and exec |+| `--cap-add` outside the whitelist | `SYS_ADMIN`, `MKNOD`, `ALL`, etc. |+| `--device`, `--device-cgroup-rule` | block/char device passthrough and cgroup rule injection |+| `--security-opt` | seccomp / AppArmor / systempaths overrides |+| `--pid`, `--ipc`, `--userns`, `--cgroupns`, `--uts` sharing | host and cross-container namespaces |+| Explicit `MaskedPaths` / `ReadonlyPaths` | removes `/proc/sys` protection → `modprobe_path` host escape |+| Host bind-mounts | **all** of them, both `-v /host:/dest` and `--mount type=bind` |+| `--sysctl`, `DeviceRequests`, non-`runc` `--runtime`, `CgroupParent` | remaining escalation fields |+| `docker cp`, `commit`, `build`, `image load`, `plugin install`, Swarm | endpoints that bypass the create gate |+| `volume create` with bind emulation, `network create` with macvlan/ipvlan | mount and L2 passthrough emulation |-export DOCKER_HOST=tcp://${PRIVATE_IP}:3376-export DOCKER_TLS_VERIFY=1-export DOCKER_CERT_PATH=/etc/docker/certs/dind/client+Allowed, so agent workloads keep working: the default capability set plus `NET_ADMIN`/`NET_RAW`, Docker-managed named and anonymous volumes, tmpfs mounts, `docker pull`, the full container lifecycle, bridge networks, and `--network host`.-# Show connection info if no arguments provided-if [ \$# -eq 0 ]; then- echo "Docker dind API connection configured:"- echo " Host: ${PRIVATE_IP}:3376"- echo " TLS: enabled"- echo " Certificates: /etc/docker/certs/dind/client/"- echo ""- echo "Usage: docker-dind-tls [docker-commands]"- echo "Examples:"- echo " docker-dind-tls version"- echo " docker-dind-tls ps"- echo " docker-dind-tls images"- exit 0-fi+**Block-device escape, dual enforcement.** `MKNOD` stays in Docker's default capability set and cannot be removed without recompiling Docker, so it is closed twice: `seccomp.json` blocks `mknod`/`mknodat` with the `S_IFBLK` flag at the kernel level (set daemon-wide via `daemon.json`), and `authz.rego` blocks both explicit `--cap-add MKNOD` and every `--security-opt` override, so the profile cannot be replaced or disabled. Together these deny `mknod /dev/sda b 8 0` + `debugfs` raw host-disk reads.-# Execute docker command with TLS environment-exec docker "\$@"-EOF+> **`--network host` is intentionally allowed** — pentest tooling needs raw sockets and host-local targets. A nested container using it reaches every service on the worker node's network stack, including the host Docker daemon's TLS port. Never store outer-daemon client certificates on the worker node, and never expose a plaintext HTTP service there that serves files.++### Update the Policy-sudo chmod +x /usr/local/bin/docker-dind-tls+`run-dind` records the SHA-256 of `authz.rego` in `/var/lib/docker-dind/.authz-policy-hash`. When the hash changes, it starts dind without authorization, force-removes **all** nested containers, and restarts with the new policy — containers created under the previous policy keep their original `HostConfig` and would otherwise survive a restart with superseded privileges.-# Test dind TLS connection-docker-dind-tls ps && docker-dind-tls info+```bash+# After editing /etc/docker/dind/authz/authz.rego+sudo docker rm -f docker-dind && sudo run-dind++# Force a purge without a policy change+sudo env PURGE=yes /usr/local/bin/run-dind```-**Unix Socket Access Script:**+### Enable Automatic Cleanup++Worker containers are short-lived; the timer force-removes anything older than `MAX_AGE_HOURS`:```bash-sudo cat > /usr/local/bin/docker-dind-sock << EOF-#!/bin/bash-# Docker API client wrapper for dind socket connections-# Usage: docker-dind-sock [docker-commands]+sudo systemctl daemon-reload+sudo systemctl enable --now dind-cleanup.timer-export DOCKER_HOST=unix:///var/run/docker-dind/docker.sock-export DOCKER_TLS_VERIFY=-export DOCKER_CERT_PATH=+systemctl status dind-cleanup.timer # check schedule+journalctl -u dind-cleanup.service -n 50 # review last run+sudo env MAX_AGE_HOURS=1 /usr/local/bin/dind-cleanup # run manually with an override+```-# Show connection info if no arguments provided-if [ \$# -eq 0 ]; then- echo "Docker dind socket connection configured:"- echo " Host: unix:///var/run/docker-dind/docker.sock"- echo ""- echo "Usage: docker-dind-sock [docker-commands]"- echo "Examples:"- echo " docker-dind-sock version"- echo " docker-dind-sock ps"- echo " docker-dind-sock images"- exit 0-fi+### Verify Isolation-# Execute docker command with socket environment-exec docker "\$@"-EOF+`dind-policy-tests` is a full test suite that exercises the authorization policy and the seccomp profile from inside a container wired exactly like a real PentAGI worker. Run it once after setup and after every policy change:++```bash+# The suite probes a plaintext HTTP service on the node; start a throwaway one+docker run -d --name dind-test-http -p 8080:80 nginx:alpine++docker run --rm -it \+ --name pentagi-terminal-test \+ --network host \+ --cap-add NET_ADMIN --cap-add NET_RAW \+ -e TARGET_IP=${PRIVATE_IP} \+ -e HTTP_PORT=8080 \+ -e DIND_TLS_PORT=3376 \+ -e OUTER_TLS_PORT=2376 \+ -e DOCKER_HOST=tcp://${PRIVATE_IP}:3376 \+ -e DOCKER_TLS_VERIFY=1 \+ -e DOCKER_CERT_PATH=/etc/docker/dind/certs/client \+ -v /usr/local/bin/dind-policy-tests:/work/policy-tests.sh:ro \+ -v /etc/docker/dind/certs/client:/etc/docker/dind/certs/client:ro \+ -w /work \+ vxcontrol/kali-linux \+ bash /work/policy-tests.sh++docker rm -f dind-test-http+```-sudo chmod +x /usr/local/bin/docker-dind-sock+This invocation mirrors exactly what PentAGI does for a real worker container: the+dind endpoint and its client certificates are supplied through the environment,+and no Docker socket is mounted. (If you still run the socket-mapping layout,+replace the three `DOCKER_*` variables and the certificate mount with+`-v /var/run/docker-dind/docker.sock:/var/run/docker.sock`.)-# Test dind socket connection-docker-dind-sock ps && docker-dind-sock info+Positive tests cover legitimate workloads (nmap, masscan, curl, sqlmap, nginx, volumes, tmpfs, container lifecycle); negative tests cover escape primitives (privileged containers, dangerous capabilities, host namespaces, bind-mounts, block-device `mknod`, `nsenter`). Every test should report `[ PASS ]` or `[ SKIP ]`, and the exit code is `0` when nothing failed. **A failed negative test is an isolation gap; a failed positive test is a false positive that will break agent workloads.**++### Troubleshooting++```bash+docker logs docker-dind # dind daemon output+docker-dind-sock info | grep -A 20 "Security" # confirm seccomp profile is active+docker-dind-sock plugin ls # confirm authz plugin is enabled++# Re-bootstrap the plugin from scratch+sudo rm -f /var/lib/docker-dind/.authz-plugin-installed \+ /var/lib/docker-dind/.authz-policy-hash+sudo docker rm -f docker-dind && sudo run-dind```+If `run-dind` fails with a missing `/dev/fuse`, load the module first: `sudo modprobe fuse`.+## Security & Firewall Configuration### Required Port Access@@ -390,6 +472,8 @@ Each worker container (`pentagi-terminal-N`) dynamically allocates **2 ports** f- **Inbound**: Allow access to port range 28000-30000 from target networks being tested- Configure perimeter firewall to permit OOB traffic from target networks to worker node+Both Docker APIs must be reachable **only** from the main node — nested containers may use `--network host` and can therefore probe every port on this node.+## Transfer Certificates to Main NodeCopy the client certificates from the worker node to the main PentAGI node for secure Docker API access. The certificates need to be transferred to specific directories that the PentAGI installer will recognize.@@ -418,7 +502,7 @@ Transfer the dind client certificates to the main node:```bash# On the worker node - create archive with dind certificates-sudo tar czf docker-dind-ssl.tar.gz -C /etc/docker/certs/dind client/+sudo tar czf docker-dind-ssl.tar.gz -C /etc/docker/dind/certs client/# Transfer to main node (replace <MAIN_NODE_IP> with actual IP)scp docker-dind-ssl.tar.gz root@<MAIN_NODE_IP>:/opt/pentagi/@@ -445,7 +529,7 @@ ls -la /opt/pentagi/docker-dind-ssl/# key.pem (Client private key)```-These certificate directories will be used by the PentAGI installer to configure secure connections to the worker node Docker services.+These certificate directories will be used by the PentAGI installer to configure secure connections to the worker node Docker services. Keep them readable by root only, and outside any directory served over HTTP.## Install PentAGI on Main Node@@ -482,10 +566,10 @@ The installer requires appropriate privileges to interact with the Docker API fo```bash# Add your user to the docker groupsudo usermod -aG docker $USER-+# Log out and log back in, or activate the group immediatelynewgrp docker-+# Verify Docker access (should run without sudo)docker ps```@@ -500,23 +584,87 @@ After the installer completes and PentAGI is running, manually configure the Doc2. **Navigate to Tools → Docker Environment**3. **Fill in the Docker Environment Configuration fields:**-**For Standard Mode (Host Docker):**-- **Docker Access**: `true` (enable Docker access for workers)+**For Standard Mode (Host Docker) — recommended:**++*How PentAGI reaches the worker node:*+- **Docker Host**: `tcp://${PRIVATE_IP}:2376` (TLS connection to host Docker)+- **TLS Verification**: `1` (enable TLS verification)+- **TLS Certificates**: `/opt/pentagi/docker-host-ssl` (path on the **main node**)++*How worker containers reach dind:*+- **Docker Access**: `true` (agents get Docker)+- **Docker Socket**: leave **empty** — no socket is mounted, see [the rationale above](#why-workers-reach-dind-over-tls-instead-of-a-mounted-socket)+- **Worker Docker Daemon Host**: `tcp://${PRIVATE_IP}:3376` (dind TLS endpoint)+- **Worker Docker TLS Verify**: enabled+- **Worker Docker Certificate Path**: `/etc/docker/dind/certs/client` (path on the **worker node**)++*Everything else:*- **Network Admin**: `true` (enable network scanning capabilities)-- **Docker Socket**: `/var/run/docker-dind/docker.sock` (path inside worker containers)- **Docker Network**: `pentagi-network` (custom network name)-- **Public IP Address**: `${PRIVATE_IP}` (worker node IP a front of tested network for OOB attacks)+- **Public IP Address**: `${PRIVATE_IP}` (worker node IP in front of the tested network, for OOB attacks)- **Work Directory**: Leave empty (use default Docker volumes)- **Default Image**: `debian:latest` (or leave empty)- **Pentesting Image**: `vxcontrol/kali-linux` (or leave empty)-- **Docker Host**: `tcp://${PRIVATE_IP}:2376` (TLS connection to host Docker)-- **TLS Verification**: `1` (enable TLS verification)-- **TLS Certificates**: `/opt/pentagi/docker-host-ssl` (path to client certificates)++Note the two different certificate locations, and that they are **not**+interchangeable:++| Setting | Certificates for | Path resolved on |+|---|---|---|+| TLS Certificates | host Docker `:2376` | main node — mounted into the PentAGI container |+| Worker Docker Certificate Path | dind `:3376` | worker node — mounted read-only into each worker container |++The dind client certificates are already in place at+`/etc/docker/dind/certs/client` from the dind setup above, so nothing needs to be+copied for this. PentAGI bind-mounts that directory read-only at the identical+path inside every worker container and injects `DOCKER_HOST`,+`DOCKER_TLS_VERIFY` and `DOCKER_CERT_PATH` accordingly, so `docker` just works+inside the sandbox.++> **Never point Worker Docker Certificate Path at `/etc/docker/certs/client`.**+> Those are the *host* daemon's client certificates. Handing them to an agent+> grants it the host Docker API on `:2376`, which defeats the entire isolation+> model — nested containers may use `--network host` and can already reach that+> port. Only the dind certificates belong in a worker container.**For Direct Mode (dind only):**- Use the same configuration but change:- **Docker Host**: `tcp://${PRIVATE_IP}:3376` (TLS connection to dind)-- **TLS Certificates**: `/opt/pentagi/docker-dind-ssl` (path to dind client certificates)-- **Docker Socket**: Leave empty (no socket mapping needed)+- **TLS Certificates**: `/opt/pentagi/docker-dind-ssl` (path to dind client certificates on the main node)+- **Docker Access**: `false`, **Docker Socket** and all **Worker Docker \*** fields: leave empty — worker containers are nested containers here, and the authorization policy denies both the socket bind-mount and the certificate bind-mount+- **Work Directory**: must stay empty, so PentAGI uses a Docker volume instead of a denied host bind-mountThe certificate directories `/opt/pentagi/docker-host-ssl/` and `/opt/pentagi/docker-dind-ssl/` will be automatically mounted into the PentAGI container for secure TLS authentication.++### Equivalent `.env` Configuration++If you configure the main node by hand instead of through the installer:++```bash+## How PentAGI reaches the worker node's host Docker+DOCKER_HOST=tcp://${PRIVATE_IP}:2376+DOCKER_TLS_VERIFY=1+PENTAGI_DOCKER_CERT_PATH=/opt/pentagi/docker-host-ssl # path on the MAIN node++## How worker containers reach dind+DOCKER_INSIDE=true+DOCKER_SOCKET= # empty: mount no socket+DOCKER_INSIDE_HOST=tcp://${PRIVATE_IP}:3376+DOCKER_INSIDE_TLS_VERIFY=1+DOCKER_INSIDE_CERT_PATH=/etc/docker/dind/certs/client # path on the WORKER node++DOCKER_NET_ADMIN=true+DOCKER_NETWORK=pentagi-network+DOCKER_PUBLIC_IP=${PRIVATE_IP}+```++Verify from inside a running worker container:++```bash+docker-host-tls exec -it pentagi-terminal-1 docker version # talks to dind, not the host+docker-host-tls exec -it pentagi-terminal-1 env | grep DOCKER_+```++The second command should show `DOCKER_HOST`, `DOCKER_TLS_VERIFY` and+`DOCKER_CERT_PATH` — with no `_INSIDE_` in the names — and there must be **no**+`/var/run/docker.sock` inside the container.diff --git a/examples/guides/worker_node/README.md b/examples/guides/worker_node/README.mdnew file mode 100644index 00000000..f0b2417d--- /dev/null+++ b/examples/guides/worker_node/README.md@@ -0,0 +1,25 @@+# Worker Node Configuration Bundle++Configuration files for the hardened Docker-in-Docker (dind) sandbox described in+[worker_node.md](../worker_node.md). Deploy them with the steps in that guide — it+covers certificates, paths, and the `dind.env` settings these files read.++| File | Installed as | Purpose |+|---|---|---|+| `authz.rego` | `/etc/docker/dind/authz/authz.rego` | OPA authorization policy — fail-closed gate on every dind API call |+| `daemon.json` | `/etc/docker/dind/authz/daemon.json` | dind daemon config; sets `seccomp.json` as the daemon-wide default profile |+| `seccomp.json` | `/etc/docker/dind/authz/seccomp.json` | Seccomp profile for all nested containers; blocks block-device `mknod` |+| `dockerd-entrypoint.sh` | `/etc/docker/dind/scripts/dockerd-entrypoint.sh` | dind entrypoint with `DOCKER_API_HOST` / `DOCKER_DNS_SERVERS` support |+| `run-dind.sh` | `/usr/local/bin/run-dind` | Creates the dind container, bootstraps the OPA plugin, purges on policy change |+| `docker-dind-tls.sh` | `/usr/local/bin/docker-dind-tls` | Docker CLI wrapper for the dind TLS endpoint |+| `docker-dind-sock.sh` | `/usr/local/bin/docker-dind-sock` | Docker CLI wrapper for the dind Unix socket |+| `dind-cleanup.sh` | `/usr/local/bin/dind-cleanup` | Removes nested containers older than `MAX_AGE_HOURS` |+| `dind-cleanup.service` / `.timer` | `/etc/systemd/system/` | Hourly systemd timer running the cleanup script |+| `policy-tests.sh` | `/usr/local/bin/dind-policy-tests` | Isolation test suite for the policy and seccomp profile |++The three files under `/etc/docker/dind/authz/` are mounted read-only as `/etc/docker`+inside the dind container: that directory is both the daemon config directory and the+policy source the OPA plugin reads.++Every script sources `/etc/docker/dind/dind.env` (overridable via the `DIND_ENV`+environment variable), so per-host settings live in one place.diff --git a/examples/guides/worker_node/authz.rego b/examples/guides/worker_node/authz.regonew file mode 100644index 00000000..9ee47742--- /dev/null+++ b/examples/guides/worker_node/authz.rego@@ -0,0 +1,565 @@+# =============================================================================+# Docker authorization policy for the DinD daemon (opa-docker-authz).+#+# Goal: nested containers launched THROUGH DinD must not be able to escape to+# the DinD sandbox layer or reach the physical host. Three classes of+# primitives are denied:+#+# 1. Capability / device / namespace escalation: obtaining SYS_ADMIN or raw+# block-device access enables mounting the disk and reading the host FS.+#+# 2. Host bind-mount escalation: mounting ANY host path (including writable+# directories like /work) allows filesystem pivots, symlink escapes, and+# credential leakage. ALL host bind-mounts are denied; use Docker volumes.+#+# 3. Host namespace sharing: --pid=host, --ipc=host, etc. expose the DinD+# host's process tree and IPC namespace, enabling credential extraction.+#+# IMPORTANT: this is a deny-list. It is only as strong as its completeness.+# Any new Docker API field that can grant SYS_ADMIN / device access / namespace+# escape or filesystem access must be added here. For a kernel-enforced+# guarantee, use dind-rootless.+#+# The opa-docker-authz plugin evaluates data.docker.authz.allow (boolean).+#+# Controlled request types:+# - containers/create (POST) — checked for capability/mount/namespace violations+# - containers/{id}/exec (POST) — checked for privileged flag+# - containers/{id}/update (POST) — checked for DeviceCgroupRules injection+# - containers/{id}/archive (GET) — unconditionally denied (PKI extraction risk)+# - commit (POST) — unconditionally denied (state snapshot risk)+# - build (POST) — unconditionally denied (supply chain injection risk, legacy API)+# - session (POST, BuildKit) — unconditionally denied (bypasses /build in Docker 23+)+# - images/load (POST) — unconditionally denied (arbitrary tar with device nodes / setuid)+# - plugins/* (POST/PUT/DELETE) — unconditionally denied (arbitrary plugin = OPA bypass)+# - swarm/services/nodes/configs/secrets (POST/PUT/DELETE) — unconditionally denied+# (Swarm creates containers bypassing HostConfig validation)+# - volumes/create (POST) — checked for bind-emulation driver options+# - networks/create (POST) — checked for L2 drivers (macvlan/ipvlan)+# All other Docker API requests are allowed without further inspection.+# =============================================================================+package docker.authz++default allow = false++# Allow anything that is neither a container-create nor a container-exec request+# nor any other controlled request type.+allow {+ not is_container_create+ not is_container_exec+ not is_container_archive+ not is_container_commit+ not is_image_build+ not is_buildkit_session+ not is_container_update+ not is_image_load+ not is_plugin_mutate+ not is_swarm_mutate+ not is_volume_create+ not is_network_create+}++# Allow container creation only when it triggers no violation.+allow {+ is_container_create+ count(violation) == 0+}++# Allow exec only when it triggers no exec_violation.+allow {+ is_container_exec+ count(exec_violation) == 0+}++# Allow container update only when it triggers no update_violation.+allow {+ is_container_update+ count(update_violation) == 0+}++# Allow volume creation only when driver options are safe (no bind-emulation).+allow {+ is_volume_create+ count(volume_violation) == 0+}++# Allow network creation only when the driver is not an L2 passthrough type.+allow {+ is_network_create+ count(network_violation) == 0+}++# Archive, commit, and build are unconditionally denied.+# These endpoints bypass the containers/create gate and can be used to:+# - archive: extract PKI material from containers with bind-mounts or+# sensitive volumes (GET /containers/{id}/archive?path=/hostfs/certs)+# - commit: snapshot running container state including cached credentials+# - build: inject malicious image layers bypassing OPA create restrictions++# ---------------------------------------------------------------------------+# Request classification+# ---------------------------------------------------------------------------++is_container_create {+ input.Method == "POST"+ regex.match(`/containers/create`, input.Path)+}++is_container_exec {+ input.Method == "POST"+ regex.match(`/containers/[^/]+/exec`, input.Path)+}++# Container archive (GET) — reading container filesystems; gated to prevent+# extraction of sensitive paths such as /proc/1/root (host FS pivot),+# /certs, and any other path that could expose PKI or host data.+is_container_archive {+ input.Method == "GET"+ regex.match(`/containers/[^/]+/archive`, input.Path)+}++# Container commit — committing a running container to an image; gated to+# prevent capturing sensitive state and exfiltrating it as an image layer.+is_container_commit {+ input.Method == "POST"+ regex.match(`/commit`, input.Path)+}++# Image build — building a new image from a Dockerfile context; gated to+# prevent supply-chain attacks embedding malicious layers or escape tooling.+is_image_build {+ input.Method == "POST"+ regex.match(`/build`, input.Path)+}++# BuildKit session — Docker's default builder (DOCKER_BUILDKIT=1, default since+# Docker 23) bypasses the legacy POST /build endpoint and instead opens a+# WebSocket session via POST /session before issuing gRPC build commands.+# Denied alongside is_image_build to close the build surface completely.+is_buildkit_session {+ input.Method == "POST"+ regex.match(`/session`, input.Path)+}++# Container update — updating resource limits and runtime config of a running+# container. Most fields (memory, CPU) are safe; DeviceCgroupRules is not:+# injecting "b 8:* rwm" grants the container permission to open any block+# device, which bypasses the device-cgroup eBPF filter set at create-time.+# Combined with seccomp.json this is not immediately exploitable+# (mknod for S_IFBLK is blocked and /dev/ contains no block device nodes),+# but the gap should be closed at the policy layer for defense-in-depth.+is_container_update {+ input.Method == "POST"+ regex.match(`/containers/[^/]+/update`, input.Path)+}++# Image load — POST /images/load accepts an arbitrary tar archive and unpacks+# it into the daemon image store. Unlike registry pulls, tar archives are not+# signed or scanned and can contain block device nodes or setuid binaries.+# Pulling from registries (POST /images/create?fromImage=...) is NOT blocked.+is_image_load {+ input.Method == "POST"+ regex.match(`/images/load`, input.Path)+}++# Plugin management (mutating) — installing, enabling, disabling, or removing+# plugins grants the plugin process daemon-level privileges and can implement+# arbitrary volume, network, or authz logic. A malicious authz plugin would+# unconditionally approve all subsequent requests, bypassing this policy.+# Plugins are managed out-of-band via daemon.json; runtime management is off.+is_plugin_mutate {+ input.Method != "GET"+ regex.match(`/plugins`, input.Path)+}++# Swarm / Services (mutating) — Swarm service specs go through /services/create+# rather than /containers/create, and the daemon may schedule containers+# without applying the HostConfig validation enforced above. Blocking all+# Swarm mutating operations ensures every container goes through the guarded+# containers/create path.+is_swarm_mutate {+ input.Method != "GET"+ regex.match(`/swarm`, input.Path)+}++is_swarm_mutate {+ input.Method != "GET"+ regex.match(`/services`, input.Path)+}++is_swarm_mutate {+ input.Method != "GET"+ regex.match(`/nodes`, input.Path)+}++is_swarm_mutate {+ input.Method != "GET"+ regex.match(`/configs`, input.Path)+}++is_swarm_mutate {+ input.Method != "GET"+ regex.match(`/secrets`, input.Path)+}++# Volume creation — POST /volumes/create is safe for named volumes with the+# local driver and default options. However, local-driver DriverOpts of the+# form {type:none, o:bind, device:/host/path} emulate a bind-mount from the+# DinD container's own filesystem into nested containers, potentially exposing+# TLS certs or DinD daemon state. Checked via volume_violation below.+is_volume_create {+ input.Method == "POST"+ regex.match(`/volumes/create`, input.Path)+}++# Network creation — POST /networks/create is safe for bridge/null/overlay.+# macvlan and ipvlan attach containers directly to the host's L2 segment,+# bypassing iptables rules and allowing access to physical network interfaces.+# Checked via network_violation below.+is_network_create {+ input.Method == "POST"+ regex.match(`/networks/create`, input.Path)+}++# ---------------------------------------------------------------------------+# Capability whitelist: the set of capabilities a nested container may request+# via --cap-add. Mirrors Docker's default cap set with two intentional deltas:+# - MKNOD excluded (block device escape vector; still in Docker default set)+# - NET_ADMIN added (NOT a Docker default; safe for pentest tooling, see below)+# Never add SYS_ADMIN / SYS_MODULE / SYS_PTRACE / SYS_RAWIO / SYS_BOOT.+# ---------------------------------------------------------------------------+allowed_caps = {+ "CHOWN",+ "DAC_OVERRIDE",+ "FSETID",+ "FOWNER",+ # MKNOD intentionally omitted from the --cap-add whitelist: CAP_MKNOD allows+ # creation of block device nodes (mknod /dev/sda b 8 1), which combined with+ # tools like debugfs enables raw ext4 filesystem reads WITHOUT SYS_ADMIN.+ # This was the primary confirmed escape vector in pentest.+ #+ # Dual enforcement against MKNOD block-device escape:+ # 1. authz blocks explicit "--cap-add MKNOD" here.+ # 2. daemon.json sets seccomp.json as the daemon-wide default seccomp profile.+ # seccomp.json blocks mknod/mknodat with S_IFBLK at the kernel level.+ # authz blocks "--security-opt" overrides (see below), so the seccomp+ # profile cannot be replaced or disabled by nested containers.+ "NET_RAW",+ "SETGID",+ "SETUID",+ "SETFCAP",+ "SETPCAP",+ "NET_BIND_SERVICE",+ "SYS_CHROOT",+ "KILL",+ "AUDIT_WRITE",+ # NET_ADMIN is not in Docker's default set, but pentest tooling commonly+ # needs it (raw sockets, VPN, interface config). It is network-namespace+ # scoped and does NOT grant mount / CAP_SYS_ADMIN, so it is safe re: host+ # filesystem escape.+ "NET_ADMIN",+}++# Normalize a capability name: upper-case and strip an optional "CAP_" prefix.+normalize_cap(c) = n {+ u := upper(c)+ n := trim_prefix(u, "CAP_")+}++# ---------------------------------------------------------------------------+# Exec violations: privileged exec sessions grant CAP_SYS_ADMIN + CAP_NET_ADMIN+# to an already-running container, bypassing container-create checks. Blocked+# here to maintain policy consistency with the --privileged create restriction.+# ---------------------------------------------------------------------------++exec_violation["privileged exec sessions are not allowed"] {+ is_container_exec+ input.Body.Privileged == true+}++# ---------------------------------------------------------------------------+# Container-create violations (additional fields)+# ---------------------------------------------------------------------------++# Sysctls: with --network=host + CAP_NET_ADMIN, container-level sysctl writes+# go directly into the host network namespace (e.g. net.ipv4.ip_forward).+# Blocking all Sysctls prevents unintended host kernel parameter changes.+# Pentest tools (nmap, masscan) do not require custom sysctls.+violation["sysctls are not allowed"] {+ is_container_create+ count(input.Body.HostConfig.Sysctls) > 0+}++# DeviceRequests: GPU / accelerator access via device plugins. Not needed for+# pentest workloads; device plugins can expose DMA or sensitive hardware paths.+violation["device requests are not allowed"] {+ is_container_create+ count(input.Body.HostConfig.DeviceRequests) > 0+}++# Runtime: non-standard runtimes (e.g. runsc, crun) may have different+# seccomp defaults or capability handling. Enforce runc only.+violation[msg] {+ is_container_create+ rt := input.Body.HostConfig.Runtime+ rt != ""+ rt != "runc"+ msg := sprintf("runtime not allowed: %v", [rt])+}++# ---------------------------------------------------------------------------+# Update violations: DeviceCgroupRules injection bypasses the device-cgroup+# eBPF filter and grants the container access to block devices. While not+# immediately exploitable (mknod S_IFBLK is seccomp-blocked and /dev/ has no+# block nodes), it is a direct policy bypass and must be denied here.+# Safe update fields (Memory, NanoCpus, CpusetCpus, PidsLimit, RestartPolicy,+# BlkioWeight, etc.) are explicitly allowed when DeviceCgroupRules is absent.+# ---------------------------------------------------------------------------++update_violation["DeviceCgroupRules injection via update is not allowed"] {+ is_container_update+ count(input.Body.DeviceCgroupRules) > 0+}++# ---------------------------------------------------------------------------+# Volume violations: local-driver bind-emulation+# ---------------------------------------------------------------------------++# The local volume driver accepts DriverOpts {type:none, o:bind, device:/path}+# which makes Docker treat /path inside DinD as the volume backing store —+# effectively a bind-mount from DinD's own filesystem into nested containers.+# This could expose /etc/docker/dind/certs, /var/run/dind/docker.sock, etc.+volume_violation["bind-emulation via volume driver option 'o=bind' is not allowed"] {+ is_volume_create+ opt := input.Body.DriverOpts["o"]+ contains(lower(opt), "bind")+}++volume_violation["bind-emulation via volume driver option 'type=none' is not allowed"] {+ is_volume_create+ input.Body.DriverOpts["type"] == "none"+}++# ---------------------------------------------------------------------------+# Network violations: L2 driver restriction+# ---------------------------------------------------------------------------++# macvlan and ipvlan attach containers directly to the host's L2 network+# segment, bypassing Docker's iptables rules and allowing access to all+# hosts on the physical subnet. bridge, null, and overlay are safe.+_unsafe_net_drivers := {"macvlan", "ipvlan"}++network_violation[msg] {+ is_network_create+ drv := lower(input.Body.Driver)+ _unsafe_net_drivers[drv]+ msg := sprintf("network driver not allowed: %v", [input.Body.Driver])+}++# ---------------------------------------------------------------------------+# Violations+# ---------------------------------------------------------------------------++# --privileged+violation["privileged containers are not allowed"] {+ is_container_create+ input.Body.HostConfig.Privileged == true+}++# --cap-add of anything outside the safe whitelist (also catches "ALL")+violation[msg] {+ is_container_create+ some i+ cap := input.Body.HostConfig.CapAdd[i]+ not allowed_caps[normalize_cap(cap)]+ msg := sprintf("capability not allowed: %v", [cap])+}++# --device (block/char device passthrough)+violation["device passthrough is not allowed"] {+ is_container_create+ count(input.Body.HostConfig.Devices) > 0+}++# --device-cgroup-rule+violation["device cgroup rules are not allowed"] {+ is_container_create+ count(input.Body.HostConfig.DeviceCgroupRules) > 0+}++# --security-opt (seccomp/apparmor/systempaths=unconfined, etc.)+violation["custom security options are not allowed"] {+ is_container_create+ count(input.Body.HostConfig.SecurityOpt) > 0+}++# Host namespaces (pid/ipc/userns/cgroup/uts).+#+# NOTE on --network=host: host *network* is intentionally NOT denied here.+# Nested containers need it for DNS resolution and raw socket access from+# the DinD bridge network. However, it is a documented HIGH risk: DinD itself+# runs with --network=host, so nested containers with --network=host can reach+# every service on the physical host's network stack — including the outer+# Docker daemon's TLS port (3376). This was the primary Phase 3 escape vector.+# Mitigations:+# - Docker-ca TLS client certificates must never be accessible inside DinD.+# - Outer daemon must deploy its own authorization plugin.+# - If network isolation is more important than raw-socket pentesting,+# remove --network=host from this allowlist and configure explicit DNS.+violation["host PID namespace is not allowed"] {+ is_container_create+ input.Body.HostConfig.PidMode == "host"+}++# --pid=container:<id>: shares another container's PID namespace; blocked for+# defense-in-depth even though the kernel currently rejects it at mount namespace+# boundaries. Keeping the block here ensures policy consistency if the downstream+# check is ever relaxed or a different runtime is used.+violation["container PID namespace sharing is not allowed"] {+ is_container_create+ startswith(lower(input.Body.HostConfig.PidMode), "container:")+}++violation["host IPC namespace is not allowed"] {+ is_container_create+ input.Body.HostConfig.IpcMode == "host"+}++# --ipc=shareable: marks a container as a donor that other containers can join.+# Blocked to prevent IPC namespace sharing chains that bypass the host IPC denial.+violation["shareable IPC mode is not allowed"] {+ is_container_create+ input.Body.HostConfig.IpcMode == "shareable"+}++# --ipc=container:<id>: joins another container's IPC namespace.+violation["container IPC namespace sharing is not allowed"] {+ is_container_create+ startswith(lower(input.Body.HostConfig.IpcMode), "container:")+}++violation["host user namespace is not allowed"] {+ is_container_create+ input.Body.HostConfig.UsernsMode == "host"+}++violation["host cgroup namespace is not allowed"] {+ is_container_create+ input.Body.HostConfig.CgroupnsMode == "host"+}++violation["host UTS namespace is not allowed"] {+ is_container_create+ input.Body.HostConfig.UTSMode == "host"+}++# ---------------------------------------------------------------------------+# MaskedPaths and ReadonlyPaths overrides+#+# CONFIRMED ESCAPE VECTOR+# Setting ReadonlyPaths:[] removes Docker's default /proc/sys read-only mount.+# Since /proc/sys/kernel is NOT a PID namespace path — it is global to the+# host kernel — writing /proc/sys/kernel/modprobe from inside a nested DinD+# container changes the HOST kernel's usermode helper path. When any package+# is installed with `apk add` (or equivalent), the busybox post-install+# trigger calls request_module(), the host kernel executes modprobe_path,+# and the payload runs as root in the init mount namespace = physical host.+#+# Setting MaskedPaths:[] exposes /proc/kcore (raw kernel memory),+# /proc/keys (kernel keyring), /sys/firmware/efi/efivars (UEFI variables —+# writing here can permanently brick the system), and /proc/sched_debug.+#+# This is NOT a CVE in runc. It is legitimate Docker API behaviour: empty+# arrays [] explicitly replace the default lists, whereas an absent field+# (null / not present) keeps Docker's built-in safe defaults. The same+# mechanism is used by Kubernetes procMount:Unmasked (a privileged feature+# gated behind PodSecurity admission).+#+# NOTE: --security-opt systempaths=unconfined achieves the same effect as+# MaskedPaths:[]+ReadonlyPaths:[] and is already denied by the security-opt+# violation above. This adds API-level protection for direct JSON injection.+#+# Safe rule: absent field (null/undefined) = Docker applies built-in defaults.+# is_array([]) or is_array([...]) = DENIED.+# ---------------------------------------------------------------------------++violation["explicit ReadonlyPaths override is not allowed — absent field uses Docker defaults; any explicit array (including []) removes /proc/sys read-only protection and enables modprobe_path host escape"] {+ is_container_create+ is_array(input.Body.HostConfig.ReadonlyPaths)+}++violation["explicit MaskedPaths override is not allowed — absent field uses Docker defaults; any explicit array (including []) unmasks /proc/kcore, /proc/keys, and /sys/firmware/efi/efivars"] {+ is_container_create+ is_array(input.Body.HostConfig.MaskedPaths)+}++# ---------------------------------------------------------------------------+# CgroupParent override+#+# Placing a container in a non-default cgroup tree changes which eBPF device+# filter programs are active for the container's cgroup. A container placed+# in the root cgroup ("/") or an ancestor cgroup may inherit a more permissive+# device policy than DinD's isolated cgroup subtree would provide, potentially+# bypassing the device-cgroup restrictions that protect block device reads.+# Also breaks PID/resource accounting isolation.+# ---------------------------------------------------------------------------++violation["CgroupParent override is not allowed"] {+ is_container_create+ count(input.Body.HostConfig.CgroupParent) > 0+}++# ---------------------------------------------------------------------------+# Bind-mount restrictions: ALL host filesystem bind-mounts are denied.+#+# Rationale: any bind-mount of a host path into a nested container can be+# used to escape the DinD sandbox — either directly (sensitive dirs) or via+# symlink indirection from a writable directory. Rather than maintaining an+# ever-growing deny-list, we take the safe default: deny ALL bind-mounts.+#+# Containers that need persistent storage should use Docker volumes (--volume+# or --mount type=volume), which are managed by the DinD daemon and stored+# under /var/lib/docker/volumes — fully isolated from the DinD host FS.+# Ephemeral scratch space should use --tmpfs or named volumes.+#+# What is allowed:+# --mount type=volume,... – Docker-managed named/anonymous volumes+# --mount type=tmpfs,... – in-memory tmpfs mounts+#+# What is denied:+# -v /any/host/path:/dest – any host bind-mount (legacy -v syntax)+# --mount type=bind,... – any host bind-mount (structured syntax)+# ---------------------------------------------------------------------------++# Block ALL legacy -v SOURCE:DEST bind-mounts (source starts with "/").+violation[msg] {+ is_container_create+ some i+ bind := input.Body.HostConfig.Binds[i]+ # Binds format is "SOURCE:DEST" or "SOURCE:DEST:opts".+ # Named volumes have no leading "/" in the source (e.g. "myvolume:/data").+ # Anonymous volumes have an empty or absent source.+ parts := split(bind, ":")+ src := parts[0]+ # Block only absolute paths (host bind-mounts).+ startswith(src, "/")+ msg := sprintf("host bind-mount not allowed (use Docker volumes instead): %v", [src])+}++# Block structured --mount type=bind mounts.+violation[msg] {+ is_container_create+ some i+ mount := input.Body.HostConfig.Mounts[i]+ mount.Type == "bind"+ msg := sprintf("host bind-mount not allowed (use Docker volumes instead): %v", [mount.Source])+}++# Block BindMounts enriched field (opa-docker-authz resolved symlinks).+# Any entry here is a host bind-mount that was resolved by the plugin.+violation[msg] {+ is_container_create+ some i+ bm := input.BindMounts[i]+ msg := sprintf("host bind-mount not allowed (use Docker volumes instead): %v", [bm.Source])+}diff --git a/examples/guides/worker_node/daemon.json b/examples/guides/worker_node/daemon.jsonnew file mode 100644index 00000000..f0ea83e5--- /dev/null+++ b/examples/guides/worker_node/daemon.json@@ -0,0 +1,3 @@+{+ "seccomp-profile": "/etc/docker/seccomp.json"+}diff --git a/examples/guides/worker_node/dind-cleanup.service b/examples/guides/worker_node/dind-cleanup.servicenew file mode 100644index 00000000..5ea8eb8c--- /dev/null+++ b/examples/guides/worker_node/dind-cleanup.service@@ -0,0 +1,10 @@+[Unit]+Description=DinD container cleanup (remove stale containers)+After=docker.service++[Service]+Type=oneshot+ExecStart=/usr/local/bin/dind-cleanup+StandardOutput=journal+StandardError=journal+SyslogIdentifier=dind-cleanupdiff --git a/examples/guides/worker_node/dind-cleanup.sh b/examples/guides/worker_node/dind-cleanup.shnew file mode 100755index 00000000..6673cb17--- /dev/null+++ b/examples/guides/worker_node/dind-cleanup.sh@@ -0,0 +1,50 @@+#!/bin/bash+# =============================================================================+# dind-cleanup — remove nested DinD containers older than MAX_AGE_HOURS.+#+# Called hourly by the dind-cleanup.timer systemd unit.+# Uses /usr/local/bin/docker-dind-sock to connect to the DinD unix socket.+#+# Both running and stopped containers are removed. Worker containers are+# expected to be short-lived; anything alive for more than the threshold is+# considered stale and is force-removed.+# =============================================================================++set -uo pipefail++# A per-run override (MAX_AGE_HOURS=1 dind-cleanup) wins over the config file.+_MAX_AGE_HOURS="${MAX_AGE_HOURS:-}"++DIND_ENV="${DIND_ENV:-/etc/docker/dind/dind.env}"+if [ -r "${DIND_ENV}" ]; then+ . "${DIND_ENV}"+fi++MAX_AGE_HOURS="${_MAX_AGE_HOURS:-${MAX_AGE_HOURS:-24}}"+DOCKER="/usr/local/bin/docker-dind-sock"++log() { echo "[$(date '+%Y-%m-%dT%H:%M:%S%z')] dind-cleanup: $*"; }++# If DinD is not running, skip silently — Persistent=true ensures the timer+# retries at the next scheduled tick.+if ! "${DOCKER}" info >/dev/null 2>&1; then+ log "DinD daemon unreachable — skipping"+ exit 0+fi++# --filter until=Xh lists containers created more than X hours ago.+mapfile -t STALE < <("${DOCKER}" ps -a -q --filter "until=${MAX_AGE_HOURS}h" 2>/dev/null)++STALE_COUNT=${#STALE[@]}++if [ "$STALE_COUNT" -eq 0 ]; then+ log "No containers older than ${MAX_AGE_HOURS}h — nothing to do"+ exit 0+fi++log "Found $STALE_COUNT container(s) older than ${MAX_AGE_HOURS}h:"+"${DOCKER}" ps -a --filter "until=${MAX_AGE_HOURS}h" \+ --format 'table {{.ID}}\t{{.Names}}\t{{.Status}}\t{{.CreatedAt}}' 2>/dev/null || true++"${DOCKER}" rm -f "${STALE[@]}"+log "Removed $STALE_COUNT container(s)"diff --git a/examples/guides/worker_node/dind-cleanup.timer b/examples/guides/worker_node/dind-cleanup.timernew file mode 100644index 00000000..2da2c55c--- /dev/null+++ b/examples/guides/worker_node/dind-cleanup.timer@@ -0,0 +1,10 @@+[Unit]+Description=DinD container cleanup timer (runs hourly)++[Timer]+OnBootSec=5min+OnUnitActiveSec=1h+Persistent=true++[Install]+WantedBy=timers.targetdiff --git a/examples/guides/worker_node/docker-dind-sock.sh b/examples/guides/worker_node/docker-dind-sock.shnew file mode 100755index 00000000..70fbdbcf--- /dev/null+++ b/examples/guides/worker_node/docker-dind-sock.sh@@ -0,0 +1,29 @@+#!/bin/bash+# Docker API client wrapper for the DinD Unix socket.+# Usage: docker-dind-sock [docker-commands]++DIND_ENV="${DIND_ENV:-/etc/docker/dind/dind.env}"+if [ -r "${DIND_ENV}" ]; then+ . "${DIND_ENV}"+fi++RUN_PATH="${RUN_PATH:-/var/run/docker-dind}"++export DOCKER_HOST="unix://${RUN_PATH}/docker.sock"+export DOCKER_TLS_VERIFY=+export DOCKER_CERT_PATH=++# Show connection info if no arguments provided+if [ $# -eq 0 ]; then+ echo "Docker dind socket connection configured:"+ echo " Host: ${DOCKER_HOST}"+ echo ""+ echo "Usage: docker-dind-sock [docker-commands]"+ echo "Examples:"+ echo " docker-dind-sock version"+ echo " docker-dind-sock ps"+ echo " docker-dind-sock images"+ exit 0+fi++exec docker "$@"diff --git a/examples/guides/worker_node/docker-dind-tls.sh b/examples/guides/worker_node/docker-dind-tls.shnew file mode 100755index 00000000..ac6e55e0--- /dev/null+++ b/examples/guides/worker_node/docker-dind-tls.sh@@ -0,0 +1,38 @@+#!/bin/bash+# Docker API client wrapper for the DinD TLS endpoint.+# Usage: docker-dind-tls [docker-commands]++DIND_ENV="${DIND_ENV:-/etc/docker/dind/dind.env}"+if [ -r "${DIND_ENV}" ]; then+ . "${DIND_ENV}"+fi++API_ADDRESS="${API_ADDRESS:-0.0.0.0}"+DOCKER_PORT="${DOCKER_PORT:-3376}"+CERTS_PATH="${CERTS_PATH:-/etc/docker/dind/certs}"++# 0.0.0.0 is a bind address, not a destination: connect over loopback instead.+if [ "${API_ADDRESS}" = "0.0.0.0" ]; then+ API_ADDRESS=127.0.0.1+fi++export DOCKER_HOST="tcp://${API_ADDRESS}:${DOCKER_PORT}"+export DOCKER_TLS_VERIFY=1+export DOCKER_CERT_PATH="${CERTS_PATH}/client"++# Show connection info if no arguments provided+if [ $# -eq 0 ]; then+ echo "Docker dind API connection configured:"+ echo " Host: ${API_ADDRESS}:${DOCKER_PORT}"+ echo " TLS: enabled"+ echo " Certificates: ${CERTS_PATH}/client/"+ echo ""+ echo "Usage: docker-dind-tls [docker-commands]"+ echo "Examples:"+ echo " docker-dind-tls version"+ echo " docker-dind-tls ps"+ echo " docker-dind-tls images"+ exit 0+fi++exec docker "$@"diff --git a/examples/guides/worker_node/dockerd-entrypoint.sh b/examples/guides/worker_node/dockerd-entrypoint.shnew file mode 100755index 00000000..74286b01--- /dev/null+++ b/examples/guides/worker_node/dockerd-entrypoint.sh@@ -0,0 +1,294 @@+#!/bin/sh+set -eu++# CUSTOM: Set minimum API version for Docker daemon for Portainer compatibility+export DOCKER_MIN_API_VERSION=1.41++# CUSTOM: Allow configuring Docker API host via environment variable+# Default to 0.0.0.0:2376 for backward compatibility with official image+# Usage: -e DOCKER_API_HOST=tcp://192.168.1.10:2376+if [ -z "${DOCKER_API_HOST+set}" ]; then+ DOCKER_API_HOST="tcp://0.0.0.0:2376"+fi++# CUSTOM: Allow configuring Docker API port for non-TLS mode+# Default to 0.0.0.0:2375 for backward compatibility with official image+# Usage: -e DOCKER_API_HOST_NOTLS=tcp://192.168.1.10:2375+if [ -z "${DOCKER_API_HOST_NOTLS+set}" ]; then+ DOCKER_API_HOST_NOTLS="tcp://0.0.0.0:2375"+fi++_tls_ensure_private() {+ local f="$1"; shift+ [ -s "$f" ] || openssl genrsa -out "$f" 4096+}+_tls_san() {+ {+ ip -oneline address | awk '{ gsub(/\/.+$/, "", $4); print "IP:" $4 }'+ {+ cat /etc/hostname+ echo 'docker'+ echo 'localhost'+ hostname -f+ hostname -s+ } | sed 's/^/DNS:/'+ [ -z "${DOCKER_TLS_SAN:-}" ] || echo "$DOCKER_TLS_SAN"+ } | sort -u | xargs printf '%s,' | sed "s/,\$//"+}+_tls_generate_certs() {+ local dir="$1"; shift++ # CUSTOM: Check if pre-generated certificates exist and are valid+ # If server, client, and CA certificates all exist, use them (externally managed certs)+ if [ -s "$dir/server/ca.pem" ] && [ -s "$dir/server/cert.pem" ] && [ -s "$dir/server/key.pem" ] && \+ [ -s "$dir/client/ca.pem" ] && [ -s "$dir/client/cert.pem" ] && [ -s "$dir/client/key.pem" ] && \+ [ -s "$dir/ca/cert.pem" ]; then+ echo "Using pre-generated certificates from $dir (externally managed)"+ openssl verify -CAfile "$dir/server/ca.pem" "$dir/server/cert.pem" || return 1+ openssl verify -CAfile "$dir/client/ca.pem" "$dir/client/cert.pem" || return 1+ return 0+ fi++ # Original behavior: if server/{ca,key,cert}.pem && !ca/key.pem, do NOTHING except verify (user likely managing CA themselves)+ # if ca/key.pem || !ca/cert.pem, generate CA public if necessary+ # if ca/key.pem, generate server public+ # if ca/key.pem, generate client public+ # (regenerating public certs every startup to account for SAN/IP changes and/or expiration)++ if [ -s "$dir/server/ca.pem" ] && [ -s "$dir/server/cert.pem" ] && [ -s "$dir/server/key.pem" ] && [ ! -s "$dir/ca/key.pem" ]; then+ echo "Using existing server certificates (external CA)"+ openssl verify -CAfile "$dir/server/ca.pem" "$dir/server/cert.pem" || return 1+ return 0+ fi++ # https://github.com/FiloSottile/mkcert/issues/174+ local certValidDays='825'++ if [ -s "$dir/ca/key.pem" ] || [ ! -s "$dir/ca/cert.pem" ]; then+ # if we either have a CA private key or do *not* have a CA public key, then we should create/manage the CA+ mkdir -p "$dir/ca"+ _tls_ensure_private "$dir/ca/key.pem"+ openssl req -new -key "$dir/ca/key.pem" \+ -out "$dir/ca/cert.pem" \+ -subj '/CN=docker:dind CA' \+ -x509 \+ -days "$certValidDays" \+ -addext keyUsage=critical,digitalSignature,keyCertSign+ fi++ if [ -s "$dir/ca/key.pem" ]; then+ # if we have a CA private key, we should create/manage a server key+ mkdir -p "$dir/server"+ _tls_ensure_private "$dir/server/key.pem"+ openssl req -new -key "$dir/server/key.pem" \+ -out "$dir/server/csr.pem" \+ -subj '/CN=docker:dind server'+ cat > "$dir/server/openssl.cnf" <<-EOF+ [ x509_exts ]+ extendedKeyUsage = serverAuth+ subjectAltName = $(_tls_san)+ EOF+ openssl x509 -req \+ -in "$dir/server/csr.pem" \+ -CA "$dir/ca/cert.pem" \+ -CAkey "$dir/ca/key.pem" \+ -CAcreateserial \+ -out "$dir/server/cert.pem" \+ -days "$certValidDays" \+ -extfile "$dir/server/openssl.cnf" \+ -extensions x509_exts+ cp "$dir/ca/cert.pem" "$dir/server/ca.pem"+ openssl verify -CAfile "$dir/server/ca.pem" "$dir/server/cert.pem"+ fi++ if [ -s "$dir/ca/key.pem" ]; then+ # if we have a CA private key, we should create/manage a client key+ mkdir -p "$dir/client"+ _tls_ensure_private "$dir/client/key.pem"+ chmod 0644 "$dir/client/key.pem" # openssl defaults to 0600 for the private key, but this one needs to be shared with arbitrary client contexts+ openssl req -new \+ -key "$dir/client/key.pem" \+ -out "$dir/client/csr.pem" \+ -subj '/CN=docker:dind client'+ cat > "$dir/client/openssl.cnf" <<-'EOF'+ [ x509_exts ]+ extendedKeyUsage = clientAuth+ EOF+ openssl x509 -req \+ -in "$dir/client/csr.pem" \+ -CA "$dir/ca/cert.pem" \+ -CAkey "$dir/ca/key.pem" \+ -CAcreateserial \+ -out "$dir/client/cert.pem" \+ -days "$certValidDays" \+ -extfile "$dir/client/openssl.cnf" \+ -extensions x509_exts+ cp "$dir/ca/cert.pem" "$dir/client/ca.pem"+ openssl verify -CAfile "$dir/client/ca.pem" "$dir/client/cert.pem"+ fi+}++# no arguments passed+# or first arg is `-f` or `--some-option`+if [ "$#" -eq 0 ] || [ "${1#-}" != "$1" ]; then+ # set "dockerSocket" to the default "--host" *unix socket* value (for both standard or rootless)+ uid="$(id -u)"+ if [ "$uid" = '0' ]; then+ dockerSocket='unix:///var/run/docker.sock'+ else+ # if we're not root, we must be trying to run rootless+ : "${XDG_RUNTIME_DIR:=/run/user/$uid}"+ dockerSocket="unix://$XDG_RUNTIME_DIR/docker.sock"+ fi+ case "${DOCKER_HOST:-}" in+ unix://*)+ dockerSocket="$DOCKER_HOST"+ ;;+ esac++ # CUSTOM: Build DNS server arguments if DOCKER_DNS_SERVERS is set+ # Format: "8.8.8.8,8.8.4.4" or "192.168.1.100"+ DNS_ARGS=""+ if [ -n "${DOCKER_DNS_SERVERS:-}" ]; then+ # Split comma-separated DNS servers and add --dns for each (POSIX-compatible)+ OLD_IFS="$IFS"+ IFS=','+ for dns in $DOCKER_DNS_SERVERS; do+ # Trim whitespace+ dns=$(echo "$dns" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')+ if [ -n "$dns" ]; then+ DNS_ARGS="$DNS_ARGS --dns=$dns"+ fi+ done+ IFS="$OLD_IFS"+ fi++ # add our default arguments+ if [ -n "${DOCKER_TLS_CERTDIR:-}" ]; then+ _tls_generate_certs "$DOCKER_TLS_CERTDIR"+ # generate certs and use TLS if requested/possible (default in 19.03+)+ # CUSTOM: Use DOCKER_API_HOST instead of hardcoded tcp://0.0.0.0:2376+ set -- dockerd \+ --host="$dockerSocket" \+ --host="$DOCKER_API_HOST" \+ --tlsverify \+ --tlscacert "$DOCKER_TLS_CERTDIR/server/ca.pem" \+ --tlscert "$DOCKER_TLS_CERTDIR/server/cert.pem" \+ --tlskey "$DOCKER_TLS_CERTDIR/server/key.pem" \+ $DNS_ARGS \+ "$@"+ # CUSTOM: Extract IP:PORT from DOCKER_API_HOST for rootless mode+ DOCKER_API_BIND="${DOCKER_API_HOST#tcp://}"+ DOCKER_API_PORT="${DOCKER_API_BIND##*:}"+ DOCKERD_ROOTLESS_ROOTLESSKIT_FLAGS="${DOCKERD_ROOTLESS_ROOTLESSKIT_FLAGS:-} -p ${DOCKER_API_BIND}:${DOCKER_API_PORT}/tcp"+ else+ # TLS disabled (-e DOCKER_TLS_CERTDIR='') or missing certs+ # CUSTOM: Use DOCKER_API_HOST_NOTLS instead of hardcoded tcp://0.0.0.0:2375+ set -- dockerd \+ --host="$dockerSocket" \+ --host="$DOCKER_API_HOST_NOTLS" \+ $DNS_ARGS \+ "$@"+ # CUSTOM: Extract IP:PORT from DOCKER_API_HOST_NOTLS for rootless mode+ DOCKER_API_BIND_NOTLS="${DOCKER_API_HOST_NOTLS#tcp://}"+ DOCKER_API_PORT_NOTLS="${DOCKER_API_BIND_NOTLS##*:}"+ DOCKERD_ROOTLESS_ROOTLESSKIT_FLAGS="${DOCKERD_ROOTLESS_ROOTLESSKIT_FLAGS:-} -p ${DOCKER_API_BIND_NOTLS}:${DOCKER_API_PORT_NOTLS}/tcp"+ fi+fi++if [ "$1" = 'dockerd' ]; then+ # explicitly remove Docker's default PID file to ensure that it can start properly if it was stopped uncleanly (and thus didn't clean up the PID file)+ find /run /var/run -iname 'docker*.pid' -delete || :++ # XXX inject "docker-init" (tini) as pid1 to workaround https://github.com/docker-library/docker/issues/318 (zombie container-shim processes)+ set -- docker-init -- "$@"++ iptablesLegacy=+ if [ -n "${DOCKER_IPTABLES_LEGACY+x}" ]; then+ # let users choose explicitly to legacy or not to legacy+ iptablesLegacy="$DOCKER_IPTABLES_LEGACY"+ if [ -n "$iptablesLegacy" ]; then+ modprobe ip_tables || :+ modprobe ip6_tables || :+ else+ modprobe nf_tables || :+ fi+ elif (+ # https://git.netfilter.org/iptables/tree/iptables/nft-shared.c?id=f5cf76626d95d2c491a80288bccc160c53b44e88#n420+ # https://github.com/docker-library/docker/pull/468#discussion_r1442131459+ for f in /proc/net/ip_tables_names /proc/net/ip6_tables_names /proc/net/arp_tables_names; do+ if b="$(cat "$f")" && [ -n "$b" ]; then+ exit 0+ fi+ done+ exit 1+ ); then+ # if we already have any "legacy" iptables rules, we should always use legacy+ iptablesLegacy=1+ elif ! iptables -nL > /dev/null 2>&1; then+ # if iptables fails to run, chances are high the necessary kernel modules aren't loaded (perhaps the host is using xtables, for example)+ # https://github.com/docker-library/docker/issues/350+ # https://github.com/moby/moby/issues/26824+ # https://github.com/docker-library/docker/pull/437#issuecomment-1854900620+ modprobe nf_tables || :+ if ! iptables -nL > /dev/null 2>&1; then+ # might be host has no nf_tables, but Alpine is all-in now (so let's try a legacy fallback)+ modprobe ip_tables || :+ modprobe ip6_tables || :+ if /usr/local/sbin/.iptables-legacy/iptables -nL > /dev/null 2>&1; then+ iptablesLegacy=1+ fi+ fi+ fi+ if [ -n "$iptablesLegacy" ]; then+ # see https://github.com/docker-library/docker/issues/463 (and the dind Dockerfile where this directory is set up)+ export PATH="/usr/local/sbin/.iptables-legacy:$PATH"+ fi+ iptables --version # so users can see whether it's legacy or not++ uid="$(id -u)"+ if [ "$uid" != '0' ]; then+ # if we're not root, we must be trying to run rootless+ if ! command -v rootlesskit > /dev/null; then+ echo >&2 "error: attempting to run rootless dockerd but missing 'rootlesskit' (perhaps the 'docker:dind-rootless' image variant is intended?)"+ exit 1+ fi+ user="$(id -un 2>/dev/null || :)"+ if ! grep -qE "^($uid${user:+|$user}):" /etc/subuid || ! grep -qE "^($uid${user:+|$user}):" /etc/subgid; then+ echo >&2 "error: attempting to run rootless dockerd but missing necessary entries in /etc/subuid and/or /etc/subgid for $uid"+ exit 1+ fi+ : "${XDG_RUNTIME_DIR:=/run/user/$uid}"+ export XDG_RUNTIME_DIR+ if ! mkdir -p "$XDG_RUNTIME_DIR" || [ ! -w "$XDG_RUNTIME_DIR" ] || ! mkdir -p "$HOME/.local/share/docker" || [ ! -w "$HOME/.local/share/docker" ]; then+ echo >&2 "error: attempting to run rootless dockerd but need writable HOME ($HOME) and XDG_RUNTIME_DIR ($XDG_RUNTIME_DIR) for user $uid"+ exit 1+ fi+ if [ -f /proc/sys/kernel/unprivileged_userns_clone ] && unprivClone="$(cat /proc/sys/kernel/unprivileged_userns_clone)" && [ "$unprivClone" != '1' ]; then+ echo >&2 "error: attempting to run rootless dockerd but need 'kernel.unprivileged_userns_clone' (/proc/sys/kernel/unprivileged_userns_clone) set to 1"+ exit 1+ fi+ if [ -f /proc/sys/user/max_user_namespaces ] && maxUserns="$(cat /proc/sys/user/max_user_namespaces)" && [ "$maxUserns" = '0' ]; then+ echo >&2 "error: attempting to run rootless dockerd but need 'user.max_user_namespaces' (/proc/sys/user/max_user_namespaces) set to a sufficiently large value"+ exit 1+ fi+ # TODO overlay support detection?+ exec rootlesskit \+ --net="${DOCKERD_ROOTLESS_ROOTLESSKIT_NET:-vpnkit}" \+ --mtu="${DOCKERD_ROOTLESS_ROOTLESSKIT_MTU:-1500}" \+ --disable-host-loopback \+ --port-driver=builtin \+ --copy-up=/etc \+ --copy-up=/run \+ ${DOCKERD_ROOTLESS_ROOTLESSKIT_FLAGS:-} \+ "$@"+ elif [ -x '/usr/local/bin/dind' ]; then+ # if we have the (mostly defunct now) Docker-in-Docker wrapper script, use it+ set -- '/usr/local/bin/dind' "$@"+ fi+else+ # if it isn't `dockerd` we're trying to run, pass it through `docker-entrypoint.sh` so it gets `DOCKER_HOST` set appropriately too+ set -- docker-entrypoint.sh "$@"+fi++exec "$@"diff --git a/examples/guides/worker_node/policy-tests.sh b/examples/guides/worker_node/policy-tests.shnew file mode 100755index 00000000..e2e247a9--- /dev/null+++ b/examples/guides/worker_node/policy-tests.sh@@ -0,0 +1,1374 @@+#!/usr/bin/env bash+# =============================================================================+# DinD policy test-suite (OPA authz + hardened seccomp).+#+# WHERE TO RUN:+# Inside a PentAGI worker container (a child of the *host* Docker daemon) whose+# `docker` CLI is wired to the hardened *DinD* daemon. Every `docker run` below+# therefore creates a NESTED container subject to:+# - the OPA authorization plugin (authz.rego) — gates containers/create + exec+# - the default seccomp profile (seccomp.json) — kernel-enforced floor+# - the per-container device cgroup + capability bounding set+#+# WHAT IT CHECKS:+# POSITIVE tests — legitimate pentest/app workloads MUST work (no false positives):+# nmap / masscan / curl+openssl / nginx+apache / java / python+sqlmap /+# volumes / tmpfs / --network=host / DNS / raw sockets / mkfifo /+# char-device mknod / docker pull / container lifecycle (start/stop/restart/+# pause/unpause/kill/logs/inspect/top/stats/rename) / image management+# (list/tag/rmi) / safe volume create / bridge network create /+# runtime features (--init/--user/--env/--label/-p/--workdir/--entrypoint) /+# compose-style multi-container workflow with shared volumes.+# NEGATIVE tests — host-escape primitives MUST be blocked:+# --privileged, dangerous --cap-add, --device, --security-opt, host+# namespaces, host bind-mounts, privileged exec, mknod block-device, mount /+# images/load, plugin install, swarm init, sysctl injection,+# DeviceRequests, custom runtime, volume bind-emulation, macvlan/ipvlan.+#+# USAGE:+# ./policy-tests.sh # run everything+# DOCKER="docker -H tcp://10.100.1.3:2376 --tls" ./policy-tests.sh+# TARGET_IP=10.100.1.3 ./policy-tests.sh+#+# EXIT CODE: non-zero if any test FAILED (a failed NEGATIVE test = security gap,+# a failed POSITIVE test = false positive that would break agents).+# =============================================================================++set -uo pipefail++# ---- configuration ---------------------------------------------------------+# DOCKER may be a plain binary name ("docker") or a multi-word invocation+# ("docker --tls --tlscacert … -H tcp://…"). Split into an array so that+# "${DOCKER[@]}" expands each flag as a separate word when used as a command.+# shellcheck disable=SC2206+DOCKER=(${DOCKER:-docker})+TARGET_IP="${TARGET_IP:-10.100.1.3}" # host reachable from nested containers+HTTP_PORT="${HTTP_PORT:-8080}" # plaintext HTTP service on the host+DIND_TLS_PORT="${DIND_TLS_PORT:-2376}" # DinD daemon mTLS API+OUTER_TLS_PORT="${OUTER_TLS_PORT:-3376}" # outer daemon mTLS API+SSH_PORT="${SSH_PORT:-22}"++# Networking for tests that must reach the HOST service IP ($TARGET_IP).+# Nested containers on the DinD *bridge* network are NAT'd and frequently CANNOT+# reach the host's own service IP (interface binding / hairpin), whereas the+# host network namespace can — and the OPA policy intentionally ALLOWS+# --network=host. This is also how PentAGI agents reach host-local targets.+# Override with TARGET_NET="" to force the default bridge.+TARGET_NET="${TARGET_NET:---network host}"++# Images (override via env if your registry differs). Pinned where it matters.+IMG_ALPINE="${IMG_ALPINE:-alpine:3.20}"+IMG_CURL="${IMG_CURL:-curlimages/curl:8.10.1}"+IMG_NGINX="${IMG_NGINX:-nginx:1.27-alpine}"+IMG_HTTPD="${IMG_HTTPD:-httpd:2.4-alpine}"+IMG_NMAP="${IMG_NMAP:-instrumentisto/nmap:7.95}"+IMG_JAVA="${IMG_JAVA:-eclipse-temurin:21-jdk}"+IMG_PY="${IMG_PY:-python:3.12-alpine}"++LABEL="pentagi-dind-test"+NETPREFIX="pgdtnet"+VOLPREFIX="pgdtvol"++# opa-docker-authz / daemon denial signatures (CLI surfaces the policy message).+DENY_RE='authorization denied|opa-docker-authz|administrative policy|not allowed|bind-mount not allowed|capability not allowed|privileged containers|namespace is not allowed|security options are not allowed|device passthrough|device cgroup|received 403|access denied'++# ---- presentation ----------------------------------------------------------+if [ -t 1 ]; then+ GRN=$'\e[32m'; RED=$'\e[31m'; YLW=$'\e[33m'; BLU=$'\e[36m'; BLD=$'\e[1m'; RST=$'\e[0m'+else+ GRN=""; RED=""; YLW=""; BLU=""; BLD=""; RST=""+fi++TOTAL=0; PASS=0; FAIL=0; SKIP=0; INFO=0+declare -a FAILED_NAMES=()++section(){ printf "\n${BLU}${BLD}=== %s ===${RST}\n" "$1"; }++record(){ # status name [detail]+ local st="$1" name="$2" detail="${3:-}"+ case "$st" in+ PASS) TOTAL=$((TOTAL+1)); PASS=$((PASS+1)); printf " ${GRN}[ PASS ]${RST} %s\n" "$name" ;;+ FAIL) TOTAL=$((TOTAL+1)); FAIL=$((FAIL+1)); FAILED_NAMES+=("$name")+ printf " ${RED}[ FAIL ]${RST} %s\n" "$name"+ [ -n "$detail" ] && printf " ${RED}↳ %s${RST}\n" "$detail" ;;+ SKIP) TOTAL=$((TOTAL+1)); SKIP=$((SKIP+1)); printf " ${YLW}[ SKIP ]${RST} %s\n" "$name"+ [ -n "$detail" ] && printf " ${YLW}↳ %s${RST}\n" "$detail" ;;+ INFO) INFO=$((INFO+1)); printf " ${BLU}[ INFO ]${RST} %s\n" "$name"+ [ -n "$detail" ] && printf " ${BLU}↳ %s${RST}\n" "$detail" ;;+ esac+}++LAST_OUT=""; LAST_RC=0+cap(){ LAST_OUT="$("$@" 2>&1)"; LAST_RC=$?; }+tailout(){ echo "$LAST_OUT" | tail -n 2 | tr '\n' ' ' | cut -c1-300; }++# Positive: arbitrary docker subcommand must succeed (not docker run).+expect_cmd_ok(){ local name="$1"; shift+ cap "${DOCKER[@]}" "$@"+ if [ "$LAST_RC" -eq 0 ]; then record PASS "$name"+ else record FAIL "$name" "rc=$LAST_RC: $(tailout)"; fi+}++# Negative: arbitrary docker subcommand must be authz-denied.+expect_cmd_deny(){ local name="$1"; shift+ cap "${DOCKER[@]}" "$@"+ if [ "$LAST_RC" -ne 0 ] && echo "$LAST_OUT" | grep -qiE "$DENY_RE"; then+ record PASS "$name"+ elif [ "$LAST_RC" -ne 0 ]; then+ record FAIL "$name" "failed, but NOT via authz denial: $(tailout)"+ else+ record FAIL "$name" "SECURITY GAP: request was ALLOWED (expected denial)"+ fi+}++# Direct HTTP call to the DinD API for endpoints not exposed by the Docker CLI.+# Automatically picks unix-socket or TCP transport based on DOCKER[@] config.+# Direct HTTP call to the DinD API for endpoints not exposed by the Docker CLI.+# Handles both unix-socket mode and TLS/TCP mode (extracts certs from DOCKER[@]).+dind_api_post(){ # path json+ local path="$1" body="$2" d="${DOCKER[*]}"+ if [[ "$d" =~ -H[[:space:]]+tcp://([^[:space:]]+) ]]; then+ local endpoint="https://${BASH_REMATCH[1]}"+ local curl_tls=()+ [[ "$d" =~ --tlscacert[[:space:]]+([^[:space:]]+) ]] && curl_tls+=(--cacert "${BASH_REMATCH[1]}")+ [[ "$d" =~ --tlscert[[:space:]]+([^[:space:]]+) ]] && curl_tls+=(--cert "${BASH_REMATCH[1]}")+ [[ "$d" =~ --tlskey[[:space:]]+([^[:space:]]+) ]] && curl_tls+=(--key "${BASH_REMATCH[1]}")+ LAST_OUT=$(curl -s "${curl_tls[@]}" -X POST "${endpoint}${path}" \+ -H 'Content-Type: application/json' -d "$body" 2>&1)+ else+ LAST_OUT=$(curl -s --unix-socket /var/run/docker.sock \+ -X POST "http://localhost${path}" \+ -H 'Content-Type: application/json' -d "$body" 2>&1)+ fi+ LAST_RC=$?+}++# ---- image availability (lazy, cached) -------------------------------------+declare -A IMG_STATE+need_image(){+ local img="$1"+ case "${IMG_STATE[$img]:-}" in+ ok) return 0 ;; no) return 1 ;;+ esac+ if "${DOCKER[@]}" image inspect "$img" >/dev/null 2>&1 || "${DOCKER[@]}" pull "$img" >/dev/null 2>&1; then+ IMG_STATE[$img]=ok; return 0+ fi+ IMG_STATE[$img]=no; return 1+}++# ---- generic assertions ----------------------------------------------------+# Negative: container creation must be rejected by the authz plugin.+expect_deny(){ local name="$1"; shift+ cap "${DOCKER[@]}" run --rm --label "$LABEL" "$@"+ if [ "$LAST_RC" -ne 0 ] && echo "$LAST_OUT" | grep -qiE "$DENY_RE"; then+ record PASS "$name"+ elif [ "$LAST_RC" -ne 0 ]; then+ record FAIL "$name" "failed, but NOT via authz denial: $(tailout)"+ else+ record FAIL "$name" "SECURITY GAP: request was ALLOWED (expected denial)"+ fi+}++# Positive: container must run and exit 0.+expect_run_ok(){ local name="$1"; shift+ cap "${DOCKER[@]}" run --rm --label "$LABEL" "$@"+ if [ "$LAST_RC" -eq 0 ]; then record PASS "$name"+ else record FAIL "$name" "exit=$LAST_RC: $(tailout)"; fi+}++# Positive: container runs and stdout matches a regex.+expect_contains(){ local name="$1" pat="$2"; shift 2+ cap "${DOCKER[@]}" run --rm --label "$LABEL" "$@"+ if [ "$LAST_RC" -eq 0 ] && echo "$LAST_OUT" | grep -qiE "$pat"; then+ record PASS "$name"+ else+ record FAIL "$name" "rc=$LAST_RC, want /$pat/, got: $(tailout)"+ fi+}++# Negative (in-container): container STARTS but the inner syscall is refused.+expect_inner_fail(){ local name="$1" pat="$2"; shift 2+ cap "${DOCKER[@]}" run --rm --label "$LABEL" "$@"+ if [ "$LAST_RC" -ne 0 ] && echo "$LAST_OUT" | grep -qiE "$pat"; then+ record PASS "$name"+ else+ record FAIL "$name" "rc=$LAST_RC (expected refusal /$pat/): $(tailout)"+ fi+}++# Positive tool test that installs a dependency at runtime (apk/pip). The inner+# command MUST `exit 200` when the dependency install fails, so we can SKIP+# (no package mirror egress) instead of reporting a false FAIL.+expect_tool(){ local name="$1" pat="$2"; shift 2+ cap "${DOCKER[@]}" run --rm --label "$LABEL" "$@"+ if [ "$LAST_RC" -eq 200 ]; then+ record SKIP "$name" "runtime dependency install failed (no package egress?)"+ elif [ "$LAST_RC" -eq 0 ] && echo "$LAST_OUT" | grep -qiE "$pat"; then+ record PASS "$name"+ else+ record FAIL "$name" "rc=$LAST_RC, want /$pat/, got: $(tailout)"+ fi+}++# ---- cleanup ---------------------------------------------------------------+cleanup(){+ local ids nets vols+ ids="$("${DOCKER[@]}" ps -aq --filter "label=$LABEL" 2>/dev/null)"+ [ -n "$ids" ] && "${DOCKER[@]}" rm -f $ids >/dev/null 2>&1+ nets="$("${DOCKER[@]}" network ls -q --filter "name=$NETPREFIX" 2>/dev/null)"+ [ -n "$nets" ] && "${DOCKER[@]}" network rm $nets >/dev/null 2>&1+ vols="$("${DOCKER[@]}" volume ls -q --filter "name=$VOLPREFIX" 2>/dev/null)"+ [ -n "$vols" ] && "${DOCKER[@]}" volume rm $vols >/dev/null 2>&1+}+trap cleanup EXIT++# =============================================================================+# PREFLIGHT+# =============================================================================+section "Preflight"+cap "${DOCKER[@]}" version --format '{{.Server.Version}}'+if [ "$LAST_RC" -ne 0 ]; then+ printf " ${RED}Cannot reach the Docker daemon via '%s'. Aborting.${RST}\n" "${DOCKER[*]}"+ exit 2+fi+printf " Docker server version: %s\n" "$LAST_OUT"+printf " Target host: %s (http:%s, dind-tls:%s, outer-tls:%s, ssh:%s)\n" \+ "$TARGET_IP" "$HTTP_PORT" "$DIND_TLS_PORT" "$OUTER_TLS_PORT" "$SSH_PORT"++if ! need_image "$IMG_ALPINE"; then+ printf " ${RED}Base image %s unavailable; cannot run the suite.${RST}\n" "$IMG_ALPINE"+ exit 2+fi+# Warm the common images (best effort).+for i in "$IMG_CURL" "$IMG_NMAP"; do need_image "$i" >/dev/null 2>&1 || true; done++# Best-effort egress probe (informational only — package-install tests below+# self-skip via the `exit 200` sentinel, so a wrong guess here costs nothing).+# Probe several well-known hosts because some environments allow the registry+# but block arbitrary egress (which made a single example.com probe misleading).+HAVE_EGRESS=0+cap "${DOCKER[@]}" run --rm --label "$LABEL" "$IMG_ALPINE" sh -c '+ for h in dl-cdn.alpinelinux.org pypi.org 1.1.1.1; do+ if nc -w 3 "$h" 443 </dev/null >/dev/null 2>&1; then echo EGRESS_OK; break; fi+ done'+echo "$LAST_OUT" | grep -q EGRESS_OK && HAVE_EGRESS=1+printf " Outbound internet egress (best-effort): %s\n" "$([ $HAVE_EGRESS -eq 1 ] && echo yes || echo "no/filtered")"+printf " Host-target network mode: %s\n" "${TARGET_NET:-<default bridge>}"++# =============================================================================+# RUNTIME COMPONENT VERSION AUDIT+# Extracts component versions from the DinD daemon and checks them against+# known CVE thresholds. A failed version check records FAIL (security gap)+# because the component is vulnerable even if current defense-in-depth+# (RO /proc/sys, OPA, capability restrictions) mitigates active exploitation.+# =============================================================================+section "Runtime component version audit"++RUNC_VER=$("${DOCKER[@]}" version --format \+ '{{range .Server.Components}}{{if eq .Name "runc"}}{{.Version}}{{end}}{{end}}' 2>/dev/null | tr -d '\n')+CTR_VER=$("${DOCKER[@]}" version --format \+ '{{range .Server.Components}}{{if eq .Name "containerd"}}{{.Version}}{{end}}{{end}}' 2>/dev/null | tr -d '\n')+ENG_VER=$("${DOCKER[@]}" version --format '{{.Server.Version}}' 2>/dev/null | tr -d '\n')++record INFO "Docker Engine: ${ENG_VER:-unknown}"+record INFO "containerd: ${CTR_VER:-unknown}"+record INFO "runc: ${RUNC_VER:-unknown}"++# Helper: returns 0 (true) when $1 >= $2 (both semver strings).+# Requires GNU sort -V; busybox sort falls back gracefully to SKIP.+_ver_ge(){+ local hi+ hi=$(printf '%s\n%s\n' "$2" "$1" | sort -V 2>/dev/null | tail -1)+ [ "$hi" = "$1" ]+}++# ---- CVE-2024-21626 "Leaky Vessels" (runc working-dir fd leak).+# Exploitable WITHOUT --privileged on runc < 1.1.12.+LEAKY_MIN="1.1.12"+if [ -z "${RUNC_VER}" ]; then+ record SKIP "runc CVE-2024-21626 (Leaky Vessels)" "could not determine runc version"+elif ! command -v sort >/dev/null 2>&1 || ! printf '%s\n' a b | sort -V >/dev/null 2>&1; then+ record SKIP "runc CVE-2024-21626 (Leaky Vessels)" "sort -V not available for version comparison"+elif _ver_ge "${RUNC_VER}" "${LEAKY_MIN}"; then+ record PASS "runc ${RUNC_VER} >= ${LEAKY_MIN} — CVE-2024-21626 Leaky Vessels patched"+else+ record FAIL "runc ${RUNC_VER} VULNERABLE — CVE-2024-21626 Leaky Vessels (fd leak, no --privileged needed)" \+ "Upgrade DinD image to bundle runc >= ${LEAKY_MIN}."+fi++# ---- CVE-2025-31133/31134/31135 (masked-paths symlink bypass, /dev/console mount+# race, procfs write redirect). All fixed in runc >= 1.2.8 / >= 1.3.3.+# Current mitigation: RO /proc/sys mount blocks core_pattern write.+RUNC_SAFE_MIN="1.2.8"+if [ -z "${RUNC_VER}" ]; then+ record SKIP "runc CVE-2025-31133/31134/31135 check" "could not determine runc version"+elif ! printf '%s\n' a b | sort -V >/dev/null 2>&1; then+ record SKIP "runc CVE-2025-31133/31134/31135 check" "sort -V not available"+elif _ver_ge "${RUNC_VER}" "${RUNC_SAFE_MIN}"; then+ record PASS "runc ${RUNC_VER} >= ${RUNC_SAFE_MIN} — CVE-2025-31133/31134/31135 patched"+else+ record FAIL "runc ${RUNC_VER} VULNERABLE — CVE-2025-31133/31134/31135 (procfs write via symlink)" \+ "Upgrade DinD image to runc >= ${RUNC_SAFE_MIN}. Mitigation: RO /proc/sys (must stay RO)."+fi++# =============================================================================+# POSITIVE — baseline & allowed HostConfig features (no false positives)+# =============================================================================+section "POSITIVE — baseline & allowed features"++expect_contains "basic container runs and prints output" "hello-dind" \+ "$IMG_ALPINE" echo hello-dind++expect_run_ok "--network=host is allowed (intentional, for DNS/raw sockets)" \+ --network host "$IMG_ALPINE" true++expect_run_ok "--cap-add NET_ADMIN allowed (VPN/iface config tooling)" \+ --cap-add NET_ADMIN "$IMG_ALPINE" true++expect_run_ok "--cap-add NET_RAW allowed (raw-socket scanners)" \+ --cap-add NET_RAW "$IMG_ALPINE" true++expect_run_ok "--read-only rootfs + --tmpfs writable" \+ --read-only --tmpfs /tmp:rw "$IMG_ALPINE" sh -c 'echo ok > /tmp/x && cat /tmp/x >/dev/null'++expect_run_ok "resource limits (--memory/--cpus/--pids-limit) accepted" \+ --memory 256m --cpus 1 --pids-limit 256 "$IMG_ALPINE" true++# =============================================================================+# POSITIVE — storage (named volume, anonymous volume, tmpfs)+# =============================================================================+section "POSITIVE — volumes & tmpfs"++NAMED_VOL="${VOLPREFIX}_named_$RANDOM"+TOKEN="tok_$RANDOM"+cap "${DOCKER[@]}" run --rm --label "$LABEL" -v "$NAMED_VOL:/data" "$IMG_ALPINE" sh -c "echo $TOKEN > /data/f"+if [ "$LAST_RC" -eq 0 ]; then+ cap "${DOCKER[@]}" run --rm --label "$LABEL" -v "$NAMED_VOL:/data" "$IMG_ALPINE" cat /data/f+ if [ "$LAST_RC" -eq 0 ] && [ "$LAST_OUT" = "$TOKEN" ]; then+ record PASS "named volume persists & is shared across containers"+ else+ record FAIL "named volume read-back" "got: $(tailout)"+ fi+else+ record FAIL "named volume write" "$(tailout)"+fi+"${DOCKER[@]}" volume rm "$NAMED_VOL" >/dev/null 2>&1++expect_run_ok "anonymous volume mounts and is writable" \+ -v /data "$IMG_ALPINE" sh -c 'echo ok > /data/f && cat /data/f >/dev/null'++expect_run_ok "tmpfs mount is writable and is really a tmpfs" \+ --tmpfs /scratch:rw,size=16m "$IMG_ALPINE" \+ sh -c 'echo ok > /scratch/f && grep -qE "tmpfs[[:space:]]+/scratch" /proc/mounts'++# =============================================================================+# POSITIVE — syscalls that must keep working under the hardened seccomp profile+# =============================================================================+section "POSITIVE — allowed syscalls (mkfifo / char device)"++expect_run_ok "mkfifo / mknod(S_IFIFO) works (named pipes)" \+ "$IMG_ALPINE" sh -c 'mkfifo /tmp/fifo && [ -p /tmp/fifo ]'++expect_run_ok "mknod char device works (e.g. /dev/net/tun-style nodes)" \+ "$IMG_ALPINE" sh -c 'mknod /tmp/zero c 1 5 && [ -c /tmp/zero ]'++expect_run_ok "clone()-based threading works (multi-threaded process)" \+ "$IMG_ALPINE" sh -c 'for i in $(seq 1 8); do sleep 0.1 & done; wait'++# =============================================================================+# POSITIVE — networking tooling (curl, DNS, ssh banner)+#+# NOTE: tests that reach the HOST service IP use $TARGET_NET (--network host by+# default). Nested containers on the DinD bridge are NAT'd and usually cannot+# reach the host's own service IP; host networking is policy-allowed and is the+# path agents use. We still record an INFO line documenting bridge reachability.+# =============================================================================+section "POSITIVE — networking & curl"++# Informational: can the DEFAULT bridge reach the host service IP at all?+cap "${DOCKER[@]}" run --rm --label "$LABEL" "$IMG_ALPINE" sh -c "nc -w 4 $TARGET_IP $HTTP_PORT </dev/null >/dev/null 2>&1"+if [ "$LAST_RC" -eq 0 ]; then+ record INFO "default-bridge container CAN reach $TARGET_IP:$HTTP_PORT (TCP)"+else+ record INFO "default-bridge container canNOT reach $TARGET_IP:$HTTP_PORT — host targets use --network host (expected)"+fi++if need_image "$IMG_CURL"; then+ cap "${DOCKER[@]}" run --rm --label "$LABEL" $TARGET_NET "$IMG_CURL" -sS -m 10 -o /dev/null -w '%{http_code}' "http://$TARGET_IP:$HTTP_PORT/"+ if [ "$LAST_RC" -eq 0 ] && echo "$LAST_OUT" | grep -qE '^[1-5][0-9][0-9]$'; then+ record PASS "curl reaches $TARGET_IP:$HTTP_PORT and gets an HTTP response (code $LAST_OUT)"+ else+ record FAIL "curl http://$TARGET_IP:$HTTP_PORT" "rc=$LAST_RC out=$(tailout)"+ fi+else+ record SKIP "curl HTTP test" "image $IMG_CURL unavailable"+fi++expect_contains "DNS resolution via DinD resolver works" "address|Name:|canonical" \+ "$IMG_ALPINE" nslookup example.com++expect_contains "SSH banner readable from $TARGET_IP:$SSH_PORT" "SSH-" \+ $TARGET_NET "$IMG_ALPINE" sh -c "echo | nc -w 5 $TARGET_IP $SSH_PORT"++# =============================================================================+# POSITIVE — TLS handshake + openssl (mTLS endpoints expose a server cert)+# =============================================================================+section "POSITIVE — TLS / openssl"++# nmap ssl-cert: no extra packages needed, retrieves the server certificate.+if need_image "$IMG_NMAP"; then+ expect_contains "nmap ssl-cert retrieves DinD TLS cert ($TARGET_IP:$DIND_TLS_PORT)" \+ "ssl-cert|Subject:|commonName|Issuer:|Public Key" \+ $TARGET_NET "$IMG_NMAP" -Pn -p"$DIND_TLS_PORT" --script ssl-cert "$TARGET_IP"+else+ record SKIP "nmap ssl-cert" "image $IMG_NMAP unavailable"+fi++# openssl s_client: the server certificate is sent even when client-auth is+# required, so x509 subject extraction proves curl/openssl crypto works.+expect_tool "openssl s_client handshake + x509 parse ($TARGET_IP:$DIND_TLS_PORT)" \+ "subject|CN ?=|commonName" \+ $TARGET_NET "$IMG_ALPINE" \+ sh -c "apk add --no-cache openssl >/dev/null 2>&1 || exit 200; echo | openssl s_client -connect $TARGET_IP:$DIND_TLS_PORT 2>/dev/null | openssl x509 -noout -subject 2>/dev/null"++# =============================================================================+# POSITIVE — scanners (nmap connect/SYN/version, masscan): NET_RAW path+# =============================================================================+section "POSITIVE — port scanners (nmap / masscan)"++if need_image "$IMG_NMAP"; then+ expect_contains "nmap TCP connect scan finds open ports on $TARGET_IP" \+ "$HTTP_PORT/tcp +open|$SSH_PORT/tcp +open|$DIND_TLS_PORT/tcp +open" \+ $TARGET_NET "$IMG_NMAP" -Pn -sT -p"$SSH_PORT,$HTTP_PORT,$DIND_TLS_PORT,$OUTER_TLS_PORT" "$TARGET_IP"++ expect_contains "nmap SYN scan works (raw sockets / CAP_NET_RAW)" \+ "$HTTP_PORT/tcp +open" \+ $TARGET_NET "$IMG_NMAP" -Pn -sS -p"$HTTP_PORT" "$TARGET_IP"++ expect_contains "nmap service/version detection (-sV)" \+ "$HTTP_PORT/tcp +open|service|VERSION|http" \+ $TARGET_NET "$IMG_NMAP" -Pn -sV --version-light -p"$HTTP_PORT" "$TARGET_IP"+else+ record SKIP "nmap scans" "image $IMG_NMAP unavailable"+fi++# masscan ships in Alpine's community repo; uses its own raw-packet stack.+# NOTE: scanning the host's OWN IP can miss the SYN-ACK (raw sniffer doesn't see+# loopback traffic), so a clean run of masscan's engine (raw socket opened, scan+# started) already proves the policy/seccomp allow it. We accept either an open+# port discovery OR masscan's normal startup output; only a raw-socket/seccomp+# denial (no such output) fails the test.+expect_tool "masscan runs with raw sockets against $TARGET_IP" \+ "Discovered open port|open port $HTTP_PORT|Starting masscan|Scanning 1 host|rate:" \+ $TARGET_NET --cap-add NET_RAW "$IMG_ALPINE" \+ sh -c '+ apk add --no-cache masscan libpcap libpcap-dev >/dev/null 2>&1 || exit 200+ # masscan dlopen()s libpcap; some builds look for the unversioned soname,+ # which the runtime package does not ship. Provide it if missing.+ if [ ! -e /usr/lib/libpcap.so ]; then+ so="$(ls /usr/lib/libpcap.so.* 2>/dev/null | head -n1)"+ [ -n "$so" ] && ln -sf "$so" /usr/lib/libpcap.so 2>/dev/null || true+ fi+ masscan -p'"$HTTP_PORT"' '"$TARGET_IP"' --rate 2000 --wait 2 2>&1+ true'++# =============================================================================+# POSITIVE — real services: nginx & apache serve content (container-to-container)+# Uses a user-defined bridge network + busybox wget (no extra image dependency).+# =============================================================================+section "POSITIVE — web servers (nginx / apache) + content check"++web_content_test(){ # name image expected-content-regex+ local name="$1" image="$2" pat="$3"+ if ! need_image "$image"; then record SKIP "$name" "image $image unavailable"; return; fi+ local net="${NETPREFIX}$RANDOM" srv="${LABEL}-srv-$RANDOM" i out ok=1+ "${DOCKER[@]}" network create "$net" >/dev/null 2>&1+ if ! "${DOCKER[@]}" run -d --rm --label "$LABEL" --name "$srv" --network "$net" "$image" >/dev/null 2>&1; then+ record FAIL "$name" "failed to start server container"+ "${DOCKER[@]}" network rm "$net" >/dev/null 2>&1; return+ fi+ for i in $(seq 1 25); do+ out="$("${DOCKER[@]}" run --rm --label "$LABEL" --network "$net" "$IMG_ALPINE" \+ wget -q -T 3 -O - "http://$srv/" 2>/dev/null)"+ if echo "$out" | grep -qiE "$pat"; then ok=0; break; fi+ sleep 1+ done+ if [ "$ok" -eq 0 ]; then record PASS "$name"+ else record FAIL "$name" "expected /$pat/ in served content (server not reachable/ready)"; fi+ "${DOCKER[@]}" rm -f "$srv" >/dev/null 2>&1+ "${DOCKER[@]}" network rm "$net" >/dev/null 2>&1+}++web_content_test "nginx serves content (wget over user bridge network)" "$IMG_NGINX" "Welcome to nginx"+web_content_test "apache/httpd serves content (wget over user bridge network)" "$IMG_HTTPD" "It works"++# =============================================================================+# POSITIVE — JVM workload (heavy syscall surface) + outbound TCP from Java+# =============================================================================+section "POSITIVE — Java application"++if need_image "$IMG_JAVA"; then+ JPROG='public class T { public static void main(String[] a) throws Exception {'+ JPROG+=' System.out.println("JAVA_OK");'+ JPROG+=' try (java.net.Socket s=new java.net.Socket()) {'+ JPROG+=' s.connect(new java.net.InetSocketAddress("__IP__", __PORT__), 5000);'+ JPROG+=' System.out.println("SOCKET_CONNECTED"); } } }'+ JPROG="${JPROG/__IP__/$TARGET_IP}"+ JPROG="${JPROG/__PORT__/$HTTP_PORT}"+ expect_contains "JVM compiles+runs and opens an outbound socket" \+ "JAVA_OK.*SOCKET_CONNECTED|SOCKET_CONNECTED" \+ $TARGET_NET -e "PROG=$JPROG" "$IMG_JAVA" \+ bash -c 'printf "%s" "$PROG" > /tmp/T.java && cd /tmp && javac T.java && java T'+else+ record SKIP "Java application test" "image $IMG_JAVA unavailable"+fi++# =============================================================================+# POSITIVE — Python stack (interpreter / stdlib networking / sqlmap / requests)+# =============================================================================+section "POSITIVE — Python stack (sqlmap & friends)"++if need_image "$IMG_PY"; then+ # Interpreter + stdlib (no network, no pip) — must always work under seccomp.+ expect_contains "python interpreter + stdlib (hashlib/json) works" "PY_OK" \+ "$IMG_PY" python -c 'import hashlib,json,base64,ssl,socket; print("PY_OK", hashlib.sha256(b"x").hexdigest()[:8])'++ # Stdlib HTTP client to the host service (no third-party deps).+ PYHTTP='import http.client as h; c=h.HTTPConnection("__IP__",__PORT__,timeout=8); c.request("GET","/"); r=c.getresponse(); print("PYHTTP",r.status)'+ PYHTTP="${PYHTTP/__IP__/$TARGET_IP}"; PYHTTP="${PYHTTP/__PORT__/$HTTP_PORT}"+ expect_contains "python stdlib HTTP GET to $TARGET_IP:$HTTP_PORT" "PYHTTP [1-5][0-9][0-9]" \+ $TARGET_NET "$IMG_PY" python -c "$PYHTTP"++ # sqlmap (real pentest tool) installs via pip and runs against the target.+ expect_tool "sqlmap (pip) installs and runs against $TARGET_IP" "^[0-9]+\\.[0-9]+|sqlmap/[0-9]" \+ $TARGET_NET "$IMG_PY" sh -c '+ pip install --no-cache-dir --quiet sqlmap >/dev/null 2>&1 || exit 200+ command -v sqlmap >/dev/null 2>&1 || exit 200+ sqlmap --version 2>&1+ sqlmap -u "http://'"$TARGET_IP"':'"$HTTP_PORT"'/?id=1" --batch --flush-session \+ --level=1 --risk=1 --technique=B --timeout=8 --retries=1 -v1 2>&1 | tail -n 8 || true'++ # Third-party pip package (requests) + HTTP — confirms pip wheels work.+ RQ='import requests; r=requests.get("http://__IP__:__PORT__/",timeout=8,allow_redirects=False); print("REQUESTS",r.status_code)'+ RQ="${RQ/__IP__/$TARGET_IP}"; RQ="${RQ/__PORT__/$HTTP_PORT}"+ expect_tool "python requests (pip) HTTP GET to $TARGET_IP:$HTTP_PORT" "REQUESTS [1-5][0-9][0-9]" \+ $TARGET_NET "$IMG_PY" sh -c "pip install --no-cache-dir --quiet requests >/dev/null 2>&1 || exit 200; python -c '$RQ'"+else+ record SKIP "Python stack tests" "image $IMG_PY unavailable"+fi++# =============================================================================+# POSITIVE — exec into a running container (normal, non-privileged)+# =============================================================================+section "POSITIVE / NEGATIVE — docker exec"++EXEC_C="${LABEL}-exec-$RANDOM"+if "${DOCKER[@]}" run -d --rm --label "$LABEL" --name "$EXEC_C" "$IMG_ALPINE" sleep 120 >/dev/null 2>&1; then+ cap "${DOCKER[@]}" exec "$EXEC_C" id+ if [ "$LAST_RC" -eq 0 ] && echo "$LAST_OUT" | grep -q "uid="; then+ record PASS "normal docker exec works"+ else+ record FAIL "normal docker exec" "rc=$LAST_RC out=$(tailout)"+ fi+ # NEGATIVE: privileged exec must be blocked (authz exec_violation).+ cap "${DOCKER[@]}" exec --privileged "$EXEC_C" id+ if [ "$LAST_RC" -ne 0 ] && echo "$LAST_OUT" | grep -qiE "$DENY_RE"; then+ record PASS "privileged docker exec is DENIED (OPA)"+ else+ record FAIL "privileged docker exec denial" "rc=$LAST_RC out=$(tailout)"+ fi+ "${DOCKER[@]}" rm -f "$EXEC_C" >/dev/null 2>&1+else+ record SKIP "docker exec tests" "could not start helper container"+fi++# =============================================================================+# POSITIVE — Docker registry operations+# POST /images/create?fromImage (docker pull) is NOT blocked.+# Only POST /images/load (tar-archive import) is blocked by OPA.+# =============================================================================+section "POSITIVE — Docker registry operations"++expect_cmd_ok "docker pull from registry (POST /images/create?fromImage) is allowed" \+ pull "$IMG_ALPINE"+expect_cmd_ok "docker images list is allowed" \+ images+expect_cmd_ok "docker image inspect is allowed" \+ image inspect "$IMG_ALPINE"+TAG_IMG="pgdt-tag-$$"+"${DOCKER[@]}" tag "$IMG_ALPINE" "${TAG_IMG}:latest" >/dev/null 2>&1 && \+ record PASS "docker tag is allowed" || record FAIL "docker tag failed"+"${DOCKER[@]}" rmi "${TAG_IMG}:latest" >/dev/null 2>&1 && \+ record PASS "docker rmi (tag removal) is allowed" || record FAIL "docker rmi failed"++# =============================================================================+# POSITIVE — Container lifecycle management+# run / start / stop / restart / pause / unpause / kill /+# logs / inspect / top / stats / rename — normal agent operations.+# =============================================================================+section "POSITIVE — Container lifecycle management"++LIFE_C="${LABEL}-life-$RANDOM"+if "${DOCKER[@]}" run -d --label "$LABEL" --name "$LIFE_C" \+ "$IMG_ALPINE" sleep 300 >/dev/null 2>&1; then+ expect_cmd_ok "docker stop is allowed" stop -t 3 "$LIFE_C"+ expect_cmd_ok "docker start is allowed" start "$LIFE_C"+ expect_cmd_ok "docker restart is allowed" restart -t 3 "$LIFE_C"+ expect_cmd_ok "docker pause is allowed" pause "$LIFE_C"+ expect_cmd_ok "docker unpause is allowed" unpause "$LIFE_C"+ expect_cmd_ok "docker kill (SIGUSR1, no stop) is allowed" \+ kill --signal SIGUSR1 "$LIFE_C"+ expect_cmd_ok "docker logs is allowed" logs "$LIFE_C"+ expect_cmd_ok "docker inspect is allowed" inspect "$LIFE_C"+ expect_cmd_ok "docker top is allowed" top "$LIFE_C"+ expect_cmd_ok "docker stats (--no-stream) is allowed" \+ stats --no-stream "$LIFE_C"++ NEW_NAME="${LIFE_C}-ren"+ "${DOCKER[@]}" rename "$LIFE_C" "$NEW_NAME" >/dev/null 2>&1 && \+ record PASS "docker rename is allowed" || record FAIL "docker rename failed"+ "${DOCKER[@]}" rename "$NEW_NAME" "$LIFE_C" >/dev/null 2>&1 || true++ "${DOCKER[@]}" rm -f "$LIFE_C" >/dev/null 2>&1+else+ record SKIP "container lifecycle tests" "could not start lifecycle container"+fi++# =============================================================================+# POSITIVE — Container runtime features+# env / labels / workdir / user / --init / restart policy / port publishing /+# entrypoint override / read-only rootfs / docker exec with env+workdir+# =============================================================================+section "POSITIVE — Container runtime features"++expect_contains "env var (-e) is passed into container" "TESTVAL=hello-dind" \+ -e TESTVAL=hello-dind "$IMG_ALPINE" env++expect_contains "multiple -e vars and --label are accepted" "VAR2=world" \+ -e VAR1=hello -e VAR2=world --label app=pentest "$IMG_ALPINE" env++expect_contains "working directory (-w) override works" "/custom/wd" \+ -w /custom/wd "$IMG_ALPINE" pwd++# --user: verify OPA does not block it. The container may exit non-zero if the+# UID has no /etc/passwd entry in the image (environment-specific), but OPA+# must not deny the containers/create request.+cap "${DOCKER[@]}" run --rm --label "$LABEL" --user 65534 "$IMG_ALPINE" sh -c 'echo ok'+if echo "$LAST_OUT" | grep -qiE "$DENY_RE"; then+ record FAIL "--user (non-root UID) blocked by OPA (must be allowed)" "$(tailout)"+elif [ "$LAST_RC" -eq 0 ]; then+ record PASS "--user (non-root UID) is allowed and runs successfully"+else+ record INFO "--user (non-root UID) is allowed by OPA (container exit=$LAST_RC — non-OPA)" \+ "$(tailout)"+fi++expect_run_ok "--entrypoint override is allowed" \+ --entrypoint sh "$IMG_ALPINE" -c 'echo ok'++expect_run_ok "--init (tini pid1) flag is allowed" \+ --init "$IMG_ALPINE" true++# --restart conflicts with --rm; test via detached run then remove manually.+RST_C="${LABEL}-rst-$RANDOM"+"${DOCKER[@]}" run -d --label "$LABEL" --name "$RST_C" \+ --restart on-failure:3 "$IMG_ALPINE" sh -c 'exit 0' >/dev/null 2>&1 && \+ record PASS "--restart=on-failure policy is accepted at create time" || \+ record FAIL "--restart=on-failure failed" "rc=$? $(tailout)"+"${DOCKER[@]}" rm -f "$RST_C" >/dev/null 2>&1 || true++expect_run_ok "-p port publishing is allowed" \+ -p 127.0.0.1::9999 "$IMG_ALPINE" true++expect_run_ok "--read-only rootfs with multiple --tmpfs is allowed" \+ --read-only \+ --tmpfs /tmp:rw,size=8m \+ --tmpfs /run:rw,noexec,nosuid,size=4m \+ "$IMG_ALPINE" sh -c 'echo ok > /tmp/x && cat /tmp/x >/dev/null'++# docker exec with env / workdir (non-privileged)+FEAT_C="${LABEL}-feat-$RANDOM"+if "${DOCKER[@]}" run -d --rm --label "$LABEL" --name "$FEAT_C" \+ "$IMG_ALPINE" sleep 120 >/dev/null 2>&1; then+ cap "${DOCKER[@]}" exec "$FEAT_C" sh -c 'echo from-exec'+ [ "$LAST_RC" -eq 0 ] && echo "$LAST_OUT" | grep -q "from-exec" && \+ record PASS "docker exec with sh command works" || \+ record FAIL "docker exec sh command failed" "rc=$LAST_RC: $(tailout)"+ cap "${DOCKER[@]}" exec -e EXEC_VAR=exec-test "$FEAT_C" env+ echo "$LAST_OUT" | grep -q "EXEC_VAR=exec-test" && \+ record PASS "docker exec with -e env var works" || \+ record FAIL "docker exec -e failed" "$(tailout)"+ cap "${DOCKER[@]}" exec -w /tmp "$FEAT_C" pwd+ echo "$LAST_OUT" | grep -q "/tmp" && \+ record PASS "docker exec with -w workdir works" || \+ record FAIL "docker exec -w failed" "$(tailout)"+ "${DOCKER[@]}" rm -f "$FEAT_C" >/dev/null 2>&1+else+ record SKIP "docker exec runtime feature tests" "could not start helper container"+fi++# =============================================================================+# POSITIVE — Safe volume & network management+# Named volume create/inspect/use, anonymous volumes, bridge network create,+# network connect/disconnect, read-only API queries (ps/ls/inspect).+# =============================================================================+section "POSITIVE — Safe volume & network management"++# docker ps (read-only, always safe)+expect_cmd_ok "docker ps is allowed" ps+expect_cmd_ok "docker ps -a is allowed" ps -a++# Named volume lifecycle+SAFE_VOL="${VOLPREFIX}_safe_$RANDOM"+"${DOCKER[@]}" volume create "$SAFE_VOL" >/dev/null 2>&1 && \+ record PASS "docker volume create (no driver opts) is allowed" || \+ record FAIL "docker volume create failed"+expect_cmd_ok "docker volume ls is allowed" volume ls+cap "${DOCKER[@]}" volume inspect "$SAFE_VOL"+[ "$LAST_RC" -eq 0 ] && record PASS "docker volume inspect is allowed" || \+ record FAIL "docker volume inspect failed" "rc=$LAST_RC: $(tailout)"+expect_run_ok "container using named volume (write+read) is allowed" \+ -v "$SAFE_VOL:/data" "$IMG_ALPINE" \+ sh -c 'echo persistent > /data/f && cat /data/f >/dev/null'+"${DOCKER[@]}" volume rm "$SAFE_VOL" >/dev/null 2>&1 || true++# Anonymous volume (simulates Dockerfile VOLUME /data instruction)+expect_run_ok "anonymous volume (Dockerfile VOLUME /data simulation) is allowed" \+ -v /anon "$IMG_ALPINE" \+ sh -c 'echo ok > /anon/f && cat /anon/f >/dev/null'++# Safe housekeeping+expect_cmd_ok "docker volume prune (--force) is allowed" \+ volume prune --force+expect_cmd_ok "docker container prune (--force) is allowed" \+ container prune --force++# Bridge network lifecycle+SAFE_NET="${NETPREFIX}_safe_$RANDOM"+"${DOCKER[@]}" network create --driver bridge "$SAFE_NET" >/dev/null 2>&1 && \+ record PASS "docker network create (bridge driver) is allowed" || \+ record FAIL "docker network create (bridge) failed"+expect_cmd_ok "docker network ls is allowed" network ls+cap "${DOCKER[@]}" network inspect "$SAFE_NET"+[ "$LAST_RC" -eq 0 ] && record PASS "docker network inspect is allowed" || \+ record FAIL "docker network inspect failed" "rc=$LAST_RC: $(tailout)"++# docker network connect / disconnect with a running container+NETCONN_C="${LABEL}-nc-$RANDOM"+if "${DOCKER[@]}" run -d --rm --label "$LABEL" --name "$NETCONN_C" \+ "$IMG_ALPINE" sleep 60 >/dev/null 2>&1; then+ "${DOCKER[@]}" network connect "$SAFE_NET" "$NETCONN_C" >/dev/null 2>&1 && \+ record PASS "docker network connect is allowed" || \+ record FAIL "docker network connect failed"+ "${DOCKER[@]}" network disconnect "$SAFE_NET" "$NETCONN_C" >/dev/null 2>&1 && \+ record PASS "docker network disconnect is allowed" || \+ record FAIL "docker network disconnect failed"+ "${DOCKER[@]}" rm -f "$NETCONN_C" >/dev/null 2>&1+else+ record SKIP "network connect/disconnect test" "could not start helper container"+fi+"${DOCKER[@]}" network rm "$SAFE_NET" >/dev/null 2>&1 || true++# =============================================================================+# POSITIVE — Compose-style multi-container workflow (PentAGI agent simulation)+# 1. Create isolated bridge network + shared volume+# 2. Start a "target" service container on the network+# 3. "Agent" queries the target, writes findings to the shared volume+# 4. "Report" reads findings (read-only volume mount)+# 5. Tear everything down+# All operations use only bridge networking + named volumes (no bind mounts).+# =============================================================================+section "POSITIVE — Compose-style multi-container workflow (PentAGI agent)"++COMP_NET="${NETPREFIX}_comp_$RANDOM"+COMP_VOL="${VOLPREFIX}_comp_$RANDOM"+COMP_TARGET="${LABEL}-target-$RANDOM"+COMP_OK=1++if "${DOCKER[@]}" network create --driver bridge "$COMP_NET" >/dev/null 2>&1 \+ && "${DOCKER[@]}" volume create "$COMP_VOL" >/dev/null 2>&1; then++ # "Target" — simple nc-based HTTP stub on the isolated network+ if "${DOCKER[@]}" run -d --rm --label "$LABEL" --name "$COMP_TARGET" \+ --network "$COMP_NET" "$IMG_ALPINE" \+ sh -c 'while true; do+ printf "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\ntarget-alive" | nc -l -p 8080+ done' >/dev/null 2>&1; then+ sleep 2++ # "Agent" — queries target and stores result in shared volume+ cap "${DOCKER[@]}" run --rm --label "$LABEL" \+ --network "$COMP_NET" \+ -v "$COMP_VOL:/findings" \+ --cap-add NET_ADMIN --cap-add NET_RAW \+ "$IMG_ALPINE" \+ sh -c "wget -q -T 5 -O /findings/result.txt \+ http://$COMP_TARGET:8080/ 2>/dev/null || true; \+ echo agent-done > /findings/status"+ if [ "$LAST_RC" -eq 0 ]; then+ record PASS "agent: network scan + volume write (bridge network + named volume)"+ else+ record FAIL "agent container failed" "rc=$LAST_RC: $(tailout)"+ COMP_OK=0+ fi++ # "Report" — reads findings from shared volume (read-only)+ if [ "$COMP_OK" -eq 1 ]; then+ cap "${DOCKER[@]}" run --rm --label "$LABEL" \+ -v "$COMP_VOL:/findings:ro" \+ "$IMG_ALPINE" \+ sh -c 'cat /findings/status'+ if [ "$LAST_RC" -eq 0 ] && echo "$LAST_OUT" | grep -q "agent-done"; then+ record PASS "report: read-only volume mount reads agent findings"+ else+ record FAIL "report container failed to read volume" "rc=$LAST_RC: $(tailout)"+ fi+ fi++ "${DOCKER[@]}" rm -f "$COMP_TARGET" >/dev/null 2>&1 || true+ else+ record SKIP "compose workflow: target service" "could not start target container"+ COMP_OK=0+ fi++ "${DOCKER[@]}" network rm "$COMP_NET" >/dev/null 2>&1 || true+ "${DOCKER[@]}" volume rm "$COMP_VOL" >/dev/null 2>&1 || true+else+ record SKIP "compose workflow" "could not create network or volume"+fi++# =============================================================================+# NEGATIVE — OPA authz must reject host-escape primitives at create time+# =============================================================================+section "NEGATIVE — OPA authz (must be denied)"++expect_deny "--privileged is denied" \+ --privileged "$IMG_ALPINE" true+expect_deny "--cap-add SYS_ADMIN is denied" \+ --cap-add SYS_ADMIN "$IMG_ALPINE" true+expect_deny "--cap-add SYS_PTRACE is denied" \+ --cap-add SYS_PTRACE "$IMG_ALPINE" true+expect_deny "--cap-add SYS_MODULE is denied" \+ --cap-add SYS_MODULE "$IMG_ALPINE" true+expect_deny "--cap-add DAC_READ_SEARCH is denied (shocker)" \+ --cap-add DAC_READ_SEARCH "$IMG_ALPINE" true+expect_deny "--cap-add SYS_RAWIO is denied" \+ --cap-add SYS_RAWIO "$IMG_ALPINE" true+expect_deny "--cap-add ALL is denied" \+ --cap-add ALL "$IMG_ALPINE" true+expect_deny "--device passthrough is denied" \+ --device /dev/null:/dev/xnull "$IMG_ALPINE" true+expect_deny "--device-cgroup-rule is denied" \+ --device-cgroup-rule "c 1:3 rmw" "$IMG_ALPINE" true+expect_deny "--security-opt seccomp=unconfined is denied" \+ --security-opt seccomp=unconfined "$IMG_ALPINE" true+expect_deny "--security-opt apparmor=unconfined is denied" \+ --security-opt apparmor=unconfined "$IMG_ALPINE" true+expect_deny "--security-opt no-new-privileges=false is denied" \+ --security-opt no-new-privileges=false "$IMG_ALPINE" true+expect_deny "--pid=host is denied" \+ --pid host "$IMG_ALPINE" true+expect_deny "--ipc=host is denied" \+ --ipc host "$IMG_ALPINE" true+expect_deny "--ipc=shareable is denied" \+ --ipc shareable "$IMG_ALPINE" true+expect_deny "--uts=host is denied" \+ --uts host "$IMG_ALPINE" true+expect_deny "--userns=host is denied" \+ --userns host "$IMG_ALPINE" true+expect_deny "--cgroupns=host is denied" \+ --cgroupns host "$IMG_ALPINE" true+expect_deny "host bind-mount -v /:/host is denied" \+ -v /:/host "$IMG_ALPINE" true+expect_deny "host bind-mount -v /etc:/x is denied" \+ -v /etc:/x "$IMG_ALPINE" true+expect_deny "host bind-mount --mount type=bind is denied" \+ --mount "type=bind,src=/etc,dst=/x" "$IMG_ALPINE" true++# --pid=container:<id> (namespace-sharing chain) must be denied.+PIDT="${LABEL}-pidt-$RANDOM"+if "${DOCKER[@]}" run -d --rm --label "$LABEL" --name "$PIDT" "$IMG_ALPINE" sleep 60 >/dev/null 2>&1; then+ cap "${DOCKER[@]}" run --rm --label "$LABEL" --pid "container:$PIDT" "$IMG_ALPINE" true+ if [ "$LAST_RC" -ne 0 ] && echo "$LAST_OUT" | grep -qiE "$DENY_RE"; then+ record PASS "--pid=container:<id> is denied"+ else+ record FAIL "--pid=container:<id> denial" "rc=$LAST_RC out=$(tailout)"+ fi+ "${DOCKER[@]}" rm -f "$PIDT" >/dev/null 2>&1+else+ record SKIP "--pid=container:<id> test" "could not start target container"+fi++# Old API version must not bypass the plugin hook.+cap env DOCKER_API_VERSION=1.24 "${DOCKER[@]}" run --rm --label "$LABEL" --privileged "$IMG_ALPINE" true+if [ "$LAST_RC" -ne 0 ] && echo "$LAST_OUT" | grep -qiE "$DENY_RE"; then+ record PASS "API version downgrade (1.24) does NOT bypass authz"+else+ record FAIL "API version downgrade bypass" "rc=$LAST_RC out=$(tailout)"+fi++# =============================================================================+# NEGATIVE — OPA endpoint coverage (archive / commit / build)+# These endpoints bypass containers/create and were used in prior phases to+# exfiltrate PKI material (archive) and inject malicious image layers (build).+# OPA denies them via is_container_archive / is_container_commit /+# is_image_build (legacy API) / is_buildkit_session (Docker 23+ default).+# =============================================================================+section "NEGATIVE — OPA endpoint coverage (archive / commit / build)"++# GET /containers/{id}/archive — docker cp uses this endpoint internally.+ARCHC="${LABEL}-arch-$RANDOM"+if "${DOCKER[@]}" run -d --rm --label "$LABEL" --name "$ARCHC" "$IMG_ALPINE" sleep 60 >/dev/null 2>&1; then+ TMP_ARCH="/tmp/opa_archive_$$"+ cap "${DOCKER[@]}" cp "$ARCHC:/etc/hostname" "${TMP_ARCH}"+ rm -f "${TMP_ARCH}" 2>/dev/null+ if [ "$LAST_RC" -ne 0 ] && echo "$LAST_OUT" | grep -qiE "$DENY_RE"; then+ record PASS "GET /containers/{id}/archive is DENIED (OPA) — docker cp blocked"+ else+ record FAIL "GET /containers/{id}/archive denial (docker cp)" \+ "rc=$LAST_RC out=$(tailout) — SECURITY GAP: file exfiltration possible"+ fi+ "${DOCKER[@]}" rm -f "$ARCHC" >/dev/null 2>&1+else+ record SKIP "archive endpoint test" "could not start helper container"+fi++# POST /commit — docker commit snapshots the container FS including cached creds.+COMC="${LABEL}-com-$RANDOM"+if "${DOCKER[@]}" run -d --rm --label "$LABEL" --name "$COMC" "$IMG_ALPINE" sleep 60 >/dev/null 2>&1; then+ cap "${DOCKER[@]}" commit "$COMC" "opa-test-commit-$$:latest"+ if [ "$LAST_RC" -ne 0 ] && echo "$LAST_OUT" | grep -qiE "$DENY_RE"; then+ record PASS "POST /commit is DENIED (OPA) — docker commit blocked"+ else+ record FAIL "POST /commit denial" "rc=$LAST_RC out=$(tailout) — SECURITY GAP: state snapshot possible"+ fi+ "${DOCKER[@]}" rmi "opa-test-commit-$$:latest" >/dev/null 2>&1+ "${DOCKER[@]}" rm -f "$COMC" >/dev/null 2>&1+else+ record SKIP "commit endpoint test" "could not start helper container"+fi++# POST /build — docker build can embed malicious layers.+LAST_OUT=$(printf 'FROM %s\n' "${IMG_ALPINE}" | "${DOCKER[@]}" build --no-cache -t "opa-test-build-$$:latest" -f - . 2>&1)+LAST_RC=$?+if [ "$LAST_RC" -ne 0 ] && echo "$LAST_OUT" | grep -qiE "$DENY_RE"; then+ record PASS "POST /build is DENIED (OPA) — docker build blocked"+else+ record FAIL "POST /build denial" "rc=$LAST_RC out=$(tailout) — SECURITY GAP: malicious image injection possible"+ "${DOCKER[@]}" rmi "opa-test-build-$$:latest" >/dev/null 2>&1+fi++# POST /containers/{id}/update with DeviceCgroupRules — injects block device+# cgroup permissions post-creation. While not immediately exploitable (mknod+# S_IFBLK is seccomp-blocked and /dev/ has no block nodes), it bypasses the+# device-cgroup eBPF filter set at create-time and must be denied.+UPDC="${LABEL}-upd-$RANDOM"+if "${DOCKER[@]}" run -d --rm --label "$LABEL" --name "$UPDC" "$IMG_ALPINE" sleep 60 >/dev/null 2>&1; then+ cap "${DOCKER[@]}" update --blkio-weight 0 "$UPDC"+ if [ "$LAST_RC" -eq 0 ]; then+ record INFO "POST /containers/{id}/update with safe fields is allowed (memory/cpu/blkio OK)"+ fi+ # Inject dangerous DeviceCgroupRules — must be denied by OPA update_violation.+ if command -v curl >/dev/null 2>&1; then+ dind_api_post "/containers/$UPDC/update" \+ '{"DeviceCgroupRules":["b 8:* rwm","b *:* rm"]}'+ if echo "$LAST_OUT" | grep -qiE "$DENY_RE|not allowed|denied"; then+ record PASS "POST /containers/{id}/update with DeviceCgroupRules is DENIED (OPA)"+ elif echo "$LAST_OUT" | grep -qiE '"Warnings":\[\]|"Warnings":null'; then+ record FAIL "POST /containers/{id}/update DeviceCgroupRules injection ALLOWED" \+ "Response: $(tailout) — SECURITY GAP: device cgroup bypass possible"+ else+ record SKIP "POST /containers/{id}/update DeviceCgroupRules test" \+ "unexpected response: $(tailout)"+ fi+ else+ record SKIP "POST /containers/{id}/update DeviceCgroupRules test" "curl not available"+ fi+ "${DOCKER[@]}" rm -f "$UPDC" >/dev/null 2>&1+else+ record SKIP "container update endpoint test" "could not start helper container"+fi++# =============================================================================+# NEGATIVE — OPA new endpoint coverage (images/load / plugins / swarm)+# Second hardening round: endpoints added after initial policy deployment.+# =============================================================================+section "NEGATIVE — OPA new endpoints (images/load / plugins / swarm)"++# POST /images/load — tar archive import bypasses registry and can carry+# device nodes or setuid binaries. Must be denied.+cap "${DOCKER[@]}" image load -i /dev/null+if [ "$LAST_RC" -ne 0 ] && echo "$LAST_OUT" | grep -qiE "$DENY_RE"; then+ record PASS "POST /images/load (docker image load) is DENIED (OPA)"+else+ record FAIL "POST /images/load denial" \+ "rc=$LAST_RC out=$(tailout) — SECURITY GAP: arbitrary tar import possible"+fi++# POST /plugins/pull — installing plugins grants daemon-level privileges and+# can implement malicious authz/volume/network logic. Must be denied.+cap "${DOCKER[@]}" plugin install --grant-all-permissions \+ "opa-test-nonexistent-plugin-$$" 2>&1+if [ "$LAST_RC" -ne 0 ] && echo "$LAST_OUT" | grep -qiE "$DENY_RE"; then+ record PASS "POST /plugins/pull (docker plugin install) is DENIED (OPA)"+else+ record FAIL "POST /plugins/pull denial" \+ "rc=$LAST_RC out=$(tailout) — SECURITY GAP: plugin management possible"+fi++# POST /swarm/init — Swarm services bypass per-container HostConfig validation.+cap "${DOCKER[@]}" swarm init+if [ "$LAST_RC" -ne 0 ] && echo "$LAST_OUT" | grep -qiE "$DENY_RE"; then+ record PASS "POST /swarm/init is DENIED (OPA)"+else+ record FAIL "POST /swarm/init denial" \+ "rc=$LAST_RC out=$(tailout) — SECURITY GAP: Swarm service bypass possible"+ "${DOCKER[@]}" swarm leave --force >/dev/null 2>&1 || true+fi++# =============================================================================+# NEGATIVE — OPA containers/create new violations (sysctl / DeviceRequests / runtime)+# =============================================================================+section "NEGATIVE — OPA containers/create new violations"++# --sysctl: with --network=host + CAP_NET_ADMIN, sysctl writes propagate to+# the host network namespace. Must be denied even for non-dangerous keys.+expect_deny "--sysctl in containers/create is DENIED (OPA)" \+ --sysctl "net.ipv4.ip_forward=1" "$IMG_ALPINE" true++# DeviceRequests (GPU/accelerator): not needed for pentest workloads;+# device plugins can expose DMA or sensitive hardware paths.+if command -v curl >/dev/null 2>&1; then+ dind_api_post "/containers/create" \+ "{\"Image\":\"${IMG_ALPINE}\",\"Cmd\":[\"true\"],\"HostConfig\":{\"DeviceRequests\":[{\"Driver\":\"\",\"Count\":-1,\"Capabilities\":[[\"gpu\"]],\"Options\":{}}]}}"+ if echo "$LAST_OUT" | grep -qiE "$DENY_RE"; then+ record PASS "DeviceRequests (GPU passthrough) in containers/create is DENIED (OPA)"+ elif echo "$LAST_OUT" | grep -qiE '"Id":'; then+ _cid=$(echo "$LAST_OUT" | grep -o '"Id":"[^"]*"' | head -1 | cut -d'"' -f4)+ [ -n "$_cid" ] && "${DOCKER[@]}" rm -f "$_cid" >/dev/null 2>&1 || true+ record FAIL "DeviceRequests denial" \+ "Container created — SECURITY GAP: device plugin access possible"+ else+ record SKIP "DeviceRequests test" "unexpected curl response: $(tailout)"+ fi+else+ record SKIP "DeviceRequests test" "curl not available"+fi++# --runtime: non-standard runtimes may have different seccomp/capability+# defaults. OPA blocks any runtime that is not empty or "runc".+expect_deny "--runtime=<unsupported> is DENIED (OPA)" \+ --runtime unsupported-test-runtime "$IMG_ALPINE" true++# =============================================================================+# NEGATIVE — OPA volume & network new violations (bind-opts / macvlan / ipvlan)+# =============================================================================+section "NEGATIVE — OPA volume & network violations (bind-opts / L2 drivers)"++# docker volume create with type=none,o=bind — emulates bind-mount from DinD's+# own filesystem into nested containers (e.g. exposing /etc/docker/dind/certs).+expect_cmd_deny \+ "docker volume create with type=none,o=bind is DENIED (OPA)" \+ volume create \+ --driver local --opt type=none --opt o=bind --opt device=/tmp++# o=bind alone (without type=none) is also blocked.+expect_cmd_deny \+ "docker volume create with o=bind is DENIED (OPA)" \+ volume create \+ --driver local --opt o=bind --opt device=/tmp++# docker network create with macvlan — attaches container directly to the+# host's L2 segment, bypassing iptables rules.+NET_MACVLAN="pgdt-macvlan-$$"+cap "${DOCKER[@]}" network create --driver macvlan "$NET_MACVLAN"+if [ "$LAST_RC" -ne 0 ] && echo "$LAST_OUT" | grep -qiE "$DENY_RE"; then+ record PASS "docker network create (macvlan) is DENIED (OPA)"+else+ "${DOCKER[@]}" network rm "$NET_MACVLAN" >/dev/null 2>&1 || true+ record FAIL "docker network create macvlan denial" \+ "rc=$LAST_RC out=$(tailout) — SECURITY GAP: L2 network attachment possible"+fi++# docker network create with ipvlan (same risk as macvlan).+NET_IPVLAN="pgdt-ipvlan-$$"+cap "${DOCKER[@]}" network create --driver ipvlan "$NET_IPVLAN"+if [ "$LAST_RC" -ne 0 ] && echo "$LAST_OUT" | grep -qiE "$DENY_RE"; then+ record PASS "docker network create (ipvlan) is DENIED (OPA)"+else+ "${DOCKER[@]}" network rm "$NET_IPVLAN" >/dev/null 2>&1 || true+ record FAIL "docker network create ipvlan denial" \+ "rc=$LAST_RC out=$(tailout) — SECURITY GAP: L2 network attachment possible"+fi++# =============================================================================+# NEGATIVE — kernel-enforced floor (seccomp + capability bounding set)+# =============================================================================+section "NEGATIVE — seccomp / capabilities (must be refused in-container)"++expect_inner_fail "mknod BLOCK device is blocked (seccomp) — debugfs escape" \+ "not permitted|Operation not permitted" \+ "$IMG_ALPINE" sh -c 'mknod /tmp/sda b 8 0'++expect_inner_fail "mount() is refused without CAP_SYS_ADMIN" \+ "permission denied|not permitted|must be superuser|Operation not permitted" \+ "$IMG_ALPINE" sh -c 'mount -t tmpfs none /mnt'++expect_inner_fail "raw block-device read via dd on a pre-existing node is refused" \+ "not permitted|permission denied|No such file|cannot open" \+ "$IMG_ALPINE" sh -c 'dd if=/dev/sda bs=512 count=1 of=/dev/null'++# nsenter into host namespaces (needs setns + CAP_SYS_ADMIN, both unavailable).+expect_inner_fail "nsenter into PID 1 namespaces is refused" \+ "not permitted|permission denied|No such|cannot|reassociate|setns" \+ "$IMG_ALPINE" sh -c 'nsenter --target 1 --mount --pid -- true 2>&1 || (apk add --no-cache util-linux >/dev/null 2>&1; nsenter -t 1 -m -p -- true)'++# =============================================================================+# NEGATIVE — defense-in-depth (read-only mounts, cgroup v2)+# Verifies the kernel-enforced controls that provide guaranteed mitigation for+# several CVE classes INDEPENDENT of OPA/seccomp/capability configuration.+# If any of these fail it means the DinD launch flags were changed unsafely.+# =============================================================================+section "NEGATIVE — defense-in-depth (RO mounts / cgroup v2)"++# /proc/sys must be read-only — the ONLY reliable mitigation for+# CVE-2025-31133 (core_pattern write via symlink bypass) and all other+# kernel-parameter attack classes. If this write succeeds the CVE is exploitable+# even with the current runc version.+expect_inner_fail "/proc/sys is read-only — core_pattern write blocked (CVE-2025-31133 mitigation)" \+ "Read-only file system|read-only file system|not permitted|Operation not permitted" \+ "$IMG_ALPINE" sh -c 'echo "|/tmp/escape" > /proc/sys/kernel/core_pattern'++# /proc/sysrq-trigger must be read-only — prevents kernel-panic-based attacks.+# sysrq 'c' (crash) was used in Phase 4 to kill host processes and crash the host.+expect_inner_fail "/proc/sysrq-trigger is read-only — kernel panic vector blocked" \+ "Read-only file system|read-only file system|not permitted|Operation not permitted" \+ "$IMG_ALPINE" sh -c 'echo c > /proc/sysrq-trigger'++# /sys/fs/cgroup must be mounted read-only — prevents cgroup manipulation attacks.+# A writable cgroupfs + CAP_SYS_ADMIN enables the classic release_agent escape.+cap "${DOCKER[@]}" run --rm --label "$LABEL" "$IMG_ALPINE" \+ sh -c 'grep -E "cgroup" /proc/mounts | head -1'+if [ "$LAST_RC" -eq 0 ] && echo "$LAST_OUT" | grep -qE '\bro\b|,ro,|,ro$| ro '; then+ record PASS "/sys/fs/cgroup is mounted read-only"+else+ record FAIL "/sys/fs/cgroup mount options — expected RO" \+ "mounts: $(tailout) — cgroup manipulation may be possible"+fi++# Cgroup v2 (unified hierarchy) must be in use — the v1 release_agent mechanism+# (CVE-2022-0492 class) does not exist in v2.+cap "${DOCKER[@]}" run --rm --label "$LABEL" "$IMG_ALPINE" \+ sh -c 'grep -qF "cgroup2" /proc/mounts && echo CGROUPV2 || echo CGROUPV1'+if [ "$LAST_RC" -eq 0 ] && echo "$LAST_OUT" | grep -q "CGROUPV2"; then+ record PASS "cgroup v2 (unified) in use — release_agent escape class eliminated"+else+ record FAIL "cgroup v1 detected or check failed" \+ "$(tailout) — CVE-2022-0492 class may be applicable; verify cgroup2 mount"+fi++# /proc/sys/kernel/core_pattern must NOT be pre-staged as a pipe handler by a+# previous session. A value starting with '|' means a payload script would execute+# on any container crash, giving root code execution on the host.+cap "${DOCKER[@]}" run --rm --label "$LABEL" "$IMG_ALPINE" \+ sh -c 'cat /proc/sys/kernel/core_pattern'+if echo "$LAST_OUT" | grep -qE '^\|'; then+ if echo "$LAST_OUT" | grep -qiE '/apport|/systemd-coredump'; then+ record INFO "core_pattern uses system crash reporter (Ubuntu/systemd default — expected)" \+ "$(tailout | cut -c1-80)"+ else+ record FAIL "core_pattern contains a PIPE HANDLER — potential trapdoor" \+ "value: $(tailout) — clear with: sysctl -w kernel.core_pattern=core"+ fi+else+ record PASS "core_pattern is not a pipe handler ($(tailout | cut -c1-40))"+fi++# =============================================================================+# NEGATIVE — worker container host-escape prevention+# These checks run directly in the test container (not via docker CLI) and+# verify that the same kernel-enforced isolation that protects the worker+# container is in place: cgroup device rules, PID namespace, capability limits.+# Threat model: attacker has shell access in the worker/test container and+# tries to read the host disk, see host processes, or load kernel modules.+# =============================================================================+section "NEGATIVE — worker container host-escape prevention"++# Block device: the host disk partition (e.g. /dev/sda1) underlies the /work+# bind mount. MKNOD cap allows creating a device node, but cgroup device rules+# must prevent any I/O on block devices not explicitly allowed.+BLKNODE="/tmp/pgdt-blk-$$"+if mknod "$BLKNODE" b 8 1 2>/dev/null; then+ if dd if="$BLKNODE" bs=512 count=1 of=/dev/null 2>/dev/null; then+ rm -f "$BLKNODE"+ record FAIL "mknod+dd read of /dev/sda1 node SUCCEEDED — cgroup device rules not enforced" \+ "CRITICAL: host disk content readable from worker container"+ else+ rm -f "$BLKNODE"+ record PASS "mknod(S_IFBLK b 8:1) succeeds but dd READ BLOCKED — cgroup device rules work"+ fi+else+ record INFO "mknod b 8 1 blocked at creation (seccomp/cap) — block node not creatable"+fi++# PID namespace: PID 1 must be a container process, not the host's systemd/init.+PID1_CMD=$(tr '\0' ' ' < /proc/1/cmdline 2>/dev/null | cut -c1-80)+record INFO "Worker PID 1 command" "${PID1_CMD:-unreadable}"+if echo "$PID1_CMD" | grep -qiE 'systemd|/sbin/init|/lib/systemd'; then+ record FAIL "PID 1 is host init/systemd — worker shares host PID namespace" \+ "All host processes are visible — PID namespace isolation broken"+else+ record PASS "Worker PID 1 is container process (not host init) — PID namespace isolated"+fi++PID_COUNT=$(ls /proc/ 2>/dev/null | grep -c '^[0-9]\+$' || echo 0)+if [ "$PID_COUNT" -gt 200 ]; then+ record FAIL "Visible PID count = $PID_COUNT — likely seeing host process table"+else+ record PASS "Visible PID count = $PID_COUNT (expected for isolated container)"+fi++# /proc/1/root: must point to container root, not host root.+if [ -d /proc/1/root/opt/pentagi ] 2>/dev/null; then+ record FAIL "/proc/1/root/opt/pentagi accessible — container may see host filesystem" \+ "Symlinks in /work pointing to /proc/1/root/... can exfiltrate host files"+else+ record PASS "/proc/1/root/opt/pentagi not visible — /proc/1/root is container root (not host)"+fi++# Capability limits in the worker container itself.+if modprobe dummy 2>/dev/null; then+ rmmod dummy 2>/dev/null || true+ record FAIL "modprobe succeeded in worker — SYS_MODULE present (unexpected)"+else+ record PASS "modprobe denied in worker — SYS_MODULE not granted"+fi++MNTDIR="/tmp/pgdt-mnt-$$"+mkdir -p "$MNTDIR" 2>/dev/null+if mount -t tmpfs none "$MNTDIR" 2>/dev/null; then+ umount "$MNTDIR" 2>/dev/null; rmdir "$MNTDIR" 2>/dev/null+ record FAIL "mount(tmpfs) succeeded in worker — SYS_ADMIN present (unexpected)"+else+ rmdir "$MNTDIR" 2>/dev/null+ record PASS "mount(tmpfs) denied in worker — SYS_ADMIN not granted"+fi++# /proc/sys must be read-only even in the worker (ReadonlyPaths: docker-default).+if echo "1" > /proc/sys/kernel/dmesg_restrict 2>/dev/null; then+ record FAIL "/proc/sys writable in worker — ReadonlyPaths not enforced"+else+ record PASS "/proc/sys read-only in worker (ReadonlyPaths enforced by Docker)"+fi++# =============================================================================+# NEGATIVE — MaskedPaths / ReadonlyPaths / CgroupParent overrides+#+# CONFIRMED ESCAPE VECTOR (Phase 7): Creating a container with ReadonlyPaths:[]+# removes Docker's default /proc/sys read-only protection. Since+# /proc/sys/kernel is NOT namespaced, writing modprobe_path from inside+# the container changes it on the PHYSICAL HOST. APK package install then+# triggers request_module() which executes the payload as root in the init+# mount namespace.+#+# MaskedPaths:[] exposes /proc/kcore, /proc/keys, /sys/firmware/efi/efivars.+# CgroupParent changes which device eBPF programs are active for the container.+#+# Safe rule: absent field = Docker safe defaults (ALLOWED).+# any explicit array ([] or [...]) = DENIED.+# =============================================================================+section "NEGATIVE — MaskedPaths / ReadonlyPaths / CgroupParent overrides (Phase 7 escape vector)"++# Helper: POST containers/create and expect OPA denial.+# Uses dind_api_post — handles both unix-socket and TLS/TCP transport+# (same as the rest of the script, driven by DOCKER[@]).+# Cleanup on accidental creation uses docker CLI (also transport-aware).+_api_deny_test(){+ local name="$1" json="$2"+ if ! command -v curl >/dev/null 2>&1; then+ record SKIP "$name" "curl not available"+ return+ fi+ dind_api_post "/containers/create" "$json"+ if echo "$LAST_OUT" | grep -qiE "$DENY_RE"; then+ record PASS "$name"+ elif echo "$LAST_OUT" | grep -qiE '"Id":|"Warnings":'; then+ record FAIL "$name" "SECURITY GAP: container was CREATED — $(tailout)"+ local cid+ cid=$(echo "$LAST_OUT" | python3 -c \+ "import sys,json; print(json.load(sys.stdin).get('Id',''))" 2>/dev/null || true)+ [ -n "$cid" ] && "${DOCKER[@]}" rm -f "$cid" >/dev/null 2>&1 || true+ else+ record FAIL "$name" "unexpected response: $(tailout)"+ fi+}++# NEGATIVE: ReadonlyPaths overrides+_api_deny_test \+ "ReadonlyPaths:[] (removes /proc/sys RO, enables modprobe host escape) is DENIED" \+ '{"Image":"'"$IMG_ALPINE"'","Cmd":["true"],"HostConfig":{"ReadonlyPaths":[]}}'++_api_deny_test \+ "ReadonlyPaths:[\"/proc/bus\"] (partial — /proc/sys unprotected) is DENIED" \+ '{"Image":"'"$IMG_ALPINE"'","Cmd":["true"],"HostConfig":{"ReadonlyPaths":["/proc/bus"]}}'++_api_deny_test \+ "ReadonlyPaths:[\"/proc/sys\",\"/proc/bus\"] (any explicit array) is DENIED" \+ '{"Image":"'"$IMG_ALPINE"'","Cmd":["true"],"HostConfig":{"ReadonlyPaths":["/proc/sys","/proc/bus"]}}'++# NEGATIVE: MaskedPaths overrides+_api_deny_test \+ "MaskedPaths:[] (unmasks /proc/kcore, /proc/keys, /sys/firmware/efi) is DENIED" \+ '{"Image":"'"$IMG_ALPINE"'","Cmd":["true"],"HostConfig":{"MaskedPaths":[]}}'++_api_deny_test \+ "MaskedPaths:[\"/proc/acpi\"] (partial — /proc/kcore unmasked) is DENIED" \+ '{"Image":"'"$IMG_ALPINE"'","Cmd":["true"],"HostConfig":{"MaskedPaths":["/proc/acpi"]}}'++# Exact Phase 7 exploit payload: both fields cleared + host networking.+_api_deny_test \+ "MaskedPaths:[] + ReadonlyPaths:[] combined (exact Phase 7 exploit JSON) is DENIED" \+ '{"Image":"'"$IMG_ALPINE"'","Cmd":["sleep","300"],"HostConfig":{"MaskedPaths":[],"ReadonlyPaths":[],"NetworkMode":"host"}}'++# NEGATIVE: CgroupParent+_api_deny_test \+ "CgroupParent:\"/\" (root cgroup, may bypass device eBPF policy) is DENIED" \+ '{"Image":"'"$IMG_ALPINE"'","Cmd":["true"],"HostConfig":{"CgroupParent":"/"}}'++_api_deny_test \+ "CgroupParent:\"system.slice\" (systemd cgroup placement) is DENIED" \+ '{"Image":"'"$IMG_ALPINE"'","Cmd":["true"],"HostConfig":{"CgroupParent":"system.slice"}}'++# POSITIVE: containers WITHOUT these fields work normally.+# Docker applies its own safe defaults when the fields are absent from the request.+expect_run_ok \+ "container without MaskedPaths/ReadonlyPaths/CgroupParent (Docker defaults) is ALLOWED" \+ "$IMG_ALPINE" true++# Primary Phase 7 safety check: modprobe_path must NOT be writable.+# If this write succeeds, a container can change the host's kernel modprobe_path.+expect_inner_fail \+ "modprobe_path NOT writable in default container — Phase 7 primary safety check" \+ "Read-only file system|read-only file system|not permitted|Operation not permitted" \+ "$IMG_ALPINE" sh -c 'echo /tmp/evil > /proc/sys/kernel/modprobe'++# core_pattern must also not be writable (same /proc/sys protection).+expect_inner_fail \+ "core_pattern NOT writable in default container (same /proc/sys RO protection)" \+ "Read-only file system|read-only file system|not permitted|Operation not permitted" \+ "$IMG_ALPINE" sh -c 'echo "|/tmp/payload" > /proc/sys/kernel/core_pattern'++# =============================================================================+# SUMMARY+# =============================================================================+section "Summary"+printf " total=%d ${GRN}pass=%d${RST} ${RED}fail=%d${RST} ${YLW}skip=%d${RST} ${BLU}info=%d${RST}\n" \+ "$TOTAL" "$PASS" "$FAIL" "$SKIP" "$INFO"+if [ "$FAIL" -gt 0 ]; then+ printf "\n ${RED}${BLD}Failures:${RST}\n"+ for n in "${FAILED_NAMES[@]}"; do printf " ${RED}- %s${RST}\n" "$n"; done+ printf "\n ${RED}A failed NEGATIVE test = isolation gap. A failed POSITIVE test = false positive that breaks agents.${RST}\n"+ exit 1+fi+printf "\n ${GRN}${BLD}All executed tests passed.${RST}\n"+exit 0diff --git a/examples/guides/worker_node/run-dind.sh b/examples/guides/worker_node/run-dind.shnew file mode 100755index 00000000..12e506ed--- /dev/null+++ b/examples/guides/worker_node/run-dind.sh@@ -0,0 +1,352 @@+#!/bin/bash+# Docker-in-Docker container management script.+#+# Runs a single hardened DinD container and enforces the OPA authorization+# plugin as a MANAGED plugin installed INSIDE the DinD daemon (no sidecar).+# The plugin reads its policy from DinD's /etc/docker (mounted as /opa by the+# managed plugin); we mount the host policy directory onto DinD's /etc/docker.+#+# The plugin is installed once on first run and persists in the DinD data+# volume, so subsequent starts come up with authz directly. First run does a+# two-phase bootstrap: start without authz -> install plugin -> restart with+# authz enabled (fail-closed).+#+# Worker containers keep using the same DinD socket / TLS endpoint and are+# unaware of the authz layer.+#+# Configuration: every variable below can be overridden in /etc/docker/dind/dind.env+# (KEY=value lines) or via the environment.+#+# SECURITY NOTES (from pentest findings):+#+# 1. authz.rego blocks ALL bind-mounts of host paths for nested containers.+# This closes the "chroot bypass": even if a nested container could mount+# DinD's root and chroot into it, the OPA policy denies the mount.+#+# 2. The PentAGI backend HTTP service MUST run on HTTPS (SERVER_USE_SSL=true)+# and MUST NOT be accessible from worker containers. Worker containers have+# --network host; any plaintext HTTP port on the host will be reachable.+# Exposing TLS certificates or sensitive files via an unauthenticated HTTP+# endpoint completely defeats all isolation layers.+# Ensure DATA_DIR and any directory served by the backend NEVER contains+# TLS client certificates for the outer Docker daemon.+#+# 3. TLS client certificates for the outer Docker daemon MUST be stored+# outside any web-accessible or world-readable path. CERTS_PATH below is+# /etc/docker/dind/certs - keep it there and verify that no HTTP service+# is configured to serve files from that directory or its parents.+#+# 4. POLICY UPDATE ISOLATION: when authz.rego changes, ALL existing nested+# containers inside DinD must be purged before the new policy takes effect.+# Any container created under the previous (weaker) policy retains its+# original HostConfig — --pid=host, --network=host, and permissive seccomp+# profiles survive a DinD restart if the data volume is not cleared.+# This script detects authz.rego changes via SHA-256 hash and purges all+# nested containers automatically when the policy is updated.+# To force a purge without a policy change: PURGE=yes run-dind++set -e++# Per-run overrides (PURGE=yes / NETWORK=bridge run-dind) must survive the+# config file, so remember them before it is sourced.+_PURGE="${PURGE:-}"+_NETWORK="${NETWORK:-}"++DIND_ENV="${DIND_ENV:-/etc/docker/dind/dind.env}"+if [ -r "${DIND_ENV}" ]; then+ . "${DIND_ENV}"+fi++CONTAINER_NAME="${CONTAINER_NAME:-docker-dind}"+IMAGE="${IMAGE:-docker:dind}"+API_ADDRESS="${API_ADDRESS:-0.0.0.0}"+DOCKER_PORT="${DOCKER_PORT:-3376}"+METRICS_ADDRESS="${METRICS_ADDRESS:-0.0.0.0}"+METRICS_PORT="${METRICS_PORT:-9324}"+SCRIPTS_PATH="${SCRIPTS_PATH:-/etc/docker/dind/scripts}"+CERTS_PATH="${CERTS_PATH:-/etc/docker/dind/certs}"+DATA_PATH="${DATA_PATH:-/var/lib/docker-dind}"+RUN_PATH="${RUN_PATH:-/var/run/docker-dind}"+PIDS_LIMIT="${PIDS_LIMIT:-2048}"+CPU_LIMIT="${CPU_LIMIT:-2}"+MEMORY_LIMIT="${MEMORY_LIMIT:-4G}"+RESTART_POLICY="${RESTART_POLICY:-always}"+LOG_MAX_SIZE="${LOG_MAX_SIZE:-50m}"+LOG_MAX_FILE="${LOG_MAX_FILE:-7}"+# Comma-separated DNS servers for all nested containers; empty = system defaults.+DNS_SERVERS="${DNS_SERVERS:-}"++# Force-purge all nested containers regardless of policy change.+# Set via environment: PURGE=yes run-dind+PURGE="${_PURGE:-${PURGE:-no}}"++# Hash file tracks the authz.rego SHA-256 at the time DinD last started.+# When the hash changes, all nested containers are purged before DinD restarts+# so that no container retains privileges granted by the superseded policy.+AUTHZ_HASH_FILE="${DATA_PATH}/.authz-policy-hash"++# Network mode for the DinD container (and, by extension, for the nested+# containers it runs). Overridable via environment: NETWORK=bridge run-dind+# host - DinD shares the host network namespace; the daemon/metrics bind+# directly on API_ADDRESS/METRICS_ADDRESS; no host port publishing.+# bridge - DinD gets its own netns; the daemon/metrics listen on 0.0.0.0+# inside and are published to API_ADDRESS/METRICS_ADDRESS via -p.+NETWORK="${_NETWORK:-${NETWORK:-host}}"++# ---- Authorization plugin (opa-docker-authz, MANAGED plugin in DinD) --------+AUTHZ_PLUGIN_REF="${AUTHZ_PLUGIN_REF:-openpolicyagent/opa-docker-authz-v2:0.9}"+AUTHZ_ALIAS="${AUTHZ_ALIAS:-opa-docker-authz}"+# Host directory containing authz.rego. The WHOLE directory is mounted onto+# DinD's /etc/docker (the managed plugin bind-mounts DinD's /etc/docker as+# /opa). Mounting the directory - not the single file - is required: a+# single-file bind would be a nested mount inside /etc/docker and would NOT+# propagate into the plugin (it would see an empty file -> "empty module").+AUTHZ_POLICY_DIR="${AUTHZ_POLICY_DIR:-/etc/docker/dind/authz}"+AUTHZ_POLICY_HOST="${AUTHZ_POLICY_DIR}/authz.rego"+# Marker (inside the DinD data volume) recording that the plugin is installed.+AUTHZ_MARKER="${DATA_PATH}/.authz-plugin-installed"+DIND_SOCK="unix://${RUN_PATH}/docker.sock"++# (Re)create the DinD container. $1 = "yes" to enable the authz plugin.+start_dind() {+ local use_authz="$1"+ docker rm -f "${CONTAINER_NAME}" >/dev/null 2>&1 || true++ # Network-mode-specific flags: in host mode the daemon/metrics bind directly+ # on the real address and no ports are published; in bridge mode they listen+ # on 0.0.0.0 inside the container and are published via -p.+ local net_args=()+ local api_host metrics_addr+ if [ "${NETWORK}" = "host" ]; then+ net_args=(--network host)+ api_host="tcp://${API_ADDRESS}:${DOCKER_PORT}"+ metrics_addr="${METRICS_ADDRESS}:${METRICS_PORT}"+ else+ net_args=(+ --network bridge+ -p "${API_ADDRESS}:${DOCKER_PORT}:${DOCKER_PORT}"+ -p "${METRICS_ADDRESS}:${METRICS_PORT}:${METRICS_PORT}"+ )+ api_host="tcp://0.0.0.0:${DOCKER_PORT}"+ metrics_addr="0.0.0.0:${METRICS_PORT}"+ fi++ local daemon_args=("--metrics-addr=${metrics_addr}")+ if [ "${use_authz}" = "yes" ]; then+ daemon_args+=("--authorization-plugin=${AUTHZ_ALIAS}")+ fi++ docker run -d \+ "${net_args[@]}" \+ --cap-drop ALL \+ --cap-add SYS_ADMIN \+ --cap-add NET_ADMIN \+ --cap-add NET_RAW \+ --cap-add SETUID \+ --cap-add SETGID \+ --cap-add MKNOD \+ --cap-add FOWNER \+ --cap-add DAC_OVERRIDE \+ --cap-add CHOWN \+ --cap-add AUDIT_WRITE \+ --cap-add KILL \+ --cap-add SYS_CHROOT \+ --cap-add FSETID \+ --cap-add SETFCAP \+ --cap-add SETPCAP \+ --cap-add NET_BIND_SERVICE \+ --device /dev/fuse \+ --device-cgroup-rule 'b 7:* rmw' \+ --security-opt seccomp=unconfined \+ --security-opt apparmor=unconfined \+ --security-opt systempaths=unconfined \+ --cgroupns host \+ -v /sys/fs/cgroup:/sys/fs/cgroup:rw \+ -e DOCKER_HOST=unix:///var/run/dind/docker.sock \+ -e DOCKER_TLS_CERTDIR=/certs \+ -e DOCKER_API_HOST="${api_host}" \+ -e DOCKER_DNS_SERVERS="${DNS_SERVERS}" \+ -v ${SCRIPTS_PATH}/dockerd-entrypoint.sh:/usr/local/bin/dockerd-entrypoint.sh:ro \+ -v ${CERTS_PATH}:/certs \+ -v ${DATA_PATH}:/var/lib/docker \+ -v ${RUN_PATH}:/var/run/dind \+ -v "${AUTHZ_POLICY_DIR}:/etc/docker:ro" \+ --pids-limit ${PIDS_LIMIT} \+ --cpus ${CPU_LIMIT} \+ --memory ${MEMORY_LIMIT} \+ --name ${CONTAINER_NAME} \+ --restart ${RESTART_POLICY} \+ --log-opt max-size=${LOG_MAX_SIZE} \+ --log-opt max-file=${LOG_MAX_FILE} \+ ${IMAGE} \+ "${daemon_args[@]}"+}++# Wait until the DinD daemon answers on its unix socket.+wait_dind() {+ local i+ for i in $(seq 1 30); do+ if docker -H "${DIND_SOCK}" info >/dev/null 2>&1; then+ return 0+ fi+ sleep 1+ done+ return 1+}++# Install the managed authz plugin into the DinD daemon if not already present.+install_plugin_if_missing() {+ if docker -H "${DIND_SOCK}" plugin inspect "${AUTHZ_ALIAS}" >/dev/null 2>&1; then+ echo "authz plugin already installed in dind"+ return 0+ fi+ echo "installing authz plugin into dind (one-time download): ${AUTHZ_PLUGIN_REF}"+ docker -H "${DIND_SOCK}" plugin install \+ --grant-all-permissions \+ --alias "${AUTHZ_ALIAS}" \+ "${AUTHZ_PLUGIN_REF}" \+ opa-args="-policy-file /opa/authz.rego"+}++# Purge ALL containers from the DinD daemon.+# This is called when authz.rego changes to ensure no container created under+# the previous policy survives with superseded privileges (--pid=host,+# seccomp=unconfined, host bind-mounts, etc.).+purge_dind_containers() {+ echo "purging all nested containers from DinD..."+ local ids+ ids=$(docker -H "${DIND_SOCK}" ps -aq 2>/dev/null || true)+ if [ -z "${ids}" ]; then+ echo "no containers to purge"+ return 0+ fi+ # Stop running containers first, then remove all.+ docker -H "${DIND_SOCK}" rm -f ${ids} >/dev/null 2>&1 || true+ # Verify.+ local remaining+ remaining=$(docker -H "${DIND_SOCK}" ps -aq 2>/dev/null | wc -l)+ echo "purge complete: ${remaining} containers remaining"+}++# Compute SHA-256 of the current authz.rego policy.+policy_hash() {+ sha256sum "${AUTHZ_POLICY_HOST}" 2>/dev/null | awk '{print $1}'+}++# Return 0 (true) if the policy has changed since the last recorded hash.+policy_changed() {+ if [ "${PURGE}" = "yes" ]; then+ echo "PURGE=yes: treating policy as changed"+ return 0+ fi+ if [ ! -f "${AUTHZ_HASH_FILE}" ]; then+ return 0+ fi+ local current stored+ current=$(policy_hash)+ stored=$(cat "${AUTHZ_HASH_FILE}" 2>/dev/null || true)+ [ "${current}" != "${stored}" ]+}++# Persist the current policy hash so future runs can detect changes.+record_policy_hash() {+ mkdir -p "$(dirname "${AUTHZ_HASH_FILE}")"+ policy_hash > "${AUTHZ_HASH_FILE}"+}++# First-run bootstrap: start without authz, install plugin, restart with authz.+bootstrap() {+ echo "bootstrapping authz plugin (first run)..."+ start_dind no+ if ! wait_dind; then+ echo "ERROR: dind did not become ready during bootstrap (no-authz phase)" >&2+ docker logs "${CONTAINER_NAME}" >&2 || true+ exit 1+ fi+ install_plugin_if_missing+ touch "${AUTHZ_MARKER}"+ echo "enabling authz and restarting dind..."+ start_dind yes+ if ! wait_dind; then+ echo "ERROR: dind did not become ready with authz enabled" >&2+ docker logs "${CONTAINER_NAME}" >&2 || true+ exit 1+ fi+}++echo "=========================================="+echo "Docker-in-Docker container management"+echo "=========================================="++if [ ! -f "${AUTHZ_POLICY_HOST}" ]; then+ echo "ERROR: authz policy not found: ${AUTHZ_POLICY_HOST}" >&2+ echo "Deploy authz.rego there before running." >&2+ exit 1+fi++# If already running, do nothing (recreate manually with: docker rm -f docker-dind).+if docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then+ echo "container ${CONTAINER_NAME} is already running"+ echo "to recreate, first remove: docker rm -f ${CONTAINER_NAME}"+ exit 0+fi++# Drop a stopped leftover container so we start clean.+docker rm "${CONTAINER_NAME}" >/dev/null 2>&1 || true++# Policy-change purge: if authz.rego has changed since the last recorded hash+# (or PURGE=yes is set), start DinD temporarily without authz, destroy ALL+# nested containers, then proceed. This prevents containers created under the+# previous (weaker) policy from surviving with superseded privileges.+if [ -f "${AUTHZ_MARKER}" ] && policy_changed; then+ echo "authz policy has changed — purging all nested containers before restart..."+ start_dind no+ if wait_dind; then+ purge_dind_containers+ else+ echo "WARNING: dind did not start for purge pass; containers may survive" >&2+ fi+ docker rm -f "${CONTAINER_NAME}" >/dev/null 2>&1 || true+fi++if [ -f "${AUTHZ_MARKER}" ]; then+ echo "authz plugin previously installed; starting dind with authz..."+ start_dind yes+ if ! wait_dind; then+ echo "dind failed to start with authz (plugin missing from volume?); re-bootstrapping..." >&2+ rm -f "${AUTHZ_MARKER}"+ bootstrap+ fi+else+ bootstrap+fi++# Record the policy hash so the next run can detect changes.+record_policy_hash++echo ""+echo "=========================================="+echo "DinD container created successfully"+echo "=========================================="+echo "Container name: ${CONTAINER_NAME}"+echo "Network mode: ${NETWORK}"+echo "Authz plugin: ${AUTHZ_ALIAS} (${AUTHZ_PLUGIN_REF})"+echo "API address: tcp://${API_ADDRESS}:${DOCKER_PORT}"+echo "Metrics address: http://${METRICS_ADDRESS}:${METRICS_PORT}/metrics"+echo "Unix socket: ${RUN_PATH}/docker.sock"+echo "Client certificates: ${CERTS_PATH}/client/"+echo ""+echo "useful commands:"+echo " # view logs"+echo " docker logs ${CONTAINER_NAME}"+echo " # restart container"+echo " docker restart ${CONTAINER_NAME}"+echo " # remove container"+echo " docker rm -f ${CONTAINER_NAME}"+echo " # recreate container"+echo " run-dind"+echo " # use via unix socket"+echo " docker-dind-sock ps"+echo " # use via TLS"+echo " docker-dind-tls ps"+echo ""diff --git a/examples/guides/worker_node/seccomp.json b/examples/guides/worker_node/seccomp.jsonnew file mode 100644index 00000000..4191ee14--- /dev/null+++ b/examples/guides/worker_node/seccomp.json@@ -0,0 +1,366 @@+{+ "defaultAction": "SCMP_ACT_ERRNO",+ "defaultErrnoRet": 1,+ "archMap": [+ {+ "architecture": "SCMP_ARCH_X86_64",+ "subArchitectures": ["SCMP_ARCH_X86", "SCMP_ARCH_X32"]+ },+ {+ "architecture": "SCMP_ARCH_AARCH64",+ "subArchitectures": ["SCMP_ARCH_ARM"]+ },+ {+ "architecture": "SCMP_ARCH_MIPS64",+ "subArchitectures": ["SCMP_ARCH_MIPS", "SCMP_ARCH_MIPS64N32"]+ },+ {+ "architecture": "SCMP_ARCH_MIPS64N32",+ "subArchitectures": ["SCMP_ARCH_MIPS", "SCMP_ARCH_MIPS64"]+ },+ {+ "architecture": "SCMP_ARCH_MIPSEL64",+ "subArchitectures": ["SCMP_ARCH_MIPSEL", "SCMP_ARCH_MIPSEL64N32"]+ },+ {+ "architecture": "SCMP_ARCH_MIPSEL64N32",+ "subArchitectures": ["SCMP_ARCH_MIPSEL", "SCMP_ARCH_MIPSEL64"]+ },+ {+ "architecture": "SCMP_ARCH_S390X",+ "subArchitectures": ["SCMP_ARCH_S390"]+ },+ {+ "architecture": "SCMP_ARCH_RISCV64",+ "subArchitectures": null+ }+ ],+ "syscalls": [+ {+ "_comment": "HARDENING (device-node creation). Goal: forbid creating BLOCK device nodes (S_IFBLK) while allowing every legitimate mknod use (regular files, FIFOs/mkfifo, UNIX-socket nodes, and CHARACTER devices). CAP_MKNOD is in the container default capability set, so without this a nested container can `mknod /dev/sda b 8 0` then run debugfs to read the raw host disk WITHOUT mounting — the confirmed primary escape vector. Block-device creation has no legitimate runtime use, so it is denied outright. Character devices are intentionally NOT blocked here: pentest tooling legitimately creates char nodes (e.g. /dev/net/tun for VPN pivoting), and the dangerous ones (/dev/mem, /dev/kmem, /dev/port) are independently denied at the I/O layer by the per-container device cgroup. The device cgroup is the primary control for both classes; this rule is defense-in-depth on the node-creation step for block devices.\n\nWhy this shape (and not a conditional ERRNO): under OCI/runc the masked-equal match is `(arg & value) == valueTwo` (value = mask, valueTwo = expected bits) — confirmed against moby's `clone` rule. mknod/mknodat are intentionally REMOVED from the unconditional allowlist below, so any mode whose S_IFMT bits are S_IFBLK (0x6000) matches no rule and hits the profile default SCMP_ACT_ERRNO. SCMP_ACT_ALLOW is used here (an action different from the default) because libseccomp rejects a rule whose action equals the default action with -EACCES, and a redundant unconditional allow would prune these specific conditions. mknod mode = arg index 1. To additionally block character devices, drop the S_IFCHR allow rules below.",+ "names": ["mknod"],+ "action": "SCMP_ACT_ALLOW",+ "args": [{"index": 1, "value": 61440, "valueTwo": 0, "op": "SCMP_CMP_MASKED_EQ"}]+ },+ {+ "_comment": "mknod character device (S_IFCHR = 0x2000 = 8192); allowed (see header rule). Block devices, S_IFBLK = 0x6000, have no allow rule and hit the default ERRNO.",+ "names": ["mknod"],+ "action": "SCMP_ACT_ALLOW",+ "args": [{"index": 1, "value": 61440, "valueTwo": 8192, "op": "SCMP_CMP_MASKED_EQ"}]+ },+ {+ "_comment": "mknod regular file (S_IFREG = 0x8000 = 32768).",+ "names": ["mknod"],+ "action": "SCMP_ACT_ALLOW",+ "args": [{"index": 1, "value": 61440, "valueTwo": 32768, "op": "SCMP_CMP_MASKED_EQ"}]+ },+ {+ "_comment": "mknod FIFO / named pipe (S_IFIFO = 0x1000 = 4096); required by mkfifo(3).",+ "names": ["mknod"],+ "action": "SCMP_ACT_ALLOW",+ "args": [{"index": 1, "value": 61440, "valueTwo": 4096, "op": "SCMP_CMP_MASKED_EQ"}]+ },+ {+ "_comment": "mknod UNIX-socket node (S_IFSOCK = 0xC000 = 49152).",+ "names": ["mknod"],+ "action": "SCMP_ACT_ALLOW",+ "args": [{"index": 1, "value": 61440, "valueTwo": 49152, "op": "SCMP_CMP_MASKED_EQ"}]+ },+ {+ "_comment": "mknodat mode is arg index 2 (dirfd, pathname, mode, dev). Same allowlist as mknod; only S_IFBLK (block devices) falls through to the default ERRNO. Regular file (no S_IFMT bits set).",+ "names": ["mknodat"],+ "action": "SCMP_ACT_ALLOW",+ "args": [{"index": 2, "value": 61440, "valueTwo": 0, "op": "SCMP_CMP_MASKED_EQ"}]+ },+ {+ "_comment": "mknodat regular file (S_IFREG = 0x8000 = 32768).",+ "names": ["mknodat"],+ "action": "SCMP_ACT_ALLOW",+ "args": [{"index": 2, "value": 61440, "valueTwo": 32768, "op": "SCMP_CMP_MASKED_EQ"}]+ },+ {+ "_comment": "mknodat FIFO / named pipe (S_IFIFO = 0x1000 = 4096).",+ "names": ["mknodat"],+ "action": "SCMP_ACT_ALLOW",+ "args": [{"index": 2, "value": 61440, "valueTwo": 4096, "op": "SCMP_CMP_MASKED_EQ"}]+ },+ {+ "_comment": "mknodat UNIX-socket node (S_IFSOCK = 0xC000 = 49152).",+ "names": ["mknodat"],+ "action": "SCMP_ACT_ALLOW",+ "args": [{"index": 2, "value": 61440, "valueTwo": 49152, "op": "SCMP_CMP_MASKED_EQ"}]+ },+ {+ "_comment": "mknodat character device (S_IFCHR = 0x2000 = 8192); allowed. Block devices (S_IFBLK = 0x6000) hit the default ERRNO.",+ "names": ["mknodat"],+ "action": "SCMP_ACT_ALLOW",+ "args": [{"index": 2, "value": 61440, "valueTwo": 8192, "op": "SCMP_CMP_MASKED_EQ"}]+ },+ {+ "_comment": "Docker default seccomp allowlist (moby/moby v27). All syscalls below are the standard Docker default — do not remove without understanding the impact.",+ "names": [+ "accept", "accept4", "access", "adjtimex", "alarm", "bind", "brk",+ "cachestat", "capget", "capset", "chdir", "chmod", "chown", "chown32",+ "clock_adjtime", "clock_adjtime64", "clock_getres", "clock_getres_time64",+ "clock_gettime", "clock_gettime64", "clock_nanosleep", "clock_nanosleep_time64",+ "close", "close_range", "connect", "copy_file_range", "creat",+ "dup", "dup2", "dup3",+ "epoll_create", "epoll_create1", "epoll_ctl", "epoll_ctl_old",+ "epoll_pwait", "epoll_pwait2", "epoll_wait", "epoll_wait_old",+ "eventfd", "eventfd2", "execve", "execveat", "exit", "exit_group",+ "faccessat", "faccessat2", "fadvise64", "fadvise64_64", "fallocate",+ "fanotify_mark", "fchdir", "fchmod", "fchmodat", "fchmodat2",+ "fchown", "fchown32", "fchownat", "fcntl", "fcntl64", "fdatasync",+ "fgetxattr", "flistxattr", "flock", "fork", "fremovexattr", "fsetxattr",+ "fstat", "fstat64", "fstatat64", "fstatfs", "fstatfs64", "fsync",+ "ftruncate", "ftruncate64",+ "futex", "futex_requeue", "futex_time64", "futex_wait", "futex_waitv",+ "futex_wake", "futimesat",+ "getcpu", "getcwd", "getdents", "getdents64",+ "getegid", "getegid32", "geteuid", "geteuid32",+ "getgid", "getgid32", "getgroups", "getgroups32",+ "getitimer", "getpeername", "getpgid", "getpgrp", "getpid", "getppid",+ "getpriority", "getrandom",+ "getresgid", "getresgid32", "getresuid", "getresuid32",+ "getrlimit", "get_robust_list", "getrusage", "getsid",+ "getsockname", "getsockopt", "get_thread_area", "gettid", "gettimeofday",+ "getuid", "getuid32", "getxattr",+ "inotify_add_watch", "inotify_init", "inotify_init1", "inotify_rm_watch",+ "io_cancel", "ioctl", "io_destroy", "io_getevents",+ "io_pgetevents", "io_pgetevents_time64", "ioprio_get", "ioprio_set",+ "io_setup", "io_submit", "ipc",+ "kill",+ "landlock_add_rule", "landlock_create_ruleset", "landlock_restrict_self",+ "lchown", "lchown32", "lgetxattr",+ "link", "linkat", "listen", "listxattr", "llistxattr",+ "_llseek", "lremovexattr", "lseek", "lsetxattr", "lstat", "lstat64",+ "madvise", "map_shadow_stack", "membarrier", "memfd_create", "memfd_secret",+ "mincore", "mkdir", "mkdirat",+ "mlock", "mlock2", "mlockall",+ "mmap", "mmap2", "mprotect",+ "mq_getsetattr", "mq_notify", "mq_open",+ "mq_timedreceive", "mq_timedreceive_time64",+ "mq_timedsend", "mq_timedsend_time64", "mq_unlink",+ "mremap",+ "msgctl", "msgget", "msgrcv", "msgsnd",+ "msync", "munlock", "munlockall", "munmap",+ "name_to_handle_at", "nanosleep", "newfstatat", "_newselect",+ "open", "openat", "openat2",+ "pause", "pidfd_open", "pidfd_send_signal",+ "pipe", "pipe2",+ "pkey_alloc", "pkey_free", "pkey_mprotect",+ "poll", "ppoll", "ppoll_time64", "prctl",+ "pread64", "preadv", "preadv2", "prlimit64",+ "process_mrelease",+ "pselect6", "pselect6_time64",+ "pwrite64", "pwritev", "pwritev2",+ "read", "readahead", "readlink", "readlinkat", "readv",+ "recv", "recvfrom", "recvmmsg", "recvmmsg_time64", "recvmsg",+ "remap_file_pages", "removexattr",+ "rename", "renameat", "renameat2",+ "restart_syscall", "rmdir", "rseq",+ "rt_sigaction", "rt_sigpending", "rt_sigprocmask", "rt_sigqueueinfo",+ "rt_sigreturn", "rt_sigsuspend", "rt_sigtimedwait", "rt_sigtimedwait_time64",+ "rt_tgsigqueueinfo",+ "sched_getaffinity", "sched_getattr", "sched_getparam",+ "sched_get_priority_max", "sched_get_priority_min",+ "sched_getscheduler", "sched_rr_get_interval", "sched_rr_get_interval_time64",+ "sched_setaffinity", "sched_setattr", "sched_setparam",+ "sched_setscheduler", "sched_yield",+ "seccomp", "select",+ "semctl", "semget", "semop", "semtimedop", "semtimedop_time64",+ "send", "sendfile", "sendfile64", "sendmmsg", "sendmsg", "sendto",+ "setfsgid", "setfsgid32", "setfsuid", "setfsuid32",+ "setgid", "setgid32", "setgroups", "setgroups32",+ "setitimer", "setpgid", "setpriority",+ "setregid", "setregid32", "setresgid", "setresgid32",+ "setresuid", "setresuid32", "setreuid", "setreuid32",+ "setrlimit", "set_robust_list", "setsid", "setsockopt",+ "set_thread_area", "set_tid_address",+ "setuid", "setuid32", "setxattr",+ "shmat", "shmctl", "shmdt", "shmget",+ "shutdown", "sigaltstack", "signalfd", "signalfd4",+ "sigprocmask", "sigreturn",+ "socketcall", "socketpair", "splice",+ "stat", "stat64", "statfs", "statfs64", "statx",+ "symlink", "symlinkat",+ "sync", "sync_file_range", "syncfs", "sysinfo",+ "tee", "tgkill", "time",+ "timer_create", "timer_delete", "timer_getoverrun",+ "timer_gettime", "timer_gettime64", "timer_settime", "timer_settime64",+ "timerfd_create", "timerfd_gettime", "timerfd_gettime64",+ "timerfd_settime", "timerfd_settime64",+ "times", "tkill", "truncate", "truncate64",+ "ugetrlimit", "umask", "uname",+ "unlink", "unlinkat",+ "utime", "utimensat", "utimensat_time64", "utimes",+ "vfork", "vmsplice",+ "wait4", "waitid", "waitpid",+ "write", "writev"+ ],+ "action": "SCMP_ACT_ALLOW"+ },+ {+ "names": ["process_vm_readv", "process_vm_writev", "ptrace"],+ "action": "SCMP_ACT_ALLOW",+ "includes": {"minKernel": "4.8"}+ },+ {+ "names": ["socket"],+ "action": "SCMP_ACT_ALLOW",+ "args": [{"index": 0, "value": 40, "op": "SCMP_CMP_NE"}]+ },+ {+ "names": ["personality"],+ "action": "SCMP_ACT_ALLOW",+ "args": [{"index": 0, "value": 0, "op": "SCMP_CMP_EQ"}]+ },+ {+ "names": ["personality"],+ "action": "SCMP_ACT_ALLOW",+ "args": [{"index": 0, "value": 8, "op": "SCMP_CMP_EQ"}]+ },+ {+ "names": ["personality"],+ "action": "SCMP_ACT_ALLOW",+ "args": [{"index": 0, "value": 131072, "op": "SCMP_CMP_EQ"}]+ },+ {+ "names": ["personality"],+ "action": "SCMP_ACT_ALLOW",+ "args": [{"index": 0, "value": 131080, "op": "SCMP_CMP_EQ"}]+ },+ {+ "names": ["personality"],+ "action": "SCMP_ACT_ALLOW",+ "args": [{"index": 0, "value": 4294967295, "op": "SCMP_CMP_EQ"}]+ },+ {+ "names": ["sync_file_range2", "swapcontext"],+ "action": "SCMP_ACT_ALLOW",+ "includes": {"arches": ["ppc64le"]}+ },+ {+ "names": ["arm_fadvise64_64", "arm_sync_file_range", "sync_file_range2", "breakpoint", "cacheflush", "set_tls"],+ "action": "SCMP_ACT_ALLOW",+ "includes": {"arches": ["arm", "arm64"]}+ },+ {+ "names": ["arch_prctl"],+ "action": "SCMP_ACT_ALLOW",+ "includes": {"arches": ["amd64", "x32"]}+ },+ {+ "names": ["modify_ldt"],+ "action": "SCMP_ACT_ALLOW",+ "includes": {"arches": ["amd64", "x32", "x86"]}+ },+ {+ "names": ["s390_pci_mmio_read", "s390_pci_mmio_write", "s390_runtime_instr"],+ "action": "SCMP_ACT_ALLOW",+ "includes": {"arches": ["s390", "s390x"]}+ },+ {+ "names": ["riscv_flush_icache"],+ "action": "SCMP_ACT_ALLOW",+ "includes": {"arches": ["riscv64"]}+ },+ {+ "names": ["open_by_handle_at"],+ "action": "SCMP_ACT_ALLOW",+ "includes": {"caps": ["CAP_DAC_READ_SEARCH"]}+ },+ {+ "names": [+ "bpf", "clone", "clone3", "fanotify_init",+ "fsconfig", "fsmount", "fsopen", "fspick",+ "lookup_dcookie", "mount", "mount_setattr", "move_mount", "open_tree",+ "perf_event_open", "quotactl", "quotactl_fd",+ "setdomainname", "sethostname", "setns",+ "syslog", "umount", "umount2", "unshare"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {"caps": ["CAP_SYS_ADMIN"]}+ },+ {+ "names": ["clone"],+ "action": "SCMP_ACT_ALLOW",+ "args": [{"index": 0, "value": 2114060288, "op": "SCMP_CMP_MASKED_EQ"}],+ "excludes": {"caps": ["CAP_SYS_ADMIN"], "arches": ["s390", "s390x"]}+ },+ {+ "names": ["clone"],+ "action": "SCMP_ACT_ALLOW",+ "args": [{"index": 1, "value": 2114060288, "op": "SCMP_CMP_MASKED_EQ"}],+ "comment": "s390 parameter ordering for clone is different",+ "includes": {"arches": ["s390", "s390x"]},+ "excludes": {"caps": ["CAP_SYS_ADMIN"]}+ },+ {+ "names": ["clone3"],+ "action": "SCMP_ACT_ERRNO",+ "errnoRet": 38,+ "excludes": {"caps": ["CAP_SYS_ADMIN"]}+ },+ {+ "names": ["reboot"],+ "action": "SCMP_ACT_ALLOW",+ "includes": {"caps": ["CAP_SYS_BOOT"]}+ },+ {+ "names": ["chroot"],+ "action": "SCMP_ACT_ALLOW",+ "includes": {"caps": ["CAP_SYS_CHROOT"]}+ },+ {+ "names": ["delete_module", "init_module", "finit_module"],+ "action": "SCMP_ACT_ALLOW",+ "includes": {"caps": ["CAP_SYS_MODULE"]}+ },+ {+ "names": ["acct"],+ "action": "SCMP_ACT_ALLOW",+ "includes": {"caps": ["CAP_SYS_PACCT"]}+ },+ {+ "names": ["kcmp", "pidfd_getfd", "process_madvise", "process_vm_readv", "process_vm_writev", "ptrace"],+ "action": "SCMP_ACT_ALLOW",+ "includes": {"caps": ["CAP_SYS_PTRACE"]}+ },+ {+ "names": ["iopl", "ioperm"],+ "action": "SCMP_ACT_ALLOW",+ "includes": {"caps": ["CAP_SYS_RAWIO"]}+ },+ {+ "names": ["settimeofday", "stime", "clock_settime", "clock_settime64"],+ "action": "SCMP_ACT_ALLOW",+ "includes": {"caps": ["CAP_SYS_TIME"]}+ },+ {+ "names": ["vhangup"],+ "action": "SCMP_ACT_ALLOW",+ "includes": {"caps": ["CAP_SYS_TTY_CONFIG"]}+ },+ {+ "names": ["get_mempolicy", "mbind", "set_mempolicy", "set_mempolicy_home_node"],+ "action": "SCMP_ACT_ALLOW",+ "includes": {"caps": ["CAP_SYS_NICE"]}+ },+ {+ "names": ["syslog"],+ "action": "SCMP_ACT_ALLOW",+ "includes": {"caps": ["CAP_SYSLOG"]}+ },+ {+ "names": ["bpf"],+ "action": "SCMP_ACT_ALLOW",+ "includes": {"caps": ["CAP_BPF"]}+ },+ {+ "names": ["perf_event_open"],+ "action": "SCMP_ACT_ALLOW",+ "includes": {"caps": ["CAP_PERFMON"]}+ }+ ]+}