fix(gitops): harden compose validator against relative traversal, tenant escape, and breakouts

Closes containment and privilege escalation bypasses in validate_compose_security()
by enforcing strict path resolution, cross-tenant state isolation, and capability bans.

Previously, `validate_compose_security()` only inspected absolute host paths starting
with `/` or `~`, allowing relative traversal paths (`../../Core/nixos`) to skip
validation entirely. Furthermore, state root containment was evaluated against the
parent `~/var/lib/homelab`, allowing one workload to mount another workload's state,
and container breakouts (`cap_add`, `devices`, host namespaces, top-level `include`)
were not inspected.

- Resolve relative host paths against `allowed_root` and enforce containment strictly
  within either the workload root or the workload's dedicated state root
  (`~/var/lib/homelab/<app_name>/`), blocking cross-tenant state directory access.
- Reject container breakout capabilities (`cap_add`, `devices`), unconfined security
  profiles, host namespaces (`pid: host`, `ipc: host`, etc.), and top-level `include`.
- Reject `docker-compose.yml` symlinks that escape the workload root.
- Add 12 adversarial regression tests in `test_gitops_security.py`.
- Mark Pre-P4 compose hardening task completed in `todo.txt`.

Part of Pre-P4 Security Gate (Milestone P4 readiness).
This commit is contained in:
kiskaadee committed 2026-10-15 01:52:08 -05:00
1 parent 0d9a2ce511
commit 8356819f08
3 files changed
+197 -19

No files matched your search

