File size: 4,468 Bytes
b198790
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#!/usr/bin/env python3
"""Static policy checks for the cyber-range package."""

from __future__ import annotations

import ast
import sys
from pathlib import Path

import yaml

ROOT = Path(__file__).resolve().parent
REQUIRED_SERVICES = {"juice-shop", "waf", "nmap", "mobsf", "ollama", "soc-copilot"}
REQUIRED_DOCS = (
    "README.md",
    "docs/RUNBOOK.md",
    "docs/RESOURCES.md",
    "docs/SECURITY_ONION.md",
    "docs/GOAD.md",
    "docs/ANDROID.md",
    "docs/PORTSWIGGER.md",
    "docs/TROUBLESHOOTING.md",
)


def invalid_published_port(value: object) -> bool:
    """Return True unless a published port is explicitly loopback-only."""
    if isinstance(value, dict):
        host = str(value.get("host_ip", "0.0.0.0"))
        return host not in {"127.0.0.1", "localhost"} or not value.get("published")
    text = str(value).split("/", 1)[0]
    if ":" not in text:
        return True
    host = text.split(":", 1)[0]
    return host not in {"127.0.0.1", "localhost"}


def _load_yaml(path: Path, violations: list[str]) -> dict:
    try:
        data = yaml.safe_load(path.read_text(encoding="utf-8"))
    except (OSError, yaml.YAMLError) as exc:
        violations.append(f"{path.name}: cannot load YAML: {exc}")
        return {}
    if not isinstance(data, dict):
        violations.append(f"{path.name}: expected a YAML mapping")
        return {}
    return data


def _check_services(data: dict, source: str, violations: list[str]) -> None:
    services = data.get("services") or {}
    for name, service in services.items():
        if not isinstance(service, dict):
            violations.append(f"{source}: service {name} must be a mapping")
            continue
        if service.get("privileged") is True:
            violations.append(f"{source}: {name} must not be privileged")
        if service.get("pid") == "host":
            violations.append(f"{source}: {name} must not use the host PID namespace")
        if not service.get("mem_limit"):
            violations.append(f"{source}: {name} has no memory limit")
        for port in service.get("ports") or []:
            if invalid_published_port(port):
                violations.append(f"{source}: {name} has non-loopback port {port}")
        volumes = service.get("volumes") or []
        for volume in volumes:
            text = str(volume)
            if "/var/run/docker.sock" in text or "/run/docker.sock" in text:
                violations.append(f"{source}: {name} must not mount the Docker socket")


def validate_lab(root: Path) -> list[str]:
    violations: list[str] = []
    compose_path = root / "compose.yml"
    if not compose_path.is_file():
        violations.append("compose.yml is missing")
        return violations

    compose = _load_yaml(compose_path, violations)
    services = compose.get("services") or {}
    missing = sorted(REQUIRED_SERVICES - set(services))
    if missing:
        violations.append(f"compose.yml: missing services: {', '.join(missing)}")
    if (compose.get("networks", {}).get("range_net", {}).get("internal") is not True):
        violations.append("compose.yml: range_net must be internal")
    _check_services(compose, "compose.yml", violations)

    override_path = root / "compose.wazuh.override.yml"
    if override_path.is_file():
        override = _load_yaml(override_path, violations)
        _check_services(override, override_path.name, violations)
    else:
        violations.append("compose.wazuh.override.yml is missing")

    for relative in REQUIRED_DOCS:
        if not (root / relative).is_file():
            violations.append(f"required documentation is missing: {relative}")

    for relative in ("lab.py", "validate.py", "soc_copilot/copilot.py"):
        path = root / relative
        if not path.is_file():
            violations.append(f"required Python file is missing: {relative}")
            continue
        try:
            ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
        except (OSError, SyntaxError) as exc:
            violations.append(f"{relative}: invalid Python: {exc}")
    return violations


def main() -> int:
    violations = validate_lab(ROOT)
    if violations:
        for violation in violations:
            print(f"FAIL: {violation}", file=sys.stderr)
        return 1
    print("Static validation passed.")
    print("Runtime deployment is validated separately and requires Docker.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())