SecureCodePairs / scripts /data_ext5.py
ismailtasdelen's picture
Release v1.2.0: SecureCodePairs (470 code pairs + 30 LLM security trajectories)
2ef05ec verified
Raw
History Blame Contribute Delete
13.2 kB
#!/usr/bin/env python3
"""SecureCodePairs v1.2.0 extension records (part 5): Python deep pack (SCP-000211+).
Brings Python to a deep, varied pack. Every record is built with json-safe
helpers so there are no backslash-escape pitfalls in the source file.
"""
import json
from typing import List, Dict
L = [] # type: List[Dict]
def rec(**kw):
L.append(kw)
# 1. pickle.loads RCE
rec(id="SCP-000211", language="Python", framework="Flask",
title="Unsafe pickle load of user upload",
description="A Flask endpoint unpickles a client-supplied blob, enabling RCE.",
owasp="A08:2021 - Software and Data Integrity Failures", owasp_api="", owasp_llm="",
cwe="CWE-502", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="Critical", difficulty="Intermediate",
vulnerable_code='@app.route("/load", methods=["POST"])\ndef load():\n data = request.files["f"].read()\n obj = pickle.loads(data) # Vulnerable: RCE\n return jsonify(obj)',
secure_code='@app.route("/load", methods=["POST"])\ndef load():\n data = request.files["f"].read()\n obj = json.loads(data) # Secure: no code execution\n return jsonify(obj)',
patch='--- a/app.py\n+++ b/app.py\n@@ -1,4 +1,4 @@\n- obj = pickle.loads(data) # Vulnerable: RCE\n+ obj = json.loads(data) # Secure: no code execution',
root_cause="pickle.loads executes arbitrary code during deserialization.",
attack="Attacker uploads a pickle that runs os.system('...').",
impact="Remote code execution.", fix="Use JSON or signed, schema-validated formats.",
guideline="Never unpickle untrusted data.",
tags=["deserialization", "flask", "python", "rce"],
metadata={"domain": "E-commerce", "input_source": "form_field", "auth_required": False})
# 2. YAML full load
rec(id="SCP-000212", language="Python", framework="FastAPI",
title="YAML full load of untrusted config",
description="A FastAPI service parses uploaded YAML with yaml.load (full), enabling RCE.",
owasp="A08:2021 - Software and Data Integrity Failures", owasp_api="", owasp_llm="",
cwe="CWE-502", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="Critical", difficulty="Intermediate",
vulnerable_code='import yaml\ndef parse(body: bytes):\n return yaml.load(body) # Vulnerable: arbitrary object construction',
secure_code='import yaml\ndef parse(body: bytes):\n return yaml.safe_load(body) # Secure: no arbitrary objects',
patch='--- a/parse.py\n+++ b/parse.py\n@@ -1,3 +1,3 @@\n- return yaml.load(body)\n+ return yaml.safe_load(body)',
root_cause="yaml.load allows arbitrary Python object construction.",
attack="Upload YAML with !!python/object/apply to run code.",
impact="Remote code execution.", fix="Use yaml.safe_load.",
guideline="Use safe_load for untrusted YAML.",
tags=["deserialization", "fastapi", "python", "rce"],
metadata={"domain": "Microservices", "input_source": "request_body", "auth_required": False})
# 3. MD5 password hash
rec(id="SCP-000213", language="Python", framework="Flask",
title="Weak password hashing (md5)",
description="A Flask app stores MD5 password hashes without salt.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-916", mitre_attack="T1600 - Weaken Encryption",
severity="High", difficulty="Beginner",
vulnerable_code='import hashlib\ndef hash_pw(pw):\n return hashlib.md5(pw.encode()).hexdigest() # Vulnerable: fast + unsalted',
secure_code='import bcrypt\ndef hash_pw(pw):\n return bcrypt.hashpw(pw.encode(), bcrypt.gensalt()).decode() # Secure: slow + salt',
patch='--- a/auth.py\n+++ b/auth.py\n@@ -1,3 +1,3 @@\n- return hashlib.md5(pw.encode()).hexdigest()\n+ return bcrypt.hashpw(pw.encode(), bcrypt.gensalt()).decode()',
root_cause="MD5 is fast and unsalted; trivially cracked.",
attack="Rainbow tables / cracking recover passwords.",
impact="Credential compromise.", fix="Use bcrypt/argon2 with per-user salt.",
guideline="Hash passwords with slow, salted KDFs.",
tags=["crypto", "flask", "python", "passwords"],
metadata={"domain": "Authentication systems", "input_source": "request_body", "auth_required": False})
# 4. DEBUG=True prod
rec(id="SCP-000214", language="Python", framework="Django",
title="Django DEBUG=True in production",
description="A Django settings file enables DEBUG in production, leaking stack traces.",
owasp="A05:2021 - Security Misconfiguration", owasp_api="", owasp_llm="",
cwe="CWE-209", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="Medium", difficulty="Beginner",
vulnerable_code='DEBUG = True # Vulnerable: leaks tracebacks in prod',
secure_code='DEBUG = os.environ.get("DJANGO_DEBUG", "False") == "True" # Secure: off by default',
patch='--- a/settings.py\n+++ b/settings.py\n@@ -1,2 +1,2 @@\n-DEBUG = True\n+DEBUG = os.environ.get("DJANGO_DEBUG", "False") == "True"',
root_cause="DEBUG on in production exposes internals.",
attack="Trigger error to read settings and source.",
impact="Info disclosure.", fix="Default DEBUG off; enable per env.",
guideline="Never run DEBUG=True in production.",
tags=["config", "django", "python", "info-leak"],
metadata={"domain": "Backend", "input_source": "source_code", "auth_required": False})
# 5. Clickjacking middleware disabled
rec(id="SCP-000215", language="Python", framework="Django",
title="Clickjacking protection disabled",
description="A Django app removes the X-Frame-Options / clickjacking middleware.",
owasp="A05:2021 - Security Misconfiguration", owasp_api="", owasp_llm="",
cwe="CWE-1021", mitre_attack="T1185 - Browser Session Hijacking",
severity="Medium", difficulty="Beginner",
vulnerable_code='MIDDLEWARE = [m for m in MIDDLEWARE if "ClickjackingMiddleware" not in m] # Vulnerable',
secure_code='MIDDLEWARE = MIDDLEWARE + ["django.middleware.clickjacking.XFrameOptionsMiddleware"] # Secure',
patch='--- a/settings.py\n+++ b/settings.py\n@@ -1,3 +1,3 @@\n-MIDDLEWARE = [m for m in MIDDLEWARE if "ClickjackingMiddleware" not in m]\n+MIDDLEWARE = MIDDLEWARE + ["django.middleware.clickjacking.XFrameOptionsMiddleware"]',
root_cause="Clickjacking middleware removed.",
attack="Frame the page to trick clicks.",
impact="UI redress.", fix="Keep X-Frame-Options middleware; set DENY/SAMEORIGIN.",
guideline="Enable clickjacking protection.",
tags=["clickjacking", "django", "python", "config"],
metadata={"domain": "E-commerce", "input_source": "source_code", "auth_required": False})
# 6. Reflected XSS via flash
rec(id="SCP-000216", language="Python", framework="Flask",
title="Reflected XSS via flash message",
description="A Flask route renders a flash message containing user input without escaping.",
owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
cwe="CWE-79", mitre_attack="T1059.007 - Command and Scripting Interpreter: JavaScript",
severity="Medium", difficulty="Beginner",
vulnerable_code='flash("Hello " + request.args.get("name")) # Vulnerable: reflected\nreturn render_template("hi.html")',
secure_code='name = escape(request.args.get("name", "")) # Secure: escape\nflash("Hello " + name)\nreturn render_template("hi.html")',
patch='--- a/views.py\n+++ b/views.py\n@@ -1,4 +1,5 @@\n-flash("Hello " + request.args.get("name"))\n+name = escape(request.args.get("name", ""))\n+flash("Hello " + name)\n return render_template("hi.html")',
root_cause="User input echoed into flash without escaping.",
attack="name=<script>steal()</script> executes.",
impact="XSS.", fix="Escape on output; rely on autoescaping.",
guideline="Escape user input in messages.",
tags=["xss", "flask", "python", "injection"],
metadata={"domain": "E-commerce", "input_source": "query_param", "auth_required": False})
# 7. Missing admin dependency (authz bypass)
rec(id="SCP-000217", language="Python", framework="FastAPI",
title="Missing dependency in admin router (authz bypass)",
description="A FastAPI admin route omits the admin-role dependency.",
owasp="A01:2021 - Broken Access Control", owasp_api="API1:2023 - Broken Object Level Authorization", owasp_llm="",
cwe="CWE-862", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="Critical", difficulty="Advanced",
vulnerable_code='@app.delete("/admin/user/{uid}")\nasync def delete(uid: int): # Vulnerable: no admin check\n repo.remove(uid)',
secure_code='@app.delete("/admin/user/{uid}")\nasync def delete(uid: int, admin: AdminUser = Depends(require_admin)): # Secure\n repo.remove(uid)',
patch='--- a/admin.py\n+++ b/admin.py\n@@ -1,4 +1,5 @@\n-async def delete(uid: int):\n+async def delete(uid: int, admin: AdminUser = Depends(require_admin)):\n repo.remove(uid)',
root_cause="Admin dependency missing on destructive route.",
attack="Unauthenticated admin action.",
impact="Privilege escalation.", fix="Attach role dependency.",
guideline="Always enforce admin deps on admin routes.",
tags=["authorization", "fastapi", "python", "broken-access-control"],
metadata={"domain": "Authentication systems", "input_source": "path_param", "auth_required": True})
# 8. Hardcoded SECRET_KEY
rec(id="SCP-000218", language="Python", framework="Django",
title="Hardcoded secret key",
description="A Django project hardcodes SECRET_KEY in settings.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-798", mitre_attack="T1552.001 - Unsecured Credentials: Credentials In Files",
severity="High", difficulty="Beginner",
vulnerable_code='SECRET_KEY = "django-insecure-abc123" # Vulnerable',
secure_code='SECRET_KEY = os.environ["DJANGO_SECRET_KEY"] # Secure: from env/secret',
patch='--- a/settings.py\n+++ b/settings.py\n@@ -1,2 +1,2 @@\n-SECRET_KEY = "django-insecure-abc123"\n+SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]',
root_cause="Secret in source.",
attack="Forge sessions/signed cookies.",
impact="Auth bypass.", fix="Load from env/secret manager.",
guideline="Externalize SECRET_KEY.",
tags=["secrets", "django", "python", "config"],
metadata={"domain": "Backend", "input_source": "source_code", "auth_required": False})
# 9. subprocess shell injection
rec(id="SCP-000219", language="Python", framework="Flask",
title="Command injection in subprocess",
description="A Flask route passes user input to a shell via os.popen.",
owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
cwe="CWE-78", mitre_attack="T1059 - Command and Scripting Interpreter",
severity="High", difficulty="Beginner",
vulnerable_code='@app.route("/ping")\ndef ping():\n host = request.args.get("host")\n out = os.popen("ping -c1 " + host).read() # Vulnerable',
secure_code='@app.route("/ping")\ndef ping():\n host = request.args.get("host", "")\n if not re.match(r"^[\\w.-]+$", host): return abort(400) # Secure: validate\n out = subprocess.run(["ping", "-c1", host], capture_output=True).stdout',
patch='--- a/ping.py\n+++ b/ping.py\n@@ -1,6 +1,7 @@\n- out = os.popen("ping -c1 " + host).read()\n+ if not re.match(r"^[\\w.-]+$", host): return abort(400)\n+ out = subprocess.run(["ping", "-c1", host], capture_output=True).stdout',
root_cause="Shell string concatenation with user input.",
attack="host=1.2.3.4;cat /etc/passwd executes.",
impact="Command injection / RCE.", fix="Use argument list; validate input.",
guideline="Avoid shell; pass arg arrays.",
tags=["command-injection", "flask", "python", "rce"],
metadata={"domain": "IoT", "input_source": "query_param", "auth_required": False})
# 10. Open redirect via next param
rec(id="SCP-000220", language="Python", framework="FastAPI",
title="Open redirect via next param",
description="A FastAPI login redirects to a next parameter without validation.",
owasp="A01:2021 - Broken Access Control", owasp_api="", owasp_llm="",
cwe="CWE-601", mitre_attack="T1566 - Phishing",
severity="Medium", difficulty="Beginner",
vulnerable_code='@app.get("/login")\nasync def login(next: str = ""):\n return RedirectResponse(next or "/") # Vulnerable',
secure_code='@app.get("/login")\nasync def login(next: str = ""):\n if next and next.startswith("/") and not next.startswith("//"): # Secure\n return RedirectResponse(next)\n return RedirectResponse("/")',
patch='--- a/login.py\n+++ b/login.py\n@@ -1,4 +1,6 @@\n- return RedirectResponse(next or "/")\n+ if next and next.startswith("/") and not next.startswith("//"):\n+ return RedirectResponse(next)\n+ return RedirectResponse("/")',
root_cause="Unvalidated next redirect.",
attack="next=//evil.com phishing.",
impact="Phishing.", fix="Allowlist relative paths.",
guideline="Validate next redirects.",
tags=["open-redirect", "fastapi", "python", "phishing"],
metadata={"domain": "Authentication systems", "input_source": "query_param", "auth_required": False})
RECORDS_EXT5 = L