"""
SecureCodePairs - v1.0.0 curated dataset records.
Each record is hand-authored: realistic production-style code, distinct
vulnerable and secure implementations, and consistent security metadata.
No examples are duplicated or faked via variable renaming.
Schema fields:
id, language, framework, title, description,
owasp, owasp_api, owasp_llm, cwe, mitre_attack,
severity, difficulty, vulnerable_code, secure_code, patch,
root_cause, attack, impact, fix, guideline, tags, metadata
"""
RECORDS = [
# ------------------------------------------------------------------ PYTHON / FLASK ----------------------------------------------------------------
{
"id": "SCP-000001",
"language": "Python",
"framework": "Flask",
"title": "SQL Injection via string-formatted query",
"description": "A Flask route builds a SQL query by directly interpolating the request parameter into the statement, allowing attacker-controlled SQL.",
"owasp": "A03:2021 - Injection",
"owasp_api": "API3:2023 - Broken Object Property Level Authorization",
"owasp_llm": "",
"cwe": "CWE-89",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "High",
"difficulty": "Beginner",
"vulnerable_code": (
"from flask import Flask, request\n"
"import sqlite3\n\n"
"app = Flask(__name__)\n\n"
"@app.route('/user')\n"
"def get_user():\n"
" username = request.args.get('username')\n"
" conn = sqlite3.connect('app.db')\n"
" cur = conn.cursor()\n"
" # Vulnerable: direct interpolation\n"
" cur.execute(\"SELECT id, name FROM users WHERE name = '%s'\" % username)\n"
" return str(cur.fetchall())\n"
),
"secure_code": (
"from flask import Flask, request\n"
"import sqlite3\n\n"
"app = Flask(__name__)\n\n"
"@app.route('/user')\n"
"def get_user():\n"
" username = request.args.get('username', '')\n"
" if not username:\n"
" return 'missing username', 400\n"
" conn = sqlite3.connect('app.db')\n"
" cur = conn.cursor()\n"
" # Secure: parameterized query\n"
" cur.execute('SELECT id, name FROM users WHERE name = ?', (username,))\n"
" return str(cur.fetchall())\n"
),
"patch": (
"--- a/app.py\n"
"+++ b/app.py\n"
"@@ -8,6 +8,9 @@\n"
"- cur.execute(\"SELECT id, name FROM users WHERE name = '%s'\" % username)\n"
"+ if not username:\n"
"+ return 'missing username', 400\n"
"+ cur.execute('SELECT id, name FROM users WHERE name = ?', (username,))\n"
),
"root_cause": "User input is concatenated into the SQL string instead of being passed as a bound parameter.",
"attack": "Attacker supplies username=' OR '1'='1 to dump every row or '; DROP TABLE users;-- to destroy data.",
"impact": "Confidentiality and integrity loss: full database disclosure or destruction.",
"fix": "Use parameterized queries / prepared statements with placeholder binding so input is treated as data, never as SQL.",
"guideline": "Never build SQL by string formatting. Always use the driver's parameter binding API.",
"tags": ["sqli", "flask", "python", "sqlite"],
"metadata": {"domain": "REST API", "input_source": "query_param", "auth_required": False},
},
{
"id": "SCP-000002",
"language": "Python",
"framework": "Flask",
"title": "Reflected XSS via unescaped template variable",
"description": "A Flask handler returns user input directly into an HTML response without escaping, enabling reflected cross-site scripting.",
"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": (
"from flask import Flask, request\n\n"
"app = Flask(__name__)\n\n"
"@app.route('/greet')\n"
"def greet():\n"
" name = request.args.get('name', '')\n"
" # Vulnerable: raw HTML interpolation\n"
" return '
Hello ' + name + '
'\n"
),
"secure_code": (
"from flask import Flask, request, escape\n\n"
"app = Flask(__name__)\n\n"
"@app.route('/greet')\n"
"def greet():\n"
" name = request.args.get('name', '')\n"
" # Secure: HTML-escape user input\n"
" return 'Hello ' + escape(name) + '
'\n"
),
"patch": (
"--- a/app.py\n"
"+++ b/app.py\n"
"@@ -1,7 +1,7 @@\n"
"-from flask import Flask, request\n"
"+from flask import Flask, request, escape\n"
"@@ -6,4 +6,4 @@\n"
"- return 'Hello ' + name + '
'\n"
"+ return 'Hello ' + escape(name) + '
'\n"
),
"root_cause": "User-controlled data is embedded into HTML output without contextual output encoding.",
"attack": "Victim clicks a link like /greet?name= and the script runs in their session.",
"impact": "Session theft, account takeover, or actions performed in the victim's context.",
"fix": "Escape all untrusted data on output using the framework's escaping helpers or a templating engine with autoescaping.",
"guideline": "Escape on output, not input. Use autoescaping templates (Jinja2) instead of manual string building.",
"tags": ["xss", "flask", "python", "reflected"],
"metadata": {"domain": "REST API", "input_source": "query_param", "auth_required": False},
},
{
"id": "SCP-000003",
"language": "Python",
"framework": "Django",
"title": "Hardcoded secret in settings module",
"description": "A Django project commits a production secret key and database password directly into source code.",
"owasp": "A05:2021 - Security Misconfiguration",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-798",
"mitre_attack": "T1552.001 - Unsecured Credentials: Credentials In Files",
"severity": "High",
"difficulty": "Beginner",
"vulnerable_code": (
"# settings.py\n"
"SECRET_KEY = 'd9f8c2a1b7e6453f9a0c1d2e3f4a5b6c'\n"
"DATABASES = {\n"
" 'default': {\n"
" 'ENGINE': 'django.db.backends.postgresql',\n"
" 'NAME': 'prod',\n"
" 'USER': 'admin',\n"
" 'PASSWORD': 'Sup3rSecretPw!',\n"
" 'HOST': 'db.internal',\n"
" }\n"
"}\n"
),
"secure_code": (
"# settings.py\n"
"import os\n\n"
"SECRET_KEY = os.environ['DJANGO_SECRET_KEY']\n"
"DATABASES = {\n"
" 'default': {\n"
" 'ENGINE': 'django.db.backends.postgresql',\n"
" 'NAME': os.environ['DB_NAME'],\n"
" 'USER': os.environ['DB_USER'],\n"
" 'PASSWORD': os.environ['DB_PASSWORD'],\n"
" 'HOST': os.environ.get('DB_HOST', 'db.internal'),\n"
" }\n"
"}\n"
),
"patch": (
"--- a/settings.py\n"
"+++ b/settings.py\n"
"@@ -1,12 +1,12 @@\n"
"-SECRET_KEY = 'd9f8c2a1b7e6453f9a0c1d2e3f4a5b6c'\n"
"+import os\n"
"+SECRET_KEY = os.environ['DJANGO_SECRET_KEY']\n"
"- 'PASSWORD': 'Sup3rSecretPw!',\n"
"+ 'PASSWORD': os.environ['DB_PASSWORD'],\n"
),
"root_cause": "Credentials are embedded in source code instead of injected via environment or a secrets manager.",
"attack": "Anyone with repo access (including CI logs or a leaked .git) obtains production credentials.",
"impact": "Full compromise of the database and the ability to forge sessions via the secret key.",
"fix": "Load secrets from environment variables or a secrets manager; never commit them; rotate any leaked keys.",
"guideline": "Keep secrets out of VCS. Use 12-factor config and rotate credentials on suspected exposure.",
"tags": ["secrets", "django", "python", "config"],
"metadata": {"domain": "Backend", "input_source": "source_code", "auth_required": False},
},
{
"id": "SCP-000004",
"language": "Python",
"framework": "FastAPI",
"title": "Missing authentication on admin endpoint",
"description": "A FastAPI endpoint exposes administrative actions without any authentication dependency.",
"owasp": "A01:2021 - Broken Access Control",
"owasp_api": "API2:2023 - Broken Authentication",
"owasp_llm": "",
"cwe": "CWE-306",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "Critical",
"difficulty": "Beginner",
"vulnerable_code": (
"from fastapi import FastAPI\n\n"
"app = FastAPI()\n\n"
"@app.delete('/admin/users/{uid}')\n"
"def delete_user(uid: int):\n"
" # Vulnerable: no auth dependency\n"
" repository.remove_user(uid)\n"
" return {'deleted': uid}\n"
),
"secure_code": (
"from fastapi import FastAPI, Depends, HTTPException\n"
"from fastapi.security import HTTPBearer\n\n"
"app = FastAPI()\n"
"bearer = HTTPBearer()\n\n"
"def require_admin(token=Depends(bearer)):\n"
" claims = decode_token(token.credentials)\n"
" if not claims.get('role') == 'admin':\n"
" raise HTTPException(status_code=403, detail='forbidden')\n"
" return claims\n\n"
"@app.delete('/admin/users/{uid}')\n"
"def delete_user(uid: int, _=Depends(require_admin)):\n"
" repository.remove_user(uid)\n"
" return {'deleted': uid}\n"
),
"patch": (
"--- a/main.py\n"
"+++ b/main.py\n"
"@@ -1,8 +1,16 @@\n"
"+from fastapi import Depends, HTTPException\n"
"+from fastapi.security import HTTPBearer\n"
"+def require_admin(token=Depends(bearer)):\n"
"+ claims = decode_token(token.credentials)\n"
"+ if not claims.get('role') == 'admin':\n"
"+ raise HTTPException(status_code=403, detail='forbidden')\n"
"-def delete_user(uid: int):\n"
"+def delete_user(uid: int, _=Depends(require_admin)):\n"
),
"root_cause": "Authorization logic was never attached to the protected route.",
"attack": "Any unauthenticated caller hits DELETE /admin/users/1 and removes arbitrary accounts.",
"impact": "Privilege escalation to full administrative control and data loss.",
"fix": "Enforce authentication and role-based authorization via route dependencies or middleware.",
"guideline": "Deny by default. Every sensitive route must declare an auth dependency.",
"tags": ["auth", "authorization", "fastapi", "python"],
"metadata": {"domain": "REST API", "input_source": "path_param", "auth_required": True},
},
{
"id": "SCP-000005",
"language": "Python",
"framework": "FastAPI",
"title": "Insecure deserialization with pickle",
"description": "A service unpickles attacker-controlled bytes, enabling remote code execution.",
"owasp": "A08:2021 - Software and Data Integrity Failures",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-502",
"mitre_attack": "T1059 - Command and Scripting Interpreter",
"severity": "Critical",
"difficulty": "Intermediate",
"vulnerable_code": (
"import pickle\n"
"from fastapi import FastAPI, Request\n\n"
"app = FastAPI()\n\n"
"@app.post('/load')\n"
"async def load(req: Request):\n"
" data = await req.body()\n"
" # Vulnerable: unpickling untrusted data\n"
" obj = pickle.loads(data)\n"
" return {'ok': True, 'items': obj.get('items')}\n"
),
"secure_code": (
"import json\n"
"from fastapi import FastAPI, Request\n\n"
"app = FastAPI()\n\n"
"@app.post('/load')\n"
"async def load(req: Request):\n"
" # Secure: parse only structured, safe data\n"
" obj = await req.json()\n"
" items = obj.get('items', [])\n"
" if not isinstance(items, list):\n"
" return {'ok': False, 'error': 'bad shape'}, 400\n"
" return {'ok': True, 'items': items}\n"
),
"patch": (
"--- a/main.py\n"
"+++ b/main.py\n"
"@@ -1,12 +1,13 @@\n"
"-import pickle\n"
"+import json\n"
"- obj = pickle.loads(data)\n"
"+ obj = await req.json()\n"
"+ if not isinstance(obj.get('items', []), list):\n"
"+ return {'ok': False, 'error': 'bad shape'}, 400\n"
),
"root_cause": "pickle executes arbitrary code during deserialization; trusting it with external input is unsafe.",
"attack": "Attacker posts a crafted pickle payload that runs os.system('...') on load.",
"impact": "Full remote code execution on the server.",
"fix": "Replace pickle with a safe serialization format (JSON) and validate the resulting structure/schema.",
"guideline": "Never deserialize untrusted data with code-executing formats. Use JSON with schema validation.",
"tags": ["deserialization", "fastapi", "python", "rce"],
"metadata": {"domain": "REST API", "input_source": "request_body", "auth_required": False},
},
{
"id": "SCP-000006",
"language": "Python",
"framework": "Flask",
"title": "Command injection via os.system",
"description": "A Flask endpoint passes user input straight into a shell command.",
"owasp": "A03:2021 - Injection",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-78",
"mitre_attack": "T1059.004 - Command and Scripting Interpreter: Unix Shell",
"severity": "Critical",
"difficulty": "Beginner",
"vulnerable_code": (
"import os\n"
"from flask import Flask, request\n\n"
"app = Flask(__name__)\n\n"
"@app.post('/ping')\n"
"def ping():\n"
" host = request.form['host']\n"
" # Vulnerable: shell interpolation\n"
" os.system('ping -c 1 ' + host)\n"
" return 'done'\n"
),
"secure_code": (
"import subprocess\n"
"from flask import Flask, request\n\n"
"app = Flask(__name__)\n\n"
"@app.post('/ping')\n"
"def ping():\n"
" host = request.form.get('host', '')\n"
" if not _is_valid_hostname(host):\n"
" return 'invalid host', 400\n"
" # Secure: no shell, pass args as a list\n"
" subprocess.run(['ping', '-c', '1', host], timeout=5, check=False)\n"
" return 'done'\n\n"
"def _is_valid_hostname(h):\n"
" import re\n"
" return re.fullmatch(r'[A-Za-z0-9.\\-]{1,253}', h) is not None\n"
),
"patch": (
"--- a/app.py\n"
"+++ b/app.py\n"
"@@ -1,10 +1,17 @@\n"
"-import os\n"
"+import subprocess, re\n"
"- os.system('ping -c 1 ' + host)\n"
"+ if not re.fullmatch(r'[A-Za-z0-9.\\\\-]{1,253}', host):\n"
"+ return 'invalid host', 400\n"
"+ subprocess.run(['ping', '-c', '1', host], timeout=5, check=False)\n"
),
"root_cause": "Untrusted input is concatenated into a shell command and executed via a shell.",
"attack": "Attacker sends host=8.8.8.8; rm -rf / to execute arbitrary commands.",
"impact": "Remote code execution and full host compromise.",
"fix": "Avoid shells; use subprocess with a list of arguments and validate/whitelist input.",
"guideline": "Use argument lists (no shell=True) and validate input against a strict allowlist.",
"tags": ["command-injection", "flask", "python", "rce"],
"metadata": {"domain": "CLI tool", "input_source": "form_field", "auth_required": False},
},
{
"id": "SCP-000007",
"language": "Python",
"framework": "Django",
"title": "IDOR on invoice download",
"description": "A Django view returns an object purely by its numeric id without checking ownership.",
"owasp": "A01:2021 - Broken Access Control",
"owasp_api": "API1:2023 - Broken Object Level Authorization",
"owasp_llm": "",
"cwe": "CWE-639",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "High",
"difficulty": "Beginner",
"vulnerable_code": (
"from django.http import HttpResponse\n"
"from .models import Invoice\n\n"
"def download_invoice(request, invoice_id):\n"
" # Vulnerable: no ownership check\n"
" inv = Invoice.objects.get(pk=invoice_id)\n"
" return HttpResponse(inv.pdf, content_type='application/pdf')\n"
),
"secure_code": (
"from django.http import HttpResponse, Http404\n"
"from .models import Invoice\n\n"
"def download_invoice(request, invoice_id):\n"
" # Secure: scope to the authenticated user\n"
" try:\n"
" inv = Invoice.objects.get(pk=invoice_id, user=request.user)\n"
" except Invoice.DoesNotExist:\n"
" raise Http404\n"
" return HttpResponse(inv.pdf, content_type='application/pdf')\n"
),
"patch": (
"--- a/views.py\n"
"+++ b/views.py\n"
"@@ -3,6 +3,10 @@\n"
"- inv = Invoice.objects.get(pk=invoice_id)\n"
"+ try:\n"
"+ inv = Invoice.objects.get(pk=invoice_id, user=request.user)\n"
"+ except Invoice.DoesNotExist:\n"
"+ raise Http404\n"
),
"root_cause": "Object access is keyed only by an attacker-controllable identifier, not by caller ownership.",
"attack": "User changes invoice_id from 1001 to 1002 and downloads another customer's invoice.",
"impact": "Disclosure of other users' financial documents (PII, billing data).",
"fix": "Always scope database queries by the authenticated principal (user/tenant).",
"guideline": "Enforce object-level authorization on every record lookup.",
"tags": ["idor", "django", "python", "access-control"],
"metadata": {"domain": "E-commerce", "input_source": "path_param", "auth_required": True},
},
{
"id": "SCP-000008",
"language": "Python",
"framework": "Flask",
"title": "Weak cryptographic hash for passwords",
"description": "A Flask app stores passwords hashed with MD5 and no salt.",
"owasp": "A02:2021 - Cryptographic Failures",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-916",
"mitre_attack": "T1110 - Brute Force",
"severity": "High",
"difficulty": "Intermediate",
"vulnerable_code": (
"import hashlib\n"
"from flask import Flask, request\n\n"
"app = Flask(__name__)\n\n"
"@app.post('/register')\n"
"def register():\n"
" pw = request.form['password']\n"
" # Vulnerable: fast unsalted MD5\n"
" h = hashlib.md5(pw.encode()).hexdigest()\n"
" db.save(request.form['user'], h)\n"
" return 'ok'\n"
),
"secure_code": (
"from flask import Flask, request\n"
"from werkzeug.security import generate_password_hash\n\n"
"app = Flask(__name__)\n\n"
"@app.post('/register')\n"
"def register():\n"
" pw = request.form['password']\n"
" # Secure: adaptive, salted, slow hash\n"
" h = generate_password_hash(pw, method='scrypt', salt_length=16)\n"
" db.save(request.form['user'], h)\n"
" return 'ok'\n"
),
"patch": (
"--- a/app.py\n"
"+++ b/app.py\n"
"@@ -1,11 +1,11 @@\n"
"-import hashlib\n"
"+from werkzeug.security import generate_password_hash\n"
"- h = hashlib.md5(pw.encode()).hexdigest()\n"
"+ h = generate_password_hash(pw, method='scrypt', salt_length=16)\n"
),
"root_cause": "A fast, unsalted digest is used for password storage, enabling rainbow-table and brute-force attacks.",
"attack": "Attacker dumps the user table and cracks most passwords within minutes using GPUs/rainbow tables.",
"impact": "Mass account compromise, especially given password reuse.",
"fix": "Use a memory-hard, salted password hash (bcrypt, scrypt, Argon2) with a per-user random salt.",
"guideline": "Never roll your own password storage. Use Argon2id/bcrypt/scrypt via a vetted library.",
"tags": ["crypto", "flask", "python", "passwords"],
"metadata": {"domain": "Authentication systems", "input_source": "form_field", "auth_required": False},
},
# ------------------------------------------------------------------ JAVA / SPRING BOOT ----------------------------------------------------------------
{
"id": "SCP-000009",
"language": "Java",
"framework": "Spring Boot",
"title": "SQL injection in Spring Data JPA native query",
"description": "A Spring repository uses a concatenated native query with a request parameter.",
"owasp": "A03:2021 - Injection",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-89",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "High",
"difficulty": "Intermediate",
"vulnerable_code": (
"@Repository\n"
"public class UserRepository {\n"
" @Autowired\n"
" private JdbcTemplate jdbc;\n\n"
" public List