+84 -18
View File
@@ -278,26 +278,49 @@ ALLOWED_ACTIONS = {"git_pull", "compose_up", "compose_build", "compose_restart"}
ALLOWED_STRATEGIES = {"compose"}
def validate_compose_security(compose_file: Path, allowed_root: Path) -> tuple[bool, str | None]:
PROHIBITED_HOST_NAMESPACES = {"host"}
DANGEROUS_SECURITY_OPTS = {"unconfined", "apparmor:unconfined", "seccomp:unconfined"}
def validate_compose_security(
compose_file: Path,
allowed_root: Path,
app_name: str | None = None,
) -> tuple[bool, str | None]:
"""
Pre-flight AST inspection of workload docker-compose.yml to reject security violations:
1. privileged: true
2. /var/run/docker.sock bind mounts
3. network_mode: host
4. host root bind mounts outside allowed state root or workload directory
Pre-flight AST inspection of workload docker-compose.yml enforcing Core platform security invariants:
1. File Integrity: regular file, non-symlink (or strictly contained symlink).
2. Privilege Containment: blocks 'privileged: true', 'cap_add', 'devices', and 'security_opt: unconfined'.
3. Host Namespace Isolation: blocks 'pid: host', 'ipc: host', 'uts: host', 'userns_mode: host', 'network_mode: host'.
4. Docker Socket Ban: blocks direct mounts of /var/run/docker.sock.
5. Top-Level Inclusion Ban: blocks top-level 'include' directives.
6. Bind-Mount & Tenant State Isolation: resolves all relative and absolute host paths. Requires containment
strictly within either the workload root (allowed_root) OR the workload's dedicated state root
(~/var/lib/homelab/<app_name>/). Cross-tenant state mounts are rejected fail-closed.
"""
if not compose_file.is_file():
if not compose_file.exists():
return True, None
if not compose_file.is_file():
return False, f"Compose file '{compose_file}' is not a regular file."
canonical_allowed_root = allowed_root.resolve()
if compose_file.is_symlink():
resolved_compose = compose_file.resolve()
if not resolved_compose.is_relative_to(canonical_allowed_root):
return False, f"Compose file symlink escapes workload root: {compose_file} -> {resolved_compose}"
try:
content = compose_file.read_text(encoding="utf-8")
except OSError as e:
return False, f"Failed to read compose file {compose_file}: {e}"
yaml_errors = (yaml.YAMLError,) if yaml is not None else ()
if yaml is not None:
try:
data = yaml.safe_load(content) or {}
except yaml.YAMLError as e:
except yaml_errors as e:
return False, f"Failed to parse compose YAML {compose_file}: {e}"
else:
# Fallback regex inspection if yaml module is not present
@@ -307,16 +330,29 @@ def validate_compose_security(compose_file: Path, allowed_root: Path) -> tuple[b
return False, "Docker socket mounts are prohibited in workload compose files."
if re.search(r"^\s*network_mode:\s*[\"']?host[\"']?", content, re.MULTILINE | re.IGNORECASE):
return False, "Host networking (network_mode: host) is prohibited in workload compose files."
if re.search(r"^\s*cap_add:\s*", content, re.MULTILINE | re.IGNORECASE):
return False, "Linux capabilities (cap_add) are prohibited in workload compose files."
if re.search(r"^\s*devices:\s*", content, re.MULTILINE | re.IGNORECASE):
return False, "Host device mounts (devices) are prohibited in workload compose files."
if re.search(r"^\s*include:\s*", content, re.MULTILINE | re.IGNORECASE):
return False, "Top-level include directives are prohibited in workload compose files."
return True, None
if not isinstance(data, dict):
return False, f"Invalid compose root in {compose_file}: expected mapping"
if "include" in data:
return False, "Top-level 'include' directives are prohibited in workload compose files."
services = data.get("services")
if not isinstance(services, dict):
return True, None
state_root = Path(os.environ.get("HOMELAB_STATE_ROOT", Path.home() / "var/lib/homelab")).resolve()
target_app_name = app_name or allowed_root.name
target_state_root = (state_root / target_app_name).resolve()
top_volumes = set(data.get("volumes", {}).keys()) if isinstance(data.get("volumes"), dict) else set()
for svc_name, svc in services.items():
if not isinstance(svc, dict):
@@ -325,9 +361,24 @@ def validate_compose_security(compose_file: Path, allowed_root: Path) -> tuple[b
if svc.get("privileged") is True:
return False, f"Service '{svc_name}' specifies prohibited 'privileged: true'."
net_mode = str(svc.get("network_mode", "")).strip().lower()
if net_mode == "host":
return False, f"Service '{svc_name}' specifies prohibited 'network_mode: host'."
cap_add = svc.get("cap_add")
if cap_add:
return False, f"Service '{svc_name}' specifies prohibited 'cap_add' capabilities: {cap_add}."
devices = svc.get("devices")
if devices:
return False, f"Service '{svc_name}' specifies prohibited host device mount: {devices}."
sec_opts = svc.get("security_opt", [])
if isinstance(sec_opts, list):
for opt in sec_opts:
if any(bad in str(opt).lower() for bad in ("unconfined", "disable")):
return False, f"Service '{svc_name}' specifies prohibited security_opt: {opt}."
for ns_key in ("network_mode", "pid", "ipc", "uts", "userns_mode"):
val = str(svc.get(ns_key, "")).strip().lower()
if val in PROHIBITED_HOST_NAMESPACES:
return False, f"Service '{svc_name}' specifies prohibited host namespace '{ns_key}: {val}'."
volumes = svc.get("volumes", [])
if isinstance(volumes, list):
@@ -345,18 +396,33 @@ def validate_compose_security(compose_file: Path, allowed_root: Path) -> tuple[b
if vol.get("type") == "bind":
host_path = src
# Evaluate host_path escapes
if host_path and host_path.startswith(("/", "~")):
if not host_path:
continue
# Declared top-level named volume without path separators
if host_path in top_volumes and not (host_path.startswith((".", "/", "~")) or "/" in host_path or "\\" in host_path):
continue
# Host bind mount evaluation
if host_path.startswith("~"):
expanded = Path(host_path).expanduser().resolve()
# Allowed if inside the workload directory or inside the state root
is_in_workload = allowed_root.is_dir() and expanded.is_relative_to(allowed_root.resolve())
is_in_state = state_root.is_dir() and expanded.is_relative_to(state_root)
if not (is_in_workload or is_in_state):
return False, f"Service '{svc_name}' specifies prohibited host bind mount: '{host_path}'."
elif Path(host_path).is_absolute():
expanded = Path(host_path).resolve()
else:
# Relative path resolved against workload root
expanded = (allowed_root / host_path).resolve()
# Containment check: strictly within workload directory or dedicated state root
is_in_workload = allowed_root.is_dir() and expanded.is_relative_to(canonical_allowed_root)
is_in_own_state = expanded.is_relative_to(target_state_root)
if not (is_in_workload or is_in_own_state):
return False, f"Service '{svc_name}' specifies prohibited host bind mount: '{host_path}'."
return True, None
def validate_manifest_deployment(manifest: dict) -> tuple[bool, str]:
"""
Validate deployment policy inside app.yaml.
+111
View File
@@ -7,6 +7,8 @@ import sys
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
# Add Core to path so scripts can be imported
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(CORE_ROOT / "scripts"))
@@ -786,6 +788,115 @@ def test_validate_compose_security_nonexistent_file(tmp_path: Path):
assert err is None
@pytest.mark.parametrize("malicious_volume", [
"../../etc/passwd:/mnt/passwd:ro",
"./../../Core/nixos/secrets.yaml:/secrets.yaml",
"../other-workload/data:/data",
])
def test_validate_compose_security_blocks_relative_traversal(
tmp_path: Path, malicious_volume: str
):
"""Ensure relative path traversals in volume mounts cannot escape workload root."""
app_dir = tmp_path / "my-app"
app_dir.mkdir(parents=True)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"services:\n web:\n image: nginx\n volumes:\n - '{malicious_volume}'\n",
encoding="utf-8",
)
valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
assert valid is False, f"Expected relative traversal '{malicious_volume}' to be rejected!"
assert err is not None and "prohibited host bind mount" in err
def test_validate_compose_security_blocks_cross_tenant_state_mounts(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
"""Ensure workload 'my-app' cannot mount another workload's state directory ('other-app')."""
sites_dir = tmp_path / "Sites"
app_dir = sites_dir / "my-app"
app_dir.mkdir(parents=True)
state_root = tmp_path / "var/lib/homelab"
(state_root / "my-app").mkdir(parents=True)
(state_root / "other-app").mkdir(parents=True)
monkeypatch.setenv("HOMELAB_STATE_ROOT", str(state_root))
# Cross-tenant state mount
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"services:\n web:\n image: nginx\n volumes:\n - '{state_root}/other-app:/data'\n",
encoding="utf-8",
)
valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
assert valid is False, "Expected cross-tenant state mount to be rejected!"
assert err is not None and ("prohibited host bind mount" in err or "cross-tenant" in err.lower())
# Authorized own state mount must pass
compose_file.write_text(
f"services:\n web:\n image: nginx\n volumes:\n - '{state_root}/my-app:/data'\n",
encoding="utf-8",
)
valid_own, err_own = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
assert valid_own is True, f"Own state mount should be permitted, got error: {err_own}"
@pytest.mark.parametrize("unsafe_directive", [
"cap_add:\n - SYS_ADMIN",
"pid: host",
"ipc: host",
"userns_mode: host",
"devices:\n - /dev/sda:/dev/sda",
"security_opt:\n - apparmor:unconfined",
])
def test_validate_compose_security_blocks_privilege_escalation_primitives(
tmp_path: Path, unsafe_directive: str
):
"""Ensure dangerous container breakout capabilities and host namespaces are blocked."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text(
f"services:\n app:\n image: alpine\n {unsafe_directive}\n",
encoding="utf-8",
)
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path, app_name="app")
assert valid is False, f"Directive should be blocked:\n{unsafe_directive}"
assert err is not None
def test_validate_compose_security_rejects_top_level_include(tmp_path: Path):
"""Ensure top-level Compose include directives are rejected to prevent out-of-tree includes."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text("""
include:
- /etc/shadow
services:
app:
image: alpine
""", encoding="utf-8")
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path, app_name="app")
assert valid is False
assert err is not None and "include" in err.lower()
def test_validate_compose_security_rejects_symlink_escape(tmp_path: Path):
"""Ensure docker-compose.yml cannot be a symlink escaping the workload directory."""
app_dir = tmp_path / "my-app"
app_dir.mkdir(parents=True)
outside_file = tmp_path / "outside-compose.yml"
outside_file.write_text("services:\n app:\n image: alpine\n", encoding="utf-8")
compose_link = app_dir / "docker-compose.yml"
compose_link.symlink_to(outside_file)
valid, err = gitops_dispatcher.validate_compose_security(compose_link, app_dir, app_name="my-app")
assert valid is False
assert err is not None and "symlink" in err.lower()
+2 -1
View File
@@ -14,7 +14,8 @@ x 2026-10-13 (C) Establish P4 acceptance test matrix and definition of done befo
x 2026-10-14 (A) Eliminate eval in scripts/appctl and enforce strict env key validation in scripts/core_manifest.py +security @appctl
x 2026-10-15 (A) Enforce deployments.yaml as sole registry and remove dynamic discovery fallback in scripts/gitops_dispatcher.py +registry @gitops
(A) Harden validate_compose_security in scripts/gitops_dispatcher.py blocking relative traversal, cross-tenant mounts, and privilege escalation +compose @gitops
x 2026-10-15 (A) Harden validate_compose_security in scripts/gitops_dispatcher.py blocking relative traversal, cross-tenant mounts, and privilege escalation +compose @gitops
(A) Unify manifest parsing on core_manifest.py and eliminate duplicate parsers in scripts/appctl_engine.py +manifest @engine
(A) Scaffold asyncio daemon server supporting dual transports (Unix socket /run/homelab/appctl.sock and HTTP) in scripts/appctl_daemon.py +daemon @p4
(A) Implement unit and integration tests for dual-transport requests and error handling in tests/unit/test_appctl_daemon.py +test @p4