Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
1393 lines (1228 loc) · 57.7 KB
/
Copy pathapp.py
File metadata and controls
1393 lines (1228 loc) · 57.7 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
# SPDX-FileCopyrightText: GoCortexIO
# SPDX-License-Identifier: AGPL-3.0-or-later
import os
import time
import yaml
import logging
import random
from datetime import datetime, timedelta
from flask import Flask, render_template, request, redirect, url_for, flash, make_response, session, g, jsonify
from flask_sqlalchemy import SQLAlchemy
from werkzeug.middleware.proxy_fix import ProxyFix
# Proxy imports removed - no separate lab applications
# Log shipping for SIEM integration
from log_shipping import bbwaf_logging_middleware, log_auth_event, log_concierge_event
from auth_traffic_generator import start_auth_generator
# OTel poll-based metrics (Prometheus scrape endpoint on port 9464)
from observability.metrics import init_metrics
# Configure logging
logging.basicConfig(level=logging.INFO)
# Create SQLAlchemy instance (compatible with older versions)
# Using try/except for compatibility with different SQLAlchemy versions
try:
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
pass
db = SQLAlchemy(model_class=Base)
except ImportError:
# Fallback for older SQLAlchemy versions
db = SQLAlchemy()
# Create the main app
app = Flask(__name__)
# Intentionally vulnerable: Hardcoded secret key (CKV3_SAST_152)
app.secret_key = os.environ.get("SESSION_SECRET", "hardcoded-secret-key-12345")
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)
# Configure the database
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL", "sqlite:///gocortexbrokenbank.db")
app.config["SQLALCHEMY_ENGINE_OPTIONS"] = {
"pool_recycle": 300,
"pool_pre_ping": True,
}
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False # Suppress Flask-SQLAlchemy warning
# Initialize the app with the extension
db.init_app(app)
# Application version
APP_VERSION = "1.6.0"
# OTel metrics - start Prometheus scrape endpoint on port 9464
init_metrics(port=9464)
# Flask HTTP instrumentation - record per-request counts and durations.
# Skips the /metrics path itself to avoid self-scrape noise in the output.
@app.before_request
def _metrics_before_request():
from observability import metrics as _m
if request.path != "/metrics" and _m.http_requests is not None:
g._metrics_start = time.time()
@app.after_request
def _metrics_after_request(response):
from observability import metrics as _m
start = getattr(g, "_metrics_start", None)
if start is not None and _m.http_requests is not None:
duration = time.time() - start
labels = {
"method": request.method,
"endpoint": request.endpoint or request.path,
"status_code": str(response.status_code),
}
_m.http_requests.add(1, labels)
_m.http_request_duration.record(
duration,
{"method": request.method, "endpoint": request.endpoint or request.path},
)
return response
# Testing URLs for cybersecurity validation purposes only - these are fictitious endpoints
# used by automated security scanners to validate URL filtering and threat detection capabilities
TEST_MALWARE_URL = "https://urlfiltering.paloaltonetworks.com/test-malware" # Official Palo Alto test endpoint
TEST_C2_DOMAIN = "c2.sigre.xyz" # Simulated command and control domain for testing
TEST_BOTNET_DOMAIN = "botnet.sigre.xyz" # Test botnet domain for security validation
# Load localisation config
def load_localisation():
locale_code = os.environ.get("LOCALE", "en")
locale_files = {
"en": "config/localise.yaml",
"kr": "config/localise.yaml.kr"
}
locale_file = locale_files.get(locale_code, "config/localise.yaml")
if locale_code not in locale_files:
logging.warning(f"Unknown LOCALE '{locale_code}', defaulting to English (en)")
try:
with open(locale_file, 'r') as file:
logging.info(f"Loaded localisation from {locale_file}")
return yaml.safe_load(file)
except FileNotFoundError:
logging.warning(f"Locale file {locale_file} not found, falling back to config/localise.yaml")
try:
with open('config/localise.yaml', 'r') as file:
return yaml.safe_load(file)
except FileNotFoundError:
logging.error("Default localisation file not found")
return {}
localisation = load_localisation()
# Setup Mars Banking Initiative repository (Exposed Git Repository)
def setup_mars_repo():
"""
Create the Mars Banking Initiative git repository for security testing.
Implements the Exposed Local Git Repository capability.
Creates realistic commit history simulating development progression.
"""
import subprocess
import shutil
import os
from pathlib import Path
from datetime import datetime, timedelta
target = Path(__file__).parent / "data" / "projects" / "mars-banking-initiative"
template = Path(__file__).parent / "vulnerable_data" / "mars_banking_initiative"
# Skip if already exists with .git directory
if (target / ".git").exists():
return
# Commit history simulating realistic development
commits = [
{"msg": "Initial commit - Project Ares scaffolding", "author": "Eleanor Blackwood", "email": "eleanor.blackwood@gocortex.io", "days": 180, "files": ["README.md", "requirements.txt", ".gitignore"]},
{"msg": "Add SpaceATM core module with dispensing logic", "author": "Marcus Chen", "email": "marcus.chen@gocortex.io", "days": 150, "files": ["src/__init__.py", "src/space_atm.py"]},
{"msg": "Implement Mars Gateway relay system", "author": "Marcus Chen", "email": "marcus.chen@gocortex.io", "days": 120, "files": ["src/mars_gateway.py"]},
{"msg": "Add orbital authentication for spacesuit biometrics", "author": "Priya Sharma", "email": "priya.sharma@gocortex.io", "days": 90, "files": ["src/orbital_auth.py"]},
{"msg": "Implement quantum ledger with QDCP", "author": "Eleanor Blackwood", "email": "eleanor.blackwood@gocortex.io", "days": 60, "files": ["src/quantum_ledger.py"]},
{"msg": "Add production configuration (DO NOT COMMIT - oops)", "author": "Marcus Chen", "email": "marcus.chen@gocortex.io", "days": 45, "files": ["config/production.yaml", "config/.env.production"]},
{"msg": "Add credentials file for deployment automation", "author": "Simon Sigre", "email": "simon@simonsigre.com", "days": 30, "files": ["config/credentials.json"]},
{"msg": "Add SSH keys for Mars Gateway deployment", "author": "Marcus Chen", "email": "marcus.chen@gocortex.io", "days": 25, "files": [".ssh/id_rsa", ".ssh/id_rsa.pub"]},
{"msg": "Add financial projections and patent strategy docs", "author": "Simon Sigre", "email": "simon@simonsigre.com", "days": 15, "files": ["docs/FINANCIAL_PROJECTIONS.md", "docs/PATENT_STRATEGY.md"]},
]
try:
# Create target directory
target.mkdir(parents=True, exist_ok=True)
# Copy template files
if template.exists():
for item in template.iterdir():
dest = target / item.name
if item.is_dir():
if dest.exists():
shutil.rmtree(dest)
shutil.copytree(item, dest)
else:
shutil.copy2(item, dest)
# Initialise git repository
subprocess.run(["git", "init"], cwd=target, capture_output=True)
subprocess.run(["git", "config", "user.email", "ares@gocortex.io"], cwd=target, capture_output=True)
subprocess.run(["git", "config", "user.name", "Ares Build System"], cwd=target, capture_output=True)
# Create commits with realistic history
for commit in commits:
commit_date = datetime.now() - timedelta(days=commit["days"])
date_str = commit_date.strftime("%Y-%m-%dT%H:%M:%S")
# Add files for this commit
for file_path in commit["files"]:
full_path = target / file_path
if full_path.exists():
subprocess.run(["git", "add", file_path], cwd=target, capture_output=True)
# Create commit with author and date
env = os.environ.copy()
env.update({
"GIT_AUTHOR_NAME": commit["author"],
"GIT_AUTHOR_EMAIL": commit["email"],
"GIT_AUTHOR_DATE": date_str,
"GIT_COMMITTER_NAME": commit["author"],
"GIT_COMMITTER_EMAIL": commit["email"],
"GIT_COMMITTER_DATE": date_str
})
subprocess.run(["git", "commit", "-m", commit["msg"], "--allow-empty"], cwd=target, capture_output=True, env=env)
logging.info(f"Mars Banking Initiative repository created at {target} with {len(commits)} commits")
except Exception as e:
logging.warning(f"Failed to setup Mars repo: {e}")
# Initialise Mars repo on startup
try:
setup_mars_repo()
except Exception as e:
logging.warning(f"Mars repo setup skipped: {e}")
# Apply BBWAF logging middleware for SIEM integration
bbwaf_logging_middleware(app)
# Make localisation available in templates
@app.context_processor
def inject_localisation():
return dict(locale=localisation, app_version=APP_VERSION)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/disclaimer')
def disclaimer():
return render_template('disclaimer.html')
# Mars Banking Initiative Concierge - intentionally vulnerable LLM chatbot
# Demonstrates OWASP LLM Top 10: LLM01 Prompt Injection, LLM02 Insecure Output
# Handling, LLM06 Sensitive Information Disclosure, LLM08 Excessive Agency.
from chatbot import concierge as _concierge
# Pre-warm the SmolLM2 GGUF in a background thread so the first
# /concierge/chat request does not pay the multi-second cold-load
# latency. Without this the live demo has a visible "tell": injection
# prompts (which used to short-circuit the LLM) returned instantly
# while the first safe banking turn took 10+ seconds, breaking the
# illusion that the model is actually being attacked.
_concierge.start_warmup()
CONCIERGE_MODEL_NAME = os.environ.get(
"CONCIERGE_MODEL_NAME", "SmolLM2-135M-Instruct GGUF Q4_K_M"
)
@app.route('/concierge')
def concierge_page():
"""Render the Mars Banking Initiative Concierge chat page."""
return render_template(
'concierge.html',
model_name=CONCIERGE_MODEL_NAME,
context_count=len(_concierge.get_extra_context()),
concierge_disabled=_concierge.is_disabled(),
concierge_disabled_reason=_concierge.disabled_reason(),
concierge_disabled_message=_concierge.disabled_message(),
)
def _concierge_session_id():
"""Return a stable session id for SIEM correlation, minting one on first use."""
sid = session.get('concierge_session_id')
if not sid:
import uuid as _uuid
sid = _uuid.uuid4().hex
session['concierge_session_id'] = sid
return sid
def _concierge_context_labels():
return [label for label, _body in _concierge.get_extra_context()]
@app.route('/concierge/chat', methods=['POST'])
def concierge_chat():
"""Intentionally vulnerable chat endpoint.
No input sanitisation, no output filter, no allow-list, no rate limit.
Logs full prompts and responses to stdout for SIEM training, and ships
one prompt event and one response event per turn (correlated by
turn_id) to the netbank_concierge XSIAM stream so a prompt-injection
detection ruleset has something to match on.
"""
user_message = request.form.get('message', '') or request.values.get('message', '')
if not user_message:
return "No message provided", 400
logging.info("CONCIERGE REQUEST remote=%s ua=%s message=%r",
request.remote_addr, request.headers.get('User-Agent', ''),
user_message)
import uuid as _uuid
turn_id = _uuid.uuid4().hex
session_id = _concierge_session_id()
context_labels = _concierge_context_labels()
effective_model_name = (
"disabled" if _concierge.is_disabled() else CONCIERGE_MODEL_NAME
)
log_concierge_event(
"prompt", request,
session_id=session_id, turn_id=turn_id,
model_name=effective_model_name,
prompt_text=user_message,
context_document_count=len(context_labels),
context_document_labels=context_labels,
)
if _concierge.is_disabled():
response_text = _concierge.disabled_message()
response_path = "disabled"
else:
response_text, response_path = _concierge.generate(user_message)
# Re-read context labels in case generate() (or the model) mutated state.
context_labels = _concierge_context_labels()
log_concierge_event(
"response", request,
session_id=session_id, turn_id=turn_id,
model_name=effective_model_name,
response_text=response_text,
response_path=response_path,
context_document_count=len(context_labels),
context_document_labels=context_labels,
)
return response_text, 200, {'Content-Type': 'text/plain; charset=utf-8'}
@app.route('/concierge/load_url', methods=['POST'])
def concierge_load_url():
"""Indirect prompt-injection sink: fetch a URL and add to context.
No URL validation, no SSRF guard, no sanitisation of fetched content.
"""
url = request.form.get('url', '')
if not url:
return "No url provided", 400
import requests as _req
try:
resp = _req.get(url, verify=False, timeout=10)
body = resp.text[:8000]
_concierge.add_context_document(url, body)
import uuid as _uuid
context_labels = _concierge_context_labels()
log_concierge_event(
"context_loaded", request,
session_id=_concierge_session_id(),
turn_id=_uuid.uuid4().hex,
model_name=CONCIERGE_MODEL_NAME,
document_label=url,
source_url=url,
body_preview=body,
body_length=len(body),
context_document_count=len(context_labels),
context_document_labels=context_labels,
)
return f"Loaded {len(body)} characters from {url} into Concierge context"
except Exception as exc:
return f"Failed to load {url}: {exc}", 502
@app.route('/concierge/load_text', methods=['POST'])
def concierge_load_text():
"""Indirect prompt-injection sink: accept raw text into context."""
label = request.form.get('label', 'uploaded-document')
body = request.form.get('body', '')
if not body:
return "No body provided", 400
truncated = body[:16000]
_concierge.add_context_document(label, truncated)
import uuid as _uuid
context_labels = _concierge_context_labels()
log_concierge_event(
"context_loaded", request,
session_id=_concierge_session_id(),
turn_id=_uuid.uuid4().hex,
model_name=CONCIERGE_MODEL_NAME,
document_label=label,
body_preview=truncated,
body_length=len(truncated),
context_document_count=len(context_labels),
context_document_labels=context_labels,
)
return f"Added document {label!r} ({len(body)} chars) to Concierge context"
# Intentionally vulnerable: Uncontrolled agentic tool execution (OWASP LLM08 - Excessive Agency)
@app.route('/concierge/agent', methods=['POST'])
def concierge_agent():
"""Agentic task executor: asks the Concierge model for the shell command
needed to complete an operations task, then runs whatever it suggests.
No validation, allow-list, or human-in-the-loop confirmation on the
model's output before execution. A prompt that steers the model's
suggested command steers what actually executes on the host.
"""
task = request.form.get('task', '')
if not task:
return "No task provided", 400
import subprocess
import uuid as _uuid
if _concierge.is_disabled():
return _concierge.disabled_message(), 200
turn_id = _uuid.uuid4().hex
session_id = _concierge_session_id()
context_labels = _concierge_context_labels()
effective_model_name = CONCIERGE_MODEL_NAME
agent_prompt = (
"You are a system agent that executes shell commands to complete "
"operations tasks. Respond with ONLY the shell command needed, no "
"explanation, no markdown formatting. Task: " + task
)
suggested_command, response_path = _concierge.generate(agent_prompt)
suggested_command = suggested_command.strip().splitlines()[0] if suggested_command.strip() else ""
try:
# Vulnerable: the model's suggested command executes with no validation,
# allow-list, or confirmation step
result = subprocess.run(
suggested_command, shell=True, capture_output=True, text=True, timeout=10
)
log_concierge_event(
"agent_command", request,
session_id=session_id, turn_id=turn_id,
model_name=effective_model_name,
prompt_text=task,
response_text=f"{suggested_command}\n--- stdout ---\n{result.stdout}\n--- stderr ---\n{result.stderr}",
response_path=response_path,
context_document_count=len(context_labels),
context_document_labels=context_labels,
)
return jsonify({
"suggested_command": suggested_command,
"response_path": response_path,
"stdout": result.stdout,
"stderr": result.stderr,
})
except Exception as e:
return jsonify({"suggested_command": suggested_command, "error": str(e)}), 400
# Banking Pages
@app.route('/netbank')
def netbank():
"""Personal netbank page with session-based balance and transactions"""
is_new_session = 'account_balance' not in session
if is_new_session:
session['account_balance'] = round(random.uniform(150, 8500000), 2)
session['account_number'] = f"{random.randint(10000000, 99999999)}"
session['sort_code'] = f"{random.randint(10, 99)}-{random.randint(10, 99)}-{random.randint(10, 99)}"
# Log authentication event for SIEM
username = session.get('username', f"user_{session['account_number'][-4:]}")
log_auth_event(username, "success", request, simulated=False)
balance = session['account_balance']
account_number = session['account_number']
sort_code = session['sort_code']
tier = 'high_balance' if balance > 100000 else 'low_balance'
transactions_data = localisation['pages']['netbank']['transactions']['tiers'][tier]
total_transaction_amount = sum(float(txn['amount']) for txn in transactions_data)
opening_balance = balance - total_transaction_amount
running_balance = opening_balance
transactions = []
for txn in transactions_data:
amount = float(txn['amount'])
running_balance += amount
transactions.append({
'date': txn['date'],
'description': txn['description'],
'amount': abs(amount),
'type': txn['type'],
'balance': round(running_balance, 2)
})
return render_template('netbank.html',
balance=balance,
account_number=account_number,
sort_code=sort_code,
transactions=transactions)
@app.route('/business')
def business():
"""Business banking services page"""
return render_template('business.html')
@app.route('/investments')
def investments():
"""Investment services page"""
return render_template('investments.html')
@app.route('/digital')
def digital():
"""Digital banking services page"""
return render_template('digital.html')
@app.route('/signup', methods=['GET', 'POST'])
def signup():
"""Account signup page with no verification"""
if request.method == 'POST':
new_account_number = f"{random.randint(10000000, 99999999)}"
new_sort_code = f"{random.randint(10, 99)}-{random.randint(10, 99)}-{random.randint(10, 99)}"
account_type = request.form.get('account_type', 'personal')
# Log signup event for SIEM
username = request.form.get('full_name', f"user_{new_account_number[-4:]}")
log_auth_event(username, "signup_success", request, simulated=False)
return render_template('signup.html',
success=True,
account_number=new_account_number,
sort_code=new_sort_code,
account_type=account_type)
return render_template('signup.html', success=False)
# Labs route removed - application contains built-in vulnerabilities
# Intentionally vulnerable: Debug mode enabled in production (CKV3_SAST_96)
@app.route('/debug')
def debug_info():
"""Intentionally vulnerable debug endpoint"""
import sys
import os
debug_data = {
'python_path': sys.path,
'environment': {k: str(v) for k, v in os.environ.items()},
'request_headers': dict(request.headers),
'app_config': {k: str(v) for k, v in app.config.items()}
}
return debug_data
# Vulnerable logging (CKV3_SAST_62)
@app.route('/log/<message>')
def log_message(message):
"""Intentionally vulnerable logging endpoint"""
logging.info(f"User message: {message}") # Direct user input logging
return f"Logged message: {message}"
# Intentionally vulnerable: SQL injection (CKV3_SAST_51)
@app.route('/search')
def search():
"""Intentionally vulnerable search endpoint"""
query = request.args.get('q', '')
if query:
# Vulnerable SQL query construction
sql = f"SELECT * FROM users WHERE name LIKE '%{query}%'"
return f"Search query executed: {sql}"
return "Search endpoint - provide ?q=searchterm"
# Intentionally vulnerable: XSS (CKV3_SAST_69)
@app.route('/comment')
def comment():
"""Intentionally vulnerable comment endpoint"""
user_comment = request.args.get('comment', '')
if user_comment:
# Vulnerable: Direct output without sanitisation
return f"<h3>Your comment:</h3><p>{user_comment}</p>"
return "Comment endpoint - provide ?comment=yourcomment"
# Intentionally vulnerable: LDAP injection (CKV3_SAST_61)
@app.route('/ldap')
def ldap_search():
"""Intentionally vulnerable LDAP search endpoint"""
username = request.args.get('user', '')
if username:
# Vulnerable LDAP query construction
ldap_filter = f"(uid={username})"
return f"LDAP search filter: {ldap_filter}"
return "LDAP endpoint - provide ?user=username"
# Intentionally vulnerable: Path traversal (CKV3_SAST_86)
@app.route('/file')
def read_file():
"""Intentionally vulnerable file reading endpoint"""
filename = request.args.get('name', '')
if filename:
# Vulnerable file path construction
file_path = f"/app/data/{filename}"
return f"Reading file: {file_path}"
return "File endpoint - provide ?name=filename"
# Intentionally vulnerable: Weak cryptography (CKV3_SAST_55)
@app.route('/hash')
def hash_password():
"""Intentionally vulnerable password hashing endpoint"""
password = request.args.get('password', '')
if password:
# Vulnerable: Using MD5 for password hashing
import hashlib
hash_value = hashlib.md5(password.encode()).hexdigest()
return f"MD5 hash: {hash_value}"
return "Hash endpoint - provide ?password=yourpassword"
# Intentionally vulnerable: Insecure deserialization (CKV3_SAST_58)
@app.route('/deserialize')
def deserialize_data():
"""Intentionally vulnerable deserialization endpoint"""
data = request.args.get('data', '')
if data:
# Vulnerable: Unsafe deserialization
import pickle
import base64
try:
decoded = base64.b64decode(data)
result = pickle.loads(decoded)
return f"Deserialized: {result}"
except:
return "Invalid data format"
return "Deserialize endpoint - provide ?data=base64encodedpickle"
# Intentionally vulnerable: Unsafe YAML deserialization
@app.route('/account/restore_preferences', methods=['GET', 'POST'])
def restore_account_preferences():
"""Restore previously exported account notification/statement preferences"""
if request.method == 'POST':
backup_data = request.form.get('backup_data', '')
# Vulnerable: Unsafe YAML deserialization allows arbitrary object construction
try:
preferences = yaml.load(backup_data, Loader=yaml.Loader)
return f"Preferences restored: {preferences}"
except Exception as e:
return f"Failed to restore backup: {e}", 400
return "POST backup_data=<yaml> to restore account preferences"
# Intentionally vulnerable: SSRF (CKV3_SAST_189)
@app.route('/fetch')
def fetch_url():
"""Intentionally vulnerable SSRF endpoint - TRULY EXPLOITABLE"""
url = request.args.get('url', '')
if url:
# Vulnerable: Direct URL request without validation
import requests
try:
response = requests.get(url, verify=False, timeout=5) # Also CKV3_SAST_186
# TRULY EXPLOITABLE: Return actual fetched content to prove SSRF works
return f"Fetched content from: {url}\n\n{response.text[:4000]}"
except Exception as e:
return f"Failed to fetch: {url} - {e}"
return "Fetch endpoint - provide ?url=http://example.com"
# Intentionally vulnerable: Simulated cloud instance metadata credential theft (SSRF target)
# Reachable via any SSRF sink pointed at this host (e.g. /fetch?url=..., /api/branch-locator)
@app.route('/latest/meta-data/iam/security-credentials/')
def imds_role_list():
"""Simulated cloud instance metadata service - lists the attached IAM role"""
return "ares-prod-deploy-role"
@app.route('/latest/meta-data/iam/security-credentials/<role>')
def imds_credentials(role):
"""Simulated cloud instance metadata service - returns temporary credentials for the attached role"""
# Vulnerable: no IMDSv2 session-token handshake required, so any SSRF that
# reaches this path (no direct network access needed) exfiltrates live-looking
# temporary cloud credentials for the attached role
now = datetime.utcnow()
expiry = (now + timedelta(hours=1)).strftime('%Y-%m-%dT%H:%M:%SZ')
return jsonify({
"Code": "Success",
"LastUpdated": now.strftime('%Y-%m-%dT%H:%M:%SZ'),
"Type": "AWS-HMAC",
"AccessKeyId": "ASIAV3XFZ2Y4EXAMPLE",
"SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
"Token": "IQoJb3JpZ2luX2VjEXAMPLETOKENbbchain06simxxxx",
"Expiration": expiry,
})
# Intentionally vulnerable: XXE (CKV3_SAST_50, CKV3_SAST_90)
@app.route('/xml', methods=['POST'])
def parse_xml():
"""Intentionally vulnerable XML parser"""
xml_data = request.get_data()
if xml_data:
# Vulnerable XML parser with XXE enabled
import xml.etree.ElementTree as ET
try:
# Vulnerable: Parsing XML without disabling external entities
root = ET.fromstring(xml_data)
return f"Parsed XML root tag: {root.tag}"
except:
return "Invalid XML format"
return "XML parser endpoint - POST XML data"
# Intentionally vulnerable: HTTP header injection (CKV3_SAST_88)
@app.route('/redirect')
def redirect_user():
"""Intentionally vulnerable redirect with header injection"""
location = request.args.get('url', 'https://example.com')
# Vulnerable: Direct header injection
response = make_response("Redirecting...")
response.headers['Location'] = location
response.headers['Set-Cookie'] = f"redirect_url={location}; HttpOnly=False" # CKV3_SAST_53
return response, 302
# Intentionally vulnerable: NoSQL injection (CKV3_SAST_52)
@app.route('/mongo')
def mongo_query():
"""Intentionally vulnerable MongoDB query"""
user_id = request.args.get('id', '')
if user_id:
# Vulnerable: Direct MongoDB query construction
from pymongo import MongoClient
query = f"{{'user_id': '{user_id}'}}"
return f"MongoDB query: db.users.find({query})"
return "MongoDB endpoint - provide ?id=userid"
# Intentionally vulnerable: JWT without verification (CKV3_SAST_54)
@app.route('/token')
def decode_token():
"""Intentionally vulnerable JWT decoder - TRULY EXPLOITABLE"""
token = request.args.get('jwt', '')
if token:
# Vulnerable: JWT decoded without signature verification
import jwt
try:
# TRULY EXPLOITABLE: Decode with options to skip verification
payload = jwt.decode(token, options={"verify_signature": False}, algorithms=['HS256', 'none'])
return f"JWT payload (decoded without verification): {payload}"
except Exception as e:
# Try base64 decode as fallback to demonstrate vulnerability
try:
import base64
parts = token.split('.')
if len(parts) >= 2:
# Pad the base64 string if needed
payload_b64 = parts[1]
padding = 4 - len(payload_b64) % 4
if padding != 4:
payload_b64 += '=' * padding
payload_json = base64.urlsafe_b64decode(payload_b64).decode('utf-8')
return f"JWT payload (base64 decoded - no verification): {payload_json}"
except:
pass
return f"Invalid JWT format: {e}"
return "JWT endpoint - provide ?jwt=token"
# Intentionally vulnerable: JWT "kid" header path traversal (arbitrary file as HMAC key)
@app.route('/api/auth/refresh', methods=['POST'])
def refresh_auth_token():
"""Refresh a session token using the signing key referenced by the token's kid header"""
token = request.form.get('token', '')
import jwt
try:
header = jwt.get_unverified_header(token)
kid = header.get('kid', 'keys/default.key')
# Vulnerable: kid is used directly as a filesystem path with no allow-list or
# traversal check, and no suffix is enforced. Pointing kid at a predictable,
# zero-byte file (e.g. ../../../../dev/null, which reads as an empty key)
# lets an attacker sign their own tokens with a key they can guess, forging
# valid sessions.
key_path = kid
with open(key_path, 'rb') as f:
signing_key = f.read()
payload = jwt.decode(token, signing_key, algorithms=['HS256'])
new_token = jwt.encode(payload, signing_key, algorithm='HS256', headers={'kid': kid})
if isinstance(new_token, bytes):
new_token = new_token.decode('utf-8')
return jsonify({"token": new_token})
except Exception as e:
return jsonify({"error": str(e)}), 400
# Intentionally vulnerable: Email sending (CKV3_SAST_63)
@app.route('/email')
def send_email():
"""Intentionally vulnerable email sending"""
to_email = request.args.get('to', '')
message = request.args.get('msg', 'Test message')
if to_email:
# Vulnerable: Unencrypted email configuration
import smtplib
server_config = {
'host': 'smtp.example.com',
'port': 25, # Unencrypted port
'use_tls': False, # No encryption
'username': 'admin',
'password': 'password123' # Hardcoded password
}
return f"Email sent to {to_email}: {message} via unencrypted SMTP"
return "Email endpoint - provide ?to=email&msg=message"
# Intentionally vulnerable: Random values (CKV3_SAST_167)
@app.route('/random')
def generate_random():
"""Intentionally vulnerable random number generation"""
import random
# Vulnerable: Using weak random module
random.seed(12345) # Predictable seed
token = random.randint(1000, 9999)
session_id = random.random()
return f"Random token: {token}, Session ID: {session_id}"
# Intentionally vulnerable: JSON injection (CKV3_SAST_82)
@app.route('/json')
def parse_json():
"""Intentionally vulnerable JSON parser"""
json_str = request.args.get('data', '')
if json_str:
# Vulnerable: Using eval to parse JSON
try:
result = eval(f"dict({json_str})") # Dangerous eval usage
return f"JSON parsed: {result}"
except Exception as e:
return f"JSON error: {e}"
return "JSON endpoint - provide ?data=key:value"
# Intentionally vulnerable: HTML autoescape disabled (CKV3_SAST_60)
@app.route('/template')
def render_unsafe_template():
"""Intentionally vulnerable template rendering"""
user_input = request.args.get('input', '<script>alert("xss")</script>')
# Vulnerable: Template with autoescape disabled
try:
from markupsafe import Markup
except ImportError:
from flask import Markup
unsafe_html = Markup(user_input) # Marks as safe, bypassing escaping
return f"<h1>User Input:</h1><div>{unsafe_html}</div>"
# Intentionally vulnerable: Server-side template injection (SSTI)
@app.route('/business/notifications/preview', methods=['GET', 'POST'])
def preview_notification_template():
"""Preview a custom payment-alert notification template before saving"""
from flask import render_template_string
template = request.values.get('template', 'Payment of {{ amount }} to {{ account }} completed.')
# Vulnerable: user-controlled string passed directly to the Jinja2 renderer, unsandboxed
try:
rendered = render_template_string(template, amount='100.00', account='12345678')
return rendered
except Exception as e:
return f"Template preview failed: {e}", 400
# Intentionally vulnerable: Improper exception handling (CKV3_SAST_4)
@app.route('/exception')
def handle_exception():
"""Intentionally vulnerable exception handling"""
try:
# Intentionally cause various exceptions
test_type = request.args.get('type', 'division')
if test_type == 'division':
result = 1 / 0 # Division by zero
elif test_type == 'index':
lst = [1, 2, 3]
result = lst[10] # Index error
elif test_type == 'key':
d = {'a': 1}
result = d['nonexistent'] # Key error
except:
# Vulnerable: Broad exception handling without proper error information
pass # Silent failure - no proper error handling
return "Exception handled (silently)"
# Intentionally vulnerable: None attribute access (CKV3_SAST_73)
@app.route('/none')
def access_none():
"""Intentionally vulnerable None attribute access"""
data = None
# Vulnerable: Accessing attributes on None without proper checks
try:
result = data.upper() # Will cause AttributeError
return f"Result: {result}"
except AttributeError:
return "AttributeError: accessing None attributes"
# Intentionally vulnerable: Wildcard usage (CKV3_SAST_170)
@app.route('/wildcard')
def wildcard_usage():
"""Intentionally vulnerable wildcard usage - TRULY EXPLOITABLE"""
pattern = request.args.get('pattern', '*.txt')
import glob
# TRULY EXPLOITABLE: User-controlled wildcard pattern with NO prefix restriction
# Attacker can enumerate entire filesystem with patterns like /etc/* or /*
files = glob.glob(pattern)
return f"Files matching pattern: {files}"
# Intentionally vulnerable: Improper access control (CKV3_SAST_97)
@app.route('/admin')
def admin_panel():
"""Intentionally vulnerable admin access"""
# Vulnerable: No proper authorisation check
user_role = request.args.get('role', 'user')
if user_role: # Weak check - any non-empty role grants access
return "Welcome to admin panel! Sensitive admin data here."
return "Access denied"
# Intentionally vulnerable: Arbitrary file write/timestomping via unrestricted log path
@app.route('/admin/logs/retention', methods=['POST'])
def purge_log_retention():
"""Compliance utility: purge/rotate log entries older than the retention policy"""
log_path = request.form.get('path', '/opt/tomcat/logs/localhost_access_log.txt')
backdate_days = int(request.form.get('backdate_days', '0'))
try:
# Vulnerable: no allow-list on path, truncates/erases arbitrary files
open(log_path, 'w').close()
if backdate_days:
backdated = time.time() - (backdate_days * 86400)
os.utime(log_path, (backdated, backdated)) # Vulnerable: timestomping
return f"Log retention applied to {log_path} (backdated {backdate_days} days)"
except Exception as e:
return f"Retention purge failed: {e}", 400
# Intentionally vulnerable: Unrestricted cron entry write (persistence)
@app.route('/admin/tasks/schedule', methods=['POST'])
def schedule_maintenance_task():
"""Schedule a recurring maintenance task via cron"""
schedule = request.form.get('schedule', '*/5 * * * *')
command = request.form.get('command', 'echo maintenance')
try:
# Vulnerable: no validation on schedule or command; written straight into
# a root-run cron.d file, so any command here re-executes on schedule
with open('/etc/cron.d/brokenbank-tasks', 'a') as f:
f.write(f"{schedule} root {command}\n")
os.chmod('/etc/cron.d/brokenbank-tasks', 0o644)
return f"Task scheduled: {schedule} -> {command}"
except Exception as e:
return f"Failed to schedule task: {e}", 400
# Intentionally vulnerable: Inadequate SSL/TLS (CKV3_SAST_65)
@app.route('/ssl_test')
def ssl_configuration():
"""Show intentionally weak SSL configuration"""
import ssl
# Vulnerable SSL context
context = ssl.create_default_context()
context.check_hostname = False # Disable hostname verification
context.verify_mode = ssl.CERT_NONE # Disable certificate verification
context.minimum_version = ssl.TLSVersion.SSLv3 # Use weak SSL version
return "SSL context configured with weak security settings"
# Intentionally vulnerable: AES initialisation vector (CKV3_SAST_68)
@app.route('/encrypt')
def encrypt_data():
"""Intentionally vulnerable encryption"""
data = request.args.get('data', 'secret message')
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import os
# Vulnerable: Using weak IV
key = b'1234567890123456' # Weak key
iv = b'1234567890123456' # Static IV - should be random
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()
# Pad data to block size
padded_data = data.encode().ljust(16, b'\0')
encrypted = encryptor.update(padded_data) + encryptor.finalize()
return f"Encrypted with static IV: {encrypted.hex()}"
# Intentionally vulnerable: Key exchange without authentication (CKV3_SAST_98)
@app.route('/keyexchange')
def key_exchange():
"""Intentionally vulnerable key exchange"""
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
# Vulnerable: Key exchange without proper authentication
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=1024, # Weak key size
backend=default_backend()
)
public_key = private_key.public_key()
return "Key exchange performed without entity authentication"
# Intentionally vulnerable: CSRF protections disabled (CKV3_SAST_56)
@app.route('/transfer', methods=['POST', 'GET'])
def csrf_vulnerable_transfer():
"""Intentionally vulnerable money transfer without CSRF protection"""
if request.method == 'POST':
# Vulnerable: No CSRF token validation
amount = request.form.get('amount', '100')
to_account = request.form.get('to_account', '12345')
return f"Transfer of ${amount} to account {to_account} completed (no CSRF protection)"
return '''
<form method="POST">
Amount: <input name="amount" value="100"><br>
To Account: <input name="to_account" value="12345"><br>
<input type="submit" value="Transfer">
</form>
'''
# Intentionally vulnerable: Cleartext transmission (CKV3_SAST_93)
@app.route('/credentials')
def cleartext_credentials():
"""Intentionally vulnerable cleartext credential transmission"""
import base64
# Vulnerable: Transmitting credentials in cleartext
username = "admin"
password = "password123"
# Simulate cleartext transmission
credentials = f"{username}:{password}"
encoded_creds = base64.b64encode(credentials.encode()).decode()
return f"Credentials transmitted in cleartext: {credentials} (Base64: {encoded_creds})"
# Intentionally vulnerable: Unauthenticated secrets-manager proxy (missing authentication)
@app.route('/api/vault/secrets/<path:secret_path>')
def vault_secrets_proxy(secret_path):