philippefunk commited on
Commit
b198790
·
verified ·
1 Parent(s): 55c5066

Publish core lab configuration

Browse files
Files changed (11) hide show
  1. .dockerignore +8 -0
  2. .gitattributes +5 -35
  3. .gitignore +12 -0
  4. LICENSE +25 -0
  5. README.md +175 -1
  6. VALIDATION.md +85 -0
  7. compose.wazuh.override.yml +51 -0
  8. compose.yml +121 -0
  9. lab.py +369 -0
  10. requirements-dev.txt +1 -0
  11. validate.py +123 -0
.dockerignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ .git
2
+ .env
3
+ .vendor
4
+ __pycache__
5
+ *.pyc
6
+ tests
7
+ docs
8
+ reports
.gitattributes CHANGED
@@ -1,35 +1,5 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ * text=auto eol=lf
2
+ *.zip binary
3
+ *.png binary
4
+ *.jpg binary
5
+ *.jpeg binary
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .env
2
+ .vendor/
3
+ __pycache__/
4
+ *.py[cod]
5
+ .pytest_cache/
6
+ reports/
7
+ *.log
8
+ .DS_Store
9
+ cyber-range.zip
10
+ docs/superpowers/
11
+ .publish-tools/
12
+ .venv-publish/
LICENSE ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Philippe Funk
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ Third-party projects, container images, and virtual-machine platforms retain
16
+ their respective licenses. This license applies to the original orchestration,
17
+ controller, copilot, tests, and documentation in this repository.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
README.md CHANGED
@@ -1,3 +1,177 @@
1
  ---
2
- license: apache-2.0
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ license: mit
3
+ pretty_name: Cyber Range Virtual Lab
4
+ tags:
5
+ - cybersecurity
6
+ - blue-team
7
+ - red-team
8
+ - wazuh
9
+ - owasp
10
+ - docker
11
+ - soc
12
+ - homelab
13
  ---
