File size: 51,246 Bytes
2ef05ec | 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 | #!/usr/bin/env python3
"""SecureCodePairs v1.2.0 extension (part 10): domain deepen (SCP-000431+)."""
from typing import List, Dict
L: List[Dict] = []
def rec(**kw):
L.append(kw)
rec(id="SCP-000431", language="Python", framework="FastAPI", title="FHIR Patient IDOR", description="FastAPI FHIR server returns Patient by id without tenant scoping.", owasp="A01:2021 - Broken Access Control", owasp_api="API1:2023 - BOLA", owasp_llm="", cwe="CWE-639", mitre_attack="T1190", severity="High", difficulty="Intermediate", vulnerable_code="@app.get(\"/fhir/Patient/{pid}\")\nasync def get_p(pid: str):\n return repo.get_patient(pid) # no tenant", secure_code="@app.get(\"/fhir/Patient/{pid}\")\nasync def get_p(pid: str, ctx: Tenant = Depends(tenant)):\n return repo.get_patient_for(pid, ctx.tenant_id) # scoped", patch="--- a/fhir.py\n+++ b/fhir.py\n@@ -1,3 +1,4 @@\n-async def get_p(pid: str):\n- return repo.get_patient(pid)\n+async def get_p(pid: str, ctx: Tenant = Depends(tenant)):\n+ return repo.get_patient_for(pid, ctx.tenant_id)", root_cause="No tenant scoping on PHI read.", attack="Enumerate other tenants' patients.", impact="PHI disclosure (HIPAA).", fix="Scope reads by tenant.", guideline="Authorize PHI reads by tenant.", tags=['idor', 'fhir', 'healthcare', 'phi'], metadata={'auth_required': True, 'domain': 'Healthcare', 'input_source': 'path_param'})
rec(id="SCP-000432", language="Python", framework="Flask", title="eval on FHIR observation value", description="Flask FHIR endpoint evals a coded value from the request.", owasp="A03:2021 - Injection", owasp_api="", owasp_llm="", cwe="CWE-95", mitre_attack="T1059", severity="Critical", difficulty="Advanced", vulnerable_code="@app.route(\"/calc\", methods=[\"POST\"])\ndef calc():\n return str(eval(request.json[\"expr\"])) # RCE", secure_code="@app.route(\"/calc\", methods=[\"POST\"])\ndef calc():\n return str(safe_calc(request.json[\"expr\"])) # sandboxed parser", patch="--- a/calc.py\n+++ b/calc.py\n@@ -1,3 +1,3 @@\n- return str(eval(request.json[\"expr\"]))\n+ return str(safe_calc(request.json[\"expr\"]))", root_cause="eval on user expression.", attack="expr=__import__('os').system('...')", impact="Remote code execution.", fix="Use a safe expression parser.", guideline="Never eval user input.", tags=['injection', 'eval', 'healthcare', 'rce'], metadata={'auth_required': False, 'domain': 'Healthcare', 'input_source': 'request_body'})
rec(id="SCP-000433", language="Python", framework="Django", title="PHI logged in plaintext", description="Django view logs full patient payload including PHI.", owasp="A09:2021 - Logging Failures", owasp_api="", owasp_llm="", cwe="CWE-532", mitre_attack="T1552", severity="Medium", difficulty="Beginner", vulnerable_code="logger.info(\"patient=%s\", patient.full_record()) # PHI in logs", secure_code="logger.info(\"patient_id=%s\", patient.id) # no PHI", patch="--- a/views.py\n+++ b/views.py\n@@ -1,2 +1,2 @@\n-logger.info(\"patient=%s\", patient.full_record())\n+logger.info(\"patient_id=%s\", patient.id)", root_cause="PHI in logs.", attack="Log access reveals PHI.", impact="HIPAA violation.", fix="Log identifiers only.", guideline="Redact PHI in logs.", tags=['logging', 'phi', 'healthcare', 'hipaa'], metadata={'auth_required': False, 'domain': 'Healthcare', 'input_source': 'server'})
rec(id="SCP-000434", language="Java", framework="Spring Boot", title="FHIR transaction without authz", description="Spring FHIR endpoint accepts bundle transactions without role check.", owasp="A01:2021 - Broken Access Control", owasp_api="API1:2023 - BOLA", owasp_llm="", cwe="CWE-862", mitre_attack="T1190", severity="Critical", difficulty="Advanced", vulnerable_code="@PostMapping(\"/fhir\")\npublic Bundle transaction(@RequestBody Bundle b) {\n return svc.process(b);\n}", secure_code="@PreAuthorize(\"hasRole('CLINICIAN')\")\n@PostMapping(\"/fhir\")\npublic Bundle transaction(@RequestBody Bundle b) {\n return svc.process(b);\n}", patch="--- a/FhirCtrl.java\n+++ b/FhirCtrl.java\n@@ -1,3 +1,4 @@\n+@PreAuthorize(\"hasRole('CLINICIAN')\")\n @PostMapping(\"/fhir\")\n public Bundle transaction(@RequestBody Bundle b) {\n return svc.process(b);\n }", root_cause="No role on FHIR transaction.", attack="Unauthenticated PHI mutation.", impact="PHI breach.", fix="Enforce clinician role.", guideline="Authorize FHIR writes.", tags=['authorization', 'fhir', 'healthcare', 'broken-access-control'], metadata={'auth_required': True, 'domain': 'Healthcare', 'input_source': 'request_body'})
rec(id="SCP-000435", language="Python", framework="FastAPI", title="Lab result IDOR", description="Lab result endpoint returns by id without ownership.", owasp="A01:2021 - Broken Access Control", owasp_api="API1:2023 - BOLA", owasp_llm="", cwe="CWE-639", mitre_attack="T1190", severity="High", difficulty="Beginner", vulnerable_code="@app.get(\"/lab/{lid}\")\nasync def lab(lid: str):\n return repo.lab(lid) # no owner", secure_code="@app.get(\"/lab/{lid}\")\nasync def lab(lid: str, u: User = Depends(current)):\n return repo.lab_for(lid, u.id) # scoped", patch="--- a/lab.py\n+++ b/lab.py\n@@ -1,3 +1,4 @@\n-async def lab(lid: str):\n- return repo.lab(lid)\n+async def lab(lid: str, u: User = Depends(current)):\n+ return repo.lab_for(lid, u.id)", root_cause="No ownership scoping.", attack="Read others lab results.", impact="PHI disclosure.", fix="Scope by owner.", guideline="Authorize reads by owner.", tags=['idor', 'healthcare', 'phi', 'access-control'], metadata={'auth_required': True, 'domain': 'Healthcare', 'input_source': 'path_param'})
rec(id="SCP-000436", language="Go", framework="Gin", title="Race condition on balance", description="Transfer handler updates balance without locking.", owasp="A04:2021 - Insecure Design", owasp_api="API3:2023", owasp_llm="", cwe="CWE-362", mitre_attack="T1190", severity="High", difficulty="Advanced", vulnerable_code="acc.Balance -= amt // concurrent double-spend", secure_code="tx := db.Begin(); defer tx.Rollback()\ntx.Model(&acc).Where(\"balance >= ?\", amt).\n Update(\"balance\", gorm.Expr(\"balance - ?\", amt))\ntx.Commit() // atomic", patch="--- a/transfer.go\n+++ b/transfer.go\n@@ -1,2 +1,5 @@\n-acc.Balance -= amt\n+tx := db.Begin(); defer tx.Rollback()\n+tx.Model(&acc).Where(\"balance >= ?\", amt).\n+ Update(\"balance\", gorm.Expr(\"balance - ?\", amt))\n+tx.Commit()", root_cause="Unlocked shared mutation.", attack="Double-spend via concurrent requests.", impact="Financial loss.", fix="Use DB transactions.", guideline="Protect financial state.", tags=['race-condition', 'fintech', 'banking', 'concurrency'], metadata={'auth_required': True, 'domain': 'Banking', 'input_source': 'request_body'})
rec(id="SCP-000437", language="Go", framework="Gin", title="No idempotency on payment", description="Payment endpoint lacks an idempotency key, allowing duplicate charges.", owasp="A04:2021 - Insecure Design", owasp_api="API3:2023", owasp_llm="", cwe="CWE-840", mitre_attack="T1190", severity="High", difficulty="Intermediate", vulnerable_code="func pay(c *gin.Context) {\n repo.Charge(req)\n}", secure_code="func pay(c *gin.Context) {\n key := c.GetHeader(\"Idempotency-Key\")\n if seen(key) { c.JSON(200, prior); return }\n repo.Charge(req); markSeen(key)\n}", patch="--- a/pay.go\n+++ b/pay.go\n@@ -1,2 +1,4 @@\n-func pay(c *gin.Context) { repo.Charge(req) }\n+key := c.GetHeader(\"Idempotency-Key\")\n+if seen(key) { c.JSON(200, prior); return }\n+repo.Charge(req); markSeen(key)", root_cause="No idempotency.", attack="Replay request to double-charge.", impact="Financial loss.", fix="Require idempotency key.", guideline="Make payments idempotent.", tags=['business-logic', 'fintech', 'banking', 'idempotency'], metadata={'auth_required': True, 'domain': 'Banking', 'input_source': 'request_body'})
rec(id="SCP-000438", language="Python", framework="Flask", title="Hardcoded Stripe key", description="Fintech app hardcodes a Stripe secret key.", owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="", cwe="CWE-798", mitre_attack="T1552.001", severity="Critical", difficulty="Beginner", vulnerable_code="stripe.api_key = \"sk_live_51Hx9fKe2mN\" # Vulnerable", secure_code="stripe.api_key = os.environ[\"STRIPE_SECRET_KEY\"] # env", patch="--- a/payments.py\n+++ b/payments.py\n@@ -1,2 +1,2 @@\n-stripe.api_key = \"sk_live_51Hx9fKe2mN\"\n+stripe.api_key = os.environ[\"STRIPE_SECRET_KEY\"]", root_cause="Secret in source.", attack="Charge cards / read transactions.", impact="Payment fraud.", fix="Use env/secret manager.", guideline="Externalize payment keys.", tags=['secrets', 'fintech', 'banking', 'config'], metadata={'auth_required': False, 'domain': 'Banking', 'input_source': 'source_code'})
rec(id="SCP-000439", language="Java", framework="Spring Boot", title="SQLi in ledger query", description="Spring ledger query concatenates account id.", owasp="A03:2021 - Injection", owasp_api="", owasp_llm="", cwe="CWE-89", mitre_attack="T1190", severity="High", difficulty="Intermediate", vulnerable_code="String q = \"SELECT * FROM ledger WHERE acct='\" + acct + \"'\";", secure_code="String q = \"SELECT * FROM ledger WHERE acct = ?\";\nps.setString(1, acct); // bound", patch="--- a/Ledger.java\n+++ b/Ledger.java\n@@ -1,3 +1,4 @@\n-String q = \"SELECT * FROM ledger WHERE acct='\" + acct + \"'\";\n+String q = \"SELECT * FROM ledger WHERE acct = ?\";\n+ps.setString(1, acct);", root_cause="String concat into SQL.", attack="acct=' OR 1=1 leaks ledger.", impact="Financial data disclosure.", fix="Use bound parameters.", guideline="Bind all SQL params.", tags=['sqli', 'fintech', 'banking', 'injection'], metadata={'auth_required': False, 'domain': 'Banking', 'input_source': 'query_param'})
rec(id="SCP-000440", language="JavaScript", framework="Node.js", title="Prototype pollution in config merge", description="Node fintech service deep-merges untrusted config.", owasp="A08:2021 - Integrity Failures", owasp_api="", owasp_llm="", cwe="CWE-1321", mitre_attack="T1190", severity="High", difficulty="Advanced", vulnerable_code="const cfg = _.merge(base, JSON.parse(req.body.config));", secure_code="const cfg = JSON.parse(req.body.config);\nconst safe = JSON.parse(JSON.stringify(cfg)); // no proto keys", patch="--- a/config.js\n+++ b/config.js\n@@ -1,2 +1,3 @@\n-const cfg = _.merge(base, JSON.parse(req.body.config));\n+const cfg = JSON.parse(req.body.config);\n+const safe = JSON.parse(JSON.stringify(cfg));", root_cause="Untrusted deep merge.", attack="config={__proto__:{isAdmin:True}}", impact="Privilege escalation.", fix="Avoid recursive merge of untrusted.", guideline="Sanitize proto keys.", tags=['prototype-pollution', 'fintech', 'node', 'injection'], metadata={'auth_required': False, 'domain': 'Banking', 'input_source': 'request_body'})
rec(id="SCP-000441", language="TypeScript", framework="NestJS", title="No rate limit on login", description="NestJS auth controller has no throttle.", owasp="A07:2021 - Auth Failures", owasp_api="API4:2023", owasp_llm="", cwe="CWE-307", mitre_attack="T1110", severity="Medium", difficulty="Beginner", vulnerable_code="@Post(\"login\")\nasync login(d: LoginDto) { return this.auth.login(d); }", secure_code="@UseGuards(ThrottlerGuard)\n@Throttle(5, 60)\n@Post(\"login\")\nasync login(d: LoginDto) { return this.auth.login(d); }", patch="--- a/auth.controller.ts\n+++ b/auth.controller.ts\n@@ -1,4 +1,5 @@\n+@UseGuards(ThrottlerGuard)\n+@Throttle(5, 60)\n @Post(\"login\")\n async login(d: LoginDto) { return this.auth.login(d); }", root_cause="No throttle on auth.", attack="Brute force credentials.", impact="Account takeover.", fix="Throttle login.", guideline="Rate limit auth.", tags=['rate-limiting', 'nestjs', 'typescript', 'auth'], metadata={'auth_required': False, 'domain': 'Authentication systems', 'input_source': 'request_body'})
rec(id="SCP-000442", language="TypeScript", framework="Express", title="XSS via innerHTML", description="Express handler sets innerHTML with user input.", owasp="A03:2021 - Injection", owasp_api="", owasp_llm="", cwe="CWE-79", mitre_attack="T1059.007", severity="Medium", difficulty="Beginner", vulnerable_code="res.render(\"post\", { html: req.query.c }); // view: el.innerHTML = html", secure_code="res.render(\"post\", { text: req.query.c }); // view: el.textContent = text", patch="--- a/post.ts\n+++ b/post.ts\n@@ -1,3 +1,3 @@\n-res.render(\"post\", { html: req.query.c });\n+res.render(\"post\", { text: req.query.c });", root_cause="innerHTML with user input.", attack="c=<script>steal()</script> runs.", impact="XSS.", fix="Use textContent.", guideline="Avoid innerHTML on user input.", tags=['xss', 'express', 'typescript', 'template'], metadata={'auth_required': False, 'domain': 'E-commerce', 'input_source': 'query_param'})
rec(id="SCP-000443", language="JavaScript", framework="Next.js", title="Server action SQL injection", description="Next.js server action builds a query by concatenation.", owasp="A03:2021 - Injection", owasp_api="", owasp_llm="", cwe="CWE-89", mitre_attack="T1190", severity="High", difficulty="Intermediate", vulnerable_code="'use server';\nexport async function search(q) {\n return db.query(`SELECT * FROM p WHERE name = '${q}'`);\n}", secure_code="'use server';\nexport async function search(q) {\n return db.query('SELECT * FROM p WHERE name = $1', [q]);\n}", patch="--- a/actions.ts\n+++ b/actions.ts\n@@ -1,4 +1,4 @@\n-export async function search(q) {\n- return db.query(`SELECT * FROM p WHERE name = '${q}'`);\n+export async function search(q) {\n+ return db.query('SELECT * FROM p WHERE name = $1', [q]);", root_cause="Template literal into SQL.", attack="q=' OR 1=1 dumps rows.", impact="Data disclosure.", fix="Use bound parameters.", guideline="Bind all SQL params.", tags=['sqli', 'nextjs', 'javascript', 'injection'], metadata={'auth_required': False, 'domain': 'E-commerce', 'input_source': 'form_field'})
rec(id="SCP-000444", language="PHP", framework="Laravel", title="IDOR on document", description="Laravel document route returns by id without owner check.", owasp="A01:2021 - Broken Access Control", owasp_api="API1:2023 - BOLA", owasp_llm="", cwe="CWE-639", mitre_attack="T1190", severity="High", difficulty="Beginner", vulnerable_code="$doc = Document::find($id);\nreturn response()->file($doc->path); // no owner", secure_code="$doc = Document::where(\"id\", $id)\n ->where(\"user_id\", auth()->id())->firstOrFail();\nreturn response()->file($doc->path); // scoped", patch="--- a/DocsController.php\n+++ b/DocsController.php\n@@ -1,3 +1,4 @@\n-$doc = Document::find($id);\n-return response()->file($doc->path);\n+$doc = Document::where(\"id\", $id)\n+ ->where(\"user_id\", auth()->id())->firstOrFail();\n+return response()->file($doc->path);", root_cause="No ownership scoping.", attack="Enumerate others documents.", impact="PII disclosure.", fix="Scope by owner.", guideline="Authorize reads by owner.", tags=['idor', 'laravel', 'php', 'access-control'], metadata={'auth_required': True, 'domain': 'E-commerce', 'input_source': 'path_param'})
rec(id="SCP-000445", language="Ruby", framework="Rails", title="Weak JWT secret in Rails", description="Rails API uses a short, guessable JWT secret.", owasp="A07:2021 - Auth Failures", owasp_api="API2:2023", owasp_llm="", cwe="CWE-345", mitre_attack="T1600", severity="Critical", difficulty="Advanced", vulnerable_code="secret = \"secret123\" # brute-forceable", secure_code="secret = ENV[\"JWT_SECRET\"] # 32+ random bytes", patch="--- a/initializers/jwt.rb\n+++ b/initializers/jwt.rb\n@@ -1,2 +1,2 @@\n-secret = \"secret123\"\n+secret = ENV[\"JWT_SECRET\"]", root_cause="Weak JWT secret.", attack="Brute-force / crack signature.", impact="Auth bypass.", fix="Use strong random secret.", guideline="Long random JWT secret.", tags=['jwt', 'rails', 'ruby', 'auth'], metadata={'auth_required': True, 'domain': 'Authentication systems', 'input_source': 'server'})
rec(id="SCP-000446", language="C#", framework="ASP.NET Core", title="Open redirect", description="ReturnUrl param used directly in a redirect.", owasp="A01:2021 - Broken Access Control", owasp_api="", owasp_llm="", cwe="CWE-601", mitre_attack="T1566", severity="Medium", difficulty="Beginner", vulnerable_code="return LocalRedirect(returnUrl); // not local", secure_code="if (Url.IsLocalUrl(returnUrl))\n return LocalRedirect(returnUrl);\nreturn RedirectToAction(\"Index\");", patch="--- a/AccountController.cs\n+++ b/AccountController.cs\n@@ -1,3 +1,4 @@\n-return LocalRedirect(returnUrl);\n+if (Url.IsLocalUrl(returnUrl))\n+ return LocalRedirect(returnUrl);\n+return RedirectToAction(\"Index\");", root_cause="Unvalidated redirect.", attack="returnUrl=//evil.com phishing.", impact="Phishing.", fix="Use IsLocalUrl.", guideline="Validate redirects.", tags=['open-redirect', 'csharp', 'aspnet', 'phishing'], metadata={'auth_required': False, 'domain': 'Authentication systems', 'input_source': 'query_param'})
rec(id="SCP-000447", language="Go", framework="Gin", title="Verbose error in response", description="Handler returns raw error strings.", owasp="A05:2021 - Misconfiguration", owasp_api="", owasp_llm="", cwe="CWE-209", mitre_attack="T1190", severity="Low", difficulty="Beginner", vulnerable_code="c.JSON(500, gin.H{\"error\": err.Error()})", secure_code="c.JSON(500, gin.H{\"error\": \"internal_error\"})\nlog.Printf(\"err: %v\", err)", patch="--- a/handler.go\n+++ b/handler.go\n@@ -1,2 +1,2 @@\n-c.JSON(500, gin.H{\"error\": err.Error()})\n+c.JSON(500, gin.H{\"error\": \"internal_error\"})\n+log.Printf(\"err: %v\", err)", root_cause="Raw error to client.", attack="Extract stack/paths.", impact="Info disclosure.", fix="Generic errors to client.", guideline="Log detailed, return generic.", tags=['info-leak', 'go', 'gin', 'error-handling'], metadata={'auth_required': False, 'domain': 'Backend', 'input_source': 'server'})
rec(id="SCP-000448", language="Rust", framework="Actix", title="Insecure deserialization", description="Actix handler decodes untrusted bytes with a deserializer.", owasp="A08:2021 - Integrity Failures", owasp_api="", owasp_llm="", cwe="CWE-502", mitre_attack="T1190", severity="Medium", difficulty="Advanced", vulnerable_code="let v: MyStruct = ron::de::from_bytes(&body)?;", secure_code="let v: MyStruct = serde_json::from_slice(&body)?; // strict schema", patch="--- a/handler.rs\n+++ b/handler.rs\n@@ -1,2 +1,2 @@\n-let v: MyStruct = ron::de::from_bytes(&body)?;\n+let v: MyStruct = serde_json::from_slice(&body)?;", root_cause="Deserializing untrusted bytes.", attack="Craft malicious payload.", impact="Logic abuse / RCE.", fix="Use strict schema deserializer.", guideline="Validate deserialized data.", tags=['deserialization', 'rust', 'actix', 'injection'], metadata={'auth_required': False, 'domain': 'Microservices', 'input_source': 'request_body'})
rec(id="SCP-000449", language="Scala", framework="Play", title="No rate limit on login", description="Play login has no throttling.", owasp="A07:2021 - Auth Failures", owasp_api="API4:2023", owasp_llm="", cwe="CWE-307", mitre_attack="T1110", severity="Medium", difficulty="Beginner", vulnerable_code="def login = Action { req => auth(...) }", secure_code="def login = RateLimitAction(5, 1.minute) { req => auth(...) }", patch="--- a/Auth.scala\n+++ b/Auth.scala\n@@ -1,2 +1,2 @@\n-def login = Action { req => auth(...) }\n+def login = RateLimitAction(5, 1.minute) { req => auth(...) }", root_cause="No throttle on auth.", attack="Brute force credentials.", impact="Account takeover.", fix="Rate limit login.", guideline="Throttle auth endpoints.", tags=['rate-limiting', 'scala', 'play', 'auth'], metadata={'auth_required': False, 'domain': 'Authentication systems', 'input_source': 'request_body'})
rec(id="SCP-000450", language="C++", framework="Qt", title="SQL injection in Qt query", description="Qt app builds query by string concatenation.", owasp="A03:2021 - Injection", owasp_api="", owasp_llm="", cwe="CWE-89", mitre_attack="T1190", severity="High", difficulty="Intermediate", vulnerable_code="QString q = \"SELECT * FROM u WHERE name='\" + name + \"'\";\nQSqlQuery(q).exec();", secure_code="QSqlQuery q;\nq.prepare(\"SELECT * FROM u WHERE name = ?\");\nq.addBindValue(name); q.exec(); // bound", patch="--- a/db.cpp\n+++ b/db.cpp\n@@ -1,4 +1,4 @@\n-QString q = \"SELECT * FROM u WHERE name='\" + name + \"'\";\n-QSqlQuery(q).exec();\n+QSqlQuery q;\n+q.prepare(\"SELECT * FROM u WHERE name = ?\");\n+q.addBindValue(name); q.exec();", root_cause="String concat into SQL.", attack="name=' OR 1=1 dumps rows.", impact="Data disclosure.", fix="Use prepared statements.", guideline="Bind all SQL params.", tags=['sqli', 'cpp', 'qt', 'injection'], metadata={'auth_required': False, 'domain': 'E-commerce', 'input_source': 'query_param'})
rec(id="SCP-000451", language="Python", framework="FastAPI", title="GraphQL introspection in prod", description="FastAPI GraphQL leaves introspection on in production.", owasp="A05:2021 - Misconfiguration", owasp_api="", owasp_llm="", cwe="CWE-215", mitre_attack="T1190", severity="Low", difficulty="Beginner", vulnerable_code="app.add_route(\"/graphql\", graphql_view(schema))", secure_code="app.add_route(\"/graphql\", graphql_view(schema, introspection=DEBUG))", patch="--- a/graphql.py\n+++ b/graphql.py\n@@ -1,2 +1,2 @@\n-app.add_route(\"/graphql\", graphql_view(schema))\n+app.add_route(\"/graphql\", graphql_view(schema, introspection=DEBUG))", root_cause="Introspection exposed.", attack="Map full schema for attacks.", impact="Info disclosure.", fix="Disable introspection in prod.", guideline="Limit GraphQL introspection.", tags=['graphql', 'fastapi', 'python', 'config'], metadata={'auth_required': False, 'domain': 'REST API', 'input_source': 'server'})
rec(id="SCP-000452", language="TypeScript", framework="NestJS", title="GraphQL field-level authz missing", description="NestJS resolver returns admin fields without role check.", owasp="A01:2021 - Broken Access Control", owasp_api="API1:2023 - BOLA", owasp_llm="", cwe="CWE-862", mitre_attack="T1190", severity="Critical", difficulty="Advanced", vulnerable_code="@Query(() => User)\nasync user(@Args(\"id\") id: string) {\n return repo.user(id);\n}", secure_code="@Query(() => User)\n@UseGuards(AdminGuard)\nasync user(@Args(\"id\") id: string) {\n return repo.user(id);\n}", patch="--- a/user.resolver.ts\n+++ b/user.resolver.ts\n@@ -1,4 +1,5 @@\n @Query(() => User)\n+@UseGuards(AdminGuard)\n async user(@Args(\"id\") id: string) {\n return repo.user(id);\n }", root_cause="No field-level authz.", attack="Any user reads admin fields.", impact="Privilege escalation.", fix="Add field guards.", guideline="Enforce GraphQL field authz.", tags=['authorization', 'nestjs', 'graphql', 'broken-access-control'], metadata={'auth_required': True, 'domain': 'Authentication systems', 'input_source': 'query_param'})
rec(id="SCP-000453", language="Rust", framework="Actix", title="GraphQL query depth bomb", description="Actix GraphQL has no depth/complexity limit.", owasp="A04:2021 - Insecure Design", owasp_api="API4:2023", owasp_llm="", cwe="CWE-400", mitre_attack="T1499", severity="Medium", difficulty="Intermediate", vulnerable_code="Schema::build(Query, EmptyMutation, EmptySubscription).finish()", secure_code="let schema = Schema::build(...).finish();\n// reject queries exceeding depth 10 / complexity 1000", patch="--- a/graphql.rs\n+++ b/graphql.rs\n@@ -1,2 +1,3 @@\n-Schema::build(Query, EmptyMutation, EmptySubscription).finish()\n+let schema = Schema::build(...).finish();\n+// reject queries exceeding depth 10 / complexity 1000", root_cause="No query depth limit.", attack="Nested query exhausts CPU.", impact="DoS.", fix="Enforce depth/complexity.", guideline="Limit GraphQL query depth.", tags=['graphql', 'actix', 'rust', 'dos'], metadata={'auth_required': False, 'domain': 'REST API', 'input_source': 'query_param'})
rec(id="SCP-000454", language="Python", framework="Flask", title="gRPC method without auth", description="gRPC method exposed without authentication.", owasp="A01:2021 - Broken Access Control", owasp_api="API2:2023", owasp_llm="", cwe="CWE-306", mitre_attack="T1190", severity="Critical", difficulty="Intermediate", vulnerable_code="class AdminServicer(admin_pb2_grpc.AdminServicer):\n def DeleteUser(self, request, ctx):\n ...", secure_code="def DeleteUser(self, request, ctx):\n if not ctx.invocation_metadata().get(\"authorization\"):\n ctx.set_code(grpc.StatusCode.UNAUTHENTICATED)\n return\n ...", patch="--- a/admin_grpc.py\n+++ b/admin_grpc.py\n@@ -1,3 +1,5 @@\n-def DeleteUser(self, request, ctx):\n- ...\n+def DeleteUser(self, request, ctx):\n+ if not ctx.invocation_metadata().get(\"authorization\"):\n+ ctx.set_code(grpc.StatusCode.UNAUTHENTICATED)\n+ return", root_cause="No auth on gRPC method.", attack="Unauthenticated admin call.", impact="Privilege escalation.", fix="Enforce auth metadata.", guideline="Authenticate gRPC calls.", tags=['grpc', 'flask', 'python', 'auth'], metadata={'auth_required': True, 'domain': 'Authentication systems', 'input_source': 'rpc'})
rec(id="SCP-000455", language="Go", framework="gRPC", title="gRPC unauthenticated service", description="Go gRPC server registers service without auth interceptor.", owasp="A01:2021 - Broken Access Control", owasp_api="API2:2023", owasp_llm="", cwe="CWE-306", mitre_attack="T1190", severity="Critical", difficulty="Intermediate", vulnerable_code="s := grpc.NewServer()\npb.RegisterAdminServer(s, &admin{})", secure_code="s := grpc.NewServer(grpc.UnaryInterceptor(authInterceptor))\npb.RegisterAdminServer(s, &admin{})", patch="--- a/server.go\n+++ b/server.go\n@@ -1,3 +1,3 @@\n-s := grpc.NewServer()\n-pb.RegisterAdminServer(s, &admin{})\n+s := grpc.NewServer(grpc.UnaryInterceptor(authInterceptor))\n+pb.RegisterAdminServer(s, &admin{})", root_cause="No auth interceptor.", attack="Unauthenticated RPC calls.", impact="Privilege escalation.", fix="Add auth interceptor.", guideline="Authenticate gRPC.", tags=['grpc', 'go', 'auth', 'broken-access-control'], metadata={'auth_required': True, 'domain': 'Authentication systems', 'input_source': 'rpc'})
rec(id="SCP-000456", language="Java", framework="Spring Boot", title="No CSRF on GraphQL mutations", description="Spring GraphQL allows batching enabling CSRF.", owasp="A01:2021 - Broken Access Control", owasp_api="", owasp_llm="", cwe="CWE-352", mitre_attack="T1190", severity="Medium", difficulty="Intermediate", vulnerable_code="@PostMapping(\"/graphql\")\npublic ResponseEntity q(@RequestBody body) { ... }", secure_code="@PostMapping(\"/graphql\")\n@CsrfToken\npublic ResponseEntity q(@RequestBody body) { ... }", patch="--- a/GraphqlCtrl.java\n+++ b/GraphqlCtrl.java\n@@ -1,3 +1,4 @@\n @PostMapping(\"/graphql\")\n+@CsrfToken\n public ResponseEntity q(@RequestBody body) { ... }", root_cause="Batched queries + no CSRF.", attack="Batch authenticated mutations via CSRF.", impact="Unauthorized actions.", fix="Require CSRF on mutations.", guideline="Protect GraphQL mutations.", tags=['csrf', 'graphql', 'spring', 'config'], metadata={'auth_required': True, 'domain': 'E-commerce', 'input_source': 'request_body'})
rec(id="SCP-000457", language="C#", framework="gRPC", title="gRPC auth metadata not validated", description="C# gRPC service ignores auth metadata.", owasp="A01:2021 - Broken Access Control", owasp_api="API2:2023", owasp_llm="", cwe="CWE-306", mitre_attack="T1190", severity="Critical", difficulty="Intermediate", vulnerable_code="public override Task Delete(DeleteReq r, ServerCallContext c) {\n ...\n}", secure_code="public override Task Delete(DeleteReq r, ServerCallContext c) {\n if (!c.RequestHeaders.Has(\"authorization\"))\n throw new RpcException(Status.Unauthenticated);\n ...\n}", patch="--- a/AdminService.cs\n+++ b/AdminService.cs\n@@ -1,3 +1,4 @@\n-public override Task Delete(DeleteReq r, ServerCallContext c) { ... }\n+public override Task Delete(DeleteReq r, ServerCallContext c) {\n+ if (!c.RequestHeaders.Has(\"authorization\")) throw new RpcException(Status.Unauthenticated);\n+ ...}", root_cause="No auth metadata check.", attack="Unauthenticated delete.", impact="Privilege escalation.", fix="Validate auth metadata.", guideline="Authenticate gRPC calls.", tags=['grpc', 'csharp', 'aspnet', 'auth'], metadata={'auth_required': True, 'domain': 'Authentication systems', 'input_source': 'rpc'})
rec(id="SCP-000458", language="Python", framework="FastAPI", title="Excessive data exposure", description="Endpoint returns full ORM object including secrets.", owasp="A01:2021 - Broken Access Control", owasp_api="API3:2023", owasp_llm="", cwe="CWE-200", mitre_attack="T1190", severity="Medium", difficulty="Beginner", vulnerable_code="@app.get(\"/me\")\nasync def me(u: User = Depends(current)):\n return u # leaks internal fields", secure_code="@app.get(\"/me\")\nasync def me(u: User = Depends(current)):\n return UserPublic.from_orm(u) # whitelisted", patch="--- a/me.py\n+++ b/me.py\n@@ -1,3 +1,4 @@\n-async def me(u: User = Depends(current)):\n- return u\n+async def me(u: User = Depends(current)):\n+ return UserPublic.from_orm(u)", root_cause="Full object serialization.", attack="Read internal/private fields.", impact="Info disclosure.", fix="Use response schemas.", guideline="Whitelist response fields.", tags=['exposure', 'fastapi', 'python', 'api'], metadata={'auth_required': True, 'domain': 'E-commerce', 'input_source': 'cookie'})
rec(id="SCP-000459", language="JavaScript", framework="Express", title="No authorization on admin route", description="Express admin route lacks role middleware.", owasp="A01:2021 - Broken Access Control", owasp_api="API1:2023 - BOLA", owasp_llm="", cwe="CWE-862", mitre_attack="T1190", severity="Critical", difficulty="Intermediate", vulnerable_code="app.delete(\"/admin/user/:id\", (req, res) =>\n repo.remove(req.params.id));", secure_code="app.delete(\"/admin/user/:id\", requireAdmin, (req, res) =>\n repo.remove(req.params.id));", patch="--- a/admin.js\n+++ b/admin.js\n@@ -1,3 +1,3 @@\n-app.delete(\"/admin/user/:id\", (req, res) =>\n- repo.remove(req.params.id));\n+app.delete(\"/admin/user/:id\", requireAdmin, (req, res) =>\n+ repo.remove(req.params.id));", root_cause="No role middleware.", attack="Any user deletes accounts.", impact="Privilege escalation.", fix="Add role middleware.", guideline="Enforce admin authz.", tags=['authorization', 'express', 'node', 'broken-access-control'], metadata={'auth_required': True, 'domain': 'Authentication systems', 'input_source': 'path_param'})
rec(id="SCP-000460", language="PHP", framework="Laravel", title="Reversible token storage", description="Laravel stores API tokens with reversible encoding.", owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="", cwe="CWE-916", mitre_attack="T1552", severity="High", difficulty="Intermediate", vulnerable_code="$store = base64_encode($token); // reversible", secure_code="$store = hash(\"sha256\", $token); // one-way", patch="--- a/TokenStore.php\n+++ b/TokenStore.php\n@@ -1,2 +1,2 @@\n-$store = base64_encode($token);\n+$store = hash(\"sha256\", $token);", root_cause="Reversible encoding as encryption.", attack="Decode stored tokens.", impact="Token theft.", fix="Hash or encrypt properly.", guideline="One-way hash tokens.", tags=['crypto', 'laravel', 'php', 'tokens'], metadata={'auth_required': False, 'domain': 'Authentication systems', 'input_source': 'server'})
rec(id="SCP-000461", language="Go", framework="Gin", title="SSRF in proxy endpoint", description="Gin proxy fetches arbitrary user URLs.", owasp="A10:2021 - SSRF", owasp_api="", owasp_llm="", cwe="CWE-918", mitre_attack="T1190", severity="High", difficulty="Intermediate", vulnerable_code="resp, _ := http.Get(c.Query(\"url\")) // SSRF", secure_code="u, err := url.Parse(c.Query(\"url\"))\nif err != nil || !allowlist[u.Host] { c.AbortWithStatus(403); return }\nresp, _ := http.Get(u.String())", patch="--- a/proxy.go\n+++ b/proxy.go\n@@ -1,2 +1,4 @@\n-resp, _ := http.Get(c.Query(\"url\"))\n+u, err := url.Parse(c.Query(\"url\"))\n+if err != nil || !allowlist[u.Host] { c.AbortWithStatus(403); return }\n+resp, _ := http.Get(u.String())", root_cause="Unvalidated fetch URL.", attack="Fetch cloud metadata.", impact="Metadata theft.", fix="Allowlist hosts.", guideline="Validate fetch targets.", tags=['ssrf', 'go', 'gin', 'rce'], metadata={'auth_required': False, 'domain': 'Cloud', 'input_source': 'query_param'})
rec(id="SCP-000462", language="Python", framework="Django", title="SSRF in image proxy", description="Django view fetches remote image by URL.", owasp="A10:2021 - SSRF", owasp_api="", owasp_llm="", cwe="CWE-918", mitre_attack="T1190", severity="High", difficulty="Intermediate", vulnerable_code="def proxy(request):\n return HttpResponse(requests.get(request.GET[\"u\"]).content)", secure_code="def proxy(request):\n u = urlparse(request.GET[\"u\"])\n if u.scheme != \"https\" or u.hostname not in ALLOWED:\n return HttpResponseForbidden()\n return HttpResponse(requests.get(request.GET[\"u\"]).content)", patch="--- a/proxy.py\n+++ b/proxy.py\n@@ -1,3 +1,5 @@\n-def proxy(request):\n- return HttpResponse(requests.get(request.GET[\"u\"]).content)\n+def proxy(request):\n+ u = urlparse(request.GET[\"u\"])\n+ if u.scheme != \"https\" or u.hostname not in ALLOWED:\n+ return HttpResponseForbidden()", root_cause="Unvalidated fetch URL.", attack="Fetch internal services.", impact="Metadata theft.", fix="Allowlist schemes/hosts.", guideline="Validate fetch targets.", tags=['ssrf', 'django', 'python', 'rce'], metadata={'auth_required': False, 'domain': 'Cloud', 'input_source': 'query_param'})
rec(id="SCP-000463", language="Ruby", framework="Rails", title="SSRF in webhook tester", description="Rails action fetches user-supplied webhook URL.", owasp="A10:2021 - SSRF", owasp_api="", owasp_llm="", cwe="CWE-918", mitre_attack="T1190", severity="High", difficulty="Intermediate", vulnerable_code="def test\n render plain: Net::HTTP.get(URI(params[:url]))\nend", secure_code="def test\n uri = URI(params[:url])\n raise \"bad\" unless uri.host.in?(ALLOWED)\n render plain: Net::HTTP.get(uri)\nend", patch="--- a/webhooks_controller.rb\n+++ b/webhooks_controller.rb\n@@ -1,3 +1,5 @@\n-def test\n- render plain: Net::HTTP.get(URI(params[:url]))\n+def test\n+ uri = URI(params[:url])\n+ raise \"bad\" unless uri.host.in?(ALLOWED)\n+ render plain: Net::HTTP.get(uri)\n end", root_cause="Unvalidated fetch URL.", attack="Fetch internal metadata.", impact="Metadata theft.", fix="Allowlist hosts.", guideline="Validate fetch targets.", tags=['ssrf', 'rails', 'ruby', 'rce'], metadata={'auth_required': False, 'domain': 'Cloud', 'input_source': 'query_param'})
rec(id="SCP-000464", language="C#", framework="ASP.NET Core", title="SSRF in HttpClient", description="Controller fetches user-supplied URL.", owasp="A10:2021 - SSRF", owasp_api="", owasp_llm="", cwe="CWE-918", mitre_attack="T1190", severity="High", difficulty="Intermediate", vulnerable_code="var html = await client.GetStringAsync(url);", secure_code="if (!Uri.TryCreate(url, UriKind.Absolute, out var u) ||\n !ALLOWED_HOSTS.Contains(u.Host))\n return BadRequest();\nvar html = await client.GetStringAsync(u);", patch="--- a/ProxyController.cs\n+++ b/ProxyController.cs\n@@ -1,2 +1,4 @@\n-var html = await client.GetStringAsync(url);\n+if (!Uri.TryCreate(url, UriKind.Absolute, out var u) ||\n+ !ALLOWED_HOSTS.Contains(u.Host)) return BadRequest();\n+var html = await client.GetStringAsync(u);", root_cause="Unvalidated fetch URL.", attack="Fetch internal metadata.", impact="Metadata theft.", fix="Allowlist hosts.", guideline="Validate fetch targets.", tags=['ssrf', 'csharp', 'aspnet', 'rce'], metadata={'auth_required': False, 'domain': 'Cloud', 'input_source': 'query_param'})
rec(id="SCP-000465", language="PHP", framework="Laravel", title="Session fixation in login", description="Laravel login does not regenerate session id.", owasp="A07:2021 - Auth Failures", owasp_api="API2:2023", owasp_llm="", cwe="CWE-384", mitre_attack="T1539", severity="Medium", difficulty="Beginner", vulnerable_code="Auth::login($user); // same session id", secure_code="Auth::login($user);\nrequest()->session()->regenerate(); // new id", patch="--- a/AuthController.php\n+++ b/AuthController.php\n@@ -1,3 +1,4 @@\n-Auth::login($user);\n+Auth::login($user);\n+request()->session()->regenerate();", root_cause="No session regeneration.", attack="Fixation: pre-set session reused.", impact="Account takeover.", fix="Regenerate session.", guideline="Rotate session on auth.", tags=['session', 'laravel', 'php', 'auth'], metadata={'auth_required': True, 'domain': 'Authentication systems', 'input_source': 'request_body'})
rec(id="SCP-000466", language="Java", framework="Spring Boot", title="Session fixation in Spring", description="Spring login does not configure session fixation protection.", owasp="A07:2021 - Auth Failures", owasp_api="API2:2023", owasp_llm="", cwe="CWE-384", mitre_attack="T1539", severity="Medium", difficulty="Beginner", vulnerable_code="http.formLogin();", secure_code="http.sessionManagement()\n .sessionFixation().migrateSession();", patch="--- a/SecurityConfig.java\n+++ b/SecurityConfig.java\n@@ -1,2 +1,3 @@\n-http.formLogin();\n+http.sessionManagement()\n+ .sessionFixation().migrateSession();", root_cause="No session fixation policy.", attack="Fixation attack.", impact="Account takeover.", fix="Migrate session on auth.", guideline="Rotate session on login.", tags=['session', 'spring', 'java', 'auth'], metadata={'auth_required': True, 'domain': 'Authentication systems', 'input_source': 'form_field'})
rec(id="SCP-000467", language="Go", framework="Gin", title="Session fixation in Gin", description="Gin login does not rotate session id.", owasp="A07:2021 - Auth Failures", owasp_api="API2:2023", owasp_llm="", cwe="CWE-384", mitre_attack="T1539", severity="Medium", difficulty="Beginner", vulnerable_code="session.Set(\"uid\", uid) // same id", secure_code="old := session.ID()\nsession.Set(\"uid\", uid)\nsession.Save()\n_ = store.RegenID(old, session) // rotate", patch="--- a/login.go\n+++ b/login.go\n@@ -1,2 +1,5 @@\n-session.Set(\"uid\", uid)\n+old := session.ID()\n+session.Set(\"uid\", uid)\n+session.Save()\n+_ = store.RegenID(old, session)", root_cause="No session rotation.", attack="Fixation.", impact="Account takeover.", fix="Rotate session id.", guideline="Rotate session on auth.", tags=['session', 'go', 'gin', 'auth'], metadata={'auth_required': True, 'domain': 'Authentication systems', 'input_source': 'request_body'})
rec(id="SCP-000468", language="Ruby", framework="Rails", title="Timing-unsafe token compare", description="Rails API compares tokens with ==.", owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="", cwe="CWE-208", mitre_attack="T1600", severity="Low", difficulty="Intermediate", vulnerable_code="def valid?(t); t == session[:csrf]; end", secure_code="def valid?(t)\n ActiveSupport::SecurityUtils.secure_compare(t, session[:csrf])\nend", patch="--- a/csrf.rb\n+++ b/csrf.rb\n@@ -1,2 +1,3 @@\n-def valid?(t); t == session[:csrf]; end\n+def valid?(t)\n+ ActiveSupport::SecurityUtils.secure_compare(t, session[:csrf])\n+end", root_cause="Non-constant-time compare.", attack="Timing attack on CSRF.", impact="Token forgery.", fix="Use secure_compare.", guideline="Constant-time compare.", tags=['crypto', 'rails', 'ruby', 'timing'], metadata={'auth_required': False, 'domain': 'Authentication systems', 'input_source': 'cookie'})
rec(id="SCP-000469", language="Python", framework="Django", title="Insecure redirect after login", description="Django login redirects to next without validation.", owasp="A01:2021 - Broken Access Control", owasp_api="", owasp_llm="", cwe="CWE-601", mitre_attack="T1566", severity="Medium", difficulty="Beginner", vulnerable_code="return redirect(request.GET.get(\"next\", \"/\"))", secure_code="next = request.GET.get(\"next\", \"/\")\nif not url_has_allowed_host_and_scheme(next, ALLOWED):\n next = \"/\"\nreturn redirect(next)", patch="--- a/views.py\n+++ b/views.py\n@@ -1,2 +1,4 @@\n-return redirect(request.GET.get(\"next\", \"/\"))\n+next = request.GET.get(\"next\", \"/\")\n+if not url_has_allowed_host_and_scheme(next, ALLOWED):\n+ next = \"/\"\n+return redirect(next)", root_cause="Unvalidated redirect.", attack="next=//evil.com phishing.", impact="Phishing.", fix="Allowlist hosts.", guideline="Validate redirects.", tags=['open-redirect', 'django', 'python', 'phishing'], metadata={'auth_required': False, 'domain': 'Authentication systems', 'input_source': 'query_param'})
rec(id="SCP-000470", language="JavaScript", framework="Express", title="JWT none algorithm accepted", description="Express JWT verifier allows none.", owasp="A07:2021 - Auth Failures", owasp_api="API2:2023", owasp_llm="", cwe="CWE-345", mitre_attack="T1600", severity="Critical", difficulty="Advanced", vulnerable_code="jwt.verify(t, key, { algorithms: [\"HS256\", \"none\"] });", secure_code="jwt.verify(t, key, { algorithms: [\"HS256\"] }); // no none", patch="--- a/auth.js\n+++ b/auth.js\n@@ -1,2 +1,2 @@\n-jwt.verify(t, key, { algorithms: [\"HS256\", \"none\"] });\n+jwt.verify(t, key, { algorithms: [\"HS256\"] });", root_cause="none algorithm allowed.", attack="Forge alg=none token.", impact="Auth bypass.", fix="Forbid none.", guideline="Pin JWT algorithm.", tags=['jwt', 'express', 'node', 'auth'], metadata={'auth_required': True, 'domain': 'Authentication systems', 'input_source': 'header'})
rec(id="SCP-000471", language="Go", framework="Gin", title="Hardcoded JWT secret in Go", description="Gin service uses hardcoded JWT signing secret.", owasp="A02:2021 - Cryptographic Failures", owasp_api="API2:2023", owasp_llm="", cwe="CWE-798", mitre_attack="T1600", severity="Critical", difficulty="Intermediate", vulnerable_code="var jwtSecret = []byte(\"secret\") // brute-forceable", secure_code="var jwtSecret = []byte(os.Getenv(\"JWT_SECRET\")) // env", patch="--- a/auth.go\n+++ b/auth.go\n@@ -1,2 +1,2 @@\n-var jwtSecret = []byte(\"secret\")\n+var jwtSecret = []byte(os.Getenv(\"JWT_SECRET\"))", root_cause="Weak hardcoded secret.", attack="Forge tokens.", impact="Auth bypass.", fix="Use env secret.", guideline="Externalize JWT secret.", tags=['jwt', 'go', 'gin', 'auth'], metadata={'auth_required': True, 'domain': 'Authentication systems', 'input_source': 'server'})
rec(id="SCP-000472", language="Ruby", framework="Rails", title="Mass assignment of role", description="Rails update binds role from params.", owasp="A04:2021 - Insecure Design", owasp_api="API3:2023", owasp_llm="", cwe="CWE-915", mitre_attack="T1190", severity="High", difficulty="Beginner", vulnerable_code="@user.update(params[:user]) // role bound", secure_code="@user.update(params.require(:user).permit(:name, :email))", patch="--- a/users_controller.rb\n+++ b/users_controller.rb\n@@ -1,2 +1,2 @@\n-@user.update(params[:user])\n+@user.update(params.require(:user).permit(:name, :email))", root_cause="All params bound.", attack="POST user[role]=admin.", impact="Privilege escalation.", fix="Use strong parameters.", guideline="Whitelist assignable fields.", tags=['mass-assignment', 'rails', 'ruby', 'auth'], metadata={'auth_required': True, 'domain': 'E-commerce', 'input_source': 'request_body'})
rec(id="SCP-000473", language="PHP", framework="Laravel", title="Insecure password hash compare", description="Laravel login compares hashes with ==.", owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="", cwe="CWE-208", mitre_attack="T1600", severity="Low", difficulty="Intermediate", vulnerable_code="if ($hash == $input) { ... } // timing", secure_code="if (hash_equals($hash, $input)) { ... } // constant-time", patch="--- a/Auth.php\n+++ b/Auth.php\n@@ -1,2 +1,2 @@\n-if ($hash == $input) { ... }\n+if (hash_equals($hash, $input)) { ... }", root_cause="Non-constant-time compare.", attack="Timing attack.", impact="Hash recovery.", fix="Use hash_equals.", guideline="Constant-time compare.", tags=['crypto', 'laravel', 'php', 'timing'], metadata={'auth_required': False, 'domain': 'Authentication systems', 'input_source': 'request_body'})
rec(id="SCP-000474", language="Java", framework="Spring Boot", title="Weak OTP random", description="Spring OTP generator uses Math.random.", owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="", cwe="CWE-338", mitre_attack="T1600", severity="High", difficulty="Intermediate", vulnerable_code="int otp = (int)(Math.random() * 1000000);", secure_code="int otp = new SecureRandom().nextInt(1000000);", patch="--- a/OtpService.java\n+++ b/OtpService.java\n@@ -1,2 +1,2 @@\n-int otp = (int)(Math.random() * 1000000);\n+int otp = new SecureRandom().nextInt(1000000);", root_cause="Non-CSPRNG OTP.", attack="Predict OTP.", impact="Account takeover.", fix="Use SecureRandom.", guideline="Use CSPRNG for OTP.", tags=['crypto', 'spring', 'java', 'otp'], metadata={'auth_required': False, 'domain': 'Authentication systems', 'input_source': 'server'})
rec(id="SCP-000475", language="Python", framework="FastAPI", title="Weak password policy", description="Signup does not enforce password complexity.", owasp="A07:2021 - Auth Failures", owasp_api="API2:2023", owasp_llm="", cwe="CWE-521", mitre_attack="T1110", severity="Medium", difficulty="Beginner", vulnerable_code="def signup(pw: str):\n create_user(pw) # any pw", secure_code="import re\ndef signup(pw: str):\n if not re.match(r\"^(?=.*[A-Z])(?=.*[0-9]).{8,}$\", pw):\n raise HTTPException(400)\n create_user(pw)", patch="--- a/auth.py\n+++ b/auth.py\n@@ -1,3 +1,5 @@\n-def signup(pw: str):\n- create_user(pw)\n+import re\n+def signup(pw: str):\n+ if not re.match(r\"^(?=.*[A-Z])(?=.*[0-9]).{8,}$\", pw):\n+ raise HTTPException(400)\n+ create_user(pw)", root_cause="No password policy.", attack="Weak/crackable passwords.", impact="Account takeover.", fix="Enforce complexity.", guideline="Strong password policy.", tags=['passwords', 'fastapi', 'python', 'auth'], metadata={'auth_required': False, 'domain': 'Authentication systems', 'input_source': 'request_body'})
rec(id="SCP-000476", language="TypeScript", framework="NestJS", title="Insecure JWT secret in NestJS", description="NestJS JWT module uses weak secret.", owasp="A07:2021 - Auth Failures", owasp_api="API2:2023", owasp_llm="", cwe="CWE-345", mitre_attack="T1600", severity="Critical", difficulty="Advanced", vulnerable_code="JwtModule.register({ secret: \"secret\", signOptions: { expiresIn: \"1h\" } })", secure_code="JwtModule.register({ secret: process.env.JWT_SECRET, signOptions: { expiresIn: \"1h\" } })", patch="--- a/auth.module.ts\n+++ b/auth.module.ts\n@@ -1,2 +1,2 @@\n-JwtModule.register({ secret: \"secret\", signOptions: { expiresIn: \"1h\" } })\n+JwtModule.register({ secret: process.env.JWT_SECRET, signOptions: { expiresIn: \"1h\" } })", root_cause="Weak hardcoded secret.", attack="Forge tokens.", impact="Auth bypass.", fix="Use env secret.", guideline="Externalize JWT secret.", tags=['jwt', 'nestjs', 'typescript', 'auth'], metadata={'auth_required': True, 'domain': 'Authentication systems', 'input_source': 'server'})
rec(id="SCP-000477", language="Rust", framework="Actix", title="No rate limit on Actix login", description="Actix login has no throttling.", owasp="A07:2021 - Auth Failures", owasp_api="API4:2023", owasp_llm="", cwe="CWE-307", mitre_attack="T1110", severity="Medium", difficulty="Beginner", vulnerable_code=".route(\"/login\", web::post().to(login))", secure_code=".route(\"/login\", web::post().to(login))\n.wrap(RateLimiter::new(5, 60))", patch="--- a/routes.rs\n+++ b/routes.rs\n@@ -1,2 +1,3 @@\n-.route(\"/login\", web::post().to(login))\n+.route(\"/login\", web::post().to(login))\n+.wrap(RateLimiter::new(5, 60))", root_cause="No throttle on auth.", attack="Brute force credentials.", impact="Account takeover.", fix="Rate limit login.", guideline="Throttle auth endpoints.", tags=['rate-limiting', 'actix', 'rust', 'auth'], metadata={'auth_required': False, 'domain': 'Authentication systems', 'input_source': 'request_body'})
rec(id="SCP-000478", language="C", framework="POSIX", title="Stack buffer overflow in gets", description="C program copies with unbounded gets.", owasp="A03:2021 - Injection", owasp_api="", owasp_llm="", cwe="CWE-120", mitre_attack="T1203", severity="High", difficulty="Beginner", vulnerable_code="char buf[64];\ngets(buf); // no bound", secure_code="char buf[64];\nif (!fgets(buf, sizeof buf, stdin)) return; // bounded", patch="--- a/legacy.c\n+++ b/legacy.c\n@@ -1,3 +1,4 @@\n-char buf[64];\n-gets(buf);\n+char buf[64];\n+if (!fgets(buf, sizeof buf, stdin)) return;", root_cause="gets has no bounds.", attack="Overflow stack.", impact="RCE.", fix="Use fgets/string.", guideline="Never use gets.", tags=['buffer-overflow', 'c', 'memory-safety'], metadata={'auth_required': False, 'domain': 'IoT', 'input_source': 'stdin'})
rec(id="SCP-000479", language="Go", framework="Gin", title="Insecure cookie SameSite Lax with CSRF", description="Gin session uses SameSite=Lax but state-changing GET.", owasp="A01:2021 - Broken Access Control", owasp_api="", owasp_llm="", cwe="CWE-352", mitre_attack="T1190", severity="Medium", difficulty="Beginner", vulnerable_code="c.SetCookie(\"sid\", t, 3600, \"/\", \"app\", True, false) // Lax + GET state", secure_code="// POST + CSRF token for state changes; SameSite=Strict\nc.SetCookie(\"sid\", t, 3600, \"/\", \"app\", True, true)", patch="--- a/auth.go\n+++ b/auth.go\n@@ -1,2 +1,3 @@\n-c.SetCookie(\"sid\", t, 3600, \"/\", \"app\", True, false)\n+// POST + CSRF token for state changes; SameSite=Strict\n+c.SetCookie(\"sid\", t, 3600, \"/\", \"app\", True, true)", root_cause="Lax cookie + GET state change.", attack="CSRF on GET action.", impact="Unauthorized action.", fix="POST + CSRF + Strict.", guideline="Protect state changes.", tags=['csrf', 'go', 'gin', 'cookies'], metadata={'auth_required': True, 'domain': 'E-commerce', 'input_source': 'cookie'})
rec(id="SCP-000480", language="Python", framework="Flask", title="Logging injection via unsanitized input", description="Flask logs user input containing newlines, enabling log forging.", owasp="A09:2021 - Logging Failures", owasp_api="", owasp_llm="", cwe="CWE-117", mitre_attack="T1190", severity="Low", difficulty="Beginner", vulnerable_code="logger.info(\"user %s logged in\", request.args.get(\"u\"))", secure_code="u = request.args.get(\"u\", \"\").replace(\"\\n\", \" \").replace(\"\\r\", \" \")\nlogger.info(\"user %s logged in\", u)", patch="--- a/views.py\n+++ b/views.py\n@@ -1,2 +1,3 @@\n-logger.info(\"user %s logged in\", request.args.get(\"u\"))\n+u = request.args.get(\"u\", \"\").replace(\"\\n\", \" \").replace(\"\\r\", \" \")\n+logger.info(\"user %s logged in\", u)", root_cause="Unsanitized log input.", attack="Inject fake log lines.", impact="Log integrity loss.", fix="Sanitize log input.", guideline="Strip newlines from log data.", tags=['logging', 'flask', 'python', 'log-injection'], metadata={'auth_required': False, 'domain': 'Backend', 'input_source': 'query_param'})
RECORDS_EXT10 = L |