cyber-range / lab.py
philippefunk's picture
Publish core lab configuration
b198790 verified
Raw History Blame Contribute Delete
12.7 kB
#!/usr/bin/env python3
"""Cross-platform controller for the isolated cyber-range."""
from __future__ import annotations
import argparse
import ctypes
import ipaddress
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent
VENDOR_DIR = ROOT / ".vendor" / "wazuh-docker"
WAZUH_VERSION = "4.14.10"
WAZUH_URL = "https://github.com/wazuh/wazuh-docker.git"
_HOSTNAME = re.compile(r"^(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$")
_PROFILE_BUDGETS = {
"core": 2.5,
"blue": 9.0,
"mobile": 3.0,
"ai": 6.5,
"red": 3.0,
"all-containers": 19.0,
}
class LabError(RuntimeError):
"""An actionable lab lifecycle error."""
def validate_nmap_target(target: str) -> str:
value = target.strip()
if not value or value.startswith("-") or any(c in value for c in ";&|`$()<>\n\r"):
raise ValueError("Invalid or unsafe scan target")
try:
ipaddress.ip_network(value, strict=False)
return value
except ValueError:
pass
if not _HOSTNAME.fullmatch(value) or ".." in value:
raise ValueError("Target must be an IP, CIDR, hostname, or Compose service name")
return value
def build_nmap_command(target: str, extra: list[str]) -> list[str]:
allowed_flags = {"-sV", "-sT", "-sS", "-Pn", "-O", "--open"}
allowed_values = {"--top-ports", "-p"}
index = 0
while index < len(extra):
option = extra[index]
base = option.split("=", 1)[0]
if base in allowed_flags and option == base:
index += 1
continue
if base not in allowed_values:
raise ValueError(f"Unsupported Nmap option: {option}")
if "=" in option:
value = option.split("=", 1)[1]
else:
index += 1
if index >= len(extra):
raise ValueError(f"Missing value for {base}")
value = extra[index]
if not re.fullmatch(r"[0-9,-]+", value):
raise ValueError(f"Invalid numeric/port value for {base}")
index += 1
return [
"docker", "compose", "--profile", "tools", "run", "--rm",
"--cap-add=NET_RAW", "nmap", *extra, validate_nmap_target(target),
]
WAF_BLOCK = """
<!-- cyber-range-waf -->
<localfile>
<log_format>syslog</log_format>
<location>/var/log/waf/error.log</location>
</localfile>
"""
def patch_wazuh_manager_config(path: Path) -> None:
text = path.read_text(encoding="utf-8")
if "<!-- cyber-range-waf -->" in text:
return
marker = "</ossec_config>"
if marker not in text:
raise ValueError(f"Unexpected Wazuh configuration: {path}")
path.write_text(text.replace(marker, WAF_BLOCK + marker, 1), encoding="utf-8")
def profile_budget_gib(profile: str) -> float:
try:
return _PROFILE_BUDGETS[profile]
except KeyError as exc:
raise ValueError(f"Unknown profile: {profile}") from exc
def detect_memory_gib() -> float:
if os.name == "nt":
class MemoryStatus(ctypes.Structure):
_fields_ = [
("dwLength", ctypes.c_ulong),
("dwMemoryLoad", ctypes.c_ulong),
("ullTotalPhys", ctypes.c_ulonglong),
("ullAvailPhys", ctypes.c_ulonglong),
("ullTotalPageFile", ctypes.c_ulonglong),
("ullAvailPageFile", ctypes.c_ulonglong),
("ullTotalVirtual", ctypes.c_ulonglong),
("ullAvailVirtual", ctypes.c_ulonglong),
("ullAvailExtendedVirtual", ctypes.c_ulonglong),
]
status = MemoryStatus()
status.dwLength = ctypes.sizeof(MemoryStatus)
if not ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)):
raise LabError("Could not detect Windows physical memory")
return status.ullTotalPhys / (1024 ** 3)
try:
return os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES") / (1024 ** 3)
except (AttributeError, OSError, ValueError) as exc:
raise LabError("Could not detect physical memory") from exc
def _run(command: list[str], cwd: Path = ROOT) -> None:
print("+", shlex.join(str(part) for part in command), flush=True)
subprocess.run([str(part) for part in command], cwd=cwd, check=True)
def _require_docker() -> None:
if not shutil.which("docker"):
raise LabError(
"Docker is unavailable. Install and start Docker Desktop with Compose v2, "
"then rerun preflight. See docs/TROUBLESHOOTING.md."
)
result = subprocess.run(
["docker", "info", "--format", "{{.ServerVersion}}"],
cwd=ROOT,
capture_output=True,
text=True,
check=False,
)
if result.returncode:
raise LabError("Docker CLI exists, but the engine is not running or accessible")
def _single_node() -> Path:
return VENDOR_DIR / "single-node"
def _ensure_volumes() -> None:
_run(["docker", "volume", "create", "cyber-range-wazuh-logs"])
_run(["docker", "volume", "create", "cyber-range-waf-logs"])
def _check_vendor() -> None:
compose = _single_node() / "docker-compose.yml"
if not compose.is_file():
raise LabError("Wazuh is not installed; run: python lab.py wazuh-setup")
if f"wazuh/wazuh-manager:{WAZUH_VERSION}" not in compose.read_text(encoding="utf-8"):
raise LabError(
f"The vendored Wazuh release is not {WAZUH_VERSION}; move .vendor/wazuh-docker "
"aside and run wazuh-setup again"
)
def _wazuh_compose(command: list[str]) -> None:
override = ROOT / "compose.wazuh.override.yml"
local_override = _single_node() / "lab.override.yml"
shutil.copyfile(override, local_override)
_run(
["docker", "compose", "-f", "docker-compose.yml", "-f", local_override.name, *command],
cwd=_single_node(),
)
def wazuh_setup() -> None:
_require_docker()
if not VENDOR_DIR.exists():
if not shutil.which("git"):
raise LabError("Git is required to fetch the official Wazuh deployment")
VENDOR_DIR.parent.mkdir(parents=True, exist_ok=True)
_run([
"git", "clone", "--branch", f"v{WAZUH_VERSION}", "--depth", "1",
WAZUH_URL, str(VENDOR_DIR),
])
_check_vendor()
_ensure_volumes()
patch_wazuh_manager_config(_single_node() / "config" / "wazuh_cluster" / "wazuh_manager.conf")
_run(
["docker", "compose", "-f", "generate-indexer-certs.yml", "run", "--rm", "generator"],
cwd=_single_node(),
)
_wazuh_compose(["up", "-d"])
print("Wazuh dashboard: https://127.0.0.1:5443 (self-signed certificate)")
print("Official local defaults: admin / SecretPassword. Keep this lab on localhost.")
def up(profile: str) -> None:
_require_docker()
memory = detect_memory_gib()
budget = profile_budget_gib(profile)
print(f"Profile {profile}: approximate container memory ceiling {budget:.1f} GiB; host {memory:.1f} GiB")
if profile == "all-containers" and memory < 30:
raise LabError("all-containers requires at least 30 GiB physical RAM; use separate profiles")
if profile == "all-containers":
_check_vendor()
if profile == "blue":
_check_vendor()
_ensure_volumes()
_wazuh_compose(["up", "-d"])
if profile == "all-containers":
_ensure_volumes()
_wazuh_compose(["up", "-d"])
if profile == "ai":
_ensure_volumes()
_run(["docker", "compose", "--profile", profile, "up", "-d", "--build"])
print("Keep Security Onion and GOAD VMs stopped while using heavyweight container profiles.")
if profile in {"ai", "all-containers"}:
print("Optional model download: python lab.py pull-model")
def down() -> None:
_require_docker()
_run(["docker", "compose", "down", "--remove-orphans"])
if (_single_node() / "docker-compose.yml").is_file():
_wazuh_compose(["down"])
print("Containers stopped; named volumes and lab data were preserved.")
def status() -> None:
_require_docker()
_run(["docker", "compose", "ps"])
if (_single_node() / "docker-compose.yml").is_file():
_wazuh_compose(["ps"])
def urls() -> None:
configured = {
"WAF -> Juice Shop": "http://127.0.0.1:8080",
"MobSF": "http://127.0.0.1:8000",
"SOC copilot": "http://127.0.0.1:8082",
"Wazuh dashboard": "https://127.0.0.1:5443",
"PortSwigger Academy": "https://portswigger.net/web-security/all-labs",
}
for name, url in configured.items():
print(f"{name}: {url}")
print("These are configured endpoints; use status to confirm running services.")
def scan(target: str, extra: list[str]) -> None:
_require_docker()
if extra and extra[0] == "--":
extra = extra[1:]
_run(build_nmap_command(target, extra))
def pull_model(model: str) -> None:
_require_docker()
if not re.fullmatch(r"[A-Za-z0-9._/-]+:[A-Za-z0-9._-]+", model):
raise ValueError("Model must be a namespaced Ollama tag such as llama3.2:3b")
_run(["docker", "compose", "exec", "ollama", "ollama", "pull", model])
def triage(path: Path) -> None:
from soc_copilot.copilot import extract_json_objects, fallback_triage
alerts = extract_json_objects(path.read_text(encoding="utf-8"))
if not alerts:
raise LabError("No valid JSON alerts found")
for alert in alerts:
print(json.dumps(fallback_triage(alert), ensure_ascii=False))
def preflight() -> int:
print(f"Workspace: {ROOT}")
print(f"Python: {sys.version.split()[0]}")
print(f"Physical memory: {detect_memory_gib():.1f} GiB")
docker = shutil.which("docker")
print(f"Docker CLI: {docker or 'NOT FOUND'}")
print(f"Git CLI: {shutil.which('git') or 'NOT FOUND (only needed for Wazuh/GOAD)'}")
for profile in _PROFILE_BUDGETS:
print(f"Budget {profile}: approximately {profile_budget_gib(profile):.1f} GiB")
print("Heavy VM rule: never run Security Onion or GOAD with all-containers.")
if not docker:
print("RESULT: configuration can be tested, but containers cannot be deployed yet.")
return 1
try:
_require_docker()
except LabError as exc:
print(f"RESULT: {exc}")
return 1
print("RESULT: Docker engine is available.")
return 0
def validate() -> int:
from validate import validate_lab
violations = validate_lab(ROOT)
for violation in violations:
print(f"FAIL: {violation}", file=sys.stderr)
if violations:
return 1
print("Static validation passed; runtime deployment requires Docker.")
return 0
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser("preflight")
up_parser = sub.add_parser("up")
up_parser.add_argument("profile", choices=tuple(_PROFILE_BUDGETS))
sub.add_parser("down")
sub.add_parser("status")
sub.add_parser("urls")
sub.add_parser("wazuh-setup")
scan_parser = sub.add_parser("scan")
scan_parser.add_argument("target")
scan_parser.add_argument("extra", nargs=argparse.REMAINDER)
model_parser = sub.add_parser("pull-model")
model_parser.add_argument("model", nargs="?", default="llama3.2:3b")
triage_parser = sub.add_parser("triage")
triage_parser.add_argument("path", type=Path)
sub.add_parser("validate")
return parser
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
try:
if args.command == "preflight":
return preflight()
if args.command == "up":
up(args.profile)
elif args.command == "down":
down()
elif args.command == "status":
status()
elif args.command == "urls":
urls()
elif args.command == "wazuh-setup":
wazuh_setup()
elif args.command == "scan":
scan(args.target, args.extra)
elif args.command == "pull-model":
pull_model(args.model)
elif args.command == "triage":
triage(args.path)
elif args.command == "validate":
return validate()
return 0
except (LabError, ValueError, OSError, subprocess.CalledProcessError) as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 1
except KeyboardInterrupt:
print("Interrupted", file=sys.stderr)
return 130
if __name__ == "__main__":
raise SystemExit(main())