File size: 12,665 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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
#!/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())