#!/usr/bin/env python3
"""SecureCodePairs v1.2.0 extension records (part 9): C#/PHP/Rust/Kotlin/Swift/YAML (SCP-000326+).
Built with json-safe helpers (rec() with = kwargs).
"""
import json
from typing import List, Dict
L: List[Dict] = []
def rec(**kw):
L.append(kw)
# ---------------- C# (SCP-000326 - 000345) ----------------
rec(id="SCP-000326", language="C#", framework="ASP.NET Core",
title="SQL injection via string concat",
description="An ASP.NET Core controller builds a query by concatenation.",
owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
cwe="CWE-89", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="High", difficulty="Intermediate",
vulnerable_code="string q = \"SELECT * FROM Users WHERE Name='\" + name + \"'\";\nusing var cmd = new SqlCommand(q, conn); // Vulnerable",
secure_code="using var cmd = new SqlCommand(\"SELECT * FROM Users WHERE Name=@n\", conn);\ncmd.Parameters.AddWithValue(\"@n\", name); // Secure: parameterized",
patch="--- a/UsersController.cs\n+++ b/UsersController.cs\n@@ -1,3 +1,4 @@\n-string q = \"SELECT * FROM Users WHERE Name='\" + name + \"'\";\n-using var cmd = new SqlCommand(q, conn);\n+using var cmd = new SqlCommand(\"SELECT * FROM Users WHERE Name=@n\", conn);\n+cmd.Parameters.AddWithValue(\"@n\", name);",
root_cause="String concat into SQL.",
attack="name=\' OR 1=1 dumps rows.", impact="Data disclosure.",
fix="Use parameterized queries.", guideline="Bind all SQL params.",
tags=["sqli", "csharp", "aspnet", "injection"],
metadata={"domain": "E-commerce", "input_source": "query_param", "auth_required": False})
rec(id="SCP-000327", language="C#", framework="ASP.NET Core",
title="Command injection via Process.Start",
description="A controller runs a shell command with user input.",
owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
cwe="CWE-78", mitre_attack="T1059 - Command and Scripting Interpreter",
severity="High", difficulty="Intermediate",
vulnerable_code="Process.Start(\"cmd.exe\", \"/c ping \" + host); // Vulnerable: shell\\",
secure_code="if (!Regex.IsMatch(host, @\"^[\\w.-]+$\")) return BadRequest();\\nProcess.Start(\"ping\", \"-c1 \" + host); // Secure: validate + arg\\",
patch="--- a/PingController.cs\\n+++ b/PingController.cs\\n@@ -1,3 +1,4 @@\\n-Process.Start(\"cmd.exe\", \"/c ping \" + host);\\n+if (!Regex.IsMatch(host, @\"^[\\w.-]+$\")) return BadRequest();\\n+Process.Start(\"ping\", \"-c1 \" + host);\\",
root_cause="Shell string with user input.",
attack="host=;del /F /Q * executes.", impact="Command injection.",
fix="Validate + arg array.", guideline="Avoid shell interpolation.",
tags=["command-injection", "csharp", "aspnet", "rce"],
metadata={"domain": "IoT", "input_source": "query_param", "auth_required": False})
rec(id="SCP-000328", language="C#", framework="ASP.NET Core",
title="Path traversal in file result",
description="A controller returns a file from a user path.",
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="return PhysicalFile(\"/data/\" + name, \"application/octet-stream\"); // Vulnerable: traversal\\",
secure_code="var safe = Path.GetFullPath(Path.Combine(\"/data\", name));\\nif (!safe.StartsWith(\"/data\")) return Forbid(); // Secure\\nreturn PhysicalFile(safe, \"application/octet-stream\");\\",
patch="--- a/FilesController.cs\\n+++ b/FilesController.cs\\n@@ -1,3 +1,5 @@\\n-return PhysicalFile(\"/data/\" + name, \"application/octet-stream\");\\n+var safe = Path.GetFullPath(Path.Combine(\"/data\", name));\\n+if (!safe.StartsWith(\"/data\")) return Forbid();\\n+return PhysicalFile(safe, \"application/octet-stream\");\\",
root_cause="Unsanitized filename.",
attack="name=../../etc/passwd reads file.", impact="File disclosure.",
fix="Confine to base dir.", guideline="Confine file paths.",
tags=["path-traversal", "csharp", "aspnet", "file-read"],
metadata={"domain": "Backend", "input_source": "query_param", "auth_required": False})
rec(id="SCP-000329", language="C#", framework="ASP.NET Core",
title="Missing authorization on admin endpoint",
description="An admin endpoint lacks [Authorize(Roles=...)]",
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="Intermediate",
vulnerable_code="[HttpDelete(\"admin/user/{id}\")]\\npublic IActionResult Delete(int id) { repo.Remove(id); return Ok(); } // Vulnerable: no role\\",
secure_code="[Authorize(Roles = \"Admin\")] // Secure\\n[HttpDelete(\"admin/user/{id}\")]\\npublic IActionResult Delete(int id) { repo.Remove(id); return Ok(); }\\",
patch="--- a/AdminController.cs\\n+++ b/AdminController.cs\\n@@ -1,4 +1,5 @@\\n+[Authorize(Roles = \"Admin\")]\\n [HttpDelete(\"admin/user/{id}\")]\\n public IActionResult Delete(int id) { repo.Remove(id); return Ok(); }\\",
root_cause="No role check.",
attack="Any user deletes accounts.", impact="Privilege escalation.",
fix="Add [Authorize(Roles)].", guideline="Enforce role checks.",
tags=["authorization", "csharp", "aspnet", "broken-access-control"],
metadata={"domain": "Authentication systems", "input_source": "path_param", "auth_required": True})
rec(id="SCP-000330", language="C#", framework="ASP.NET Core",
title="Hardcoded connection string",
description="An appsettings.json contains a plaintext DB password.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-798", mitre_attack="T1552.001 - Unsecured Credentials: Credentials In Files",
severity="High", difficulty="Beginner",
vulnerable_code="\"ConnectionStrings\": { \"Default\": \"Server=db;User=sa;Password=P@ssw0rd!\" } // Vulnerable\\",
secure_code="\"ConnectionStrings\": { \"Default\": \"%DB_CONN%\" } // Secure: from env/secret\\",
patch="--- a/appsettings.json\\n+++ b/appsettings.json\\n@@ -1,2 +1,2 @@\\n-\"ConnectionStrings\": { \"Default\": \"Server=db;User=sa;Password=P@ssw0rd!\" }\\n+\"ConnectionStrings\": { \"Default\": \"%DB_CONN%\" }\\",
root_cause="Secret in config.",
attack="Read config for DB creds.", impact="DB compromise.",
fix="Externalize secrets.", guideline="Use secret manager.",
tags=["secrets", "csharp", "aspnet", "config"],
metadata={"domain": "Backend", "input_source": "source_code", "auth_required": False})
rec(id="SCP-000331", language="C#", framework="ASP.NET Core",
title="XSS via Html.Raw",
description="A Razor view renders user input with Html.Raw.",
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="
@Html.Raw(Model.Comment)
\\",
secure_code="@Model.Comment
\\",
patch="--- a/Show.cshtml\\n+++ b/Show.cshtml\\n@@ -1,2 +1,2 @@\\n-@Html.Raw(Model.Comment)
\\n+@Model.Comment
\\",
root_cause="Html.Raw disables encoding.",
attack="Comment= runs.", impact="XSS.",
fix="Use default encoding.", guideline="Avoid Html.Raw on user input.",
tags=["xss", "csharp", "aspnet", "template"],
metadata={"domain": "E-commerce", "input_source": "db", "auth_required": False})
rec(id="SCP-000332", language="C#", framework="ASP.NET Core",
title="No rate limit on login",
description="A login action has no throttling.",
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="Beginner",
vulnerable_code="[HttpPost(\"login\")]\\npublic IActionResult Login(Login m) { return Ok(auth(m)); } // Vulnerable: no throttle\\",
secure_code="[HttpPost(\"login\")]\\n[EnableRateLimiting(\"login\")] // Secure\\npublic IActionResult Login(Login m) { return Ok(auth(m)); }\\",
patch="--- a/AuthController.cs\\n+++ b/AuthController.cs\\n@@ -1,4 +1,5 @@\\n+[EnableRateLimiting(\"login\")]\\n [HttpPost(\"login\")]\\n public IActionResult Login(Login m) { return Ok(auth(m)); }\\",
root_cause="No throttle on auth.",
attack="Brute force credentials.", impact="Account takeover.",
fix="Rate limit login.", guideline="Throttle auth endpoints.",
tags=["rate-limiting", "csharp", "aspnet", "auth"],
metadata={"domain": "Authentication systems", "input_source": "request_body", "auth_required": False})
rec(id="SCP-000333", language="C#", framework="ASP.NET Core",
title="Insecure JWT validation (no signature check)",
description="A JWT is parsed without validating the signature.",
owasp="A07:2021 - Identification and Authentication Failures", owasp_api="API2:2023 - Broken Authentication", owasp_llm="",
cwe="CWE-345", mitre_attack="T1600 - Weaken Encryption",
severity="Critical", difficulty="Advanced",
vulnerable_code="var handler = new JwtSecurityTokenHandler();\\nvar t = handler.ReadJwtToken(token); // Vulnerable: no signature validation\\",
secure_code="var t = handler.ValidateToken(token, new TokenValidationParameters {\\n ValidateIssuerSigningKey = true, IssuerSigningKey = key\\n}, out _); // Secure\\",
patch="--- a/Auth.cs\\n+++ b/Auth.cs\\n@@ -1,3 +1,5 @@\\n-var t = handler.ReadJwtToken(token);\\n+var t = handler.ValidateToken(token, new TokenValidationParameters {\\n+ ValidateIssuerSigningKey = true, IssuerSigningKey = key\\n+}, out _);\\",
root_cause="Signature not validated.",
attack="Forge token with any payload.", impact="Auth bypass.",
fix="Validate signature/issuer.", guideline="Always validate JWT signature.",
tags=["jwt", "csharp", "aspnet", "auth"],
metadata={"domain": "Authentication systems", "input_source": "header", "auth_required": True})
rec(id="SCP-000334", language="C#", framework="ASP.NET Core",
title="Deserialization of untrusted JSON (TypeNameHandling)",
description="Newtonsoft Json.NET uses TypeNameHandling.All on untrusted input.",
owasp="A08:2021 - Software and Data Integrity Failures", owasp_api="", owasp_llm="",
cwe="CWE-502", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="Critical", difficulty="Advanced",
vulnerable_code="JsonConvert.DeserializeObject(json, new JsonSerializerSettings {\\n TypeNameHandling = TypeNameHandling.All }); // Vulnerable: RCE gadget\\",
secure_code="JsonConvert.DeserializeObject(json, new JsonSerializerSettings {\\n TypeNameHandling = TypeNameHandling.None }); // Secure\\",
patch="--- a/Parse.cs\\n+++ b/Parse.cs\\n@@ -1,4 +1,4 @@\\n-JsonConvert.DeserializeObject(json, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });\\n+JsonConvert.DeserializeObject(json, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.None });\\",
root_cause="TypeNameHandling on untrusted data.",
attack="Embed $type gadget for RCE.", impact="Remote code execution.",
fix="Use TypeNameHandling.None / DTOs.", guideline="Never use All on untrusted JSON.",
tags=["deserialization", "csharp", "aspnet", "rce"],
metadata={"domain": "Microservices", "input_source": "request_body", "auth_required": False})
rec(id="SCP-000335", language="C#", framework="ASP.NET Core",
title="IDOR on order read",
description="An action returns an order by id without owner 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="[HttpGet(\"order/{id}\")]\\npublic IActionResult Get(int id) => Ok(repo.GetOrder(id)); // Vulnerable: no owner\\",
secure_code="[HttpGet(\"order/{id}\")]\\npublic IActionResult Get(int id) =>\\n Ok(repo.GetOrderOwned(id, User.FindFirst(\"sub\").Value)); // Secure: scoped\\",
patch="--- a/OrdersController.cs\\n+++ b/OrdersController.cs\\n@@ -1,3 +1,4 @@\\n-[HttpGet(\"order/{id}\")]\\npublic IActionResult Get(int id) => Ok(repo.GetOrder(id));\\n+[HttpGet(\"order/{id}\")]\\n+public IActionResult Get(int id) => Ok(repo.GetOrderOwned(id, User.FindFirst(\"sub\").Value));\\",
root_cause="No ownership scoping.",
attack="Enumerate others orders.", impact="PII disclosure.",
fix="Scope by owner.", guideline="Authorize reads by owner.",
tags=["idor", "csharp", "aspnet", "access-control"],
metadata={"domain": "E-commerce", "input_source": "path_param", "auth_required": True})
rec(id="SCP-000336", language="C#", framework="ASP.NET Core",
title="Open redirect",
description="A returnUrl param is used directly in a redirect.",
owasp="A01:2021 - Broken Access Control", owasp_api="", owasp_llm="",
cwe="CWE-601", mitre_attack="T1566 - Phishing",
severity="Medium", difficulty="Beginner",
vulnerable_code="return Redirect(returnUrl); // Vulnerable: unvalidated\\",
secure_code="if (Url.IsLocalUrl(returnUrl)) return Redirect(returnUrl); // Secure\\nreturn RedirectToAction(\"Index\");\\",
patch="--- a/AccountController.cs\\n+++ b/AccountController.cs\\n@@ -1,3 +1,4 @@\\n-return Redirect(returnUrl);\\n+if (Url.IsLocalUrl(returnUrl)) return Redirect(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={"domain": "Authentication systems", "input_source": "query_param", "auth_required": False})
rec(id="SCP-000337", language="C#", framework="ASP.NET Core",
title="Weak password hashing (SHA1)",
description="A service stores SHA1 password hashes without salt.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-916", mitre_attack="T1600 - Weaken Encryption",
severity="High", difficulty="Beginner",
vulnerable_code="var hash = SHA1.HashData(Encoding.UTF8.GetBytes(pw)); // Vulnerable: fast, unsalted\\",
secure_code="var hash = Rfc2898DeriveBytes.Pbkdf2(pw, salt, 100_000, HashAlgorithmName.SHA256, 32); // Secure\\",
patch="--- a/Auth.cs\\n+++ b/Auth.cs\\n@@ -1,3 +1,3 @@\\n-var hash = SHA1.HashData(Encoding.UTF8.GetBytes(pw));\\n+var hash = Rfc2898DeriveBytes.Pbkdf2(pw, salt, 100_000, HashAlgorithmName.SHA256, 32);\\",
root_cause="SHA1 unsalted/fast.",
attack="Crack hashes.", impact="Credential compromise.",
fix="Use PBKDF2/bcrypt/argon2.", guideline="Slow salted KDFs.",
tags=["crypto", "csharp", "aspnet", "passwords"],
metadata={"domain": "Authentication systems", "input_source": "request_body", "auth_required": False})
rec(id="SCP-000338", language="C#", framework="ASP.NET Core",
title="XML external entity (XmlDocument)",
description="An XmlDocument parses untrusted XML with DTDs enabled.",
owasp="A05:2021 - Security Misconfiguration", owasp_api="", owasp_llm="",
cwe="CWE-611", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="High", difficulty="Intermediate",
vulnerable_code="var d = new XmlDocument(); d.LoadXml(body); // Vulnerable: XXE if DTDs on\\",
secure_code="var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit };\\nusing var r = XmlReader.Create(new StringReader(body), settings); // Secure\\",
patch="--- a/XmlCtrl.cs\\n+++ b/XmlCtrl.cs\\n@@ -1,3 +1,4 @@\\n-var d = new XmlDocument(); d.LoadXml(body);\\n+var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit };\\n+using var r = XmlReader.Create(new StringReader(body), settings);\\",
root_cause="DTD processing enabled.",
attack="DOCTYPE reads files / SSRF.", impact="File disclosure.",
fix="Prohibit DTDs.", guideline="Harden XML parsing.",
tags=["xxe", "csharp", "aspnet", "xml"],
metadata={"domain": "REST API", "input_source": "request_body", "auth_required": False})
rec(id="SCP-000339", language="C#", framework="ASP.NET Core",
title="CORS allow-all with credentials",
description="CORS policy allows any origin with credentials.",
owasp="A05:2021 - Security Misconfiguration", owasp_api="", owasp_llm="",
cwe="CWE-942", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="Medium", difficulty="Beginner",
vulnerable_code="policy.AllowAnyOrigin().AllowCredentials(); // Vulnerable\\",
secure_code="policy.WithOrigins(\"https://app.example.com\").AllowCredentials(); // Secure\\",
patch="--- a/Program.cs\\n+++ b/Program.cs\\n@@ -1,2 +1,2 @@\\n-policy.AllowAnyOrigin().AllowCredentials();\\n+policy.WithOrigins(\"https://app.example.com\").AllowCredentials();\\",
root_cause="Wildcard origin + credentials.",
attack="Cross-origin read with cookies.", impact="Data theft.",
fix="Pin origins.", guideline="Restrict CORS.",
tags=["cors", "csharp", "aspnet", "config"],
metadata={"domain": "E-commerce", "input_source": "header", "auth_required": True})
rec(id="SCP-000340", language="C#", framework="ASP.NET Core",
title="Business logic: negative amount transfer",
description="A transfer action accepts a negative amount from client.",
owasp="A04:2021 - Insecure Design", owasp_api="API3:2023 - Broken Object Property Level Authorization", owasp_llm="",
cwe="CWE-840", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="Medium", difficulty="Intermediate",
vulnerable_code="[HttpPost(\"transfer\")]\\npublic IActionResult Transfer(Transfer t) { acc.Balance += t.Amount; return Ok(); } // Vulnerable: negative\\",
secure_code="if (t.Amount <= 0 || t.Amount > 1_000_000) return BadRequest(); // Secure\\nacc.Balance += t.Amount; return Ok();\\",
patch="--- a/AccountController.cs\\n+++ b/AccountController.cs\\n@@ -1,3 +1,4 @@\\n-[HttpPost(\"transfer\")]\\npublic IActionResult Transfer(Transfer t) { acc.Balance += t.Amount; return Ok(); }\\n+if (t.Amount <= 0 || t.Amount > 1_000_000) return BadRequest();\\n+acc.Balance += t.Amount; return Ok();\\",
root_cause="Client amount not validated.",
attack="Amount=-100 increases balance.", impact="Financial abuse.",
fix="Validate amount server-side.", guideline="Validate business values.",
tags=["business-logic", "csharp", "aspnet", "banking"],
metadata={"domain": "Banking", "input_source": "request_body", "auth_required": True})
rec(id="SCP-000341", language="C#", framework="ASP.NET Core",
title="Insecure random for token (System.Random)",
description="A token generator uses System.Random.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-338", mitre_attack="T1600 - Weaken Encryption",
severity="High", difficulty="Intermediate",
vulnerable_code="var r = new Random(); var tok = r.Next().ToString(); // Vulnerable: predictable\\",
secure_code="var bytes = RandomNumberGenerator.GetBytes(32); var tok = Convert.ToBase64String(bytes); // Secure: CSPRNG\\",
patch="--- a/Token.cs\\n+++ b/Token.cs\\n@@ -1,3 +1,3 @@\\n-var r = new Random(); var tok = r.Next().ToString();\\n+var bytes = RandomNumberGenerator.GetBytes(32); var tok = Convert.ToBase64String(bytes);\\",
root_cause="Non-CSPRNG token.",
attack="Predict token.", impact="Token forgery.",
fix="Use RandomNumberGenerator.", guideline="Use CSPRNG for tokens.",
tags=["crypto", "csharp", "aspnet", "tokens"],
metadata={"domain": "Authentication systems", "input_source": "server", "auth_required": False})
rec(id="SCP-000342", language="C#", framework="ASP.NET Core",
title="Missing antiforgery on POST",
description="A POST action has no antiforgery token validation.",
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="[HttpPost(\"update\")]\\npublic IActionResult Update(Profile p) { repo.Save(p); return Ok(); } // Vulnerable: no CSRF\\",
secure_code="[HttpPost(\"update\")]\\n[ValidateAntiForgeryToken] // Secure\\npublic IActionResult Update(Profile p) { repo.Save(p); return Ok(); }\\",
patch="--- a/ProfileController.cs\\n+++ b/ProfileController.cs\\n@@ -1,4 +1,5 @@\\n+[ValidateAntiForgeryToken]\\n [HttpPost(\"update\")]\\n public IActionResult Update(Profile p) { repo.Save(p); return Ok(); }\\",
root_cause="No CSRF token on POST.",
attack="Cross-site POST forges update.", impact="Unauthorized change.",
fix="Add antiforgery token.", guideline="Protect state changes.",
tags=["csrf", "csharp", "aspnet", "config"],
metadata={"domain": "E-commerce", "input_source": "form_field", "auth_required": True})
rec(id="SCP-000343", language="C#", framework="ASP.NET Core",
title="Improper certificate validation (ServerCertificateCustomValidationCallback)",
description="An HttpClient accepts any server certificate.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-295", mitre_attack="T1557 - Adversary-in-the-Middle",
severity="Critical", difficulty="Advanced",
vulnerable_code="handler.ServerCertificateCustomValidationCallback = (m, c, ch, e) => true; // Vulnerable: accept all\\",
secure_code="// Use default validation; do not override the callback\\nusing var client = new HttpClient(); // Secure: validates chain\\",
patch="--- a/Client.cs\\n+++ b/Client.cs\\n@@ -1,3 +1,3 @@\\n-handler.ServerCertificateCustomValidationCallback = (m, c, ch, e) => true;\\n+// Use default validation; do not override the callback\\",
root_cause="Certificate validation disabled.",
attack="MITM intercepts TLS.", impact="Credential/data theft.",
fix="Keep default validation.", guideline="Always verify TLS peers.",
tags=["tls", "csharp", "aspnet", "mitm"],
metadata={"domain": "Banking", "input_source": "network", "auth_required": False})
rec(id="SCP-000344", language="C#", framework="ASP.NET Core",
title="File upload without extension check",
description="An upload stores any file by its original name.",
owasp="A04:2021 - Insecure Design", owasp_api="", owasp_llm="",
cwe="CWE-434", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="High", difficulty="Intermediate",
vulnerable_code="await file.CopyToAsync(new FileStream(\"/up/\" + file.FileName, FileMode.Create)); // Vulnerable: any type\\",
secure_code="if (Path.GetExtension(file.FileName) != \".png\") return BadRequest(); // Secure: allowlist\\nvar name = Guid.NewGuid() + \".png\";\\nawait file.CopyToAsync(new FileStream(\"/up/\" + name, FileMode.Create));\\",
patch="--- a/UploadController.cs\\n+++ b/UploadController.cs\\n@@ -1,3 +1,5 @@\\n-await file.CopyToAsync(new FileStream(\"/up/\" + file.FileName, FileMode.Create));\\n+if (Path.GetExtension(file.FileName) != \".png\") return BadRequest();\\n+var name = Guid.NewGuid() + \".png\";\\n+await file.CopyToAsync(new FileStream(\"/up/\" + name, FileMode.Create));\\",
root_cause="No extension validation.",
attack="Upload .aspx webshell.", impact="RCE.",
fix="Allowlist extensions; randomize.", guideline="Validate uploads.",
tags=["file-upload", "csharp", "aspnet", "rce"],
metadata={"domain": "E-commerce", "input_source": "form_field", "auth_required": True})
rec(id="SCP-000345", language="C#", framework="ASP.NET Core",
title="LDAP injection in filter",
description="An LDAP search concatenates user input into a filter.",
owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
cwe="CWE-90", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="High", difficulty="Intermediate",
vulnerable_code="string filter = \"(uid=\" + user + \")\"; // Vulnerable: inject\\",
secure_code="string filter = \"(uid=\" + user.Replace(\"\\\", \"\\\\\").Replace(\"*\", \"\\*\") + \")\"; // Secure: escape\\",
patch="--- a/LdapService.cs\\n+++ b/LdapService.cs\\n@@ -1,3 +1,3 @@\\n-string filter = \"(uid=\" + user + \")\";\\n+string filter = \"(uid=\" + user.Replace(\"\\\", \"\\\\\").Replace(\"*\", \"\\*\") + \")\";\\",
root_cause="Unescaped LDAP filter.",
attack="user=*)(|(uid=* bypasses.", impact="Auth bypass.",
fix="Escape LDAP specials.", guideline="Sanitize LDAP input.",
tags=["ldap-injection", "csharp", "aspnet", "injection"],
metadata={"domain": "Authentication systems", "input_source": "query_param", "auth_required": False})
# ---------------- PHP (SCP-000346 - 000365) ----------------
rec(id="SCP-000346", language="PHP", framework="Laravel",
title="SQL injection via raw query",
description="A Laravel query uses raw SQL with string interpolation.",
owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
cwe="CWE-89", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="High", difficulty="Intermediate",
vulnerable_code="$rows = DB::select(\"SELECT * FROM users WHERE name = '$name'\"); // Vulnerable\\",
secure_code="$rows = DB::select(\"SELECT * FROM users WHERE name = ?\", [$name]); // Secure: bound\\",
patch="--- a/UserRepo.php\\n+++ b/UserRepo.php\\n@@ -1,2 +1,2 @@\\n-$rows = DB::select(\"SELECT * FROM users WHERE name = '$name'\");\\n+$rows = DB::select(\"SELECT * FROM users WHERE name = ?\", [$name]);\\",
root_cause="String interpolation into SQL.",
attack="name=\' OR 1=1 dumps rows.", impact="Data disclosure.",
fix="Use bound parameters.", guideline="Bind all SQL params.",
tags=["sqli", "php", "laravel", "injection"],
metadata={"domain": "E-commerce", "input_source": "query_param", "auth_required": False})
rec(id="SCP-000347", language="PHP", framework="Laravel",
title="Command injection via shell_exec",
description="A Laravel controller passes user input to shell_exec.",
owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
cwe="CWE-78", mitre_attack="T1059 - Command and Scripting Interpreter",
severity="High", difficulty="Intermediate",
vulnerable_code="$out = shell_exec(\"ping -c1 \" . $host); // Vulnerable: shell\\",
secure_code="if (!preg_match(\"/^[\\w.-]+$/\", $host)) abort(400);\\n$out = shell_exec(escapeshellarg(\"ping -c1 \") . escapeshellarg($host)); // Secure\\",
patch="--- a/PingController.php\\n+++ b/PingController.php\\n@@ -1,3 +1,4 @@\\n-$out = shell_exec(\"ping -c1 \" . $host);\\n+if (!preg_match(\"/^[\\w.-]+$/\", $host)) abort(400);\\n+$out = shell_exec(escapeshellarg(\"ping -c1 \") . escapeshellarg($host));\\",
root_cause="Shell with user input.",
attack="host=;cat /etc/passwd executes.", impact="Command injection.",
fix="Validate + escapeshellarg.", guideline="Avoid shell; escape args.",
tags=["command-injection", "php", "laravel", "rce"],
metadata={"domain": "IoT", "input_source": "query_param", "auth_required": False})
rec(id="SCP-000348", language="PHP", framework="Laravel",
title="Path traversal in file response",
description="A controller serves a file from a user path.",
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="return response()->file(\"/data/\" . $request->input(\"name\")); // Vulnerable: traversal\\",
secure_code="$name = basename($request->input(\"name\"));\\n$path = \"/data/\" . $name;\\nif (!str_starts_with(realpath($path), \"/data\")) abort(403); // Secure\\nreturn response()->file($path);\\",
patch="--- a/FilesController.php\\n+++ b/FilesController.php\\n@@ -1,3 +1,5 @@\\n-return response()->file(\"/data/\" . $request->input(\"name\"));\\n+$name = basename($request->input(\"name\"));\\n+$path = \"/data/\" . $name;\\n+if (!str_starts_with(realpath($path), \"/data\")) abort(403);\\n+return response()->file($path);\\",
root_cause="Unsanitized filename.",
attack="name=../../etc/passwd reads file.", impact="File disclosure.",
fix="Basename + confine.", guideline="Confine file paths.",
tags=["path-traversal", "php", "laravel", "file-read"],
metadata={"domain": "Backend", "input_source": "query_param", "auth_required": False})
rec(id="SCP-000349", language="PHP", framework="Laravel",
title="Missing authorization on admin route",
description="An admin route has no middleware check.",
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="Intermediate",
vulnerable_code="Route::delete(\"/admin/user/{id}\", [Admin::class, \"delete\"]); // Vulnerable: no middleware\\",
secure_code="Route::delete(\"/admin/user/{id}\", [Admin::class, \"delete\"])->middleware(\"can:admin\"); // Secure\\",
patch="--- a/routes/web.php\\n+++ b/routes/web.php\\n@@ -1,2 +1,2 @@\\n-Route::delete(\"/admin/user/{id}\", [Admin::class, \"delete\"]);\\n+Route::delete(\"/admin/user/{id}\", [Admin::class, \"delete\"])->middleware(\"can:admin\");\\",
root_cause="No authz middleware.",
attack="Any user deletes accounts.", impact="Privilege escalation.",
fix="Add middleware.", guideline="Enforce admin authz.",
tags=["authorization", "php", "laravel", "broken-access-control"],
metadata={"domain": "Authentication systems", "input_source": "path_param", "auth_required": True})
rec(id="SCP-000350", language="PHP", framework="Laravel",
title="Hardcoded APP_KEY / secret",
description="A .env file contains a static APP_KEY.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-798", mitre_attack="T1552.001 - Unsecured Credentials: Credentials In Files",
severity="High", difficulty="Beginner",
vulnerable_code="APP_KEY=base64:abcdef1234567890= # Vulnerable: static\\",
secure_code="APP_KEY=${APP_KEY} # Secure: from secret manager\\",
patch="--- a/.env\\n+++ b/.env\\n@@ -1,2 +1,2 @@\\n-APP_KEY=base64:abcdef1234567890=\\n+APP_KEY=${APP_KEY}\\",
root_cause="Static secret in repo.",
attack="Decrypt sessions/cookies.", impact="Auth bypass.",
fix="Generate + externalize.", guideline="Externalize APP_KEY.",
tags=["secrets", "php", "laravel", "config"],
metadata={"domain": "Backend", "input_source": "source_code", "auth_required": False})
rec(id="SCP-000351", language="PHP", framework="Laravel",
title="XSS via echoed request input",
description="A Blade view echoes input without escaping.",
owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
cwe="CWE-79", mitre_attack="T1059.007 - Command and Scripting Interpreter: JavaScript",
severity="Medium", difficulty="Beginner",
vulnerable_code="{!! $comment !!}
\\",
secure_code="{{ $comment }}
\\",
patch="--- a/show.blade.php\\n+++ b/show.blade.php\\n@@ -1,2 +1,2 @@\\n-{!! $comment !!}
\\n+{{ $comment }}
\\",
root_cause="{!! !!} disables escaping.",
attack="comment= runs.", impact="XSS.",
fix="Use {{ }} escaping.", guideline="Avoid {!! !!} on user input.",
tags=["xss", "php", "laravel", "template"],
metadata={"domain": "E-commerce", "input_source": "db", "auth_required": False})
rec(id="SCP-000352", language="PHP", framework="Laravel",
title="No rate limit on login",
description="A login route has no throttling.",
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="Beginner",
vulnerable_code="Route::post(\"/login\", [Auth::class, \"login\"]); // Vulnerable: no throttle\\",
secure_code="Route::post(\"/login\", [Auth::class, \"login\"])->middleware(\"throttle:5,1\"); // Secure\\",
patch="--- a/routes/web.php\\n+++ b/routes/web.php\\n@@ -1,2 +1,2 @@\\n-Route::post(\"/login\", [Auth::class, \"login\"]);\\n+Route::post(\"/login\", [Auth::class, \"login\"])->middleware(\"throttle:5,1\");\\",
root_cause="No throttle on auth.",
attack="Brute force credentials.", impact="Account takeover.",
fix="Throttle login.", guideline="Rate limit auth.",
tags=["rate-limiting", "php", "laravel", "auth"],
metadata={"domain": "Authentication systems", "input_source": "request_body", "auth_required": False})
rec(id="SCP-000353", language="PHP", framework="Laravel",
title="Insecure JWT (none alg / weak key)",
description="A Laravel JWT verifier accepts none or uses a weak secret.",
owasp="A07:2021 - Identification and Authentication Failures", owasp_api="API2:2023 - Broken Authentication", owasp_llm="",
cwe="CWE-345", mitre_attack="T1600 - Weaken Encryption",
severity="Critical", difficulty="Advanced",
vulnerable_code="JWTAuth::decode($t, \"weak\", [\"HS256\",\"none\"]); // Vulnerable: none + weak key\\",
secure_code="JWTAuth::decode($t, config(\"jwt.secret\"), [\"HS256\"]); // Secure: strong secret, no none\\",
patch="--- a/Auth.php\\n+++ b/Auth.php\\n@@ -1,2 +1,2 @@\\n-JWTAuth::decode($t, \"weak\", [\"HS256\",\"none\"]);\\n+JWTAuth::decode($t, config(\"jwt.secret\"), [\"HS256\"]);\\",
root_cause="Weak key + none allowed.",
attack="Forge token with none / brute weak key.", impact="Auth bypass.",
fix="Strong secret; forbid none.", guideline="Pin algorithm; strong key.",
tags=["jwt", "php", "laravel", "auth"],
metadata={"domain": "Authentication systems", "input_source": "header", "auth_required": True})
rec(id="SCP-000354", language="PHP", framework="Laravel",
title="IDOR on profile update",
description="An update action uses a client-supplied user id.",
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="$u = User::find($request->input(\"user_id\")); $u->email = ...; // Vulnerable: arbitrary id\\",
secure_code="$u = $request->user(); $u->email = ...; // Secure: current authenticated user\\",
patch="--- a/ProfileController.php\\n+++ b/ProfileController.php\\n@@ -1,3 +1,3 @@\\n-$u = User::find($request->input(\"user_id\")); $u->email = ...;\\n+$u = $request->user(); $u->email = ...;\\",
root_cause="Client id not bound to session.",
attack="Edit any user by id.", impact="Account takeover.",
fix="Use authenticated user.", guideline="Bind to session user.",
tags=["idor", "php", "laravel", "access-control"],
metadata={"domain": "E-commerce", "input_source": "request_body", "auth_required": True})
rec(id="SCP-000355", language="PHP", framework="Laravel",
title="Open redirect",
description="A redirect uses a param without validation.",
owasp="A01:2021 - Broken Access Control", owasp_api="", owasp_llm="",
cwe="CWE-601", mitre_attack="T1566 - Phishing",
severity="Medium", difficulty="Beginner",
vulnerable_code="return redirect()->to($request->input(\"url\")); // Vulnerable\\",
secure_code="$url = $request->input(\"url\");\\nif (!str_starts_with($url, \"/\") || str_starts_with($url, \"//\")) $url = \"/\"; // Secure\\nreturn redirect()->to($url);\\",
patch="--- a/AuthController.php\\n+++ b/AuthController.php\\n@@ -1,3 +1,5 @@\\n-return redirect()->to($request->input(\"url\"));\\n+$url = $request->input(\"url\");\\n+if (!str_starts_with($url, \"/\") || str_starts_with($url, \"//\")) $url = \"/\";\\n+return redirect()->to($url);\\",
root_cause="Unvalidated redirect.",
attack="url=//evil.com phishing.", impact="Phishing.",
fix="Allowlist relative.", guideline="Validate redirects.",
tags=["open-redirect", "php", "laravel", "phishing"],
metadata={"domain": "Authentication systems", "input_source": "query_param", "auth_required": False})
rec(id="SCP-000356", language="PHP", framework="Laravel",
title="Weak password hashing (MD5)",
description="A Laravel app stores MD5 password hashes.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-916", mitre_attack="T1600 - Weaken Encryption",
severity="High", difficulty="Beginner",
vulnerable_code="$hash = md5($password); // Vulnerable: fast, unsalted\\",
secure_code="$hash = password_hash($password, PASSWORD_BCRYPT, [\"cost\" => 12]); // Secure: salted\\",
patch="--- a/Auth.php\\n+++ b/Auth.php\\n@@ -1,2 +1,2 @@\\n-$hash = md5($password);\\n+$hash = password_hash($password, PASSWORD_BCRYPT, [\"cost\" => 12]);\\",
root_cause="MD5 unsalted/fast.",
attack="Crack hashes.", impact="Credential compromise.",
fix="Use password_hash.", guideline="Slow salted KDFs.",
tags=["crypto", "php", "laravel", "passwords"],
metadata={"domain": "Authentication systems", "input_source": "request_body", "auth_required": False})
rec(id="SCP-000357", language="PHP", framework="Laravel",
title="Unrestricted file upload",
description="An upload stores any file type by its name.",
owasp="A04:2021 - Insecure Design", owasp_api="", owasp_llm="",
cwe="CWE-434", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="High", difficulty="Intermediate",
vulnerable_code="$request->file(\"avatar\")->storeAs(\"public\", $file->getClientOriginalName()); // Vulnerable: any type\\",
secure_code="if (!in_array($file->getClientOriginalExtension(), [\"png\",\"jpg\"])) abort(400); // Secure\\n$file->storeAs(\"public\", Str::uuid() . \".png\");\\",
patch="--- a/UploadController.php\\n+++ b/UploadController.php\\n@@ -1,3 +1,4 @@\\n-$request->file(\"avatar\")->storeAs(\"public\", $file->getClientOriginalName());\\n+if (!in_array($file->getClientOriginalExtension(), [\"png\",\"jpg\"])) abort(400);\\n+$file->storeAs(\"public\", Str::uuid() . \".png\");\\",
root_cause="No extension validation.",
attack="Upload .php webshell.", impact="RCE.",
fix="Allowlist extensions; randomize.", guideline="Validate uploads.",
tags=["file-upload", "php", "laravel", "rce"],
metadata={"domain": "E-commerce", "input_source": "form_field", "auth_required": True})
rec(id="SCP-000358", language="PHP", framework="Laravel",
title="CSRF protection disabled",
description="A form POST skips CSRF verification.",
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=" \\",
secure_code=" \\",
patch="--- a/edit.blade.php\\n+++ b/edit.blade.php\\n@@ -1,2 +1,2 @@\\n-\\n+\\",
root_cause="Missing CSRF token.",
attack="Cross-site POST forges change.", impact="Unauthorized action.",
fix="Add @csrf.", guideline="Protect state changes.",
tags=["csrf", "php", "laravel", "config"],
metadata={"domain": "E-commerce", "input_source": "form_field", "auth_required": True})
rec(id="SCP-000359", language="PHP", framework="Laravel",
title="Mass assignment via fill()",
description="A model uses fill() with all request input including role.",
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="User::find($id)->fill($request->all())->save(); // Vulnerable: role mass-assigned\\",
secure_code="User::find($id)->fill($request->only([\"name\",\"email\"]))->save(); // Secure: guarded\\",
patch="--- a/UserController.php\\n+++ b/UserController.php\\n@@ -1,2 +1,2 @@\\n-User::find($id)->fill($request->all())->save();\\n+User::find($id)->fill($request->only([\"name\",\"email\"]))->save();\\",
root_cause="All fields fillable.",
attack="POST role=admin escalates.", impact="Privilege escalation.",
fix="Use $fillable / only().", guideline="Whitelist assignable fields.",
tags=["mass-assignment", "php", "laravel", "auth"],
metadata={"domain": "E-commerce", "input_source": "request_body", "auth_required": True})
rec(id="SCP-000360", language="PHP", framework="Laravel",
title="XML external entity",
description="A controller parses XML with external entity resolution on.",
owasp="A05:2021 - Security Misconfiguration", owasp_api="", owasp_llm="",
cwe="CWE-611", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="High", difficulty="Intermediate",
vulnerable_code="$xml = simplexml_load_string($body, \"SimpleXMLElement\", LIBXML_NOENT); // Vulnerable: XXE\\",
secure_code="libxml_disable_entity_loader(true);\\n$xml = simplexml_load_string($body, \"SimpleXMLElement\", LIBXML_NONET); // Secure\\",
patch="--- a/XmlController.php\\n+++ b/XmlController.php\\n@@ -1,3 +1,4 @@\\n-$xml = simplexml_load_string($body, \"SimpleXMLElement\", LIBXML_NOENT);\\n+libxml_disable_entity_loader(true);\\n+$xml = simplexml_load_string($body, \"SimpleXMLElement\", LIBXML_NONET);\\",
root_cause="External entities enabled.",
attack="DOCTYPE reads files / SSRF.", impact="File disclosure.",
fix="Disable entities.", guideline="Harden XML parsing.",
tags=["xxe", "php", "laravel", "xml"],
metadata={"domain": "REST API", "input_source": "request_body", "auth_required": False})
rec(id="SCP-000361", language="PHP", framework="Laravel",
title="Business logic: negative quantity",
description="A cart uses a client-supplied quantity without bounds.",
owasp="A04:2021 - Insecure Design", owasp_api="API3:2023 - Broken Object Property Level Authorization", owasp_llm="",
cwe="CWE-840", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="Medium", difficulty="Intermediate",
vulnerable_code="$cart->qty = $request->input(\"qty\"); $cart->save(); // Vulnerable: negative\\",
secure_code="$q = (int)$request->input(\"qty\");\\nif ($q <= 0 || $q > 100) abort(400); // Secure\\n$cart->qty = $q; $cart->save();\\",
patch="--- a/CartController.php\\n+++ b/CartController.php\\n@@ -1,3 +1,5 @@\\n-$cart->qty = $request->input(\"qty\"); $cart->save();\\n+$q = (int)$request->input(\"qty\");\\n+if ($q <= 0 || $q > 100) abort(400);\\n+$cart->qty = $q; $cart->save();\\",
root_cause="Client qty not bounded.",
attack="qty=-5 => negative charge.", impact="Revenue loss.",
fix="Validate qty server-side.", guideline="Validate business values.",
tags=["business-logic", "php", "laravel", "ecommerce"],
metadata={"domain": "E-commerce", "input_source": "request_body", "auth_required": True})
rec(id="SCP-000362", language="PHP", framework="Laravel",
title="Insecure unserialize of user data",
description="A controller unserializes a cookie value.",
owasp="A08:2021 - Software and Data Integrity Failures", owasp_api="", owasp_llm="",
cwe="CWE-502", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="Critical", difficulty="Advanced",
vulnerable_code="$data = unserialize($_COOKIE[\"cart\"]); // Vulnerable: POP chain RCE\\",
secure_code="$data = json_decode($_COOKIE[\"cart\"], true); // Secure: no code execution\\",
patch="--- a/CartController.php\\n+++ b/CartController.php\\n@@ -1,2 +1,2 @@\\n-$data = unserialize($_COOKIE[\"cart\"]);\\n+$data = json_decode($_COOKIE[\"cart\"], true);\\",
root_cause="unserialize of untrusted data.",
attack="Craft POP gadget for RCE.", impact="Remote code execution.",
fix="Use json_decode.", guideline="Never unserialize user data.",
tags=["deserialization", "php", "laravel", "rce"],
metadata={"domain": "E-commerce", "input_source": "cookie", "auth_required": False})
rec(id="SCP-000363", language="PHP", framework="Laravel",
title="Verbose error display",
description="APP_DEBUG=true in production leaks stack traces.",
owasp="A05:2021 - Security Misconfiguration", owasp_api="", owasp_llm="",
cwe="CWE-209", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="Medium", difficulty="Beginner",
vulnerable_code="APP_DEBUG=true # Vulnerable: leaks in prod\\",
secure_code="APP_DEBUG=false # Secure: off in prod\\",
patch="--- a/.env\\n+++ b/.env\\n@@ -1,2 +1,2 @@\\n-APP_DEBUG=true\\n+APP_DEBUG=false\\",
root_cause="Debug on in production.",
attack="Trigger error to read source.", impact="Info disclosure.",
fix="APP_DEBUG=false.", guideline="Never debug in prod.",
tags=["info-leak", "php", "laravel", "config"],
metadata={"domain": "Backend", "input_source": "source_code", "auth_required": False})
rec(id="SCP-000364", language="PHP", framework="Laravel",
title="CORS allow-all with credentials",
description="CORS config permits any origin with credentials.",
owasp="A05:2021 - Security Misconfiguration", owasp_api="", owasp_llm="",
cwe="CWE-942", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="Medium", difficulty="Beginner",
vulnerable_code="allowed_origins => [\\'*\\'], # Vulnerable + credentials",
secure_code="allowed_origins => [\\",
patch="--- a/config/cors.php\\n+++ b/config/cors.php\\n@@ -1,2 +1,2 @@\\n-allowed_origins => [\\'*\\'],\\n+allowed_origins => [\\",
root_cause="Wildcard origin + credentials.",
attack="Cross-origin read with cookies.", impact="Data theft.",
fix="Pin origins.", guideline="Restrict CORS.",
tags=["cors", "php", "laravel", "config"],
metadata={"domain": "E-commerce", "input_source": "header", "auth_required": True})
rec(id="SCP-000365", language="PHP", framework="Laravel",
title="Insecure random for token",
description="A token generator uses mt_rand.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-338", mitre_attack="T1600 - Weaken Encryption",
severity="High", difficulty="Intermediate",
vulnerable_code="$tok = md5(mt_rand() . time()); // Vulnerable: predictable\\",
secure_code="$tok = bin2hex(random_bytes(32)); // Secure: CSPRNG\\",
patch="--- a/Token.php\\n+++ b/Token.php\\n@@ -1,2 +1,2 @@\\n-$tok = md5(mt_rand() . time());\\n+$tok = bin2hex(random_bytes(32));\\",
root_cause="Non-CSPRNG token.",
attack="Predict token sequence.", impact="Token forgery.",
fix="Use random_bytes.", guideline="Use CSPRNG for tokens.",
tags=["crypto", "php", "laravel", "tokens"],
metadata={"domain": "Authentication systems", "input_source": "server", "auth_required": False})
# ---------------- Rust (SCP-000366 - 000385) ----------------
rec(id="SCP-000366", language="Rust", framework="Actix",
title="SQL injection via string format",
description="An Actix handler builds a query by formatting.",
owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
cwe="CWE-89", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="High", difficulty="Intermediate",
vulnerable_code="let q = format!(\"SELECT * FROM users WHERE name = '{}''\", name);\\nsqlx::query(&q).fetch_all(&pool).await // Vulnerable\\",
secure_code="sqlx::query(\"SELECT * FROM users WHERE name = $1\").bind(&name).fetch_all(&pool).await // Secure: bound\\",
patch="--- a/handler.rs\\n+++ b/handler.rs\\n@@ -1,3 +1,2 @@\\n-let q = format!(\"SELECT * FROM users WHERE name = '{}''\", name);\\n-sqlx::query(&q).fetch_all(&pool).await\\n+sqlx::query(\"SELECT * FROM users WHERE name = $1\").bind(&name).fetch_all(&pool).await\\",
root_cause="Format into SQL.",
attack="name=\' OR 1=1 dumps rows.", impact="Data disclosure.",
fix="Use bound parameters.", guideline="Bind all SQL params.",
tags=["sqli", "rust", "actix", "injection"],
metadata={"domain": "E-commerce", "input_source": "query_param", "auth_required": False})
rec(id="SCP-000367", language="Rust", framework="Actix",
title="Command injection via shell",
description="An Actix handler runs a shell command with user input.",
owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
cwe="CWE-78", mitre_attack="T1059 - Command and Scripting Interpreter",
severity="High", difficulty="Intermediate",
vulnerable_code="let out = Command::new(\"sh\").arg(\"-c\").arg(format!(\"ping -c1 {}\", host)).output(); // Vulnerable\\",
secure_code="if !valid_host(&host) { return HttpResponse::BadRequest().finish(); }\\nlet out = Command::new(\"ping\").arg(\"-c1\").arg(&host).output(); // Secure: arg array\\",
patch="--- a/ping.rs\\n+++ b/ping.rs\\n@@ -1,3 +1,4 @@\\n-let out = Command::new(\"sh\").arg(\"-c\").arg(format!(\"ping -c1 {}\", host)).output();\\n+if !valid_host(&host) { return HttpResponse::BadRequest().finish(); }\\n+let out = Command::new(\"ping\").arg(\"-c1\").arg(&host).output();\\",
root_cause="Shell with user input.",
attack="host=;cat /etc/passwd executes.", impact="Command injection.",
fix="Validate + arg array.", guideline="Avoid shell.",
tags=["command-injection", "rust", "actix", "rce"],
metadata={"domain": "IoT", "input_source": "query_param", "auth_required": False})
rec(id="SCP-000368", language="Rust", framework="Actix",
title="Path traversal in file serve",
description="An Actix handler serves a file from a user path.",
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="let path = format!(\"/data/{}\", name); // Vulnerable: traversal\\nactix_files::NamedFile::open(path)?.into_response(&req)\\",
secure_code="let name = Path::new(&name).file_name().ok_or(404)?;\\nlet path = Path::new(\"/data\").join(name); // Secure: basename\\nactix_files::NamedFile::open(path)?.into_response(&req)\\",
patch="--- a/files.rs\\n+++ b/files.rs\\n@@ -1,4 +1,5 @@\\n-let path = format!(\"/data/{}\", name);\\n-actix_files::NamedFile::open(path)?.into_response(&req)\\n+let name = Path::new(&name).file_name().ok_or(404)?;\\n+let path = Path::new(\"/data\").join(name);\\n+actix_files::NamedFile::open(path)?.into_response(&req)\\",
root_cause="Unsanitized filename.",
attack="name=../../etc/passwd reads file.", impact="File disclosure.",
fix="Basename + confine.", guideline="Confine file paths.",
tags=["path-traversal", "rust", "actix", "file-read"],
metadata={"domain": "Backend", "input_source": "query_param", "auth_required": False})
rec(id="SCP-000369", language="Rust", framework="Actix",
title="Missing authorization on admin route",
description="An admin route has no guard/middleware.",
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="Intermediate",
vulnerable_code=".route(\"/admin/user/{id}\", web::delete().to(delete_user)) // Vulnerable: no guard\\",
secure_code=".route(\"/admin/user/{id}\", web::delete().guard(admin_guard).to(delete_user)) // Secure\\",
patch="--- a/routes.rs\\n+++ b/routes.rs\\n@@ -1,2 +1,2 @@\\n-.route(\"/admin/user/{id}\", web::delete().to(delete_user))\\n+.route(\"/admin/user/{id}\", web::delete().guard(admin_guard).to(delete_user))\\",
root_cause="No authz guard.",
attack="Any user deletes accounts.", impact="Privilege escalation.",
fix="Add guard.", guideline="Enforce admin authz.",
tags=["authorization", "rust", "actix", "broken-access-control"],
metadata={"domain": "Authentication systems", "input_source": "path_param", "auth_required": True})
rec(id="SCP-000370", language="Rust", framework="Actix",
title="Hardcoded secret in source",
description="A Rust service hardcodes an API key.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-798", mitre_attack="T1552.001 - Unsecured Credentials: Credentials In Files",
severity="High", difficulty="Beginner",
vulnerable_code="const API_KEY: &str = \"sk_live_7b6a5948\"; // Vulnerable\\",
secure_code="let api_key = std::env::var(\"API_KEY\").expect(\"API_KEY\"); // Secure: env\\",
patch="--- a/config.rs\\n+++ b/config.rs\\n@@ -1,2 +1,2 @@\\n-const API_KEY: &str = \"sk_live_7b6a5948\";\\n+let api_key = std::env::var(\"API_KEY\").expect(\"API_KEY\");\\",
root_cause="Secret in source.",
attack="Repo access reveals key.", impact="Key compromise.",
fix="Use env/secret.", guideline="Externalize secrets.",
tags=["secrets", "rust", "actix", "config"],
metadata={"domain": "Banking", "input_source": "source_code", "auth_required": False})
rec(id="SCP-000371", language="Rust", framework="Actix",
title="XSS via raw HTML response",
description="An Actix handler returns user input as text/html without escaping.",
owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
cwe="CWE-79", mitre_attack="T1059.007 - Command and Scripting Interpreter: JavaScript",
severity="Medium", difficulty="Beginner",
vulnerable_code="HttpResponse::Ok().content_type(\"text/html\").body(format!(\"{}
\", comment)) // Vulnerable\\",
secure_code="let esc = html_escape::encode_text(&comment); // Secure: escape\\nHttpResponse::Ok().content_type(\"text/html\").body(format!(\"{}
\", esc))\\",
patch="--- a/post.rs\\n+++ b/post.rs\\n@@ -1,3 +1,4 @@\\n-HttpResponse::Ok().content_type(\"text/html\").body(format!(\"{}
\", comment))\\n+let esc = html_escape::encode_text(&comment);\\n+HttpResponse::Ok().content_type(\"text/html\").body(format!(\"{}
\", esc))\\",
root_cause="Unescaped HTML in body.",
attack="comment= runs.", impact="XSS.",
fix="Escape output.", guideline="Escape user HTML.",
tags=["xss", "rust", "actix", "template"],
metadata={"domain": "E-commerce", "input_source": "db", "auth_required": False})
rec(id="SCP-000372", language="Rust", framework="Actix",
title="No rate limit on login",
description="A login route has no throttling.",
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="Beginner",
vulnerable_code=".route(\"/login\", web::post().to(login)) // Vulnerable: no throttle\\",
secure_code=".route(\"/login\", web::post().to(login)).wrap(RateLimiter::new(5, 60)) // Secure\\",
patch="--- a/routes.rs\\n+++ b/routes.rs\\n@@ -1,2 +1,2 @@\\n-.route(\"/login\", web::post().to(login))\\n+.route(\"/login\", web::post().to(login)).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", "rust", "actix", "auth"],
metadata={"domain": "Authentication systems", "input_source": "request_body", "auth_required": False})
rec(id="SCP-000373", language="Rust", framework="Actix",
title="Insecure JWT verification (no alg pin)",
description="A JWT verifier does not pin the algorithm.",
owasp="A07:2021 - Identification and Authentication Failures", owasp_api="API2:2023 - Broken Authentication", owasp_llm="",
cwe="CWE-345", mitre_attack="T1600 - Weaken Encryption",
severity="Critical", difficulty="Advanced",
vulnerable_code="let token = decode::(&t, &key, &Validation::new(Algorithm::HS256)); // Vulnerable if alg not pinned strictly\\",
secure_code="let mut v = Validation::new(Algorithm::HS256);\\nv.validate_nbf = true;\\nlet token = decode::(&t, &key, &v); // Secure: strict\\",
patch="--- a/auth.rs\\n+++ b/auth.rs\\n@@ -1,3 +1,4 @@\\n-let token = decode::(&t, &key, &Validation::new(Algorithm::HS256));\\n+let mut v = Validation::new(Algorithm::HS256);\\n+v.validate_nbf = true;\\n+let token = decode::(&t, &key, &v);\\",
root_cause="Loose algorithm validation.",
attack="Algorithm confusion / none.", impact="Auth bypass.",
fix="Pin algorithm strictly.", guideline="Forbid none/confusion.",
tags=["jwt", "rust", "actix", "auth"],
metadata={"domain": "Authentication systems", "input_source": "header", "auth_required": True})
rec(id="SCP-000374", language="Rust", framework="Actix",
title="IDOR on resource read",
description="A handler returns a resource by id without owner 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="let inv = repo.find_invoice(id).await?; // Vulnerable: no owner\nOk(HttpResponse::Ok().json(inv))",
secure_code="let inv = repo.find_invoice_for(id, user_id).await?; // Secure: scoped\nOk(HttpResponse::Ok().json(inv))",
patch='--- a/invoice.rs\n+++ b/invoice.rs\n@@ -1,2 +1,3 @@\n-let inv = repo.find_invoice(id).await?;\n+let inv = repo.find_invoice_for(id, user_id).await?;',
root_cause="No ownership scoping.",
attack="Enumerate others invoices.", impact="PII disclosure.",
fix="Scope by owner.", guideline="Authorize reads by owner.",
tags=["idor", "rust", "actix", "access-control"],
metadata={"domain": "E-commerce", "input_source": "path_param", "auth_required": True})
rec(id="SCP-000375", language="Rust", framework="Actix",
title="Open redirect",
description="A handler redirects to a param without validation.",
owasp="A01:2021 - Broken Access Control", owasp_api="", owasp_llm="",
cwe="CWE-601", mitre_attack="T1566 - Phishing",
severity="Medium", difficulty="Beginner",
vulnerable_code="HttpResponse::Found().insert_header((\"Location\", url)).finish() // Vulnerable\\",
secure_code="if !(url.starts_with(\"/\") && !url.starts_with(\"//\")) { url = \"/\".into(); } // Secure\\nHttpResponse::Found().insert_header((\"Location\", url)).finish()\\",
patch="--- a/links.rs\\n+++ b/links.rs\\n@@ -1,3 +1,4 @@\\n-HttpResponse::Found().insert_header((\"Location\", url)).finish()\\n+if !(url.starts_with(\"/\") && !url.starts_with(\"//\")) { url = \"/\".into(); }\\n+HttpResponse::Found().insert_header((\"Location\", url)).finish()\\",
root_cause="Unvalidated redirect.",
attack="url=//evil.com phishing.", impact="Phishing.",
fix="Allowlist relative.", guideline="Validate redirects.",
tags=["open-redirect", "rust", "actix", "phishing"],
metadata={"domain": "Authentication systems", "input_source": "query_param", "auth_required": False})
rec(id="SCP-000376", language="Rust", framework="Actix",
title="Use of unsafe with raw pointer",
description="A handler dereferences a raw pointer unsafely.",
owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
cwe="CWE-476", mitre_attack="T1203 - Exploitation for Client Execution",
severity="High", difficulty="Advanced",
vulnerable_code="unsafe { let v = *ptr; } // Vulnerable: unchecked raw ptr\\",
secure_code="if let Some(v) = ptr.as_ref() { /* use v */ } // Secure: safe wrapper\\",
patch="--- a/handler.rs\\n+++ b/handler.rs\\n@@ -1,3 +1,3 @@\\n-unsafe { let v = *ptr; }\\n+if let Some(v) = ptr.as_ref() { /* use v */ }\\",
root_cause="Unchecked unsafe deref.",
attack="Null/wild ptr crash or corrupt.", impact="Memory corruption.",
fix="Avoid unsafe; use safe wrappers.", guideline="Minimize unsafe.",
tags=["memory-safety", "rust", "actix", "unsafe"],
metadata={"domain": "IoT", "input_source": "internal", "auth_required": False})
rec(id="SCP-000377", language="Rust", framework="Actix",
title="Weak random for token (rand::random default)",
description="A token generator uses a weak RNG.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-338", mitre_attack="T1600 - Weaken Encryption",
severity="High", difficulty="Intermediate",
vulnerable_code="let tok = rand::random::().to_string(); // Vulnerable if thread_rng weak\\",
secure_code="use rand::rngs::OsRng;\\nlet mut buf = [0u8; 32]; OsRng.fill_bytes(&mut buf); // Secure: OS CSPRNG\\",
patch="--- a/token.rs\\n+++ b/token.rs\\n@@ -1,3 +1,4 @@\\n-let tok = rand::random::().to_string();\\n+use rand::rngs::OsRng;\\n+let mut buf = [0u8; 32]; OsRng.fill_bytes(&mut buf);\\",
root_cause="Weak RNG token.",
attack="Predict token.", impact="Token forgery.",
fix="Use OsRng/getrandom.", guideline="Use CSPRNG for tokens.",
tags=["crypto", "rust", "actix", "tokens"],
metadata={"domain": "Authentication systems", "input_source": "server", "auth_required": False})
rec(id="SCP-000378", language="Rust", framework="Actix",
title="Deserialization of untrusted JSON into Value",
description="A handler deserializes into serde_json::Value enabling type confusion.",
owasp="A08:2021 - Software and Data Integrity Failures", owasp_api="", owasp_llm="",
cwe="CWE-502", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="Medium", difficulty="Advanced",
vulnerable_code="let v: serde_json::Value = serde_json::from_slice(&body)?; // Vulnerable: loose typing\\",
secure_code="let v: StrictDto = serde_json::from_slice(&body)?; // Secure: typed DTO\\",
patch="--- a/handler.rs\\n+++ b/handler.rs\\n@@ -1,2 +1,2 @@\\n-let v: serde_json::Value = serde_json::from_slice(&body)?;\\n+let v: StrictDto = serde_json::from_slice(&body)?;\\",
root_cause="Untyped JSON.",
attack="Type confusion downstream.", impact="Logic abuse.",
fix="Use strict DTOs.", guideline="Type all JSON input.",
tags=["deserialization", "rust", "actix", "injection"],
metadata={"domain": "Microservices", "input_source": "request_body", "auth_required": False})
rec(id="SCP-000379", language="Rust", framework="Actix",
title="Race condition on shared state (Mutex missing)",
description="A counter is mutated across requests without a Mutex.",
owasp="A01:2021 - Broken Access Control", owasp_api="API3:2023 - Broken Object Property Level Authorization", owasp_llm="",
cwe="CWE-362", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="Medium", difficulty="Advanced",
vulnerable_code="let mut counter = counter_clone; // Vulnerable: unsynchronized mutation\\ncounter += 1;\\",
secure_code="let mut c = counter.lock().unwrap(); // Secure: Mutex\\n*c += 1;\\",
patch="--- a/handler.rs\\n+++ b/handler.rs\\n@@ -1,3 +1,3 @@\\n-let mut counter = counter_clone;\\n-counter += 1;\\n+let mut c = counter.lock().unwrap();\\n+*c += 1;\\",
root_cause="Unsynchronized shared mutation.",
attack="Lost updates.", impact="Inconsistent state.",
fix="Use Mutex/Arc.", guideline="Protect shared state.",
tags=["race-condition", "rust", "actix", "concurrency"],
metadata={"domain": "Backend", "input_source": "internal", "auth_required": False})
rec(id="SCP-000380", language="Rust", framework="Actix",
title="Insecure TLS (danger_accept_invalid_certs)",
description="A reqwest client accepts invalid certificates.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-295", mitre_attack="T1557 - Adversary-in-the-Middle",
severity="Critical", difficulty="Advanced",
vulnerable_code="let client = reqwest::Client::builder().danger_accept_invalid_certs(true).build()?; // Vulnerable\\",
secure_code="let client = reqwest::Client::builder().build()?; // Secure: verifies certs\\",
patch="--- a/client.rs\\n+++ b/client.rs\\n@@ -1,3 +1,3 @@\\n-let client = reqwest::Client::builder().danger_accept_invalid_certs(true).build()?;\\n+let client = reqwest::Client::builder().build()?;\\",
root_cause="Cert verification disabled.",
attack="MITM intercepts TLS.", impact="Credential/data theft.",
fix="Keep verification on.", guideline="Always verify TLS peers.",
tags=["tls", "rust", "actix", "mitm"],
metadata={"domain": "Banking", "input_source": "network", "auth_required": False})
rec(id="SCP-000381", language="Rust", framework="Actix",
title="LDAP injection in filter",
description="An LDAP filter is built by concatenation.",
owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
cwe="CWE-90", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="High", difficulty="Intermediate",
vulnerable_code="let filter = format!(\"(uid={})\", user); // Vulnerable: inject\\",
secure_code="let filter = format!(\"(uid={})\", user.replace(\"\\\", \"\\\\\").replace(\"*\", \"\\*\")); // Secure: escape\\",
patch="--- a/ldap.rs\\n+++ b/ldap.rs\\n@@ -1,2 +1,2 @@\\n-let filter = format!(\"(uid={})\", user);\\n+let filter = format!(\"(uid={})\", user.replace(\"\\\", \"\\\\\").replace(\"*\", \"\\*\"));\\",
root_cause="Unescaped LDAP filter.",
attack="user=*)(|(uid=* bypasses.", impact="Auth bypass.",
fix="Escape LDAP specials.", guideline="Sanitize LDAP input.",
tags=["ldap-injection", "rust", "actix", "injection"],
metadata={"domain": "Authentication systems", "input_source": "query_param", "auth_required": False})
rec(id="SCP-000382", language="Rust", framework="Actix",
title="CORS allow-all with credentials",
description="CORS permits any origin with credentials.",
owasp="A05:2021 - Security Misconfiguration", owasp_api="", owasp_llm="",
cwe="CWE-942", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="Medium", difficulty="Beginner",
vulnerable_code=".allowed_origin(Origin::star()) // Vulnerable + credentials\\",
secure_code=".allowed_origin(Origin::exact(\"https://app.example.com\".parse().unwrap())) // Secure\\",
patch="--- a/cors.rs\\n+++ b/cors.rs\\n@@ -1,2 +1,2 @@\\n-.allowed_origin(Origin::star())\\n+.allowed_origin(Origin::exact(\"https://app.example.com\".parse().unwrap()))\\",
root_cause="Wildcard origin + credentials.",
attack="Cross-origin read with cookies.", impact="Data theft.",
fix="Pin origins.", guideline="Restrict CORS.",
tags=["cors", "rust", "actix", "config"],
metadata={"domain": "E-commerce", "input_source": "header", "auth_required": True})
rec(id="SCP-000383", language="Rust", framework="Actix",
title="Business logic: negative amount",
description="A transfer handler accepts a negative amount.",
owasp="A04:2021 - Insecure Design", owasp_api="API3:2023 - Broken Object Property Level Authorization", owasp_llm="",
cwe="CWE-840", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="Medium", difficulty="Intermediate",
vulnerable_code="acc.balance += req.amount; // Vulnerable: negative allowed\\",
secure_code="if req.amount <= 0.0 || req.amount > 1_000_000.0 { return Err(...); } // Secure\\nacc.balance += req.amount;\\",
patch="--- a/account.rs\\n+++ b/account.rs\\n@@ -1,3 +1,4 @@\\n-acc.balance += req.amount;\\n+if req.amount <= 0.0 || req.amount > 1_000_000.0 { return Err(...); }\\n+acc.balance += req.amount;\\",
root_cause="Client amount not validated.",
attack="amount=-100 increases balance.", impact="Financial abuse.",
fix="Validate amount.", guideline="Validate business values.",
tags=["business-logic", "rust", "actix", "banking"],
metadata={"domain": "Banking", "input_source": "request_body", "auth_required": True})
rec(id="SCP-000384", language="Rust", framework="Actix",
title="File upload without type check",
description="An upload stores any content type.",
owasp="A04:2021 - Insecure Design", owasp_api="", owasp_llm="",
cwe="CWE-434", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="High", difficulty="Intermediate",
vulnerable_code="std::fs::write(format!(\"/up/{}\", fname), data)?; // Vulnerable: any type\\",
secure_code="if ct != \"image/png\" && ct != \"image/jpeg\" { return Err(...); } // Secure\\nlet name = format!(\"{}.png\", Uuid::new_v4());\\nstd::fs::write(format!(\"/up/{}\", name), data)?;\\",
patch="--- a/upload.rs\\n+++ b/upload.rs\\n@@ -1,3 +1,5 @@\\n-std::fs::write(format!(\"/up/{}\", fname), data)?;\\n+if ct != \"image/png\" && ct != \"image/jpeg\" { return Err(...); }\\n+let name = format!(\"{}.png\", Uuid::new_v4());\\n+std::fs::write(format!(\"/up/{}\", name), data)?;\\",
root_cause="No type validation.",
attack="Upload .rs/.sh webshell.", impact="RCE.",
fix="Allowlist types; randomize.", guideline="Validate uploads.",
tags=["file-upload", "rust", "actix", "rce"],
metadata={"domain": "E-commerce", "input_source": "form_field", "auth_required": True})
rec(id="SCP-000385", language="Rust", framework="Actix",
title="Verbose error in response",
description="A handler returns raw error strings to the client.",
owasp="A05:2021 - Security Misconfiguration", owasp_api="", owasp_llm="",
cwe="CWE-209", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="Low", difficulty="Beginner",
vulnerable_code="HttpResponse::InternalServerError().body(format!(\"err: {}\", e)) // Vulnerable: leaks\\",
secure_code="log::error!(\"err: {}\", e);\\nHttpResponse::InternalServerError().body(\"internal_error\") // Secure\\",
patch="--- a/handler.rs\\n+++ b/handler.rs\\n@@ -1,3 +1,4 @@\\n-HttpResponse::InternalServerError().body(format!(\"err: {}\", e))\\n+log::error!(\"err: {}\", e);\\n+HttpResponse::InternalServerError().body(\"internal_error\")\\",
root_cause="Raw error to client.",
attack="Extract internal details.", impact="Info disclosure.",
fix="Generic error to client.", guideline="Log detailed, return generic.",
tags=["info-leak", "rust", "actix", "error-handling"],
metadata={"domain": "Backend", "input_source": "server", "auth_required": False})
# ---------------- Kotlin (SCP-000386 - 000400) ----------------
rec(id="SCP-000386", language="Kotlin", framework="Android",
title="SQL injection in Android Room raw query",
description="An Android DAO runs a raw query with string concatenation.",
owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
cwe="CWE-89", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="High", difficulty="Intermediate",
vulnerable_code="@Query(\"SELECT * FROM users WHERE name = :name\") // ok but\\nfun search(name: String): List // misuse below\\nfun raw(n: String) = db.query(\"SELECT * FROM users WHERE name='$n'\") // Vulnerable\\",
secure_code="@Query(\"SELECT * FROM users WHERE name = :name\")\\nfun search(@Param(\"name\") name: String): List // Secure: bound param\\",
patch="--- a/UserDao.kt\\n+++ b/UserDao.kt\\n@@ -1,4 +1,3 @@\\n-fun raw(n: String) = db.query(\"SELECT * FROM users WHERE name='$n'\")\\n+@Query(\"SELECT * FROM users WHERE name = :name\")\\n+fun search(@Param(\"name\") name: String): List\\",
root_cause="Raw query with concatenation.",
attack="n=\' OR 1=1 dumps rows.", impact="Data disclosure.",
fix="Use @Query with params.", guideline="Bind all SQL params.",
tags=["sqli", "kotlin", "android", "injection"],
metadata={"domain": "Mobile", "input_source": "query_param", "auth_required": False})
rec(id="SCP-000387", language="Kotlin", framework="Android",
title="WebView JavaScript interface RCE",
description="An Android WebView exposes a Java object to JS without restriction.",
owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
cwe="CWE-79", mitre_attack="T1059.007 - Command and Scripting Interpreter: JavaScript",
severity="High", difficulty="Advanced",
vulnerable_code="webView.addJavascriptInterface(Bridge(), \"bridge\") // Vulnerable: RCE via reflection\\",
secure_code="// Never addJavascriptInterface on API < 17; restrict to trusted content\\nwebView.settings.javaScriptEnabled = false // Secure\\",
patch="--- a/MainActivity.kt\\n+++ b/MainActivity.kt\\n@@ -1,3 +1,3 @@\\n-webView.addJavascriptInterface(Bridge(), \"bridge\")\\n+webView.settings.javaScriptEnabled = false\\",
root_cause="JS bridge exposes methods.",
attack="Malicious page calls bridge methods.", impact="RCE on device.",
fix="Disable JS bridge / sandbox.", guideline="Avoid addJavascriptInterface.",
tags=["rce", "kotlin", "android", "webview"],
metadata={"domain": "Mobile", "input_source": "web", "auth_required": False})
rec(id="SCP-000388", language="Kotlin", framework="Android",
title="Insecure WebView with cleartext traffic",
description="An Android WebView allows cleartext HTTP.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-319", mitre_attack="T1557 - Adversary-in-the-Middle",
severity="Medium", difficulty="Intermediate",
vulnerable_code="android:usesCleartextTraffic=\"true\" // Vulnerable: MITM\\",
secure_code="android:usesCleartextTraffic=\"false\" // Secure: HTTPS only\\",
patch="--- a/AndroidManifest.xml\\n+++ b/AndroidManifest.xml\\n@@ -1,2 +1,2 @@\\n-android:usesCleartextTraffic=\"true\"\\n+android:usesCleartextTraffic=\"false\"\\",
root_cause="Cleartext allowed.",
attack="MITM intercepts traffic.", impact="Data theft.",
fix="Disable cleartext.", guideline="Enforce HTTPS.",
tags=["mitm", "kotlin", "android", "tls"],
metadata={"domain": "Mobile", "input_source": "network", "auth_required": False})
rec(id="SCP-000389", language="Kotlin", framework="Android",
title="Hardcoded API key in BuildConfig",
description="An Android app embeds a key in BuildConfig.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-798", mitre_attack="T1552.001 - Unsecured Credentials: Credentials In Files",
severity="High", difficulty="Beginner",
vulnerable_code="val key = BuildConfig.API_KEY // Vulnerable: extracted from APK\\",
secure_code="val key = getString(R.string.api_key) // still in APK; use backend proxy / NDK // Better: fetch at runtime\\",
patch="--- a/Api.kt\\n+++ b/Api.kt\\n@@ -1,2 +1,3 @@\\n-val key = BuildConfig.API_KEY\\n+// Fetch from backend at runtime or use NDK obfuscation\\n+val key = fetchKeyFromBackend()\\",
root_cause="Secret in APK.",
attack="Reverse APK for key.", impact="Key compromise.",
fix="Proxy via backend.", guideline="Don\'t embed secrets in APK.",
tags=["secrets", "kotlin", "android", "config"],
metadata={"domain": "Mobile", "input_source": "source_code", "auth_required": False})
rec(id="SCP-000390", language="Kotlin", framework="Android",
title="Insecure SharedPreferences storage",
description="An app stores sensitive data in world-readable SharedPreferences.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-312", mitre_attack="T1552 - Unsecured Credentials",
severity="High", difficulty="Intermediate",
vulnerable_code="getSharedPreferences(\"prefs\", Context.MODE_WORLD_READABLE) // Vulnerable: readable by others\\",
secure_code="getSharedPreferences(\"prefs\", Context.MODE_PRIVATE) // Secure + encrypt with EncryptedSharedPreferences\\",
patch="--- a/Storage.kt\\n+++ b/Storage.kt\\n@@ -1,3 +1,3 @@\\n-getSharedPreferences(\"prefs\", Context.MODE_WORLD_READABLE)\\n+getSharedPreferences(\"prefs\", Context.MODE_PRIVATE)\\",
root_cause="World-readable prefs.",
attack="Other apps read stored tokens.", impact="Credential theft.",
fix="MODE_PRIVATE + encrypt.", guideline="Encrypt local storage.",
tags=["secrets", "kotlin", "android", "storage"],
metadata={"domain": "Mobile", "input_source": "device", "auth_required": False})
rec(id="SCP-000391", language="Kotlin", framework="Android",
title="Missing intent validation (exported component)",
description="An exported Activity processes intent extras without validation.",
owasp="A01:2021 - Broken Access Control", owasp_api="", owasp_llm="",
cwe="CWE-926", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="Medium", difficulty="Intermediate",
vulnerable_code="android:exported=\"true\" // Vulnerable: untrusted intents\\nval u = intent.getStringExtra(\"url\")\\",
secure_code="android:exported=\"false\" // Secure: or validate caller + sanitize extras\\",
patch="--- a/AndroidManifest.xml\\n+++ b/AndroidManifest.xml\\n@@ -1,2 +1,2 @@\\n-android:exported=\"true\"\\n+android:exported=\"false\"\\",
root_cause="Exported component.",
attack="Malicious app sends crafted intent.", impact="Privilege escalation.",
fix="Set exported=false or validate.", guideline="Minimize exported components.",
tags=["android", "kotlin", "intent", "access-control"],
metadata={"domain": "Mobile", "input_source": "intent", "auth_required": False})
rec(id="SCP-000392", language="Kotlin", framework="Android",
title="Weak hash for password (MD5)",
description="An Android app stores MD5 password hashes.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-916", mitre_attack="T1600 - Weaken Encryption",
severity="High", difficulty="Beginner",
vulnerable_code="val hash = MessageDigest.getInstance(\"MD5\").digest(pw.toByteArray()) // Vulnerable\\",
secure_code="val hash = BCrypt.hashpw(pw, BCrypt.gensalt(12)) // Secure: salted\\",
patch="--- a/Auth.kt\\n+++ b/Auth.kt\\n@@ -1,3 +1,3 @@\\n-val hash = MessageDigest.getInstance(\"MD5\").digest(pw.toByteArray())\\n+val hash = BCrypt.hashpw(pw, BCrypt.gensalt(12))\\",
root_cause="MD5 unsalted/fast.",
attack="Crack hashes.", impact="Credential compromise.",
fix="Use bcrypt/argon2.", guideline="Slow salted KDFs.",
tags=["crypto", "kotlin", "android", "passwords"],
metadata={"domain": "Mobile", "input_source": "request_body", "auth_required": False})
rec(id="SCP-000393", language="Kotlin", framework="Android",
title="Path traversal in file provider",
description="A FileProvider path can be traversed via intent.",
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="val f = File(baseDir, intent.getStringExtra(\"name\")) // Vulnerable: traversal\\",
secure_code="val name = File(intent.getStringExtra(\"name\") ?: \"\").name // Secure: basename\\nval f = File(baseDir, name)\\",
patch="--- a/FileProvider.kt\\n+++ b/FileProvider.kt\\n@@ -1,3 +1,4 @@\\n-val f = File(baseDir, intent.getStringExtra(\"name\"))\\n+val name = File(intent.getStringExtra(\"name\") ?: \"\").name\\n+val f = File(baseDir, name)\\",
root_cause="Unsanitized filename.",
attack="name=../../etc/hosts reads file.", impact="File disclosure.",
fix="Basename + confine.", guideline="Confine file paths.",
tags=["path-traversal", "kotlin", "android", "file-read"],
metadata={"domain": "Mobile", "input_source": "intent", "auth_required": False})
rec(id="SCP-000394", language="Kotlin", framework="Android",
title="Insecure random for token",
description="A Kotlin service uses java.util.Random for tokens.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-338", mitre_attack="T1600 - Weaken Encryption",
severity="High", difficulty="Intermediate",
vulnerable_code="val tok = Random().nextInt().toString() // Vulnerable: predictable\\",
secure_code="val tok = java.security.SecureRandom().nextBytes(32).toString() // Secure: CSPRNG\\",
patch="--- a/Token.kt\\n+++ b/Token.kt\\n@@ -1,2 +1,2 @@\\n-val tok = Random().nextInt().toString()\\n+val tok = java.security.SecureRandom().nextBytes(32).toString()\\",
root_cause="Non-CSPRNG token.",
attack="Predict token.", impact="Token forgery.",
fix="Use SecureRandom.", guideline="Use CSPRNG for tokens.",
tags=["crypto", "kotlin", "android", "tokens"],
metadata={"domain": "Mobile", "input_source": "server", "auth_required": False})
rec(id="SCP-000395", language="Kotlin", framework="Android",
title="SQL injection via content resolver",
description="A content resolver query concatenates selection args.",
owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
cwe="CWE-89", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="High", difficulty="Intermediate",
vulnerable_code="cr.query(uri, null, \"name='\" + name + \"'\", null, null) // Vulnerable\\",
secure_code="cr.query(uri, null, \"name=?\", arrayOf(name), null) // Secure: selection arg\\",
patch="--- a/Provider.kt\\n+++ b/Provider.kt\\n@@ -1,3 +1,3 @@\\n-cr.query(uri, null, \"name='\" + name + \"'\", null, null)\\n+cr.query(uri, null, \"name=?\", arrayOf(name), null)\\",
root_cause="Concatenated selection.",
attack="name=\' OR 1=1 leaks rows.", impact="Data disclosure.",
fix="Use selection args.", guideline="Bind SQL/selection args.",
tags=["sqli", "kotlin", "android", "injection"],
metadata={"domain": "Mobile", "input_source": "query_param", "auth_required": False})
rec(id="SCP-000396", language="Kotlin", framework="Android",
title="Exposed broadcast receiver",
description="A broadcast receiver is exported and processes untrusted broadcasts.",
owasp="A01:2021 - Broken Access Control", owasp_api="", owasp_llm="",
cwe="CWE-926", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="Medium", difficulty="Intermediate",
vulnerable_code="android:exported=\"true\" // Vulnerable: any app can send\\",
secure_code="android:exported=\"false\" // Secure: or use permission-protected receiver\\",
patch="--- a/AndroidManifest.xml\\n+++ b/AndroidManifest.xml\\n@@ -1,2 +1,2 @@\\n-android:exported=\"true\"\\n+android:exported=\"false\"\\",
root_cause="Exported receiver.",
attack="Malicious broadcast triggers action.", impact="Privilege escalation.",
fix="Unexport or permission-gate.", guideline="Minimize exported components.",
tags=["android", "kotlin", "broadcast", "access-control"],
metadata={"domain": "Mobile", "input_source": "broadcast", "auth_required": False})
rec(id="SCP-000397", language="Kotlin", framework="Android",
title="Insecure logging of secrets",
description="An app logs sensitive data to logcat.",
owasp="A09:2021 - Security Logging and Monitoring Failures", owasp_api="", owasp_llm="",
cwe="CWE-532", mitre_attack="T1552 - Unsecured Credentials",
severity="Medium", difficulty="Beginner",
vulnerable_code="Log.d(\"auth\", \"token=$token\") // Vulnerable: leaks to logcat\\",
secure_code="// Never log secrets; use redacted identifiers\\nLog.d(\"auth\", \"tokenSet=true\") // Secure: no secret\\",
patch="--- a/Auth.kt\\n+++ b/Auth.kt\\n@@ -1,3 +1,3 @@\\n-Log.d(\"auth\", \"token=$token\")\\n+Log.d(\"auth\", \"tokenSet=true\")\\",
root_cause="Secrets in logs.",
attack="Read logcat for tokens.", impact="Credential leak.",
fix="Don\'t log secrets.", guideline="Redact sensitive logs.",
tags=["logging", "kotlin", "android", "secrets"],
metadata={"domain": "Mobile", "input_source": "device", "auth_required": False})
rec(id="SCP-000398", language="Kotlin", framework="Android",
title="Improper TLS cert pinning bypass",
description="A Kotlin TLS client disables hostname verification.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-295", mitre_attack="T1557 - Adversary-in-the-Middle",
severity="Critical", difficulty="Advanced",
vulnerable_code="builder.hostnameVerifier { _, _ -> true } // Vulnerable: accept all hosts\\",
secure_code="// Keep default hostname verification; implement proper cert pinning\\nval client = OkHttpClient.Builder().build() // Secure\\",
patch="--- a/Network.kt\\n+++ b/Network.kt\\n@@ -1,3 +1,3 @@\\n-builder.hostnameVerifier { _, _ -> true }\\n+val client = OkHttpClient.Builder().build()\\",
root_cause="Hostname verification disabled.",
attack="MITM intercepts TLS.", impact="Credential/data theft.",
fix="Keep verification.", guideline="Always verify TLS peers.",
tags=["tls", "kotlin", "android", "mitm"],
metadata={"domain": "Mobile", "input_source": "network", "auth_required": False})
rec(id="SCP-000399", language="Kotlin", framework="Android",
title="Business logic: negative in-app purchase",
description="A purchase flow accepts a negative quantity from client.",
owasp="A04:2021 - Insecure Design", owasp_api="API3:2023 - Broken Object Property Level Authorization", owasp_llm="",
cwe="CWE-840", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="Medium", difficulty="Intermediate",
vulnerable_code="order.qty = intent.getIntExtra(\"qty\", 1) // Vulnerable: negative\\",
secure_code="val qty = intent.getIntExtra(\"qty\", 1)\\nif (qty <= 0 || qty > 100) throw IllegalArgumentException(\"bad\") // Secure\\",
patch="--- a/Purchase.kt\\n+++ b/Purchase.kt\\n@@ -1,3 +1,4 @@\\n-order.qty = intent.getIntExtra(\"qty\", 1)\\n+val qty = intent.getIntExtra(\"qty\", 1)\\n+if (qty <= 0 || qty > 100) throw IllegalArgumentException(\"bad\")\\",
root_cause="Client qty not bounded.",
attack="qty=-5 => negative charge.", impact="Revenue loss.",
fix="Validate qty.", guideline="Validate business values.",
tags=["business-logic", "kotlin", "android", "ecommerce"],
metadata={"domain": "Mobile", "input_source": "intent", "auth_required": True})
rec(id="SCP-000400", language="Kotlin", framework="Android",
title="Insecure deep link handling",
description="A deep link handler trusts host input for navigation/actions.",
owasp="A01:2021 - Broken Access Control", owasp_api="", owasp_llm="",
cwe="CWE-601", mitre_attack="T1566 - Phishing",
severity="Medium", difficulty="Beginner",
vulnerable_code="val action = intent.data?.getQueryParameter(\"action\") // Vulnerable: trusted blindly\\",
secure_code="val action = intent.data?.getQueryParameter(\"action\")\\nif (action !in setOf(\"view\", \"share\")) return // Secure: allowlist\\",
patch="--- a/DeepLink.kt\\n+++ b/DeepLink.kt\\n@@ -1,3 +1,4 @@\\n-val action = intent.data?.getQueryParameter(\"action\")\\n+if (action !in setOf(\"view\", \"share\")) return\\",
root_cause="Untrusted deep link param.",
attack="Craft deeplink for unintended action.", impact="Phishing/abuse.",
fix="Allowlist actions.", guideline="Validate deep link params.",
tags=["deep-link", "kotlin", "android", "phishing"],
metadata={"domain": "Mobile", "input_source": "deeplink", "auth_required": False})
# ---------------- Swift (SCP-000401 - 000415) ----------------
rec(id="SCP-000401", language="Swift", framework="iOS",
title="SQL injection in Core Data fetch",
description="An iOS fetch uses a concatenated predicate format.",
owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
cwe="CWE-89", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="High", difficulty="Intermediate",
vulnerable_code="let req = NSFetchRequest(entityName: \"User\")\\nreq.predicate = NSPredicate(format: \"name == '\\(name)'\") // Vulnerable: format injection\\",
secure_code="req.predicate = NSPredicate(format: \"name == %@\", name) // Secure: bound arg\\",
patch="--- a/Store.swift\\n+++ b/Store.swift\\n@@ -1,4 +1,4 @@\\n-let req = NSFetchRequest(entityName: \"User\")\\n-req.predicate = NSPredicate(format: \"name == '\\(name)'\")\\n+req.predicate = NSPredicate(format: \"name == %@\", name)\\",
root_cause="Predicate format with interpolation.",
attack="name=\' OR 1=1 bypasses.", impact="Data disclosure.",
fix="Use %@ bound args.", guideline="Bind all predicates.",
tags=["sqli", "swift", "ios", "injection"],
metadata={"domain": "Mobile", "input_source": "query_param", "auth_required": False})
rec(id="SCP-000402", language="Swift", framework="iOS",
title="Hardcoded API key in Info.plist",
description="An iOS app stores a key in Info.plist.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-798", mitre_attack="T1552.001 - Unsecured Credentials: Credentials In Files",
severity="High", difficulty="Beginner",
vulnerable_code="let key = Bundle.main.infoDictionary?[\"API_KEY\"] as? String // Vulnerable: in binary\\",
secure_code="// Fetch from backend at runtime; never ship secret in bundle\\nlet key = try await fetchKey() // Secure\\",
patch="--- a/Api.swift\\n+++ b/Api.swift\\n@@ -1,3 +1,3 @@\\n-let key = Bundle.main.infoDictionary?[\"API_KEY\"] as? String\\n+let key = try await fetchKey()\\",
root_cause="Secret in bundle.",
attack="Extract from IPA.", impact="Key compromise.",
fix="Backend proxy.", guideline="Don\'t embed secrets in app.",
tags=["secrets", "swift", "ios", "config"],
metadata={"domain": "Mobile", "input_source": "source_code", "auth_required": False})
rec(id="SCP-000403", language="Swift", framework="iOS",
title="Insecure NSUserDefaults storage",
description="An app stores a token in NSUserDefaults in plaintext.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-312", mitre_attack="T1552 - Unsecured Credentials",
severity="High", difficulty="Intermediate",
vulnerable_code="UserDefaults.standard.set(token, forKey: \"auth_token\") // Vulnerable: plaintext on disk\\",
secure_code="let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecValueData as String: token]\\nSecItemAdd(query as CFDictionary, nil) // Secure: Keychain\\",
patch="--- a/Auth.swift\\n+++ b/Auth.swift\\n@@ -1,3 +1,4 @@\\n-UserDefaults.standard.set(token, forKey: \"auth_token\")\\n+let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecValueData as String: token]\\n+SecItemAdd(query as CFDictionary, nil)\\",
root_cause="Plaintext token on disk.",
attack="Read app container for token.", impact="Credential theft.",
fix="Use Keychain.", guideline="Encrypt local storage.",
tags=["secrets", "swift", "ios", "storage"],
metadata={"domain": "Mobile", "input_source": "device", "auth_required": False})
rec(id="SCP-000404", language="Swift", framework="iOS",
title="Weak hash for password (MD5)",
description="An iOS app computes MD5 password hashes.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-916", mitre_attack="T1600 - Weaken Encryption",
severity="High", difficulty="Beginner",
vulnerable_code="let hash = InsecureHash.md5(pw) // Vulnerable: fast, unsalted\\",
secure_code="let hash = try CryptoKit.SHA256(data: Data(pw.utf8)).base64EncodedString() // Better with salt+PBKDF2\\",
patch="--- a/Auth.swift\\n+++ b/Auth.swift\\n@@ -1,3 +1,3 @@\\n-let hash = InsecureHash.md5(pw)\\n+let hash = try CryptoKit.SHA256(data: Data(pw.utf8)).base64EncodedString()\\",
root_cause="MD5 unsalted/fast.",
attack="Crack hashes.", impact="Credential compromise.",
fix="Use PBKDF2/Argon2.", guideline="Slow salted KDFs.",
tags=["crypto", "swift", "ios", "passwords"],
metadata={"domain": "Mobile", "input_source": "request_body", "auth_required": False})
rec(id="SCP-000405", language="Swift", framework="iOS",
title="JS evaluation in WKWebView (evaluateJavaScript injection)",
description="A WKWebView evaluates a string built from user input.",
owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
cwe="CWE-79", mitre_attack="T1059.007 - Command and Scripting Interpreter: JavaScript",
severity="Medium", difficulty="Intermediate",
vulnerable_code="webView.evaluateJavaScript(\"show('\\(userInput)')\") // Vulnerable: JS injection\\",
secure_code="// Pass data via message handlers with JSON, not string concat\\nwebView.evaluateJavaScript(\"show(data)\") // Secure: data via addScriptMessageHandler\\",
patch="--- a/WebViewController.swift\\n+++ b/WebViewController.swift\\n@@ -1,3 +1,3 @@\\n-webView.evaluateJavaScript(\"show('\\(userInput)')\")\\n+webView.evaluateJavaScript(\"show(data)\")\\",
root_cause="JS string from user input.",
attack="userInput=alert(1) executes.", impact="XSS / JS injection.",
fix="Use message handlers + JSON.", guideline="Avoid JS string concat.",
tags=["xss", "swift", "ios", "webview"],
metadata={"domain": "Mobile", "input_source": "web", "auth_required": False})
rec(id="SCP-000406", language="Swift", framework="iOS",
title="Insecure TLS (App Transport Security disabled)",
description="An app disables ATS allowing cleartext.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-319", mitre_attack="T1557 - Adversary-in-the-Middle",
severity="Medium", difficulty="Beginner",
vulnerable_code="NSAppTransportSecurityNSAllowsArbitraryLoads // Vulnerable\\",
secure_code="NSAppTransportSecurityNSAllowsArbitraryLoads // Secure\\",
patch="--- a/Info.plist\\n+++ b/Info.plist\\n@@ -1,3 +1,3 @@\\n-NSAllowsArbitraryLoads\\n+NSAllowsArbitraryLoads\\",
root_cause="ATS disabled.",
attack="MITM intercepts traffic.", impact="Data theft.",
fix="Keep ATS enabled.", guideline="Enforce HTTPS.",
tags=["mitm", "swift", "ios", "tls"],
metadata={"domain": "Mobile", "input_source": "network", "auth_required": False})
rec(id="SCP-000407", language="Swift", framework="iOS",
title="Path traversal in document file read",
description="An app reads a file from a user-supplied name in Documents.",
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="let url = docs.appendingPathComponent(name) // Vulnerable: traversal\\",
secure_code="let safe = URL(fileURLWithPath: name).lastPathComponent\\nlet url = docs.appendingPathComponent(safe) // Secure: basename\\",
patch="--- a/Files.swift\\n+++ b/Files.swift\\n@@ -1,3 +1,4 @@\\n-let url = docs.appendingPathComponent(name)\\n+let safe = URL(fileURLWithPath: name).lastPathComponent\\n+let url = docs.appendingPathComponent(safe)\\",
root_cause="Unsanitized filename.",
attack="name=../../etc/passwd reads file.", impact="File disclosure.",
fix="Basename + confine.", guideline="Confine file paths.",
tags=["path-traversal", "swift", "ios", "file-read"],
metadata={"domain": "Mobile", "input_source": "query_param", "auth_required": False})
rec(id="SCP-000408", language="Swift", framework="iOS",
title="Insecure random for token (arc4random misuse)",
description="A token generator uses a weak RNG.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-338", mitre_attack="T1600 - Weaken Encryption",
severity="High", difficulty="Intermediate",
vulnerable_code="let tok = String(arc4random()) // Vulnerable if seeded weakly\\",
secure_code="var bytes = [UInt8](repeating: 0, count: 32)\\n_ = SecRandomCopyBytes(kSecRandomDefault, 32, &bytes) // Secure: CSPRNG\\",
patch="--- a/Token.swift\\n+++ b/Token.swift\\n@@ -1,3 +1,4 @@\\n-let tok = String(arc4random())\\n+var bytes = [UInt8](repeating: 0, count: 32)\\n+_ = SecRandomCopyBytes(kSecRandomDefault, 32, &bytes)\\",
root_cause="Non-CSPRNG token.",
attack="Predict token.", impact="Token forgery.",
fix="Use SecRandomCopyBytes.", guideline="Use CSPRNG for tokens.",
tags=["crypto", "swift", "ios", "tokens"],
metadata={"domain": "Mobile", "input_source": "server", "auth_required": False})
rec(id="SCP-000409", language="Swift", framework="iOS",
title="URL scheme hijacking (openURL without validation)",
description="An app opens a URL from a universal link without validation.",
owasp="A01:2021 - Broken Access Control", owasp_api="", owasp_llm="",
cwe="CWE-601", mitre_attack="T1566 - Phishing",
severity="Medium", difficulty="Beginner",
vulnerable_code="UIApplication.shared.open(url) // Vulnerable: opens untrusted URL\\",
secure_code="guard url.scheme == \"https\", url.host == \"app.example.com\" else { return } // Secure\\nUIApplication.shared.open(url)\\",
patch="--- a/DeepLink.swift\\n+++ b/DeepLink.swift\\n@@ -1,3 +1,4 @@\\n-UIApplication.shared.open(url)\\n+guard url.scheme == \"https\", url.host == \"app.example.com\" else { return }\\n+UIApplication.shared.open(url)\\",
root_cause="Unvalidated URL open.",
attack="Malicious universal link triggers action.", impact="Phishing/abuse.",
fix="Validate scheme/host.", guideline="Validate deep links.",
tags=["deep-link", "swift", "ios", "phishing"],
metadata={"domain": "Mobile", "input_source": "deeplink", "auth_required": False})
rec(id="SCP-000410", language="Swift", framework="iOS",
title="Insecure JWT decode without signature",
description="A JWT is decoded without verifying signature.",
owasp="A07:2021 - Identification and Authentication Failures", owasp_api="API2:2023 - Broken Authentication", owasp_llm="",
cwe="CWE-345", mitre_attack="T1600 - Weaken Encryption",
severity="Critical", difficulty="Advanced",
vulnerable_code="let t = try decode(jwt: token) // Vulnerable: no signature check\\",
secure_code="let t = try decode(jwt: token, algorithms: [\"HS256\"], secret: key) // Secure: verifies\\",
patch="--- a/Auth.swift\\n+++ b/Auth.swift\\n@@ -1,3 +1,3 @@\\n-let t = try decode(jwt: token)\\n+let t = try decode(jwt: token, algorithms: [\"HS256\"], secret: key)\\",
root_cause="No signature validation.",
attack="Forge token payload.", impact="Auth bypass.",
fix="Verify signature.", guideline="Always validate JWT signature.",
tags=["jwt", "swift", "ios", "auth"],
metadata={"domain": "Mobile", "input_source": "header", "auth_required": True})
rec(id="SCP-000411", language="Swift", framework="iOS",
title="Sensitive data in logs",
description="An app logs the auth token to console.",
owasp="A09:2021 - Security Logging and Monitoring Failures", owasp_api="", owasp_llm="",
cwe="CWE-532", mitre_attack="T1552 - Unsecured Credentials",
severity="Medium", difficulty="Beginner",
vulnerable_code="print(\"token: \\(token)\") // Vulnerable: leaks to syslog\\",
secure_code="print(\"tokenSet: true\") // Secure: no secret\\",
patch="--- a/Auth.swift\\n+++ b/Auth.swift\\n@@ -1,3 +1,3 @@\\n-print(\"token: \\(token)\")\\n+print(\"tokenSet: true\")\\",
root_cause="Secrets in logs.",
attack="Read device logs.", impact="Credential leak.",
fix="Don\'t log secrets.", guideline="Redact sensitive logs.",
tags=["logging", "swift", "ios", "secrets"],
metadata={"domain": "Mobile", "input_source": "device", "auth_required": False})
rec(id="SCP-000412", language="Swift", framework="iOS",
title="Business logic: negative transaction amount",
description="A transaction accepts a negative amount from client.",
owasp="A04:2021 - Insecure Design", owasp_api="API3:2023 - Broken Object Property Level Authorization", owasp_llm="",
cwe="CWE-840", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="Medium", difficulty="Intermediate",
vulnerable_code="account.balance += request.amount // Vulnerable: negative\\",
secure_code="guard request.amount > 0, request.amount <= 1_000_000 else { throw Error.invalid } // Secure\\naccount.balance += request.amount\\",
patch="--- a/Account.swift\\n+++ b/Account.swift\\n@@ -1,3 +1,4 @@\\n-account.balance += request.amount\\n+guard request.amount > 0, request.amount <= 1_000_000 else { throw Error.invalid }\\n+account.balance += request.amount\\",
root_cause="Client amount not validated.",
attack="amount=-100 increases balance.", impact="Financial abuse.",
fix="Validate amount.", guideline="Validate business values.",
tags=["business-logic", "swift", "ios", "banking"],
metadata={"domain": "Banking", "input_source": "request_body", "auth_required": True})
rec(id="SCP-000413", language="Swift", framework="iOS",
title="Insecure file upload (no type check)",
description="An upload sends any file type by name.",
owasp="A04:2021 - Insecure Design", owasp_api="", owasp_llm="",
cwe="CWE-434", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="High", difficulty="Intermediate",
vulnerable_code="try Data(contentsOf: fileURL) // Vulnerable: any type uploaded\\",
secure_code="guard fileURL.pathExtension == \"png\" || fileURL.pathExtension == \"jpg\" else { throw Error.bad } // Secure\\nlet data = try Data(contentsOf: fileURL)\\",
patch="--- a/Upload.swift\\n+++ b/Upload.swift\\n@@ -1,3 +1,4 @@\\n-try Data(contentsOf: fileURL)\\n+guard fileURL.pathExtension == \"png\" || fileURL.pathExtension == \"jpg\" else { throw Error.bad }\\n+let data = try Data(contentsOf: fileURL)\\",
root_cause="No type validation.",
attack="Upload malicious file.", impact="Abuse.",
fix="Allowlist types.", guideline="Validate uploads.",
tags=["file-upload", "swift", "ios", "rce"],
metadata={"domain": "Mobile", "input_source": "form_field", "auth_required": True})
rec(id="SCP-000414", language="Swift", framework="iOS",
title="Keychain item accessible when unlocked (weak protection)",
description="A Keychain item is accessible after first unlock indefinitely.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-312", mitre_attack="T1552 - Unsecured Credentials",
severity="Medium", difficulty="Intermediate",
vulnerable_code="let accessible = kSecAttrAccessibleWhenUnlocked // Vulnerable: persists after lock\\",
secure_code="let accessible = kSecAttrAccessibleWhenUnlockedThisDeviceOnly // Secure: device-bound\\",
patch="--- a/Auth.swift\\n+++ b/Auth.swift\\n@@ -1,3 +1,3 @@\\n-let accessible = kSecAttrAccessibleWhenUnlocked\\n+let accessible = kSecAttrAccessibleWhenUnlockedThisDeviceOnly\\",
root_cause="Weak Keychain accessibility.",
attack="Extract token from locked device backup.", impact="Credential theft.",
fix="Use ThisDeviceOnly.", guideline="Harden Keychain items.",
tags=["secrets", "swift", "ios", "storage"],
metadata={"domain": "Mobile", "input_source": "device", "auth_required": False})
rec(id="SCP-000415", language="Swift", framework="iOS",
title="Cross-site scripting via WKWebView loadHTMLString",
description="A WKWebView renders user HTML via loadHTMLString without sanitization.",
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="webView.loadHTMLString(userHTML, baseURL: nil) // Vulnerable: unescaped HTML\\",
secure_code="let safe = sanitizeHTML(userHTML) // Secure: strip scripts\\nwebView.loadHTMLString(safe, baseURL: nil)\\",
patch="--- a/WebViewController.swift\\n+++ b/WebViewController.swift\\n@@ -1,3 +1,3 @@\\n-webView.loadHTMLString(userHTML, baseURL: nil)\\n+let safe = sanitizeHTML(userHTML)\\n+webView.loadHTMLString(safe, baseURL: nil)\\",
root_cause="Unsanitized HTML load.",
attack="userHTML= runs.", impact="XSS.",
fix="Sanitize HTML.", guideline="Sanitize user HTML.",
tags=["xss", "swift", "ios", "webview"],
metadata={"domain": "Mobile", "input_source": "web", "auth_required": False})
# ---------------- YAML / Kubernetes (SCP-000416 - 000430) ----------------
rec(id="SCP-000416", language="YAML", framework="Kubernetes",
title="Privileged container in pod spec",
description="A Kubernetes Pod runs a container with privileged: true.",
owasp="A05:2021 - Security Misconfiguration", owasp_api="", owasp_llm="",
cwe="CWE-250", mitre_attack="T1611 - Escape to Host",
severity="Critical", difficulty="Intermediate",
vulnerable_code="containers:\\n- name: app\\n image: app:1.0\\n securityContext:\\n privileged: true # Vulnerable\\",
secure_code="containers:\\n- name: app\\n image: app:1.0\\n securityContext:\\n privileged: false # Secure: drop caps, readOnlyRootFilesystem\\",
patch="--- a/deploy.yaml\\n+++ b/deploy.yaml\\n@@ -1,6 +1,6 @@\\n- securityContext:\\n- privileged: true\\n+ securityContext:\\n+ privileged: false\\",
root_cause="Privileged container.",
attack="Escape to host via /dev access.", impact="Host compromise.",
fix="Disable privileged; drop caps.", guideline="Least privilege containers.",
tags=["kubernetes", "yaml", "privilege", "container"],
metadata={"domain": "Kubernetes", "input_source": "manifest", "auth_required": False})
rec(id="SCP-000417", language="YAML", framework="Kubernetes",
title="Container running as root",
description="A Pod does not set runAsNonRoot / runAsUser.",
owasp="A05:2021 - Security Misconfiguration", owasp_api="", owasp_llm="",
cwe="CWE-250", mitre_attack="T1611 - Escape to Host",
severity="High", difficulty="Beginner",
vulnerable_code="securityContext: {} # Vulnerable: runs as root (uid 0)\\",
secure_code="securityContext:\\n runAsNonRoot: true\\n runAsUser: 1000\\n runAsGroup: 3000 # Secure\\",
patch="--- a/deploy.yaml\\n+++ b/deploy.yaml\\n@@ -1,2 +1,5 @@\\n-securityContext: {}\\n+securityContext:\\n+ runAsNonRoot: true\\n+ runAsUser: 1000\\n+ runAsGroup: 3000\\",
root_cause="Root container.",
attack="Root in container eases escape.", impact="Host compromise.",
fix="runAsNonRoot.", guideline="Non-root containers.",
tags=["kubernetes", "yaml", "privilege", "container"],
metadata={"domain": "Kubernetes", "input_source": "manifest", "auth_required": False})
rec(id="SCP-000418", language="YAML", framework="Kubernetes",
title="Secret in plaintext ConfigMap/Env",
description="A manifest stores a secret as a plaintext env var.",
owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
cwe="CWE-798", mitre_attack="T1552.001 - Unsecured Credentials: Credentials In Files",
severity="High", difficulty="Beginner",
vulnerable_code="env:\\n- name: DB_PASSWORD\\n value: \"P@ssw0rd!\" # Vulnerable: plaintext secret\\",
secure_code="env:\\n- name: DB_PASSWORD\\n valueFrom:\\n secretKeyRef:\\n name: db-secret\\n key: password # Secure: from Secret\\",
patch="--- a/deploy.yaml\\n+++ b/deploy.yaml\\n@@ -1,4 +1,6 @@\\n-env:\\n-- name: DB_PASSWORD\\n value: \"P@ssw0rd!\"\\n+env:\\n+- name: DB_PASSWORD\\n+ valueFrom:\\n+ secretKeyRef:\\n+ name: db-secret\\n+ key: password\\",
root_cause="Secret in manifest.",
attack="Read manifest for creds.", impact="Credential leak.",
fix="Use Secret/secretKeyRef.", guideline="Externalize secrets.",
tags=["secrets", "yaml", "kubernetes", "config"],
metadata={"domain": "Kubernetes", "input_source": "manifest", "auth_required": False})
rec(id="SCP-000419", language="YAML", framework="Kubernetes",
title="Allow-all NetworkPolicy missing",
description="A namespace has no NetworkPolicy, allowing all pod-to-pod traffic.",
owasp="A05:2021 - Security Misconfiguration", owasp_api="", owasp_llm="",
cwe="CWE-284", mitre_attack="T1046 - Network Service Discovery",
severity="Medium", difficulty="Intermediate",
vulnerable_code="# No NetworkPolicy defined # Vulnerable: default-allow all\\",
secure_code="apiVersion: networking.k8s.io/v1\\nkind: NetworkPolicy\\nspec:\\n podSelector: {}\\n policyTypes: [\"Ingress\"]\\n ingress: [{from: [{podSelector: {matchLabels: {tier: frontend}}}]}] # Secure\\",
patch="--- a/networkpolicy.yaml\\n+++ b/networkpolicy.yaml\\n@@ -1,2 +1,8 @@\\n-# No NetworkPolicy defined\\n+apiVersion: networking.k8s.io/v1\\n+kind: NetworkPolicy\\n+spec:\\n+ podSelector: {}\\n+ policyTypes: [\"Ingress\"]\\n+ ingress: [{from: [{podSelector: {matchLabels: {tier: frontend}}}]}]\\",
root_cause="No network segmentation.",
attack="Lateral movement between pods.", impact="Blast radius increase.",
fix="Define NetworkPolicy.", guideline="Segment pod traffic.",
tags=["kubernetes", "yaml", "network", "segmentation"],
metadata={"domain": "Kubernetes", "input_source": "manifest", "auth_required": False})
rec(id="SCP-000420", language="YAML", framework="Kubernetes",
title="Host path volume mount",
description="A Pod mounts a hostPath to a sensitive directory.",
owasp="A05:2021 - Security Misconfiguration", owasp_api="", owasp_llm="",
cwe="CWE-552", mitre_attack="T1611 - Escape to Host",
severity="High", difficulty="Intermediate",
vulnerable_code="volumes:\\n- name: host\\n hostPath:\\n path: /etc # Vulnerable: host FS access\\",
secure_code="# Avoid hostPath; use PVC or emptyDir\\nvolumes:\\n- name: data\\n emptyDir: {} # Secure\\",
patch="--- a/deploy.yaml\\n+++ b/deploy.yaml\\n@@ -1,5 +1,4 @@\\n-volumes:\\n-- name: host\\n hostPath:\\n path: /etc\\n+volumes:\\n+- name: data\\n+ emptyDir: {}\\",
root_cause="Host path mount.",
attack="Read/write host filesystem.", impact="Host compromise.",
fix="Avoid hostPath.", guideline="No host filesystem mounts.",
tags=["kubernetes", "yaml", "volume", "container"],
metadata={"domain": "Kubernetes", "input_source": "manifest", "auth_required": False})
rec(id="SCP-000421", language="YAML", framework="Kubernetes",
title="Missing resource limits (DoS)",
description="A container has no CPU/memory limits.",
owasp="A05:2021 - Security Misconfiguration", owasp_api="API4:2023 - Unrestricted Resource Consumption", owasp_llm="",
cwe="CWE-400", mitre_attack="T1499 - Endpoint Denial of Service",
severity="Medium", difficulty="Beginner",
vulnerable_code="resources: {} # Vulnerable: no limits, can starve node\\",
secure_code="resources:\\n limits:\\n cpu: \"500m\"\\n memory: \"256Mi\"\\n requests:\\n cpu: \"100m\"\\n memory: \"128Mi\" # Secure\\",
patch="--- a/deploy.yaml\\n+++ b/deploy.yaml\\n@@ -1,2 +1,9 @@\\n-resources: {}\\n+resources:\\n+ limits:\\n+ cpu: \"500m\"\\n+ memory: \"256Mi\"\\n+ requests:\\n+ cpu: \"100m\"\\n+ memory: \"128Mi\"\\",
root_cause="No resource limits.",
attack="Resource exhaustion / node DoS.", impact="Availability loss.",
fix="Set limits/requests.", guideline="Bound container resources.",
tags=["kubernetes", "yaml", "dos", "resource"],
metadata={"domain": "Kubernetes", "input_source": "manifest", "auth_required": False})
rec(id="SCP-000422", language="YAML", framework="Kubernetes",
title="Allow privilege escalation (allowPrivilegeEscalation)",
description="A container sets allowPrivilegeEscalation: true.",
owasp="A05:2021 - Security Misconfiguration", owasp_api="", owasp_llm="",
cwe="CWE-250", mitre_attack="T1611 - Escape to Host",
severity="High", difficulty="Beginner",
vulnerable_code="securityContext:\\n allowPrivilegeEscalation: true # Vulnerable\\",
secure_code="securityContext:\\n allowPrivilegeEscalation: false # Secure\\n readOnlyRootFilesystem: true\\",
patch="--- a/deploy.yaml\\n+++ b/deploy.yaml\\n@@ -1,3 +1,4 @@\\n-securityContext:\\n allowPrivilegeEscalation: true\\n+securityContext:\\n+ allowPrivilegeEscalation: false\\n+ readOnlyRootFilesystem: true\\",
root_cause="Privilege escalation allowed.",
attack="SUID binary gains root.", impact="Container root.",
fix="Set false.", guideline="Disallow escalation.",
tags=["kubernetes", "yaml", "privilege", "container"],
metadata={"domain": "Kubernetes", "input_source": "manifest", "auth_required": False})
rec(id="SCP-000423", language="YAML", framework="Kubernetes",
title="Capability NET_ADMIN added",
description="A container adds dangerous Linux capabilities.",
owasp="A05:2021 - Security Misconfiguration", owasp_api="", owasp_llm="",
cwe="CWE-250", mitre_attack="T1611 - Escape to Host",
severity="High", difficulty="Intermediate",
vulnerable_code="securityContext:\\n capabilities:\\n add: [\"NET_ADMIN\", \"SYS_ADMIN\"] # Vulnerable\\",
secure_code="securityContext:\\n capabilities:\\n drop: [\"ALL\"] # Secure: least privilege\\",
patch="--- a/deploy.yaml\\n+++ b/deploy.yaml\\n@@ -1,5 +1,4 @@\\n-securityContext:\\n capabilities:\\n add: [\"NET_ADMIN\", \"SYS_ADMIN\"]\\n+securityContext:\\n+ capabilities:\\n+ drop: [\"ALL\"]\\",
root_cause="Dangerous capabilities added.",
attack="Manipulate networking / host.", impact="Container escape.",
fix="Drop ALL caps.", guideline="Minimal capabilities.",
tags=["kubernetes", "yaml", "capability", "container"],
metadata={"domain": "Kubernetes", "input_source": "manifest", "auth_required": False})
rec(id="SCP-000424", language="YAML", framework="Kubernetes",
title="Image pull from latest tag (unpinned)",
description="A Pod uses image:latest, enabling unpredictable/rogue deploys.",
owasp="A08:2021 - Software and Data Integrity Failures", owasp_api="", owasp_llm="",
cwe="CWE-494", mitre_attack="T1195 - Supply Chain Compromise",
severity="Medium", difficulty="Beginner",
vulnerable_code="image: myapp:latest # Vulnerable: mutable tag\\",
secure_code="image: myapp:1.4.2@sha256:abc123... # Secure: pinned digest\\",
patch="--- a/deploy.yaml\\n+++ b/deploy.yaml\\n@@ -1,2 +1,2 @@\\n-image: myapp:latest\\n+image: myapp:1.4.2@sha256:abc123...\\",
root_cause="Mutable image tag.",
attack="Tampered image pulled.", impact="Supply chain compromise.",
fix="Pin by digest.", guideline="Pin images by sha256.",
tags=["kubernetes", "yaml", "supply-chain", "image"],
metadata={"domain": "Kubernetes", "input_source": "manifest", "auth_required": False})
rec(id="SCP-000425", language="YAML", framework="Kubernetes",
title="ServiceAccount token automount enabled",
description="A Pod mounts the API token by default, widening blast radius.",
owasp="A05:2021 - Security Misconfiguration", owasp_api="", owasp_llm="",
cwe="CWE-668", mitre_attack="T1078 - Valid Accounts",
severity="Medium", difficulty="Beginner",
vulnerable_code="automountServiceAccountToken: true # Vulnerable: API token in pod\\",
secure_code="automountServiceAccountToken: false # Secure: only if needed\\",
patch="--- a/deploy.yaml\\n+++ b/deploy.yaml\\n@@ -1,2 +1,2 @@\\n-automountServiceAccountToken: true\\n+automountServiceAccountToken: false\\",
root_cause="API token mounted unnecessarily.",
attack="Token theft -> API abuse.", impact="Cluster compromise.",
fix="Disable automount.", guideline="Least privilege SA.",
tags=["kubernetes", "yaml", "token", "serviceaccount"],
metadata={"domain": "Kubernetes", "input_source": "manifest", "auth_required": False})
rec(id="SCP-000426", language="YAML", framework="Kubernetes",
title="Missing PodSecurityContext seccomp profile",
description="A Pod omits seccompProfile, allowing broad syscall surface.",
owasp="A05:2021 - Security Misconfiguration", owasp_api="", owasp_llm="",
cwe="CWE-693", mitre_attack="T1611 - Escape to Host",
severity="Medium", difficulty="Intermediate",
vulnerable_code="securityContext: {} # Vulnerable: no seccomp\\",
secure_code="securityContext:\\n seccompProfile:\\n type: RuntimeDefault # Secure: restrict syscalls\\",
patch="--- a/deploy.yaml\\n+++ b/deploy.yaml\\n@@ -1,2 +1,5 @@\\n-securityContext: {}\\n+securityContext:\\n+ seccompProfile:\\n+ type: RuntimeDefault\\",
root_cause="No seccomp profile.",
attack="Broad syscall abuse.", impact="Container escape aid.",
fix="Set RuntimeDefault.", guideline="Apply seccomp.",
tags=["kubernetes", "yaml", "seccomp", "container"],
metadata={"domain": "Kubernetes", "input_source": "manifest", "auth_required": False})
rec(id="SCP-000427", language="YAML", framework="Kubernetes",
title="Public load balancer exposes admin port",
description="A Service exposes an admin port to the internet.",
owasp="A05:2021 - Security Misconfiguration", owasp_api="", owasp_llm="",
cwe="CWE-668", mitre_attack="T1190 - Exploit Public-Facing Application",
severity="High", difficulty="Intermediate",
vulnerable_code="spec:\\n type: LoadBalancer\\n ports:\\n - port: 9090 # admin UI public # Vulnerable\\",
secure_code="spec:\\n type: ClusterIP # Secure: internal only\\n ports:\\n - port: 9090\\",
patch="--- a/svc.yaml\\n+++ b/svc.yaml\\n@@ -1,5 +1,4 @@\\n-spec:\\n type: LoadBalancer\\n ports:\\n - port: 9090\\n+spec:\\n+ type: ClusterIP\\n+ ports:\\n+ - port: 9090\\",
root_cause="Admin port public.",
attack="Attack admin UI from internet.", impact="Compromise.",
fix="Use ClusterIP / ingress auth.", guideline="Don\'t expose admin publicly.",
tags=["kubernetes", "yaml", "exposure", "network"],
metadata={"domain": "Kubernetes", "input_source": "manifest", "auth_required": False})
rec(id="SCP-000428", language="YAML", framework="Kubernetes",
title="ReadOnlyRootFilesystem not set",
description="A container allows writes to root filesystem.",
owasp="A05:2021 - Security Misconfiguration", owasp_api="", owasp_llm="",
cwe="CWE-732", mitre_attack="T1611 - Escape to Host",
severity="Medium", difficulty="Beginner",
vulnerable_code="securityContext:\\n readOnlyRootFilesystem: false # Vulnerable: writable root\\",
secure_code="securityContext:\\n readOnlyRootFilesystem: true # Secure: immutable root\\",
patch="--- a/deploy.yaml\\n+++ b/deploy.yaml\\n@@ -1,3 +1,3 @@\\n-securityContext:\\n readOnlyRootFilesystem: false\\n+securityContext:\\n+ readOnlyRootFilesystem: true\\",
root_cause="Writable root fs.",
attack="Drop malicious binaries.", impact="Persistence.",
fix="Set readOnlyRootFilesystem.", guideline="Immutable root fs.",
tags=["kubernetes", "yaml", "filesystem", "container"],
metadata={"domain": "Kubernetes", "input_source": "manifest", "auth_required": False})
rec(id="SCP-000429", language="YAML", framework="Kubernetes",
title="RBAC cluster-admin binding",
description="A ServiceAccount is bound to cluster-admin.",
owasp="A01:2021 - Broken Access Control", owasp_api="", owasp_llm="",
cwe="CWE-269", mitre_attack="T1078 - Valid Accounts",
severity="Critical", difficulty="Intermediate",
vulnerable_code="kind: ClusterRoleBinding\\nsubjects:\\n- kind: ServiceAccount\\n name: app\\nroleRef:\\n kind: ClusterRole\\n name: cluster-admin # Vulnerable\\",
secure_code="kind: RoleBinding\\n# bind only the verbs needed in the namespace\\nroleRef:\\n kind: Role\\n name: app-role # Secure: least privilege\\",
patch="--- a/rbac.yaml\\n+++ b/rbac.yaml\\n@@ -1,8 +1,5 @@\\n-kind: ClusterRoleBinding\\nsubjects:\\n- kind: ServiceAccount\\n name: app\\n-roleRef:\\n kind: ClusterRole\\n name: cluster-admin\\n+kind: RoleBinding\\n+roleRef:\\n+ kind: Role\\n+ name: app-role\\",
root_cause="Over-privileged RBAC.",
attack="SA abused for cluster control.", impact="Cluster compromise.",
fix="Least-privilege RBAC.", guideline="Minimize RBAC scope.",
tags=["kubernetes", "yaml", "rbac", "privilege"],
metadata={"domain": "Kubernetes", "input_source": "manifest", "auth_required": False})
rec(id="SCP-000430", language="YAML", framework="Kubernetes",
title="Liveness probe missing (silent failures)",
description="A deployment has no liveness/readiness probes.",
owasp="A05:2021 - Security Misconfiguration", owasp_api="", owasp_llm="",
cwe="CWE-754", mitre_attack="T1499 - Endpoint Denial of Service",
severity="Low", difficulty="Beginner",
vulnerable_code="# No probes defined # Vulnerable: hung pod not restarted\\",
secure_code="livenessProbe:\\n httpGet: {path: /healthz, port: 8080}\\n initialDelaySeconds: 10\\nreadinessProbe:\\n httpGet: {path: /readyz, port: 8080} # Secure\\",
patch="--- a/deploy.yaml\\n+++ b/deploy.yaml\\n@@ -1,2 +1,7 @@\\n-# No probes defined\\n+livenessProbe:\\n+ httpGet: {path: /healthz, port: 8080}\\n+ initialDelaySeconds: 10\\n+readinessProbe:\\n+ httpGet: {path: /readyz, port: 8080}\\",
root_cause="No health probes.",
attack="Hung pod lingers, DoS.", impact="Availability loss.",
fix="Add probes.", guideline="Define health probes.",
tags=["kubernetes", "yaml", "availability", "probe"],
metadata={"domain": "Kubernetes", "input_source": "manifest", "auth_required": False})
RECORDS_EXT9 = L