14
+
15
+ # Cyber Range — Blue Team + Red Team Virtual Lab
16
+
17
+ A profile-based learning range for the ten supplied cybersecurity resources. It combines isolated Docker services, an advisory-only local AI analyst, and supported VM/external tracks for platforms that should not be containerized.
18
+
19
+ > **Authorized use only.** Scan and exploit only this lab or systems you own or are explicitly authorized to test. Juice Shop and GOAD are deliberately vulnerable. Keep every published endpoint on localhost and every attack VM on a host-only network.
20
+
21
+ ## What is included
22
+
23
+ | # | Resource | Delivery | Start / open |
24
+ |---|---|---|---|
25
+ | 1 | Wazuh SIEM | Official single-node containers, pinned to 4.14.10 | `python lab.py wazuh-setup` |
26
+ | 2 | Web Application Firewall | OWASP ModSecurity CRS → Juice Shop | `python lab.py up core` |
27
+ | 3 | Home SOC with AI | Wazuh + WAF logs + local Ollama/copilot | Start Wazuh, then `python lab.py up ai` |
28
+ | 4 | AI SOC analyst | Advisory JSONL reports and local web UI | `http://127.0.0.1:8082` |
29
+ | 5 | Security Onion | Supported ISO/VM track | [Security Onion guide](docs/SECURITY_ONION.md) |
30
+ | 6 | Android application hacking | MobSF static analysis + OWASP crackmes | `python lab.py up mobile` |
31
+ | 7 | Nmap reconnaissance | Allowlisted, on-demand container | `python lab.py scan waf -- -sV` |
32
+ | 8 | PortSwigger Academy | Official hosted labs | [Academy track](docs/PORTSWIGGER.md) |
33
+ | 9 | OWASP Juice Shop | Isolated target behind the WAF | `http://127.0.0.1:8080` |
34
+ | 10 | Active Directory GOAD | Official Vagrant/VM track | [GOAD guide](docs/GOAD.md) |
35
+
36
+ ## Architecture
37
+
38
+ ```text
39
+ localhost :8080 internal range_net
40
+ │ ┌──────────────────────┐
41
+ ▼ │ │
42
+ OWASP CRS WAF ────────────────▶│ OWASP Juice Shop │
43
+ │ │ Nmap (on demand) │
44
+ ▼ └──────────────────────┘
45
+ named WAF log volume ─────────▶ Wazuh manager (blue profile)
46
+ │
47
+ ▼ alerts.json (read-only share)
48
+ SOC copilot ─────────▶ Ollama (local, optional)
49
+ │
50
+ ▼ localhost :8082 / JSONL
51
+ ```
52
+
53
+ - No Docker socket, host PID namespace, or privileged services.
54
+ - Juice Shop is not directly exposed to the host.
55
+ - Wazuh, MobSF, WAF, and copilot UIs bind to `127.0.0.1`.
56
+ - Ollama has no host port; alert content stays local.
57
+ - The AI analyst cannot execute containment or incident-response actions.
58
+
59
+ ## Prerequisites
60
+
61
+ - Windows 11 + Docker Desktop, or Linux/macOS with Docker Engine.
62
+ - Docker Compose v2 and enough free disk for selected images.
63
+ - Python 3.11 or later.
64
+ - Git, only for Wazuh setup and GOAD.
65
+ - PyYAML, only for static validation: `python -m pip install -r requirements-dev.txt`.
66
+
67
+ Check the host before downloading anything:
68
+
69
+ ```bash
70
+ python lab.py preflight
71
+ ```
72
+
73
+ A missing Docker engine blocks deployment but not unit/static validation.
74
+
75
+ ## Quick start
76
+
77
+ ### 1. Core web target and WAF (approximately 2.5 GiB ceiling)
78
+
79
+ ```bash
80
+ python lab.py up core
81
+ python lab.py urls
82
+ ```
83
+
84
+ Open `http://127.0.0.1:8080`. Juice Shop is reachable through the WAF, not directly.
85
+
86
+ Run a safe baseline and a WAF test:
87
+
88
+ ```bash
89
+ curl -I http://127.0.0.1:8080/
90
+ curl "http://127.0.0.1:8080/?q=%27%20OR%201%3D1--"
91
+ python lab.py scan waf -- -sV --top-ports 100
92
+ ```
93
+
94
+ The second request should be inspected and may receive a CRS `403`. Confirm behavior in logs rather than relying only on the status code. Exercises are in [the runbook](docs/RUNBOOK.md).
95
+
96
+ ### 2. Wazuh blue-team stack (approximately 9 GiB with WAF and Juice Shop)
97
+
98
+ ```bash
99
+ python lab.py wazuh-setup
100
+ ```
101
+
102
+ Open `https://127.0.0.1:5443` and accept the lab's self-signed-certificate warning. Official local defaults are `admin` / `SecretPassword`; do not expose this instance or reuse those credentials outside the disposable lab.
103
+
104
+ Setup clones the official `wazuh-docker` `v4.14.10` release into `.vendor/`, generates its certificates, applies localhost/resource overrides, and starts the stack. It downloads several gigabytes on first use.
105
+
106
+ To start an already-installed blue stack and WAF later:
107
+
108
+ ```bash
109
+ python lab.py up blue
110
+ ```
111
+
112
+ ### 3. Local AI SOC analyst (approximately 6.5 GiB plus Wazuh)
113
+
114
+ ```bash
115
+ python lab.py up ai
116
+ python lab.py pull-model
117
+ ```
118
+
119
+ The default model is `llama3.2:3b`; the download is optional. Without it, the copilot still produces deterministic triage. Open `http://127.0.0.1:8082` or read `http://127.0.0.1:8082/reports.json`.
120
+
121
+ Test the fallback immediately without Wazuh:
122
+
123
+ ```bash
124
+ python lab.py triage examples/alerts.json
125
+ ```
126
+
127
+ ### 4. Android static analysis (approximately 3 GiB)
128
+
129
+ ```bash
130
+ python lab.py up mobile
131
+ ```
132
+
133
+ Open `http://127.0.0.1:8000`; the official image's default local credentials are `mobsf` / `mobsf`. Upload only your own APK or a training APK. See [the Android track](docs/ANDROID.md) for OWASP MAS Crackmes and dynamic-analysis limitations.
134
+
135
+ ### 5. VM and hosted tracks
136
+
137
+ - [Security Onion](docs/SECURITY_ONION.md): begin with Import mode for PCAP/EVTX analysis; use Evaluation for live network visibility.
138
+ - [GOAD](docs/GOAD.md): use GOAD-Light on a 32 GiB host and keep other heavyweight workloads stopped.
139
+ - [PortSwigger Academy](docs/PORTSWIGGER.md): follow the official SQL injection, XSS, authentication, and access-control sequence.
140
+
141
+ ## Resource policy
142
+
143
+ | Profile | Approximate configured memory ceiling | Notes |
144
+ |---|---:|---|
145
+ | `core` | 2.5 GiB | WAF + Juice Shop; Nmap runs on demand |
146
+ | `blue` | 9 GiB | Wazuh + WAF/Juice Shop |
147
+ | `mobile` | 3 GiB | MobSF |
148
+ | `ai` | 6.5 GiB | Ollama + copilot; model usage varies |
149
+ | `all-containers` | 19 GiB | Requires at least 30 GiB detected physical RAM |
150
+
151
+ These are limits, not expected steady-state usage. Do not run Security Onion or GOAD with `all-containers`. Full GOAD needs about 24 GiB for its VMs alone and is tight on a 32 GiB host.
152
+
153
+ ## Lifecycle
154
+
155
+ ```bash
156
+ python lab.py status # configured Docker projects
157
+ python lab.py down # stop containers; preserve named volumes
158
+ python lab.py validate # static policy checks
159
+ python -m unittest discover -s tests -v
160
+ ```
161
+
162
+ `down` never deletes volumes. Destructive reset and backup instructions are deliberately separate in [the runbook](docs/RUNBOOK.md).
163
+
164
+ ## Configuration
165
+
166
+ Copy `.env.example` to `.env` only when changing image tags, ports, resource limits, WAF mode, or AI settings. The rolling WAF/MobSF/Ollama tags follow upstream recommendations; for a frozen classroom, pull once and pin the resulting image digests in `.env`. Juice Shop and Wazuh are version-pinned.
167
+
168
+ ## Verification status
169
+
170
+ This package contains unit tests and static policy validation. Runtime deployment requires Docker and is reported separately in [VALIDATION.md](VALIDATION.md); configuration files are not represented as proof that containers were started.
171
+
172
+ ## Documentation
173
+
174
+ - [Daily exercises and reset/backup](docs/RUNBOOK.md)
175
+ - [All official resource links](docs/RESOURCES.md)
176
+ - [Troubleshooting](docs/TROUBLESHOOTING.md)
177
+ - [Architecture/design record](docs/superpowers/specs/2026-11-26-cyber-range-design.md)
VALIDATION.md ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Validation Report
2
+
3
+ Date: 2026-11-26
4
+
5
+ ## Verified on this workstation
6
+
7
+ Host observed by preflight:
8
+
9
+ - Python 3.12.16
10
+ - 20 logical CPU threads (initial capability check)
11
+ - 31.1 GiB physical RAM
12
+ - Git available
13
+ - Docker CLI/engine unavailable
14
+
15
+ ### Unit tests
16
+
17
+ Command:
18
+
19
+ ```bash
20
+ python -m unittest discover -s tests -v
21
+ ```
22
+
23
+ Observed result: **21 tests passed, 0 failures**.
24
+
25
+ Coverage includes:
26
+
27
+ - Nmap target and option-injection rejection.
28
+ - Safe argument-array command construction.
29
+ - Wazuh patch idempotence and the official two-`<ossec_config>` layout.
30
+ - Resource-budget values and physical-memory detection.
31
+ - Loopback-only published-port validation, including Compose `${VAR:-default}` syntax.
32
+ - Deterministic alert severity, malformed JSON handling, bounded/untrusted prompts.
33
+ - Ollama-outage fallback, alert-follower restart deduplication, and report persistence.
34
+
35
+ ### Static policy and syntax checks
36
+
37
+ Command:
38
+
39
+ ```bash
40
+ python validate.py
41
+ python -m compileall -q lab.py validate.py soc_copilot tests
42
+ ```
43
+
44
+ Observed result: **passed**. The validator checked required services and guides, internal target networking, memory limits, localhost bindings, and the absence of privileged mode, host PID, and Docker-socket mounts. All Python files compiled successfully.
45
+
46
+ ### Offline behavior
47
+
48
+ Command:
49
+
50
+ ```bash
51
+ python lab.py triage examples/alerts.json
52
+ ```
53
+
54
+ Observed result: two valid advisory JSON reports, including one high-severity and one low-severity deterministic result.
55
+
56
+ ### Documentation coverage
57
+
58
+ Observed result: all ten numbered resources are present in `docs/RESOURCES.md`; dedicated VM, Android, Academy, operations, and troubleshooting guides exist.
59
+
60
+ ## Not verified: runtime deployment
61
+
62
+ Command:
63
+
64
+ ```bash
65
+ python lab.py preflight
66
+ ```
67
+
68
+ Observed result: `Docker CLI: NOT FOUND`; preflight returned exit code 1 as designed.
69
+
70
+ Therefore:
71
+
72
+ - `docker compose config` could not be run with the Docker CLI.
73
+ - No images were pulled or containers started.
74
+ - Wazuh certificate generation and manager/indexer/dashboard health were not runtime-tested.
75
+ - WAF, Juice Shop, MobSF, Ollama, and copilot HTTP endpoints were not runtime-tested.
76
+ - Security Onion and GOAD are documented VM tracks, not installed VMs.
77
+
78
+ The package is statically validated and unit-tested, but it is **not claimed to be a running or runtime-verified deployment**. After installing/starting Docker, begin with:
79
+
80
+ ```bash
81
+ python lab.py preflight
82
+ python lab.py up core
83
+ ```
84
+
85
+ Then verify `http://127.0.0.1:8080` before enabling heavier profiles.
compose.wazuh.override.yml ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ wazuh.manager:
3
+ restart: unless-stopped
4
+ mem_limit: 2g
5
+ cpus: 2.0
6
+ ports:
7
+ - "127.0.0.1:1514:1514"
8
+ - "127.0.0.1:1515:1515"
9
+ - "127.0.0.1:5514:514/udp"
10
+ - "127.0.0.1:55000:55000"
11
+ volumes:
12
+ - wazuh_api_configuration:/var/ossec/api/configuration
13
+ - wazuh_etc:/var/ossec/etc
14
+ - wazuh_logs:/var/ossec/logs
15
+ - wazuh_queue:/var/ossec/queue
16
+ - wazuh_var_multigroups:/var/ossec/var/multigroups
17
+ - wazuh_integrations:/var/ossec/integrations
18
+ - wazuh_active_response:/var/ossec/active-response/bin
19
+ - wazuh_agentless:/var/ossec/agentless
20
+ - wazuh_wodles:/var/ossec/wodles
21
+ - filebeat_etc:/etc/filebeat
22
+ - filebeat_var:/var/lib/filebeat
23
+ - ./config/wazuh_indexer_ssl_certs/root-ca-manager.pem:/etc/ssl/root-ca.pem
24
+ - ./config/wazuh_indexer_ssl_certs/wazuh.manager.pem:/etc/ssl/filebeat.pem
25
+ - ./config/wazuh_indexer_ssl_certs/wazuh.manager-key.pem:/etc/ssl/filebeat.key
26
+ - ./config/wazuh_cluster/wazuh_manager.conf:/wazuh-config-mount/etc/ossec.conf
27
+ - waf_logs:/var/log/waf:ro
28
+
29
+ wazuh.indexer:
30
+ restart: unless-stopped
31
+ mem_limit: 4g
32
+ cpus: 2.0
33
+ ports:
34
+ - "127.0.0.1:9200:9200"
35
+ environment:
36
+ - "OPENSEARCH_JAVA_OPTS=-Xms2g -Xmx2g"
37
+
38
+ wazuh.dashboard:
39
+ restart: unless-stopped
40
+ mem_limit: 1g
41
+ cpus: 1.0
42
+ ports:
43
+ - "127.0.0.1:5443:5601"
44
+
45
+ volumes:
46
+ wazuh_logs:
47
+ external: true
48
+ name: cyber-range-wazuh-logs
49
+ waf_logs:
50
+ external: true
51
+ name: cyber-range-waf-logs
compose.yml ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: cyber-range
2
+
3
+ x-lab-security: &lab-security
4
+ restart: unless-stopped
5
+ security_opt:
6
+ - no-new-privileges:true
7
+
8
+ services:
9
+ juice-shop:
10
+ <<: *lab-security
11
+ image: ${JUICE_SHOP_IMAGE:-bkimminich/juice-shop:v20.4.0}
12
+ profiles: [core, red, all-containers]
13
+ networks: [range_net]
14
+ expose:
15
+ - "3000"
16
+ mem_limit: ${JUICE_SHOP_MEMORY:-1g}
17
+ cpus: ${JUICE_SHOP_CPUS:-1.0}
18
+
19
+ waf:
20
+ <<: *lab-security
21
+ image: ${WAF_IMAGE:-owasp/modsecurity-crs:nginx}
22
+ profiles: [core, blue, red, all-containers]
23
+ environment:
24
+ BACKEND: http://juice-shop:3000
25
+ PORT: "8080"
26
+ SERVER_NAME: juice-shop.local
27
+ MODSEC_RULE_ENGINE: ${WAF_MODE:-On}
28
+ BLOCKING_PARANOIA: ${WAF_PARANOIA:-1}
29
+ DETECTION_PARANOIA: ${WAF_PARANOIA:-1}
30
+ MODSEC_AUDIT_ENGINE: RelevantOnly
31
+ MODSEC_AUDIT_LOG: /var/log/modsecurity/audit.log
32
+ MODSEC_AUDIT_LOG_FORMAT: JSON
33
+ MODSEC_AUDIT_LOG_TYPE: Serial
34
+ ERRORLOG: /var/log/modsecurity/error.log
35
+ ACCESSLOG: /var/log/modsecurity/access.log
36
+ NGINX_WORKER_PROCESSES: "1"
37
+ WORKER_CONNECTIONS: ${WAF_WORKER_CONNECTIONS:-512}
38
+ ports:
39
+ - "127.0.0.1:${WAF_PORT:-8080}:8080"
40
+ volumes:
41
+ - waf_logs:/var/log/modsecurity
42
+ depends_on:
43
+ - juice-shop
44
+ networks: [range_net]
45
+ mem_limit: ${WAF_MEMORY:-1g}
46
+ cpus: ${WAF_CPUS:-1.0}
47
+
48
+ nmap:
49
+ build: ./tools/nmap
50
+ profiles: [tools, red, all-containers]
51
+ entrypoint: [nmap]
52
+ networks: [range_net]
53
+ security_opt:
54
+ - no-new-privileges:true
55
+ mem_limit: ${NMAP_MEMORY:-512m}
56
+ cpus: ${NMAP_CPUS:-1.0}
57
+
58
+ mobsf:
59
+ <<: *lab-security
60
+ image: ${MOBSF_IMAGE:-opensecurity/mobile-security-framework-mobsf:latest}
61
+ profiles: [mobile, all-containers]
62
+ environment:
63
+ MOBSF_DISABLE_AUTHENTICATION: "0"
64
+ ports:
65
+ - "127.0.0.1:${MOBSF_PORT:-8000}:8000"
66
+ volumes:
67
+ - mobsf_data:/home/mobsf/.MobSF
68
+ mem_limit: ${MOBSF_MEMORY:-3g}
69
+ cpus: ${MOBSF_CPUS:-2.0}
70
+
71
+ ollama:
72
+ <<: *lab-security
73
+ image: ${OLLAMA_IMAGE:-ollama/ollama:latest}
74
+ profiles: [ai, all-containers]
75
+ environment:
76
+ OLLAMA_HOST: 0.0.0.0:11434
77
+ OLLAMA_NUM_PARALLEL: ${OLLAMA_NUM_PARALLEL:-1}
78
+ OLLAMA_MAX_LOADED_MODELS: ${OLLAMA_MAX_LOADED_MODELS:-1}
79
+ volumes:
80
+ - ollama_models:/root/.ollama
81
+ networks: [ai_net]
82
+ mem_limit: ${OLLAMA_MEMORY:-6g}
83
+ cpus: ${OLLAMA_CPUS:-4.0}
84
+
85
+ soc-copilot:
86
+ <<: *lab-security
87
+ build: ./soc_copilot
88
+ profiles: [ai, all-containers]
89
+ environment:
90
+ OLLAMA_URL: http://ollama:11434
91
+ OLLAMA_MODEL: ${OLLAMA_MODEL:-llama3.2:3b}
92
+ OLLAMA_TIMEOUT: ${OLLAMA_TIMEOUT:-90}
93
+ ALERTS_PATH: /alerts/alerts.json
94
+ REPORTS_PATH: /reports/triage.jsonl
95
+ MIN_RULE_LEVEL: ${MIN_RULE_LEVEL:-10}
96
+ COPILOT_PORT: "8082"
97
+ ports:
98
+ - "127.0.0.1:${COPILOT_PORT:-8082}:8082"
99
+ volumes:
100
+ - cyber-range-wazuh-logs:/alerts:ro
101
+ - copilot_reports:/reports
102
+ networks: [ai_net]
103
+ depends_on:
104
+ - ollama
105
+ mem_limit: ${COPILOT_MEMORY:-512m}
106
+ cpus: ${COPILOT_CPUS:-0.5}
107
+
108
+ networks:
109
+ range_net:
110
+ internal: true
111
+ ai_net:
112
+
113
+ volumes:
114
+ waf_logs:
115
+ name: cyber-range-waf-logs
116
+ mobsf_data:
117
+ ollama_models:
118
+ copilot_reports:
119
+ cyber-range-wazuh-logs:
120
+ external: true
121
+ name: cyber-range-wazuh-logs
lab.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Cross-platform controller for the isolated cyber-range."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import ctypes
8
+ import ipaddress
9
+ import json
10
+ import os
11
+ import re
12
+ import shlex
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ ROOT = Path(__file__).resolve().parent
19
+ VENDOR_DIR = ROOT / ".vendor" / "wazuh-docker"
20
+ WAZUH_VERSION = "4.14.10"
21
+ WAZUH_URL = "https://github.com/wazuh/wazuh-docker.git"
22
+ _HOSTNAME = re.compile(r"^(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$")
23
+ _PROFILE_BUDGETS = {
24
+ "core": 2.5,
25
+ "blue": 9.0,
26
+ "mobile": 3.0,
27
+ "ai": 6.5,
28
+ "red": 3.0,
29
+ "all-containers": 19.0,
30
+ }
31
+
32
+
33
+ class LabError(RuntimeError):
34
+ """An actionable lab lifecycle error."""
35
+
36
+
37
+ def validate_nmap_target(target: str) -> str:
38
+ value = target.strip()
39
+ if not value or value.startswith("-") or any(c in value for c in ";&|`$()<>\n\r"):
40
+ raise ValueError("Invalid or unsafe scan target")
41
+ try:
42
+ ipaddress.ip_network(value, strict=False)
43
+ return value
44
+ except ValueError:
45
+ pass
46
+ if not _HOSTNAME.fullmatch(value) or ".." in value:
47
+ raise ValueError("Target must be an IP, CIDR, hostname, or Compose service name")
48
+ return value
49
+
50
+
51
+ def build_nmap_command(target: str, extra: list[str]) -> list[str]:
52
+ allowed_flags = {"-sV", "-sT", "-sS", "-Pn", "-O", "--open"}
53
+ allowed_values = {"--top-ports", "-p"}
54
+ index = 0
55
+ while index < len(extra):
56
+ option = extra[index]
57
+ base = option.split("=", 1)[0]
58
+ if base in allowed_flags and option == base:
59
+ index += 1
60
+ continue
61
+ if base not in allowed_values:
62
+ raise ValueError(f"Unsupported Nmap option: {option}")
63
+ if "=" in option:
64
+ value = option.split("=", 1)[1]
65
+ else:
66
+ index += 1
67
+ if index >= len(extra):
68
+ raise ValueError(f"Missing value for {base}")
69
+ value = extra[index]
70
+ if not re.fullmatch(r"[0-9,-]+", value):
71
+ raise ValueError(f"Invalid numeric/port value for {base}")
72
+ index += 1
73
+ return [
74
+ "docker", "compose", "--profile", "tools", "run", "--rm",
75
+ "--cap-add=NET_RAW", "nmap", *extra, validate_nmap_target(target),
76
+ ]
77
+
78
+
79
+ WAF_BLOCK = """
80
+ <!-- cyber-range-waf -->
81
+ <localfile>
82
+ <log_format>syslog</log_format>
83
+ <location>/var/log/waf/error.log</location>
84
+ </localfile>
85
+ """
86
+
87
+
88
+ def patch_wazuh_manager_config(path: Path) -> None:
89
+ text = path.read_text(encoding="utf-8")
90
+ if "<!-- cyber-range-waf -->" in text:
91
+ return
92
+ marker = "</ossec_config>"
93
+ if marker not in text:
94
+ raise ValueError(f"Unexpected Wazuh configuration: {path}")
95
+ path.write_text(text.replace(marker, WAF_BLOCK + marker, 1), encoding="utf-8")
96
+
97
+
98
+ def profile_budget_gib(profile: str) -> float:
99
+ try:
100
+ return _PROFILE_BUDGETS[profile]
101
+ except KeyError as exc:
102
+ raise ValueError(f"Unknown profile: {profile}") from exc
103
+
104
+
105
+ def detect_memory_gib() -> float:
106
+ if os.name == "nt":
107
+ class MemoryStatus(ctypes.Structure):
108
+ _fields_ = [
109
+ ("dwLength", ctypes.c_ulong),
110
+ ("dwMemoryLoad", ctypes.c_ulong),
111
+ ("ullTotalPhys", ctypes.c_ulonglong),
112
+ ("ullAvailPhys", ctypes.c_ulonglong),
113
+ ("ullTotalPageFile", ctypes.c_ulonglong),
114
+ ("ullAvailPageFile", ctypes.c_ulonglong),
115
+ ("ullTotalVirtual", ctypes.c_ulonglong),
116
+ ("ullAvailVirtual", ctypes.c_ulonglong),
117
+ ("ullAvailExtendedVirtual", ctypes.c_ulonglong),
118
+ ]
119
+
120
+ status = MemoryStatus()
121
+ status.dwLength = ctypes.sizeof(MemoryStatus)
122
+ if not ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)):
123
+ raise LabError("Could not detect Windows physical memory")
124
+ return status.ullTotalPhys / (1024 ** 3)
125
+ try:
126
+ return os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES") / (1024 ** 3)
127
+ except (AttributeError, OSError, ValueError) as exc:
128
+ raise LabError("Could not detect physical memory") from exc
129
+
130
+
131
+ def _run(command: list[str], cwd: Path = ROOT) -> None:
132
+ print("+", shlex.join(str(part) for part in command), flush=True)
133
+ subprocess.run([str(part) for part in command], cwd=cwd, check=True)
134
+
135
+
136
+ def _require_docker() -> None:
137
+ if not shutil.which("docker"):
138
+ raise LabError(
139
+ "Docker is unavailable. Install and start Docker Desktop with Compose v2, "
140
+ "then rerun preflight. See docs/TROUBLESHOOTING.md."
141
+ )
142
+ result = subprocess.run(
143
+ ["docker", "info", "--format", "{{.ServerVersion}}"],
144
+ cwd=ROOT,
145
+ capture_output=True,
146
+ text=True,
147
+ check=False,
148
+ )
149
+ if result.returncode:
150
+ raise LabError("Docker CLI exists, but the engine is not running or accessible")
151
+
152
+
153
+ def _single_node() -> Path:
154
+ return VENDOR_DIR / "single-node"
155
+
156
+
157
+ def _ensure_volumes() -> None:
158
+ _run(["docker", "volume", "create", "cyber-range-wazuh-logs"])
159
+ _run(["docker", "volume", "create", "cyber-range-waf-logs"])
160
+
161
+
162
+ def _check_vendor() -> None:
163
+ compose = _single_node() / "docker-compose.yml"
164
+ if not compose.is_file():
165
+ raise LabError("Wazuh is not installed; run: python lab.py wazuh-setup")
166
+ if f"wazuh/wazuh-manager:{WAZUH_VERSION}" not in compose.read_text(encoding="utf-8"):
167
+ raise LabError(
168
+ f"The vendored Wazuh release is not {WAZUH_VERSION}; move .vendor/wazuh-docker "
169
+ "aside and run wazuh-setup again"
170
+ )
171
+
172
+
173
+ def _wazuh_compose(command: list[str]) -> None:
174
+ override = ROOT / "compose.wazuh.override.yml"
175
+ local_override = _single_node() / "lab.override.yml"
176
+ shutil.copyfile(override, local_override)
177
+ _run(
178
+ ["docker", "compose", "-f", "docker-compose.yml", "-f", local_override.name, *command],
179
+ cwd=_single_node(),
180
+ )
181
+
182
+
183
+ def wazuh_setup() -> None:
184
+ _require_docker()
185
+ if not VENDOR_DIR.exists():
186
+ if not shutil.which("git"):
187
+ raise LabError("Git is required to fetch the official Wazuh deployment")
188
+ VENDOR_DIR.parent.mkdir(parents=True, exist_ok=True)
189
+ _run([
190
+ "git", "clone", "--branch", f"v{WAZUH_VERSION}", "--depth", "1",
191
+ WAZUH_URL, str(VENDOR_DIR),
192
+ ])
193
+ _check_vendor()
194
+ _ensure_volumes()
195
+ patch_wazuh_manager_config(_single_node() / "config" / "wazuh_cluster" / "wazuh_manager.conf")
196
+ _run(
197
+ ["docker", "compose", "-f", "generate-indexer-certs.yml", "run", "--rm", "generator"],
198
+ cwd=_single_node(),
199
+ )
200
+ _wazuh_compose(["up", "-d"])
201
+ print("Wazuh dashboard: https://127.0.0.1:5443 (self-signed certificate)")
202
+ print("Official local defaults: admin / SecretPassword. Keep this lab on localhost.")
203
+
204
+
205
+ def up(profile: str) -> None:
206
+ _require_docker()
207
+ memory = detect_memory_gib()
208
+ budget = profile_budget_gib(profile)
209
+ print(f"Profile {profile}: approximate container memory ceiling {budget:.1f} GiB; host {memory:.1f} GiB")
210
+ if profile == "all-containers" and memory < 30:
211
+ raise LabError("all-containers requires at least 30 GiB physical RAM; use separate profiles")
212
+ if profile == "all-containers":
213
+ _check_vendor()
214
+ if profile == "blue":
215
+ _check_vendor()
216
+ _ensure_volumes()
217
+ _wazuh_compose(["up", "-d"])
218
+ if profile == "all-containers":
219
+ _ensure_volumes()
220
+ _wazuh_compose(["up", "-d"])
221
+ if profile == "ai":
222
+ _ensure_volumes()
223
+ _run(["docker", "compose", "--profile", profile, "up", "-d", "--build"])
224
+ print("Keep Security Onion and GOAD VMs stopped while using heavyweight container profiles.")
225
+ if profile in {"ai", "all-containers"}:
226
+ print("Optional model download: python lab.py pull-model")
227
+
228
+
229
+ def down() -> None:
230
+ _require_docker()
231
+ _run(["docker", "compose", "down", "--remove-orphans"])
232
+ if (_single_node() / "docker-compose.yml").is_file():
233
+ _wazuh_compose(["down"])
234
+ print("Containers stopped; named volumes and lab data were preserved.")
235
+
236
+
237
+ def status() -> None:
238
+ _require_docker()
239
+ _run(["docker", "compose", "ps"])
240
+ if (_single_node() / "docker-compose.yml").is_file():
241
+ _wazuh_compose(["ps"])
242
+
243
+
244
+ def urls() -> None:
245
+ configured = {
246
+ "WAF -> Juice Shop": "http://127.0.0.1:8080",
247
+ "MobSF": "http://127.0.0.1:8000",
248
+ "SOC copilot": "http://127.0.0.1:8082",
249
+ "Wazuh dashboard": "https://127.0.0.1:5443",
250
+ "PortSwigger Academy": "https://portswigger.net/web-security/all-labs",
251
+ }
252
+ for name, url in configured.items():
253
+ print(f"{name}: {url}")
254
+ print("These are configured endpoints; use status to confirm running services.")
255
+
256
+
257
+ def scan(target: str, extra: list[str]) -> None:
258
+ _require_docker()
259
+ if extra and extra[0] == "--":
260
+ extra = extra[1:]
261
+ _run(build_nmap_command(target, extra))
262
+
263
+
264
+ def pull_model(model: str) -> None:
265
+ _require_docker()
266
+ if not re.fullmatch(r"[A-Za-z0-9._/-]+:[A-Za-z0-9._-]+", model):
267
+ raise ValueError("Model must be a namespaced Ollama tag such as llama3.2:3b")
268
+ _run(["docker", "compose", "exec", "ollama", "ollama", "pull", model])
269
+
270
+
271
+ def triage(path: Path) -> None:
272
+ from soc_copilot.copilot import extract_json_objects, fallback_triage
273
+
274
+ alerts = extract_json_objects(path.read_text(encoding="utf-8"))
275
+ if not alerts:
276
+ raise LabError("No valid JSON alerts found")
277
+ for alert in alerts:
278
+ print(json.dumps(fallback_triage(alert), ensure_ascii=False))
279
+
280
+
281
+ def preflight() -> int:
282
+ print(f"Workspace: {ROOT}")
283
+ print(f"Python: {sys.version.split()[0]}")
284
+ print(f"Physical memory: {detect_memory_gib():.1f} GiB")
285
+ docker = shutil.which("docker")
286
+ print(f"Docker CLI: {docker or 'NOT FOUND'}")
287
+ print(f"Git CLI: {shutil.which('git') or 'NOT FOUND (only needed for Wazuh/GOAD)'}")
288
+ for profile in _PROFILE_BUDGETS:
289
+ print(f"Budget {profile}: approximately {profile_budget_gib(profile):.1f} GiB")
290
+ print("Heavy VM rule: never run Security Onion or GOAD with all-containers.")
291
+ if not docker:
292
+ print("RESULT: configuration can be tested, but containers cannot be deployed yet.")
293
+ return 1
294
+ try:
295
+ _require_docker()
296
+ except LabError as exc:
297
+ print(f"RESULT: {exc}")
298
+ return 1
299
+ print("RESULT: Docker engine is available.")
300
+ return 0
301
+
302
+
303
+ def validate() -> int:
304
+ from validate import validate_lab
305
+
306
+ violations = validate_lab(ROOT)
307
+ for violation in violations:
308
+ print(f"FAIL: {violation}", file=sys.stderr)
309
+ if violations:
310
+ return 1
311
+ print("Static validation passed; runtime deployment requires Docker.")
312
+ return 0
313
+
314
+
315
+ def build_parser() -> argparse.ArgumentParser:
316
+ parser = argparse.ArgumentParser(description=__doc__)
317
+ sub = parser.add_subparsers(dest="command", required=True)
318
+ sub.add_parser("preflight")
319
+ up_parser = sub.add_parser("up")
320
+ up_parser.add_argument("profile", choices=tuple(_PROFILE_BUDGETS))
321
+ sub.add_parser("down")
322
+ sub.add_parser("status")
323
+ sub.add_parser("urls")
324
+ sub.add_parser("wazuh-setup")
325
+ scan_parser = sub.add_parser("scan")
326
+ scan_parser.add_argument("target")
327
+ scan_parser.add_argument("extra", nargs=argparse.REMAINDER)
328
+ model_parser = sub.add_parser("pull-model")
329
+ model_parser.add_argument("model", nargs="?", default="llama3.2:3b")
330
+ triage_parser = sub.add_parser("triage")
331
+ triage_parser.add_argument("path", type=Path)
332
+ sub.add_parser("validate")
333
+ return parser
334
+
335
+
336
+ def main(argv: list[str] | None = None) -> int:
337
+ args = build_parser().parse_args(argv)
338
+ try:
339
+ if args.command == "preflight":
340
+ return preflight()
341
+ if args.command == "up":
342
+ up(args.profile)
343
+ elif args.command == "down":
344
+ down()
345
+ elif args.command == "status":
346
+ status()
347
+ elif args.command == "urls":
348
+ urls()
349
+ elif args.command == "wazuh-setup":
350
+ wazuh_setup()
351
+ elif args.command == "scan":
352
+ scan(args.target, args.extra)
353
+ elif args.command == "pull-model":
354
+ pull_model(args.model)
355
+ elif args.command == "triage":
356
+ triage(args.path)
357
+ elif args.command == "validate":
358
+ return validate()
359
+ return 0
360
+ except (LabError, ValueError, OSError, subprocess.CalledProcessError) as exc:
361
+ print(f"ERROR: {exc}", file=sys.stderr)
362
+ return 1
363
+ except KeyboardInterrupt:
364
+ print("Interrupted", file=sys.stderr)
365
+ return 130
366
+
367
+
368
+ if __name__ == "__main__":
369
+ raise SystemExit(main())
requirements-dev.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ PyYAML>=6.0,<7
validate.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Static policy checks for the cyber-range package."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import ast
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ import yaml
11
+
12
+ ROOT = Path(__file__).resolve().parent
13
+ REQUIRED_SERVICES = {"juice-shop", "waf", "nmap", "mobsf", "ollama", "soc-copilot"}
14
+ REQUIRED_DOCS = (
15
+ "README.md",
16
+ "docs/RUNBOOK.md",
17
+ "docs/RESOURCES.md",
18
+ "docs/SECURITY_ONION.md",
19
+ "docs/GOAD.md",
20
+ "docs/ANDROID.md",
21
+ "docs/PORTSWIGGER.md",
22
+ "docs/TROUBLESHOOTING.md",
23
+ )
24
+
25
+
26
+ def invalid_published_port(value: object) -> bool:
27
+ """Return True unless a published port is explicitly loopback-only."""
28
+ if isinstance(value, dict):
29
+ host = str(value.get("host_ip", "0.0.0.0"))
30
+ return host not in {"127.0.0.1", "localhost"} or not value.get("published")
31
+ text = str(value).split("/", 1)[0]
32
+ if ":" not in text:
33
+ return True
34
+ host = text.split(":", 1)[0]
35
+ return host not in {"127.0.0.1", "localhost"}
36
+
37
+
38
+ def _load_yaml(path: Path, violations: list[str]) -> dict:
39
+ try:
40
+ data = yaml.safe_load(path.read_text(encoding="utf-8"))
41
+ except (OSError, yaml.YAMLError) as exc:
42
+ violations.append(f"{path.name}: cannot load YAML: {exc}")
43
+ return {}
44
+ if not isinstance(data, dict):
45
+ violations.append(f"{path.name}: expected a YAML mapping")
46
+ return {}
47
+ return data
48
+
49
+
50
+ def _check_services(data: dict, source: str, violations: list[str]) -> None:
51
+ services = data.get("services") or {}
52
+ for name, service in services.items():
53
+ if not isinstance(service, dict):
54
+ violations.append(f"{source}: service {name} must be a mapping")
55
+ continue
56
+ if service.get("privileged") is True:
57
+ violations.append(f"{source}: {name} must not be privileged")
58
+ if service.get("pid") == "host":
59
+ violations.append(f"{source}: {name} must not use the host PID namespace")
60
+ if not service.get("mem_limit"):
61
+ violations.append(f"{source}: {name} has no memory limit")
62
+ for port in service.get("ports") or []:
63
+ if invalid_published_port(port):
64
+ violations.append(f"{source}: {name} has non-loopback port {port}")
65
+ volumes = service.get("volumes") or []
66
+ for volume in volumes:
67
+ text = str(volume)
68
+ if "/var/run/docker.sock" in text or "/run/docker.sock" in text:
69
+ violations.append(f"{source}: {name} must not mount the Docker socket")
70
+
71
+
72
+ def validate_lab(root: Path) -> list[str]:
73
+ violations: list[str] = []
74
+ compose_path = root / "compose.yml"
75
+ if not compose_path.is_file():
76
+ violations.append("compose.yml is missing")
77
+ return violations
78
+
79
+ compose = _load_yaml(compose_path, violations)
80
+ services = compose.get("services") or {}
81
+ missing = sorted(REQUIRED_SERVICES - set(services))
82
+ if missing:
83
+ violations.append(f"compose.yml: missing services: {', '.join(missing)}")
84
+ if (compose.get("networks", {}).get("range_net", {}).get("internal") is not True):
85
+ violations.append("compose.yml: range_net must be internal")
86
+ _check_services(compose, "compose.yml", violations)
87
+
88
+ override_path = root / "compose.wazuh.override.yml"
89
+ if override_path.is_file():
90
+ override = _load_yaml(override_path, violations)
91
+ _check_services(override, override_path.name, violations)
92
+ else:
93
+ violations.append("compose.wazuh.override.yml is missing")
94
+
95
+ for relative in REQUIRED_DOCS:
96
+ if not (root / relative).is_file():
97
+ violations.append(f"required documentation is missing: {relative}")
98
+
99
+ for relative in ("lab.py", "validate.py", "soc_copilot/copilot.py"):
100
+ path = root / relative
101
+ if not path.is_file():
102
+ violations.append(f"required Python file is missing: {relative}")
103
+ continue
104
+ try:
105
+ ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
106
+ except (OSError, SyntaxError) as exc:
107
+ violations.append(f"{relative}: invalid Python: {exc}")
108
+ return violations
109
+
110
+
111
+ def main() -> int:
112
+ violations = validate_lab(ROOT)
113
+ if violations:
114
+ for violation in violations:
115
+ print(f"FAIL: {violation}", file=sys.stderr)
116
+ return 1
117
+ print("Static validation passed.")
118
+ print("Runtime deployment is validated separately and requires Docker.")
119
+ return 0
120
+
121
+
122
+ if __name__ == "__main__":
123
+ raise SystemExit(main())