-
Notifications
You must be signed in to change notification settings - Fork 410
Expand file tree
/
Copy pathapp.py
More file actions
1866 lines (1601 loc) · 79.3 KB
/
app.py
File metadata and controls
1866 lines (1601 loc) · 79.3 KB
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Flask API for Attack Range Controller with OpenAPI documentation."""
import os
import sys
import time
import glob
import yaml
import threading
import traceback
import subprocess
import shutil
from datetime import datetime
from typing import Dict, Any, Optional, Tuple, List
from flask import jsonify, request
from attack_range.utils import strip_ansi
from flask_openapi3 import OpenAPI, Info, Tag
from flask_cors import CORS
from pydantic import ValidationError
# Add parent directory to path to import attack_range module
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from attack_range.attack_range_controller import AttackRangeController
from attack_range.utils import prepare_config_from_template, resolve_template_path, load_yaml_file, save_yaml_file
from api.cloud_fields import get_cloud_fields_schema, get_gcp_zones_for_region
from api.models import (
HealthResponse,
BuildRequest,
BuildResponse,
DestroyRequest,
DestroyResponse,
OperationStatusResponse,
TemplateInfo,
ServerInfo,
TemplateListResponse,
TemplateContentResponse,
ConfigInfo,
ConfigListResponse,
ConfigContentResponse,
ErrorResponse,
AttackRangeIdPath,
TemplatePath,
CloudFieldsProviderPath,
ConfigIdPath,
AttackRangeListResponse,
ProviderAvailability,
ProviderCheckResponse,
SimulateRequest,
SimulateResponse,
ShareRequest,
ShareResponse,
UpdateNameRequest,
UpdateNameResponse,
)
# Disable macOS fork safety warning
os.environ["OBJC_DISABLE_INITIALIZE_FORK_SAFETY"] = "YES"
# Initialize Flask-OpenAPI3 app
info = Info(
title="Attack Range API",
version="1.0.0",
description="REST API for building and managing Attack Range infrastructure with automated OpenAPI documentation"
)
app = OpenAPI(__name__, info=info)
# Enable CORS for all routes
# Allow requests from localhost (for direct access) and from app container
CORS(app, resources={
r"/*": {
"origins": ["http://localhost:4321", "http://localhost:3000", "http://127.0.0.1:4321", "http://127.0.0.1:3000", "http://app:4321"],
"methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
"allow_headers": ["Content-Type", "Authorization"],
"supports_credentials": True
}
})
# Define tags for grouping endpoints
health_tag = Tag(name="Health", description="Health check endpoints")
attack_range_tag = Tag(name="Attack Range", description="Attack range build and destroy operations")
template_tag = Tag(name="Templates", description="Template management endpoints")
config_tag = Tag(name="Configs", description="Configuration management endpoints")
provider_tag = Tag(name="Providers", description="Cloud provider CLI availability endpoints")
# Directory paths
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES_DIR = os.path.join(BASE_DIR, "templates")
CONFIG_DIR = os.path.join(BASE_DIR, "config")
WIREGUARD_CONFIG_DIR = os.path.join(BASE_DIR, "wireguard_config")
# Global state for tracking running operations
running_operations: Dict[str, Dict[str, Any]] = {}
operations_lock = threading.Lock()
def check_cli_available(cli_command: str, version_flag: str = "--version") -> Tuple[bool, Optional[str]]:
"""
Check if a CLI command is available.
:param cli_command: CLI command name (e.g., 'aws', 'az', 'gcloud')
:param version_flag: Flag to check version (default: '--version')
:return: Tuple of (is_available, error_message)
"""
try:
# First, try to find the command in PATH
cmd_path = shutil.which(cli_command)
if not cmd_path:
return False, f"CLI command '{cli_command}' not found in PATH"
# Use the full path to the command
result = subprocess.run(
[cmd_path, version_flag],
capture_output=True,
text=True,
timeout=5,
check=False,
env=os.environ.copy()
)
if result.returncode == 0:
return True, None
else:
# Include stderr in error message if available
error_msg = f"Command '{cli_command}' returned non-zero exit code: {result.returncode}"
if result.stderr:
error_msg += f" - {result.stderr.strip()}"
return False, error_msg
except FileNotFoundError:
return False, f"CLI command '{cli_command}' not found in PATH"
except subprocess.TimeoutExpired:
return False, f"CLI command '{cli_command}' timed out"
except Exception as e:
return False, f"Error checking CLI '{cli_command}': {str(e)}"
def check_credentials_available(provider: str) -> Tuple[bool, Optional[str]]:
"""
Check if credentials are available for a cloud provider.
:param provider: Provider name ('aws', 'azure', 'gcp')
:return: Tuple of (has_credentials, error_message)
"""
try:
if provider.lower() == "aws":
# Check for AWS credentials
aws_creds_path = os.path.expanduser("~/.aws/credentials")
aws_config_path = os.path.expanduser("~/.aws/config")
if os.path.exists(aws_creds_path) or os.path.exists(aws_config_path):
# Also check if AWS CLI can authenticate
aws_cmd = shutil.which("aws")
if not aws_cmd:
return False, "AWS CLI not found in PATH"
result = subprocess.run(
[aws_cmd, "sts", "get-caller-identity"],
capture_output=True,
text=True,
timeout=10,
check=False,
env=os.environ.copy()
)
if result.returncode == 0:
return True, None
else:
error_msg = "AWS credentials found but authentication failed"
if result.stderr:
error_msg += f": {result.stderr.strip()}"
return False, error_msg
return False, "AWS credentials not found (~/.aws/credentials or ~/.aws/config)"
elif provider.lower() == "azure":
# Check for Azure credentials
azure_config_path = os.path.expanduser("~/.azure")
if os.path.exists(azure_config_path):
# Check if Azure CLI can authenticate
az_cmd = shutil.which("az")
if not az_cmd:
return False, "Azure CLI not found in PATH"
result = subprocess.run(
[az_cmd, "account", "show"],
capture_output=True,
text=True,
timeout=10,
check=False,
env=os.environ.copy()
)
if result.returncode == 0:
return True, None
else:
error_msg = "Azure credentials found but authentication failed"
if result.stderr:
error_msg += f": {result.stderr.strip()}"
return False, error_msg
return False, "Azure credentials not found (~/.azure)"
elif provider.lower() == "gcp":
# Check for GCP credentials
gcp_config_path = os.path.expanduser("~/.config/gcloud")
if os.path.exists(gcp_config_path):
# Check if gcloud can authenticate
gcloud_cmd = shutil.which("gcloud")
if not gcloud_cmd:
return False, "GCP CLI not found in PATH"
# Check for active accounts (case-insensitive)
result = subprocess.run(
[gcloud_cmd, "auth", "list"],
capture_output=True,
text=True,
timeout=10,
check=False,
env=os.environ.copy()
)
if result.returncode != 0:
error_msg = f"Failed to check GCP authentication: {result.stderr.strip() if result.stderr else 'Unknown error'}"
return False, error_msg
# Check for ACTIVE in output (case-insensitive)
stdout_upper = result.stdout.upper()
if "ACTIVE" in stdout_upper or "*" in result.stdout:
# Verify we can actually use the credentials by checking project
project_result = subprocess.run(
[gcloud_cmd, "config", "get-value", "project"],
capture_output=True,
text=True,
timeout=10,
check=False,
env=os.environ.copy()
)
if project_result.returncode == 0:
return True, None
# If project check fails, still consider it available if auth list shows active
# (project might not be set but auth is valid)
if "ACTIVE" in stdout_upper:
return True, None
# No active authentication found
error_msg = "GCP credentials found but no active authentication"
if result.stdout:
# Include a snippet of the auth list output for debugging
lines = result.stdout.strip().split('\n')
if len(lines) > 0:
error_msg += f" (found {len([l for l in lines if l.strip() and not l.startswith('Credentialed')])} account(s))"
return False, error_msg
return False, "GCP credentials not found (~/.config/gcloud)"
return False, f"Unknown provider: {provider}"
except Exception as e:
return False, f"Error checking credentials for {provider}: {str(e)}"
def get_provider_availability(test_missing: Optional[str] = None) -> list:
"""
Get availability status for all cloud providers.
This implementation no longer checks local CLI installation or credentials;
all providers are treated as available (unless simulated as missing for tests).
:param test_missing: Optional provider name to simulate as missing (for testing)
:return: List of ProviderAvailability objects
"""
providers_config = [
{"provider": "aws", "cli": "aws"},
{"provider": "azure", "cli": "az"},
{"provider": "gcp", "cli": "gcloud"},
]
results = []
for provider_config in providers_config:
provider = provider_config["provider"]
cli_command = provider_config["cli"]
# If testing missing provider, simulate it as unavailable
if test_missing and test_missing.lower() == provider.lower():
results.append(
ProviderAvailability(
provider=provider,
available=False,
cli_command=cli_command,
error_message=f"Simulated missing CLI for testing (test_missing={test_missing})",
)
)
else:
# Treat provider as available without performing any local CLI/credential checks
results.append(
ProviderAvailability(
provider=provider,
available=True,
cli_command=cli_command,
error_message=None,
)
)
return results
def get_templates() -> list:
"""Get list of all available templates."""
templates = []
if not os.path.exists(TEMPLATES_DIR):
return templates
# Scan templates directory
for provider in ["aws", "azure", "gcp"]:
provider_dir = os.path.join(TEMPLATES_DIR, provider)
if os.path.exists(provider_dir):
yml_files = glob.glob(os.path.join(provider_dir, "*.yml"))
for yml_file in yml_files:
# Load template to get description and architecture
description = None
architecture = None
try:
template_content = load_yaml_file(yml_file)
if template_content:
general = template_content.get("general")
if general and isinstance(general, dict):
description = general.get("description")
# Extract architecture information
attack_range = template_content.get("attack_range")
if attack_range and isinstance(attack_range, list):
servers = []
for server in attack_range:
if isinstance(server, dict):
# Determine OS type
os_type = None
if server.get("linux"):
os_type = "linux"
elif server.get("windows"):
os_type = "windows"
# Extract role names
roles = []
server_roles = server.get("roles", [])
if isinstance(server_roles, list):
for role in server_roles:
if isinstance(role, dict):
role_name = role.get("role")
if role_name:
roles.append(role_name)
elif isinstance(role, str):
roles.append(role)
servers.append(ServerInfo(
name=server.get("name", ""),
instance_type=server.get("instance_type"),
ip_last_octet=server.get("ip_last_octet"),
os_type=os_type,
roles=roles if roles else None,
zeek=server.get("zeek"),
zeek_monitor=server.get("zeek_monitor")
))
architecture = servers if servers else None
except Exception as e:
# If loading fails, continue without description/architecture
# Log error for debugging
import sys
print(f"Warning: Failed to load template from {yml_file}: {e}", file=sys.stderr)
import traceback
traceback.print_exc()
templates.append(TemplateInfo(
name=os.path.basename(yml_file),
provider=provider,
path=yml_file,
description=description,
architecture=architecture
))
return templates
# Note: load_yaml_file, save_yaml_file, and resolve_template_path are now imported from attack_range.utils
# Note: get_wireguard_config and update_config_status are now handled by the controller
def get_config_path_from_attack_range_id(attack_range_id: str) -> Optional[str]:
"""Get config file path from attack_range_id."""
config_filename = f"{attack_range_id}.yml"
config_path = os.path.join(CONFIG_DIR, config_filename)
if os.path.exists(config_path):
return config_path
return None
def _write_config_error_status(config_path: str, error: str, error_phase: str) -> None:
"""Write error status into the config file without using the controller (e.g. when controller init fails)."""
try:
if not config_path or not os.path.exists(config_path):
return
config = load_yaml_file(config_path)
if "general" not in config:
config["general"] = {}
config["general"]["status"] = "error"
config["general"]["error"] = error
config["general"]["error_phase"] = error_phase
config["general"]["end_time"] = datetime.now().isoformat()
save_yaml_file(config_path, config)
except Exception:
pass
def _wait_abort_then_destroy(attack_range_id: str, config_path: str) -> None:
"""Wait for build to stop (abort or error), then run destroy. Used when user clicks Destroy during build."""
build_statuses = ("queued", "build_vpn", "build_lab")
for _ in range(45):
time.sleep(2)
with operations_lock:
cur = running_operations.get(attack_range_id)
s = (cur.get("status") if cur else None) or ""
if not s and config_path and os.path.exists(config_path):
try:
cfg = load_yaml_file(config_path)
s = cfg.get("general", {}).get("status") or ""
except Exception:
s = ""
if s not in build_statuses:
break
if not os.path.exists(config_path):
return
try:
config = load_yaml_file(config_path)
with operations_lock:
running_operations[attack_range_id] = {
"type": "destroy",
"status": "queued",
"created_time": datetime.now().isoformat(),
"attack_range_id": attack_range_id
}
# Pass current status (e.g. aborted/error) so we clear the range on destroy failure
run_destroy_operation(config, config_path, attack_range_id, previous_status=s or "")
except Exception:
pass
def _check_abort_and_set_aborted(attack_range_id: str, config_path: Optional[str] = None) -> bool:
"""If abort_requested is set for this attack_range_id, set status to aborted and return True. Else return False."""
with operations_lock:
op = running_operations.get(attack_range_id)
if not op or not op.get("abort_requested"):
return False
running_operations[attack_range_id]["status"] = "aborted"
running_operations[attack_range_id]["end_time"] = datetime.now().isoformat()
path = config_path or op.get("config_path") or get_config_path_from_attack_range_id(attack_range_id)
if path and os.path.exists(path):
try:
config = load_yaml_file(path)
if "general" not in config:
config["general"] = {}
config["general"]["status"] = "aborted"
config["general"]["end_time"] = datetime.now().isoformat()
save_yaml_file(path, config)
except Exception:
pass
return True
def run_build_vpn_phase(config: Dict[str, Any], config_path: str, attack_range_id: str):
"""Run phase 1: Build VPN infrastructure (up to VPN config generation)."""
try:
if _check_abort_and_set_aborted(attack_range_id, config_path):
return
with operations_lock:
running_operations[attack_range_id]["status"] = "build_vpn"
running_operations[attack_range_id]["start_time"] = datetime.now().isoformat()
# Create controller with config
controller = AttackRangeController(config, config_path=config_path)
# Build VPN phase (handles all steps including status updates; checks abort between steps)
router_public_ip, wireguard_config = controller.build_vpn_phase(attack_range_id, abort_check=lambda: _check_abort_and_set_aborted(attack_range_id, config_path))
wireguard_config_path = os.path.join(WIREGUARD_CONFIG_DIR, f"{attack_range_id}.conf")
# Update operation status
with operations_lock:
running_operations[attack_range_id]["status"] = "wait_for_vpn"
running_operations[attack_range_id]["attack_range_id"] = attack_range_id
running_operations[attack_range_id]["router_public_ip"] = router_public_ip
running_operations[attack_range_id]["wireguard_config"] = wireguard_config
running_operations[attack_range_id]["wireguard_config_path"] = wireguard_config_path
running_operations[attack_range_id]["config_path"] = config_path
except Exception as e:
is_aborted = "Build aborted" in str(e)
if not is_aborted:
with operations_lock:
running_operations[attack_range_id]["status"] = "error"
running_operations[attack_range_id]["end_time"] = datetime.now().isoformat()
running_operations[attack_range_id]["error"] = strip_ansi(str(e))
running_operations[attack_range_id]["error_phase"] = "build_vpn"
running_operations[attack_range_id]["traceback"] = strip_ansi(traceback.format_exc())
# Update error status in config file (via controller if available, else direct write)
try:
controller = AttackRangeController(config, config_path=config_path)
controller.config_manager.update_status("error", error=strip_ansi(str(e)), error_phase="build_vpn")
except Exception:
_write_config_error_status(config_path, strip_ansi(str(e)), "build_vpn")
def run_build_lab_phase(attack_range_id: str):
"""Run phase 2: Build lab infrastructure (after VPN connection)."""
try:
# Get config path from running_operations or from config file
with operations_lock:
config_path = running_operations[attack_range_id].get("config_path")
if not config_path:
config_path = get_config_path_from_attack_range_id(attack_range_id)
running_operations[attack_range_id]["status"] = "build_lab"
if config_path:
running_operations[attack_range_id]["config_path"] = config_path
if not config_path or not os.path.exists(config_path):
raise Exception("Config file not found for attack range")
# Load config
config = load_yaml_file(config_path)
controller = AttackRangeController(config, config_path=config_path)
abort_check = lambda: _check_abort_and_set_aborted(attack_range_id, config_path)
# Build lab phase (handles all steps including status updates)
controller.build_lab_phase(attack_range_id, abort_check=abort_check)
# Get router public IP
router_public_ip = controller.terraform_manager.get_output("router_public_ip")
# Update operation status
with operations_lock:
running_operations[attack_range_id]["status"] = "running"
running_operations[attack_range_id]["end_time"] = datetime.now().isoformat()
running_operations[attack_range_id]["result"] = {
"attack_range_id": attack_range_id,
"router_public_ip": router_public_ip,
"config_file": config_path
}
except Exception as e:
is_aborted = "Build aborted" in str(e)
config_path = None
if not is_aborted:
with operations_lock:
config_path = running_operations[attack_range_id].get("config_path")
if not config_path:
config_path = get_config_path_from_attack_range_id(attack_range_id)
running_operations[attack_range_id]["status"] = "error"
running_operations[attack_range_id]["end_time"] = datetime.now().isoformat()
running_operations[attack_range_id]["error"] = strip_ansi(str(e))
running_operations[attack_range_id]["error_phase"] = "build_lab"
running_operations[attack_range_id]["traceback"] = strip_ansi(traceback.format_exc())
# Update error status in config file (via controller if available, else direct write)
if config_path:
try:
config = load_yaml_file(config_path)
controller = AttackRangeController(config, config_path=config_path)
controller.config_manager.update_status("error", error=strip_ansi(str(e)), error_phase="build_lab")
except Exception:
_write_config_error_status(config_path, strip_ansi(str(e)), "build_lab")
def run_destroy_operation(
config: Dict[str, Any],
config_path: Optional[str],
attack_range_id: str,
previous_status: str = "",
):
"""Run destroy operation in a separate thread. When previous_status is 'error' or 'failed', we still remove the config on destroy failure so the range is cleared."""
controller = None
try:
with operations_lock:
running_operations[attack_range_id]["status"] = "destroying"
running_operations[attack_range_id]["start_time"] = datetime.now().isoformat()
if config_path:
try:
controller = AttackRangeController(config, config_path=config_path)
controller.config_manager.update_status("destroying")
except Exception:
pass
if not controller:
controller = AttackRangeController(config, config_path=config_path)
controller.destroy()
if config_path and os.path.exists(config_path):
try:
os.remove(config_path)
except Exception as e:
controller.logger.warning(f"Failed to delete config file: {e}")
with operations_lock:
if attack_range_id in running_operations:
del running_operations[attack_range_id]
except Exception as e:
with operations_lock:
running_operations[attack_range_id]["status"] = "failed"
running_operations[attack_range_id]["end_time"] = datetime.now().isoformat()
running_operations[attack_range_id]["error"] = strip_ansi(str(e))
running_operations[attack_range_id]["traceback"] = strip_ansi(traceback.format_exc())
if config_path:
try:
c = AttackRangeController(config, config_path=config_path)
c.config_manager.update_status("failed", error=strip_ansi(str(e)))
except Exception:
pass
# If this was already a failed/errored/aborted range (e.g. build_vpn error), clear it so user can start fresh
if previous_status in ("error", "failed", "aborted") and config_path and os.path.exists(config_path):
try:
os.remove(config_path)
with operations_lock:
if attack_range_id in running_operations:
del running_operations[attack_range_id]
except Exception:
pass
# ============================================================================
# HEALTH ENDPOINTS
# ============================================================================
@app.get(
"/health",
tags=[health_tag],
responses={200: HealthResponse},
summary="Health check",
description="Check if the API is running and healthy"
)
def health():
"""Health check endpoint."""
return jsonify(HealthResponse(status="healthy", version="1.0.0").model_dump())
# ============================================================================
# ATTACK RANGE ENDPOINTS
# ============================================================================
@app.post(
"/attack-range/build",
tags=[attack_range_tag],
responses={202: BuildResponse, 400: ErrorResponse, 404: ErrorResponse, 500: ErrorResponse},
summary="Build attack range",
description="Build a new attack range (provide 'template') OR continue existing build after VPN connection (provide 'attack_range_id'). This is an asynchronous operation."
)
def build_attack_range(body: BuildRequest):
"""Build a new attack range or continue existing build."""
try:
import uuid
# Determine if this is a new build or continuation
is_continuation = body.attack_range_id is not None
is_new_build = body.template is not None
# Validate input: must provide either template (new build) or attack_range_id (continuation)
if not is_new_build and not is_continuation:
return jsonify(ErrorResponse(
message="Either 'template' (for new build) or 'attack_range_id' (to continue after VPN) must be provided"
).model_dump()), 400
if is_new_build and is_continuation:
return jsonify(ErrorResponse(
message="Cannot provide both 'template' and 'attack_range_id'. Use 'template' for new builds or 'attack_range_id' to continue."
).model_dump()), 400
# Handle continuation (Phase 2: Lab build after VPN connection)
if is_continuation:
attack_range_id = body.attack_range_id
# Check status from running_operations or config file
status = None
config_path = None
with operations_lock:
if attack_range_id in running_operations:
status = running_operations[attack_range_id].get("status")
config_path = running_operations[attack_range_id].get("config_path")
# If not in running_operations, check config file
if not status:
config_path = get_config_path_from_attack_range_id(attack_range_id)
if config_path:
operation = load_operation_from_config(config_path)
if operation:
status = operation.get("status")
# Update running_operations with info from config
with operations_lock:
if attack_range_id not in running_operations:
running_operations[attack_range_id] = operation
running_operations[attack_range_id]["config_path"] = config_path
if not status:
return jsonify(ErrorResponse(
message=f"No build found for attack_range_id: {attack_range_id}",
details="Make sure you started a build first"
).model_dump()), 404
if status != "wait_for_vpn":
return jsonify(ErrorResponse(
message=f"Build is not waiting for VPN connection. Current status: {status}",
details="The attack range must be in 'wait_for_vpn' status to continue"
).model_dump()), 400
# Ensure config_path is set in running_operations
if config_path:
with operations_lock:
if attack_range_id in running_operations:
running_operations[attack_range_id]["config_path"] = config_path
# Start phase 2 in a separate thread
thread = threading.Thread(
target=run_build_lab_phase,
args=(attack_range_id,)
)
thread.daemon = True
thread.start()
return jsonify(BuildResponse(
status="accepted",
message=f"Continuing build (lab phase) for attack range: {attack_range_id}",
attack_range_id=attack_range_id,
phase="lab"
).model_dump()), 202
# Handle new build (Phase 1: VPN setup)
else:
# Prepare config from template using shared utility
try:
config, config_path, attack_range_id = prepare_config_from_template(
body.template,
TEMPLATES_DIR,
CONFIG_DIR,
generate_id=True,
cloud_overrides=body.cloud_overrides,
general_overrides=body.general_overrides
)
# Extract template name from config (already set by prepare_config_from_template)
template_name = config.get("general", {}).get("name")
except FileNotFoundError as e:
return jsonify(ErrorResponse(
message="Template not found",
details=str(e)
).model_dump()), 404
except Exception as e:
return jsonify(ErrorResponse(
message="Failed to prepare config from template",
details=str(e)
).model_dump()), 500
# Initialize operation state (keyed by attack_range_id)
with operations_lock:
running_operations[attack_range_id] = {
"type": "build",
"status": "queued",
"created_time": datetime.now().isoformat(),
"attack_range_id": attack_range_id,
"template_name": template_name
}
# Status is already set to "queued" by prepare_config_from_template
# Start phase 1 in a separate thread
thread = threading.Thread(
target=run_build_vpn_phase,
args=(config, config_path, attack_range_id)
)
thread.daemon = True
thread.start()
return jsonify(BuildResponse(
status="accepted",
message=f"Build operation started (VPN phase). Attack Range ID: {attack_range_id}",
attack_range_id=attack_range_id,
phase="vpn"
).model_dump()), 202
except Exception as e:
return jsonify(ErrorResponse(
message="Failed to start build operation",
details=str(e)
).model_dump()), 500
@app.post(
"/attack-range/destroy",
tags=[attack_range_tag],
responses={202: DestroyResponse, 400: ErrorResponse, 404: ErrorResponse, 500: ErrorResponse},
summary="Destroy attack range",
description="Destroy an existing attack range infrastructure by attack_range_id."
)
def destroy_attack_range(body: DestroyRequest):
"""Destroy an attack range. If a build is in progress, requests abort and waits for it to stop, then runs destroy."""
try:
attack_range_id = body.attack_range_id
config_filename = f"{attack_range_id}.yml" if not attack_range_id.endswith('.yml') else attack_range_id
config_path = os.path.join(CONFIG_DIR, config_filename)
if not os.path.exists(config_path):
return jsonify(ErrorResponse(
message=f"Config file not found for attack_range_id: {attack_range_id}",
details="Make sure the attack range exists"
).model_dump()), 404
# If a build is in progress, request abort and run "wait for abort then destroy" in a thread
build_statuses = ("queued", "build_vpn", "build_lab")
with operations_lock:
current = running_operations.get(attack_range_id)
status = (current.get("status") if current else None) or ""
if not status and os.path.exists(config_path):
config_for_status = load_yaml_file(config_path)
status = config_for_status.get("general", {}).get("status") or ""
if status in build_statuses:
with operations_lock:
op = running_operations.get(attack_range_id)
if op:
op["abort_requested"] = True
# Run wait-for-abort-then-destroy in background; return 202 immediately
thread = threading.Thread(
target=_wait_abort_then_destroy,
args=(attack_range_id, config_path)
)
thread.daemon = True
thread.start()
return jsonify(DestroyResponse(
status="accepted",
message=f"Build abort requested; destroy will run when build stops. Attack Range ID: {attack_range_id}"
).model_dump()), 202
# Remember if we're cleaning up an already-failed/errored range (so we can clear it even when destroy fails)
previous_status = status.strip().lower() if status else ""
config = load_yaml_file(config_path)
config_attack_range_id = config.get("general", {}).get("attack_range_id")
if config_attack_range_id and config_attack_range_id != attack_range_id:
return jsonify(ErrorResponse(
message=f"attack_range_id mismatch. Expected: {attack_range_id}, Found in config: {config_attack_range_id}"
).model_dump()), 400
with operations_lock:
running_operations[attack_range_id] = {
"type": "destroy",
"status": "queued",
"created_time": datetime.now().isoformat(),
"attack_range_id": attack_range_id
}
try:
controller = AttackRangeController(config, config_path=config_path)
controller.config_manager.update_status("destroying")
except Exception:
pass
thread = threading.Thread(
target=run_destroy_operation,
args=(config, config_path, attack_range_id, previous_status)
)
thread.daemon = True
thread.start()
return jsonify(DestroyResponse(
status="accepted",
message=f"Destroy operation started. Attack Range ID: {attack_range_id}"
).model_dump()), 202
except Exception as e:
return jsonify(ErrorResponse(
message="Failed to start destroy operation",
details=str(e)
).model_dump()), 500
@app.post(
"/attack-range/abort",
tags=[attack_range_tag],
responses={200: DestroyResponse, 400: ErrorResponse, 404: ErrorResponse, 500: ErrorResponse},
summary="Abort attack range build",
description="Abort a build operation in progress. Sets status to 'aborted'."
)
def abort_attack_range(body: DestroyRequest):
"""Abort a build operation by setting abort_requested flag and status to aborted."""
try:
attack_range_id = body.attack_range_id
config_filename = f"{attack_range_id}.yml" if not attack_range_id.endswith('.yml') else attack_range_id
config_path = os.path.join(CONFIG_DIR, config_filename)
if not os.path.exists(config_path):
return jsonify(ErrorResponse(
message=f"Config file not found for attack_range_id: {attack_range_id}",
details="Make sure the attack range exists"
).model_dump()), 404
# Check if build is in progress
build_statuses = ("queued", "build_vpn", "build_lab")
with operations_lock:
current = running_operations.get(attack_range_id)
status = (current.get("status") if current else None) or ""
if not status and os.path.exists(config_path):
try:
config_for_status = load_yaml_file(config_path)
status = config_for_status.get("general", {}).get("status") or ""
except Exception:
status = ""
if status not in build_statuses:
return jsonify(ErrorResponse(
message=f"Cannot abort: attack range is not in a build state. Current status: {status}",
details="Abort can only be called during build (queued, build_vpn, build_lab)"
).model_dump()), 400
# Set abort_requested flag
with operations_lock:
op = running_operations.get(attack_range_id)
if op:
op["abort_requested"] = True
else:
# If not in running_operations, create entry
running_operations[attack_range_id] = {
"type": "build",
"status": status,
"abort_requested": True,
"attack_range_id": attack_range_id
}
# Immediately set status to aborted
_check_abort_and_set_aborted(attack_range_id, config_path)
return jsonify(DestroyResponse(
status="accepted",
message=f"Build abort requested. Attack Range ID: {attack_range_id}"
).model_dump()), 200
except Exception as e:
return jsonify(ErrorResponse(
message="Failed to abort build operation",
details=str(e)
).model_dump()), 500
@app.get(
"/attack-range/status/<attack_range_id>",
tags=[attack_range_tag],
responses={200: OperationStatusResponse, 404: ErrorResponse},
summary="Get attack range status",
description="Get the status of a build or destroy operation by attack_range_id"
)
def get_attack_range_status(path: AttackRangeIdPath):
"""Get status of an attack range operation."""
attack_range_id = path.attack_range_id
operation = None
config_path = get_config_path_from_attack_range_id(attack_range_id)
# First check running_operations
with operations_lock:
if attack_range_id in running_operations:
operation = running_operations[attack_range_id].copy()
operation["attack_range_id"] = attack_range_id
# If config file exists, prioritize status from config file over running_operations
if config_path and os.path.exists(config_path):
config_content = load_yaml_file(config_path)
if config_content:
general = config_content.get("general", {})
config_status = general.get("status")
if config_status and operation:
# Config file is source of truth for status
operation["status"] = config_status
# Merge sharing from config (e.g. after a share) when available
if operation and general.get("sharing") and isinstance(general.get("sharing"), dict):
operation["sharing"] = general["sharing"]
# Load attack_range_name from config
if operation:
attack_range_name = general.get("attack_range_name")
if attack_range_name:
operation["attack_range_name"] = attack_range_name
# If not in running_operations, try to load from config file
if not operation:
if config_path:
operation = load_operation_from_config(config_path)
if not operation:
return jsonify(ErrorResponse(
message=f"Attack range not found: {attack_range_id}"
).model_dump()), 404
# If running and has config_file, load architecture and Guacamole info
# This ensures architecture and guacamole_info are loaded even when operation is in running_operations