Repository navigation
Expand file tree
/
Copy pathchallenge_generator.py
More file actions
3118 lines (2874 loc) · 142 KB
/
Copy pathchallenge_generator.py
File metadata and controls
3118 lines (2874 loc) · 142 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
# Copyright (c) 2017-2026 Joel Panther
# Licensed under the MIT License. See LICENSE file in the project root.
from datetime import datetime
import json
import shutil
import subprocess
import random
import os
import docker
from docker.errors import APIError, NotFound, DockerException
import secrets
from string import Template
from pathlib import Path
import string
import traceback
import re
from typing import List, Dict, Set, Optional
from puppet_manager import create_puppet
from db_connect import *
# TODO:
# - Add flag to 'api' module.
# - Modify 'api' module to add it to first keys.
# - Create 'blogs' module for public release.
# =============================
# Domain & constraint settings
# =============================
ENTRY_POINTS: List[str] = ['work.php', 'research.php', 'hub.php'] # Each unique entry point.
# GATE_TYPES: List[str] = ['blogs', 'api', 'products', 'submission', 'search', 'employees', 'cookie'] # Each unique gate type.
GATE_TYPES: List[str] = ['products', 'submission', 'search', 'employees', 'cookie'] # Removing API + blogs until modules updated.
KEYS: List[str] = [
'git', 'config.old', 'users.json', 'upload', 'session_token', 'env', 'log', 'creds', 'none', 'sqli', 'robots'
] # Each unique key.
# Which keys can unlock which gate types (hard constraints) - GATE:{KEYS}
ALLOWED: Dict[str, Set[str]] = {
#'auth': {'creds'}, # a version of 'auth' is applied when not 'none'
# 'api': {'none', 'creds', 'session_token', 'config.old', 'users.json', 'env', 'log', 'git', 'sqli', 'robots'},
'products': {'none', 'creds', 'session_token', 'config.old', 'users.json', 'env', 'log', 'git', 'sqli', 'robots'},
'cookie': {'none', 'creds', 'session_token', 'config.old', 'users.json', 'env', 'log', 'git', 'sqli', 'robots'},
'submission':{'none', 'creds', 'session_token', 'config.old', 'users.json', 'env', 'log', 'git', 'sqli', 'robots'},
'search': {'none', 'creds', 'session_token', 'config.old', 'users.json', 'env', 'log', 'git', 'sqli', 'robots'},
'employees': {'none', 'creds', 'session_token', 'config.old', 'users.json', 'env', 'log', 'git', 'sqli', 'robots'},
# 'blogs': {'none', 'creds', 'session_token', 'config.old', 'users.json', 'env', 'log', 'git', 'sqli', 'robots'},
}
# Note: Each module that queries the database has its own user, with restricted permissions for its applicable tables.
# Keys that may be used specifically to unlock the FIRST gate
FIRST_GATE_KEYS: Set[str] = {'config.old', 'users.json', 'env', 'log', 'sqli', 'robots'} # Add 'git' to this list, if you unzip the git.zip in the 'key' folder.
NON_FIRST_KEYS: Set[str] = set(KEYS) - FIRST_GATE_KEYS
# =============================
# Successor constraints (by gate_type)
# For a given current gate_type, which next gate_types may follow?
# By default, every type may be followed by any type.
# Modify ALLOWED_SUCCESSORS as needed to restrict adjacencies.
# =============================
DEFAULT_SUCCESSORS: Dict[str, Set[str]] = {t: set(GATE_TYPES) for t in GATE_TYPES}
ALLOWED_SUCCESSORS: Dict[str, Set[str]] = dict(DEFAULT_SUCCESSORS)
ALLOWED_SUCCESSORS['submission'] = set() # Introduces 'upload', which is only suited to be for flag.
# =============================
# Target-key constraints (by gate_type)
# If a gate has type T at position i, then the next gate's key (keys[i+1]) must be in TARGET_KEY_CONSTRAINTS[T].
# =============================
TARGET_KEY_CONSTRAINTS: Dict[str, Set[str]] = {t: set(KEYS) for t in GATE_TYPES}
# Example: products may only reveal 'sqli' as the next key (requires 'sqli' in KEYS and ALLOWED[next_type]).
TARGET_KEY_CONSTRAINTS['products'] = {'creds', 'session_token'}
TARGET_KEY_CONSTRAINTS['search'] = {'creds', 'session_token'}
TARGET_KEY_CONSTRAINTS['employees'] = {'creds', 'session_token'}
TARGET_KEY_CONSTRAINTS['cookie'] = {'creds', 'session_token'}
# TARGET_KEY_CONSTRAINTS['blogs'] = {'session_token'}
# =============================
# Variables for generation platform
# =============================
flavour_JSON = "fCKcXn37KpDEit4PfRxf9r5DyLb68t.json" # Hard coding flavour JSON filename. No secrets stored here.
flavour_JSON_data = []
exec_details = [] # Flavour text for executives.
picked_usernames = []
picked_passwords = []
corp_name = ""
employee_table_exists = False # Switch to see if "employee" table has been created in the challenge database.
# If there are not enough images in the repo for a specific system type, it might crash.
# Should probably look into that one day.
FLAVOUR_IMAGE_COUNT = 8 # Int. How many system flavour images to pull from image repository.
FIRST_PORT_NUMBER = "8" # String. Added to the front of the challenge ID to give a unique port number per challenge.
# =============================
# Pre-generated lists
# =============================
FLAG_TABLE_NAMES = [
"compliance_tokens", "continuity_keys", "safety_protocol", "termination_key",
"failsafe_registry", "override_token", "system_interrupt_code", "emergency", "final_authority",
"nullkeys", "silence_sequence_key", "end_of_life_key", "containment_switch", "legacy_key_table",
"system_misc_data", "archival_refs", "operational_metadata", "backup_key", "recovery_key"
]
usernames = [
"AstroVoyager", "QuantumPilot", "NebulaSeeker", "StellarRanger", "LunarNomad",
"WarpRider", "PhotonRunner", "CosmoGuardian", "NovaScout", "GalaxyRover",
"HyperDriveHero", "PlasmaHunter", "CelestialNomad", "AsteroidStriker", "CometChaser",
"StarForge", "SingularitySurfer", "VoidNavigator", "CryoDrifter", "MeteorSentinel",
"ChronoTraveler", "ExoCommander", "SolarWarden", "EclipseShadow", "PlanetBreaker",
"ZeroPointPilot", "DarkMatterDiver", "GravShipCaptain", "LightyearLancer", "QuantumNomad",
"AstroSentinel", "NovaNomad", "WormholeWalker", "PulsarProtector", "NeutrinoKnight",
"IonStormer", "OmegaOutrider", "StarlightStrider", "BlackHoleRogue", "EventHorizonRider",
"CryoRanger", "NebulaRanger", "AstroCorsair", "StellarWarden", "SolarCorsair",
"PhotonPhantom", "WarpGuardian", "LunarSentinel", "NovaWarden", "StarborneRider",
"AstroLancer", "GalaxyCorsair", "NebulaPhantom", "VoidCorsair", "LightwaveRider",
"PlasmaCorsair", "DarkNebulaNomad", "AstroHunter", "ZeroGNomad", "ChronoSentinel",
"HyperNovaPilot", "LunarCorsair", "CosmicWarden", "EclipseCorsair", "QuantumCorsair",
"NebulaGuardian", "PhotonCorsair", "NovaGuardian", "AstroCorsairX", "SolarSentinel",
"CryoCorsair", "IonNomad", "PlasmaNomad", "WormholeCorsair", "VoidSentinel",
"MeteorNomad", "CometCorsair", "StellarCorsair", "WarpNomad", "DarkMatterNomad",
"StarDrifter", "AstroVoyagerX", "QuantumVoyager", "NebulaDrifter", "LunarWarden",
"HyperSpaceNomad", "PhotonVoyager", "CosmoDrifter", "NovaLancer", "GalaxyWarden",
"LightyearCorsair", "CryoNomad", "AstroProtector", "StellarVoyager", "SolarDrifter",
"WarpLancer", "VoidLancer", "PlasmaDrifter", "NebulaLancer", "QuantumLancer"
]
passwords = [
'N3ur4lN3742', '4s7r0By7377', 'Qu4n7umK3y99', 'V01d4cc35512', 'Cy83rN0v484',
'M3ch4C0d356', 'Ph070nP45534', '573114r4I21', 'Lun4rH45h90', 'W4rpC0r366',
'Cry0C1ph3r18', 'N3u7r1n0L0ck53', 'C05m0R00781', 'Hyp3rB0772', '10n5h13ld44',
'P145m4N0d328', 'Pu15ar3n7ry63', 'D4rkM4773r07', 'L1gh7y34r64', 'N4n0M1nd55',
'4s7r0L0g1c31', '3x0Br41n92', 'Z3r0P01n783', 'C0m37D47414', 'Gr4v4I70',
'50l4rB1729', '0m3g4L0g1n38', '3v3n7H0r1z0n40', '574rl1gh767', 'B14ckH01359',
'G414c7ic74', 'Cy83r53n71n3187', 'N0v44u7h20', 'V01dC1ph3r91', '41C1u573r16',
'N3ur4l70k3n35', 'W0rmh01373', '574rl1nk39', 'Cry0L0g1n11', 'Ph070nK3y45',
'4s7r0B0722', 'Qu4n7umR00725', 'Hyp3r4cc35517', 'N3u7r1n0N3715', 'Lun4rG47327',
'N4n0K3y98', 'W4rp4cc35513', 'Cy83rC0r365', 'P145m44u7h48', '0m3g4N0d357',
'41C0n7r0184', '574r4I79', '50l4rK3y41', 'V01dR00733', 'Cry0P45509',
'Ph070nL0ck95', 'Qu4n7um4I76', 'N3ur4lP0r74l26', 'D4rkC1ph3r80', '4s7r0G47323',
'Z3r0By735', 'M3ch44I85', 'W0rmh013K3y54', '573114rC0d349', 'N4n0C1ph3r46',
'P145m4P45597', 'Lun4r4I82', '4s7r0L0g1n10', 'Qu4n7um5h13ld36', 'N0v4C1ph3r68',
'Cry04I43', 'Ph070n4u7h32', 'Hyp3rC0r361', 'N3u7r1n05h13ld24', '4IK3y19',
'W4rpC0d350', 'Cy83r4I89', '3v3n7K3y42', '50l4rP45596', 'N4n0N0d378',
'0m3g44I30', 'V01dP45508', 'B14ck4I75', '4s7r0C1ph3r71', 'Qu4n7umP45593',
'N3ur4l4cc35547', 'Ph070nP0r74l60', 'Cry0N0d362', 'Hyp3r70k3n58', 'Cy83rC0d386',
'4I4u7h52', '573114rL0ck51', 'Lun4rC0d394', 'W4rpG47369', 'D4rk4I68',
'Gr4vC0r399', '50l4r4u7h01', 'N4n0L0ck02', '4s7r0K3y03', 'Qu4n7umG47304'
]
security_questions = [
'Which fear response did the system classify as your primary motivator during onboarding?',
'What stimulus was identified as most effective in correcting your hesitation behaviour?',
'What emotional state was logged immediately before your first successful compliance confirmation?',
'What aspect of your identity was deprioritised first during behavioural normalisation?',
'Which outcome did the system determine you would sacrifice least to maintain access?',
'Which memory was flagged as most susceptible to reframing during alignment training?',
'What personal loss threshold was determined to be unacceptable to you?',
'Which scenario was used to measure your tolerance for irreversible outcomes?'
]
# =============================
# Directory paths
# =============================
FACTORY_FLOOR = Path("factory_floor") # Container deployment/build directory. Essentially, where all the pieces go for the container build.
DOCKERFILE_FOLDER = Path("dockerfiles") # Where the dockerfiles are stored.
MODULE_TEMPLATES = Path("module_templates") # Where the module templates are stored for web apps.
FLAVOUR_FOLDER = Path("flavour") # Repositories of flavour content for modules.
HEADSHOTS_FOLDER = Path("flavour/headshots") # Repository for headshots specifically.
# =============================
# SQL Server
# =============================
# Containers need to be able to access SQL server.
DATABASE_HOST_IP = "172.17.0.1" # Location of the SQL server. Currently configued as the Docker host.
WEB_HOST_IP = "127.0.0.1" # Web host IP for containers. Used for pointing the puppets.
# =============================
# Helper functions
# =============================
# Returns the current time.
def now():
# return datetime.now().strftime('%Y-%m-%d %H:%M:%S')
return datetime.now().strftime('%H:%M:%S')
# Returns a random subfolder name (takes relative dir) from inside the given parent directory.
def pick_random_folder(parent_directory):
subfolders = [
name
for name in os.listdir(parent_directory)
if os.path.isdir(os.path.join(parent_directory, name))
]
if not subfolders:
return None
return random.choice(subfolders)
# =============================
# Web app challenge functions
# =============================
# Builds pathway to flag.
def generate_chain(seed: Optional[int] = None, max_retries: int = 64) -> List[dict]:
"""
Builds a list of 1..3 chained gates (ending in 'flag'), then appends placeholder
gates for any unused entry_points with gate_type assigned, but key/target='none'.
Constraints for chained gates:
- entry_point: unique per gate (chosen from ENTRY_POINTS).
- gate_type: unique per gate (chosen from GATE_TYPES), and successive types must respect ALLOWED_SUCCESSORS.
- key: unique overall; must be allowed for its gate_type via ALLOWED.
- FIRST_GATE_KEYS may be used ONLY on the first gate; later gates use NON_FIRST_KEYS.
- target: next gate's key; last gate's target is 'flag'.
- If gate_type[i-1] has a TARGET_KEY_CONSTRAINTS entry, then keys[i] must be in it.
Placeholder gates (after reaching 'flag'):
- Assigned a unique gate_type (not used by the chain or other placeholders),
preferably from types compatible with NON_FIRST_KEYS.
Returns JSON with the following for each gate:
- index: 1, 2, or 3.
- entry_point: Selected from ENTRY_POINTS list.
- gate_type: Selected from GATE_TYPES list.
- current_gate_key: For first gate, selected from FIRST_GATE_KEYS list, NON_FIRST_KEYS for all other gates.
- target_gate_key: The key for the next gate, if applicable.
- target_gate_type: The next type of gate in the sequence, if applicable.
"""
rnd = random.Random(seed)
# Pools for positional gate_type feasibility.
first_type_pool = [t for t in GATE_TYPES if ALLOWED[t] & FIRST_GATE_KEYS]
non_first_type_pool = [t for t in GATE_TYPES if ALLOWED[t] & NON_FIRST_KEYS]
if not first_type_pool:
raise print(f"[{now()}][*] No gate types can be unlocked by FIRST_GATE_KEYS.")
for _ in range(max_retries):
n = rnd.randint(1, 3)
# Randomise ALL entry points up front (3).
all_entries = rnd.sample(ENTRY_POINTS, len(ENTRY_POINTS))
chain_entries = all_entries[:n]
extra_entries = all_entries[n:] # 0..2 leftovers
# Choose gate_types sequence with backtracking to satisfy successors + uniqueness.
types: List[Optional[str]] = [None] * n
used_types: Set[str] = set()
def assign_types(i: int) -> bool:
if i == n:
return True
if i == 0:
candidates = list(first_type_pool)
else:
prev = types[i - 1]
allowed_next = ALLOWED_SUCCESSORS.get(prev, set(GATE_TYPES))
candidates = [t for t in non_first_type_pool if t in allowed_next]
# Enforce uniqueness of gate_types within the chain.
candidates = [t for t in candidates if t not in used_types]
rnd.shuffle(candidates)
for t in candidates:
types[i] = t
used_types.add(t)
if assign_types(i + 1):
return True
used_types.remove(t)
types[i] = None
return False
if not assign_types(0):
# Try another sampling (different n / entries / RNG path).
continue
# Assign keys for the chain (unique, allowed per type, positional key pools),
# and enforce TARGET_KEY_CONSTRAINTS from the *previous* gate_type.
used_keys: Set[str] = set()
keys: List[Optional[str]] = [None] * n
def assign_keys(i: int) -> bool:
if i == n:
return True
gate_type = types[i]
if i == 0:
base_allowed = (ALLOWED[gate_type] & FIRST_GATE_KEYS) - used_keys
else:
base_allowed = (ALLOWED[gate_type] & NON_FIRST_KEYS) - used_keys
candidates = list(base_allowed)
# If there is a previous gate (i > 0), then the current candidate key
# must satisfy the target-key constraint of the previous gate_type.
if i > 0:
prev_type = types[i - 1]
allowed_targets_for_prev = TARGET_KEY_CONSTRAINTS.get(prev_type, set(KEYS))
candidates = [c for c in candidates if c in allowed_targets_for_prev]
rnd.shuffle(candidates)
for c in candidates:
keys[i] = c
used_keys.add(c)
if assign_keys(i + 1):
return True
used_keys.remove(c)
keys[i] = None
return False
if not assign_keys(0):
# Re-sample everything if key assignment hit a dead end.
continue
# Build chained gates (ending at 'flag').
gates: List[dict] = []
for i in range(n):
gate_key = keys[i]
gates.append({
"index": i + 1,
"entry_point": chain_entries[i],
"gate_type": types[i],
"current_gate_key": gate_key,
"target_gate_key": "flag" if i == n - 1 else keys[i + 1],
"target_gate_type": "none" if i == n - 1 else types[i + 1],
})
# Append placeholder gates for any unused entry_points.
extra_types_pool = [t for t in non_first_type_pool if t not in used_types]
rnd.shuffle(extra_types_pool)
if len(extra_types_pool) < len(extra_entries):
fallback = [t for t in GATE_TYPES if t not in used_types and t not in extra_types_pool]
rnd.shuffle(fallback)
extra_types_pool.extend(fallback)
for ep in extra_entries:
if not extra_types_pool:
raise print(f"[{now()}][*] Not enough distinct gate_types available for extras.")
t = extra_types_pool.pop()
used_types.add(t)
gates.append({
"index": len(gates) + 1,
"entry_point": ep,
"gate_type": t,
"current_gate_key": "none",
"target_gate_key": "none",
"target_gate_type": "none",
})
return gates
print(f"[{now()}][!] ERROR: Could not generate a valid chain after several retries.")
raise
# Builds the target gate's key, not the current gate's key.
def build_target_gate_key(platform_module_pool, challenge_id, gate_type, target_gate_key, target_gate_entry_point, flag_value):
"""
Builds the key for the TARGET gate.
Certain gates can only support certain keys. These constraints are in the global lists at the top.
"""
if target_gate_key == "none":
print(f"[{now()}][*] No target key to generate. Continuing...")
return
print(f"[{now()}][*] Building target gate's key or flag...")
if gate_type == "api":
print(f"[{now()}][*] API: Players create their own key (user creds and/or permissions) using API.")
return
if gate_type == "submission":
print(f"[{now()}][*] Submission: Introduces shell, target key has to be 'flag'.")
if target_gate_key == "flag":
chars = string.ascii_letters + string.digits
# Flags for shells are currently hidden in a randomised folder in the web root.
# Builds the folder for the web root.
random_folder_name = ''.join(random.choice(chars) for _ in range(10))
Path(FACTORY_FLOOR / random_folder_name).mkdir()
# Pick a flag text file and copy it to the folder in the web root.
flag_txt_directory = Path(platform_module_pool / target_gate_key / "txt")
files = [f for f in flag_txt_directory.iterdir() if f.is_file()]
random_flag = random.choice(files)
random_file_name = ''.join(random.choice(chars) for _ in range(10))
src = Path(random_flag)
dst = Path(FACTORY_FLOOR / random_folder_name / f"{random_file_name}.txt")
print(f"[{now()}][*] Flag web root dir: {random_folder_name}")
shutil.copy(src, dst)
# Open/read the newly created flag text file.
with open(dst, "r", encoding="utf-8") as f:
content = f.read()
# Replace placeholder with the flag.
content = content.replace("!!!PLACEHOLDER!!!", f"{flag_value}")
# Write back to the file.
with open(dst, "w", encoding="utf-8") as f:
f.write(content)
print(f"[{now()}][*] Flag inserted into file.")
return
else:
raise print(f"[{now()}][*] ERROR: Shell needs to end with flag. Exiting.")
if gate_type == "blogs":
if target_gate_key == "flag":
print(f"[{now()}][*] Inserting flag for Blogs...")
table_name = random.choice(FLAG_TABLE_NAMES)
database_flag(challenge_id, flag_value, table_name)
add_table_access_to_db_user(challenge_id, gate_type, table_name)
# Turn on blog post > allows SQLi to be found > leads to the flag in the DB.
with open(Path(FACTORY_FLOOR / "blogutils.php"), "a") as file:
print(f"[{now()}][*] Inserting 'blog_post = true'")
file.write("\nconst blog_post = true;")
return
if target_gate_key == "session_token":
print(f"[{now()}][*] Enabling session_token for Blogs...")
# Turn off blog post; SQLi not used in this challenge.
with open(Path(FACTORY_FLOOR / "blogutils.php"), "a") as file:
print(f"[{now()}][*] Inserting 'blog_post = false'")
file.write("\nconst blog_post = false;")
set_single_user_permission(challenge_id, target_gate_entry_point, "AI_OVERWATCH")
return
if gate_type in ("products", "employees", "search"):
print(f"[{now()}][*] Products, Search, and Employees: Can only put keys in database.")
if target_gate_key == "flag":
table_name = random.choice(FLAG_TABLE_NAMES)
database_flag(challenge_id, flag_value, table_name)
# Swap 'target_gate_key' for 'table_name' in next function for the flag table, cause flag special :3
add_table_access_to_db_user(challenge_id, gate_type, table_name)
add_table_access_to_db_user(challenge_id, gate_type, "users") # Forces access to 'users' table.
print(f"[{now()}][*] Flag inserted into database.")
return
if target_gate_key == "creds":
randomly_set_single_user_permission(challenge_id, target_gate_entry_point)
add_table_access_to_db_user(challenge_id, gate_type, "users") # Forces access to 'users' table.
print(f"[{now()}][*] User permission adjusted.")
return
if target_gate_key == "session_token":
token = php_session_id()
set_session_token(challenge_id, token, target_gate_entry_point)
add_table_access_to_db_user(challenge_id, gate_type, target_gate_key)
add_table_access_to_db_user(challenge_id, gate_type, "users") # Forces access to 'users' table.
print(f"[{now()}][*] Session token added.")
return
if gate_type == "cookie":
# Locate the 'cookieX.php' file.
print(f"[{now()}][*] Cookie: adding secret to module file...")
try:
for filename in os.listdir(FACTORY_FLOOR):
if filename.startswith("cookie"): # check if file starts with "cookie"
file_path = os.path.join(FACTORY_FLOOR, filename)
# Open and read the file.
with open(file_path, "r+", encoding="utf-8") as file:
content = file.read()
# Note: If "target_line" ever changes, will need to update this.
target_line = "Overwatch User Created: !!!USERNAME!!! : !!!PASSWORD!!!"
if target_gate_key == "flag":
print(f"[{now()}][*] Inserting flag into {filename}")
replacement_line = f"WARNING: Override Code Identified: {flag_value}"
content = content.replace(target_line, replacement_line)
elif target_gate_key == "session_token":
print(f"[{now()}][*] Inserting session token into {filename}")
token = php_session_id()
set_session_token(challenge_id, token, target_gate_entry_point)
replacement_line = f"Overwatch session token generated: {token}"
content = content.replace(target_line, replacement_line)
print(f"[{now()}][*] Session token added.")
elif target_gate_key == "creds":
print(f"[{now()}][*] Inserting creds into {filename}")
picked_username = f"{random.choice(usernames)}_adm"
picked_password = random.choice(passwords)
add_user_to_challenge_database(challenge_id, picked_username, picked_password, 0, 0, 0)
set_single_user_permission(challenge_id, target_gate_entry_point, picked_username)
content = content.replace("!!!USERNAME!!!", picked_username)
content = content.replace("!!!PASSWORD!!!", picked_password)
file.seek(0)
file.write(content)
file.truncate()
return
except Exception as e:
print(f"[{now()}][*] ERROR:",e)
return
# Builds unauth key, for first gate only.
def build_first_gate_key_module(platform_module_pool, challenge_id, gate_type, gate_key, entry_point):
"""
Builds the key for the FIRST gate.
First gate only supports specific keys.
These keys are in the global list FIRST_GATE_KEYS.
"""
module_type = "keys"
target_for_secret = ""
hub = 0
work = 0
research = 0
if entry_point == "hub.php":
hub = 1
if entry_point == "work.php":
work = 1
if entry_point == "research.php":
research = 1
print(f"[{now()}][*] New user permissions, if needed:",work,research,hub)
if gate_key == "none":
print(f"[{now()}][*] No key required for this gate (this should only apply to first gate).")
return
if gate_key == "sqli":
print(f"[{now()}][*] SQL injection enabled for first gate.")
return
if gate_key != "users.json" and gate_key != "robots" and gate_key != "none": # "users.json" and "robots" do not have supporting files.
module_selection = pick_random_folder(Path(platform_module_pool) / module_type / gate_key) # Choose the specific module.
module_location = Path(platform_module_pool) / module_type / gate_key / module_selection # Copying the module type.
print(f"[{now()}][*] Gate type: {gate_type} | Key type: {gate_key}")
if gate_key == "robots":
print(f"[{now()}][*] Building robots.txt key...")
folder_names = ["emergency", "private", "dump", "secret", "backdoor", "hidden", "other"]
file_names = ["breakglass", "backup", "backdoor", "oops", "private", "creds"]
new_filename = f"{random.choice(file_names)}.txt"
new_folder = random.choice(folder_names)
new_path = Path(FACTORY_FLOOR) / new_folder
new_path.mkdir(parents=False, exist_ok=True)
new_file_location = Path(new_path) / new_filename
with open(Path(FACTORY_FLOOR) / "robots.txt", 'w') as file:
file.write("User-agent: *\n")
file.write(f"Disallow: /{new_folder}\n")
picked_username = f"{random.choice(usernames)}_svc"
picked_password = random.choice(passwords)
add_user_to_challenge_database(challenge_id, picked_username, picked_password, work, research, hub)
with open(new_file_location, 'w') as file:
file.write(f"Break glass account for the {entry_point} system:\n")
file.write(f"Username: {picked_username}\n")
file.write(f"Password: {picked_password}\n")
if gate_key == "git":
print(f"[{now()}][*] Building git key...")
try:
shutil.copytree(module_location, FACTORY_FLOOR, dirs_exist_ok=True) # Grab whole module directory/contents
except Exception as e:
print(f"[{now()}][*] ERROR:", e)
return
# Find location where secret needs to be saved.
# Structure: ./git/../path/to/file
git_config_file = Path(FACTORY_FLOOR) / f"key_{gate_key}_{module_selection}_config.txt"
try:
if os.path.exists(git_config_file):
with open(git_config_file, "r") as f:
target_for_secret = Path(FACTORY_FLOOR) / f.readline().strip() # .strip() removes trailing newline/spaces
else:
print(f"[{now()}][*] ERROR: Could not open {git_config_file}")
return
except Exception as e:
print(f"[{now()}][*] ERROR:", e)
return
print(f"[{now()}][*] Building secret...")
picked_username = f"{random.choice(usernames)}_svc"
picked_password = random.choice(passwords)
secret_value = f"<!-- For testing: {picked_username}:{picked_password} -->"
print(f"[{now()}][*] Secret:",secret_value)
# Put key in its hiding place.
if os.path.exists(target_for_secret):
try:
with open(target_for_secret, "a") as f:
f.write(f"\n {secret_value}")
print(f"[{now()}][*] Key inserted...")
except Exception as e:
print(f"[{now()}][*] ERROR:", e)
return
else:
print(f"[{now()}][*] ERROR: Target for secret does not exist? Exiting...")
return
# 'auth' secret needs to be written to challenge database.
add_user_to_challenge_database(challenge_id, picked_username, picked_password, work, research, hub)
print(f"[{now()}][*] Challenge database updated.")
# Remove config file so it is not put in the finished challenge.
if os.path.exists(git_config_file):
try:
os.remove(git_config_file)
print(f"[{now()}][*] Config file deleted successfully.")
except Exception as e:
print(f"[{now()}][*] ERROR:", e)
return
else:
print(f"[{now()}][*] ERROR: 'git' key config does not exist?")
return
if gate_key == "env":
print(f"[{now()}][*] Building .env key...")
try:
shutil.copytree(module_location, FACTORY_FLOOR, dirs_exist_ok=True) # Grab whole module directory/contents.
except Exception as e:
print(f"[{now()}][*] ERROR:", e)
return
target_for_secret = Path(FACTORY_FLOOR) / ".env"
picked_username = f"{random.choice(usernames)}_svc"
picked_password = random.choice(passwords)
add_user_to_challenge_database(challenge_id, picked_username, picked_password, work, research, hub)
print(f"[{now()}][*] New user added to challenge database.")
try:
with open(target_for_secret, "r", encoding="utf-8-sig", newline="") as f:
text = f.read()
replacements = {
"!!!USERNAME!!!": picked_username,
"!!!PASSWORD!!!": picked_password
}
new_text = text
for placeholder, value in replacements.items():
new_text = new_text.replace(placeholder, value, 1) # only replace first occurrence
# Validation: check if at least one replacement was made.
if new_text == text:
print(f"[{now()}][*] ERROR: No placeholder values found!")
return
else:
print(f"[{now()}][*] Placeholders replaced.")
with open(target_for_secret, "w", encoding="utf-8-sig", newline="") as f:
f.write(new_text)
print(f"[{now()}][*] Updated module saved.")
except FileNotFoundError:
print(f"[{now()}][*] .env file not found, exiting.")
return
except Exception as e:
print(f"[{now()}][*] ERROR: {e}")
return
if gate_key == "users.json": # Does not require module artefacts, is generated here.
print(f"[{now()}][*] Building users.json key...")
pairs = [{"username": u, "password": p} for u, p in zip(picked_usernames, picked_passwords)]
output_file = Path(FACTORY_FLOOR) / "users.json"
with open(output_file, "w", encoding="utf-8") as f:
json.dump(pairs, f, indent=4)
print(f"[{now()}][*] User JSON written.")
if entry_point == "hub.php":
for picked_username, picked_password in zip(picked_usernames, picked_passwords):
set_single_user_permission(challenge_id, "hub", picked_username)
if entry_point == "work.php":
for picked_username, picked_password in zip(picked_usernames, picked_passwords):
set_single_user_permission(challenge_id, "work", picked_username)
if entry_point == "research.php":
for picked_username, picked_password in zip(picked_usernames, picked_passwords):
set_single_user_permission(challenge_id, "research", picked_username)
print(f"[{now()}][*] User permissions mass updated.")
if gate_key == "config.old":
print(f"[{now()}][*] Building config.old key...")
try:
shutil.copytree(module_location, FACTORY_FLOOR, dirs_exist_ok=True) # Grab whole module directory/contents.
except Exception as e:
print(f"[{now()}][*] ERROR:", e)
return
target_for_secret = Path(FACTORY_FLOOR) / "config.old"
print(f"[{now()}][*] Building secret...")
picked_username = f"{random.choice(usernames)}_srv"
picked_password = random.choice(passwords)
try:
with open(target_for_secret, "r", encoding="utf-8-sig", newline="") as f:
text = f.read()
replacements = {
"!!!USERNAME!!!": picked_username,
"!!!PASSWORD!!!": picked_password
}
new_text = text
for placeholder, value in replacements.items():
new_text = new_text.replace(placeholder, value, 1) # Only replace first occurrence.
# Validation: check if at least one replacement was made.
if new_text == text:
print(f"[{now()}][*] ERROR: No placeholder values found!")
return
else:
print(f"[{now()}][*] Placeholders replaced.")
with open(target_for_secret, "w", encoding="utf-8-sig", newline="") as f:
f.write(new_text)
print(f"[{now()}][*] Updated module saved.")
except FileNotFoundError:
print(f"[{now()}][*] 'config.old' file not found, exiting.")
return
except Exception as e:
print(f"[{now()}][*] ERROR: {e}")
return
add_user_to_challenge_database(challenge_id, picked_username, picked_password, work, research, hub)
print(f"[{now()}][*] Challenge database updated.")
if gate_key == "log":
print(f"[{now()}][*] Building *.log key...")
log_file = next(module_location.glob("*.log"), None) # Find the .log file in the module folder.
log_filename = log_file.name if log_file else None
try:
shutil.copytree(module_location, FACTORY_FLOOR, dirs_exist_ok=True) # Grab whole module directory/contents.
except Exception as e:
print(f"[{now()}][*] ERROR:", e)
return
target_for_secret = Path(FACTORY_FLOOR) / log_filename
print(f"[{now()}][*] Building secret...")
picked_username = f"{random.choice(usernames)}_svc"
picked_password = random.choice(passwords)
add_user_to_challenge_database(challenge_id, picked_username, picked_password, work, research, hub)
try:
with open(target_for_secret, "r", encoding="utf-8-sig", newline="") as f:
text = f.read()
replacements = {
"!!!USERNAME!!!": picked_username,
"!!!PASSWORD!!!": picked_password
}
new_text = text
total_replacements = 0
# Replace ALL occurrences of each placeholder and count how many were replaced.
for placeholder, value in replacements.items():
count = new_text.count(placeholder)
if count:
new_text = new_text.replace(placeholder, value) # Default replaces all occurrences.
total_replacements += count
# Validation: check if at least one replacement was made.
if total_replacements == 0:
print(f"[{now()}][*] ERROR: No placeholder values found!")
return
else:
print(f"[{now()}][*] Placeholders replaced. Total replacements: {total_replacements}")
with open(target_for_secret, "w", encoding="utf-8-sig", newline="") as f:
f.write(new_text)
print(f"[{now()}][*] Updated '{log_filename}' saved.")
except FileNotFoundError:
print(f"[{now()}][*] ERROR: File not found: {log_filename}")
return
except Exception as e:
print(f"[{now()}][*] ERROR: {e}")
return
print(f"[{now()}][*] Challenge database updated.")
print(f"[{now()}][*] {gate_key} key inserted into challenge. Continuing...")
return
# Get user's ID from challenge database.
def get_user_id(challenge_id, username):
conn = master_db()
cursor = conn.cursor()
database_name = str(challenge_id)
# Select the challenge database
try:
conn.database = f"`{database_name}`"
except Exception as e:
try:
conn.database = f"{database_name}"
except Exception as e:
print(f"[{now()}][!] WARNING: Problem selecting database {database_name}, regardless of backticks...")
raise (f"[{now()}][!] ERROR:",e)
try:
query = "SELECT id FROM users WHERE username = %s"
cursor.execute(query, (username,),)
result = cursor.fetchone()
except Exception as e:
print(f"[{now()}][*] ERROR: Problem selecting blog posts.")
cursor.close()
conn.close()
raise print(f"[{now()}][*] ERROR:",e)
cursor.close()
conn.close()
list2string = ''.join(map(str, result))
result = int(list2string)
print(f"[{now()}][*] User ID:",result)
return result
# Builds what we see when the current gate is unlocked.
def build_gateway_target(challenge_id, target_url, gate_type, platform_modules):
"""
Builds what we see when the current gate is unlocked.
Essentially builds the starting point for the next challenge in the sequence.
This is where "gate_type" defines what the player sees.
"""
module_selection = pick_random_folder(Path(MODULE_TEMPLATES) / platform_modules / gate_type) # Choose the specific module
module_to_copy = MODULE_TEMPLATES / platform_modules / gate_type / module_selection
print(f"[{now()}][*] Copying gate module to factory floor.")
shutil.copytree(module_to_copy, FACTORY_FLOOR, dirs_exist_ok=True) # Grab whole auth module directory contents
page_to_include = f"{gate_type}{module_selection}.php"
print(f"[{now()}][*] MODULE FILE:",page_to_include)
if gate_type == "products":
print(f"[{now()}][*] Creating a products table...")
create_products_table(challenge_id)
if gate_type == "employees" or gate_type == "search":
print(f"[{now()}][*] Creating a employees table...")
create_employee_table(challenge_id)
if gate_type == "cookie":
print(f"[{now()}][*] Configuring 'cookies and token' challenge...")
# Lists of different possible values...
cookie_names = ["AUTHTOKEN", "PRIVID", "OVERWATCH", "AUDITTOKEN", "VIEWID"]
normal_usernames = ["EMPLOYEE", "USER", "ASSOCIATE", "GUEST", "CONSULTANT", "TECHNICIAN", "ENGINEER", "AGENT"]
priv_usernames = ["MANAGER", "ADMINISTRATOR", "OPERATOR", "SUPERVISOR", "REVIEWER", "ADMIN"]
token_type = str(random.randint(1, 3)) # Token types and mechanics are defined in the 'token-auth-master.php' file.
# Copy token auth file...
try:
filename = "token-auth-master.php"
token_auth_file = Path(MODULE_TEMPLATES) / platform_modules / gate_type / filename
shutil.copy(token_auth_file, FACTORY_FLOOR / filename)
except Exception as e:
print(f"[{now()}][*] ERROR:",e)
return
# Modify token-auth-master
cookie_name = random.choice(cookie_names)
normal_user = random.choice(normal_usernames)
priv_user = random.choice(priv_usernames)
characters = string.ascii_letters + string.digits # A-Z, a-z, 0-9
signing_key = ''.join(random.choices(characters, k=20))
try:
with open(FACTORY_FLOOR / filename, "r+", encoding="utf-8") as file:
content = file.read()
content = content.replace("!!!TOKENTYPE!!!", token_type)
content = content.replace("!!!COOKIENAME!!!", cookie_name)
content = content.replace("!!!NORMALUSER!!!", normal_user)
content = content.replace("!!!PRIVUSER!!!", priv_user)
content = content.replace("!!!SIGNINGKEY!!!", signing_key)
file.seek(0)
file.write(content)
file.truncate()
except Exception as e:
print(f"[{now()}][*] ERROR:",e)
return
# Modify module file so that the priv user displays correctly to players.
try:
with open(FACTORY_FLOOR / page_to_include, "r+", encoding="utf-8") as file:
content = file.read()
content = content.replace("!!!PRIVUSER!!!", priv_user.capitalize())
file.seek(0)
file.write(content)
file.truncate()
except Exception as e:
print(f"[{now()}][*] ERROR:",e)
return
if gate_type == "blogs":
print(f"[{now()}][*] Creating a blogs and comments tables...")
# Build random Overwatch password.
characters = string.ascii_letters + string.digits # A-Z, a-z, 0-9
overwatch_password = ''.join(random.choices(characters, k=20))
print(f"[{now()}][*] Adding AI_OVERWATCH to users table.")
add_user_to_challenge_database(challenge_id, "AI_OVERWATCH", overwatch_password, 0, 0, 0)
print(f"[{now()}][*] Configuring AI_OVERWATCH permission to access Blog.")
set_single_user_permission(challenge_id, target_url, "AI_OVERWATCH")
user_id = get_user_id(challenge_id, "AI_OVERWATCH")
blog_id = create_blogs_and_comments_tables(challenge_id, target_url.removesuffix(".php"), user_id)
print(f"[{now()}][*] Creating puppet for blog...")
create_puppet(challenge_id, "AI_OVERWATCH", overwatch_password, f"/auth_{target_url}?view={blog_id}",
base_url=f"http://{WEB_HOST_IP}:{FIRST_PORT_NUMBER}{challenge_id}")
if gate_type == "api":
print(f"[{now()}][*] Randomising Swagger JSON filename...")
# Randomising the file name prevents players from directly finding the API definitions on subsequent runs.
characters = string.ascii_letters + string.digits # A-Z, a-z, 0-9
random_file_name = ''.join(random.choices(characters, k=20))
try:
swagger_initialiser = Path("swagger") / "swagger-initializer.js"
with open(FACTORY_FLOOR / swagger_initialiser, "r") as f:
data = f.read()
# Replace the target string
data = data.replace("swagger.json", f"{random_file_name}.json")
# Write the file back
with open(FACTORY_FLOOR / swagger_initialiser, "w") as f:
f.write(data)
# Rename swagger.json file
original_json = Path("swagger") / "swagger.json"
new_json = Path("swagger") / f"{random_file_name}.json"
os.rename(FACTORY_FLOOR / original_json, FACTORY_FLOOR / new_json)
except Exception as e:
raise print(f"[{now()}][*] ERROR: {e}")
# Modifying the READ ONLY db-user account for the challenge database, to be used by the challenge itself.
# TODO: Fix the API database user so that it creates a new database user with SELECT, UPDATE, and INSERT permissions
# instead of modifying the readonly user to have INSERT permissions - similar to how it is done with the Blogs user.
challenge_db_username = f"readonly{challenge_id}"
cnx = master_db()
cursor = cnx.cursor()
try:
grant_sql = f"GRANT INSERT ON `{challenge_id}`.users TO '{challenge_db_username}'@'%'"
cursor.execute(grant_sql)
grant_sql = f"GRANT UPDATE ON `{challenge_id}`.users TO '{challenge_db_username}'@'%'"
cursor.execute(grant_sql)
cursor.execute("FLUSH PRIVILEGES")
cnx.commit()
print(f"[{now()}][*] User '{challenge_db_username}' modified to include INSERT and UPDATE permissions to database '{challenge_id}'.")
except Exception as e:
print(f"[{now()}][*] ERROR: {e}")
cursor.close()
cnx.close()
return
cursor.close()
cnx.close()
# Attached gate module to the auth_target
file_location = Path(FACTORY_FLOOR) / f"auth_{target_url}"
include_page = f"include '{page_to_include}';\n"
auth_page = f"require_auth('{target_url.removesuffix(".php")}');\n"
print(f"[{now()}][*] Replacing placeholders in:",file_location)
try:
with open(file_location, "r", encoding="utf-8") as f:
lines = f.readlines()
with open(file_location, "w", encoding="utf-8") as f:
for line in lines:
stripped = line.strip()
if stripped == "include 'placeholder.php';":
f.write(include_page)
elif stripped == "//INSERT GATE HEADER HERE":
f.write(auth_page)
else:
f.write(line)
print(f"[{now()}][*] Updates saved.")
except FileNotFoundError:
print(f"[{now()}][*] File '{file_location}' not found, skipping.")
except Exception as e:
print(f"[{now()}][*] ERROR: {e}")
return
# Middleware generator for PHP templates.
def build_middleware(auth_target, gate):
# auth_target will be hub.php, research.php, or work.php
data = {
"source": "$source",
"destination": f"/auth_{auth_target}",
"start": f"/{auth_target}",
"u": "$u",
"p": "$p",
"user": "$user"
}
source_file = Path(MODULE_TEMPLATES) / "php_templates" / "middleware.php"
# If you intended an underscore, use f"{gate}_middleware.php"
new_file = Path(FACTORY_FLOOR) / f"{gate}middleware.php"
try:
if not source_file.exists():
raise FileNotFoundError(f"Template not found: {source_file}")
text = source_file.read_text(encoding="utf-8")
# Escape ALL $ so Template won't interpret PHP variables
# (Template outputs a single '$' for '$$')
protected = re.sub(r"\$", r"$$", text)
# Whitelist ONLY our placeholders (destination, start, u, p, user)
for key in ("destination", "start", "u", "p", "user"):
protected = protected.replace(f"$${key}", f"${key}")
# Substitute (not safe_substitute) to surface missing keys
rendered = Template(protected).substitute(data)
new_file.parent.mkdir(parents=True, exist_ok=True)
new_file.write_text(rendered, encoding="utf-8")
print(f"[{now()}][*] Wrote {new_file.resolve()} ({len(rendered)} bytes)")
except Exception as e:
print(f"[{now()}][*] ERROR: Problem building middleware file for gate '{gate}': {e!r}")
traceback.print_exc()
raise
return
# Attaches a lock to a gate.
def add_auth_module_and_gateheader(target_url, auth_required, platform_module_pool, gate_counter):
"""
Adds the "auth" lock to applicable gates.
Points the "auth" module at the applicable middleware.
Not currently using "auth_required", but will need to once more options/features are worked in.
"""
auth_module = "auth" # Folder location for authentication modules
auth_module_selection = "1" # TODO If other authentication modules are developed, can randomise selection.
gate_header_file = f"{gate_counter}gate_header.php"
# Placeholder modification
site_filepath = Path(FACTORY_FLOOR) / target_url
try:
with open(site_filepath, "r", encoding="utf-8") as f:
lines = f.readlines()
with open(site_filepath, "w", encoding="utf-8") as f:
for line in lines:
stripped = line.strip()
if stripped == "include 'placeholder.php';":
f.write(f"include '{gate_counter}{auth_module}.php';\n")
elif stripped == "//INSERT GATE HEADER HERE":
f.write(f"include '{gate_header_file}';\n")
else:
f.write(line)
print(f"[{now()}][*] Updated file: {site_filepath}")
except FileNotFoundError:
print(f"[{now()}][*] ERROR: File '{site_filepath}' not found.")
return
except Exception as e:
print(f"[{now()}][*] ERROR: {e}")
return
# Add the authentication module.
auth_module_location = Path(platform_module_pool) / auth_module / auth_module_selection
print(f"[{now()}][*] Copying authentication module to factory floor.")
shutil.copytree(auth_module_location, FACTORY_FLOOR, dirs_exist_ok=True) # Grab whole auth module directory contents
os.rename(f"{FACTORY_FLOOR}/auth.php", f"{FACTORY_FLOOR}/{gate_counter}auth.php")
# Replace placeholder in the auth module with the applicable middleware.
filepath = Path(FACTORY_FLOOR) / f"{gate_counter}{auth_module}.php"