#!/usr/bin/env python3 """SecureCodePairs v1.1.0 extension records (part 2): SCP-000087+. Domains: fintech, FHIR/healthcare, Kubernetes, IoT. Languages deepened: Python, Java, Go, TypeScript, C#, PHP, Kotlin, Swift, Rust. """ from typing import List, Dict RECORDS_EXT2: List[Dict] = [ # ================================================================== FINTECH (Python/FastAPI) ================================================================== { "id": "SCP-000087", "language": "Python", "framework": "FastAPI", "title": "Missing idempotency on payment endpoint", "description": "A payment endpoint processes the same request twice if retried, double-charging.", "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": "High", "difficulty": "Intermediate", "vulnerable_code": ( "@app.post('/pay')\n" "def pay(req: PaymentReq):\n" " # Vulnerable: no idempotency key check\n" " charge_card(req.user, req.amount)\n" " return {'ok': True}\n" ), "secure_code": ( "@app.post('/pay')\n" "def pay(req: PaymentReq, idem: str = Header(...)):\n" " # Secure: dedupe by idempotency key\n" " if redis.exists('idem:' + idem):\n" " return {'ok': True, 'cached': True}\n" " charge_card(req.user, req.amount)\n" " redis.setex('idem:' + idem, 86400, '1')\n" " return {'ok': True}\n" ), "patch": ( "--- a/pay.py\n" "+++ b/pay.py\n" "@@ -1,5 +1,10 @@\n" "-def pay(req: PaymentReq):\n" "- charge_card(req.user, req.amount)\n" "+def pay(req: PaymentReq, idem: str = Header(...)):\n" "+ if redis.exists('idem:' + idem):\n" " return {'ok': True, 'cached': True}\n" "+ charge_card(req.user, req.amount)\n" "+ redis.setex('idem:' + idem, 86400, '1')\n" ), "root_cause": "No idempotency key, so client retries cause duplicate charges.", "attack": "Network retry or replay of the request double-charges the customer.", "impact": "Financial loss, customer trust damage.", "fix": "Require and dedupe on an idempotency key per mutating request.", "guideline": "Make payment endpoints idempotent via idempotency keys.", "tags": ["business-logic", "fintech", "fastapi", "idempotency"], "metadata": {"domain": "Banking", "input_source": "header", "auth_required": True}, }, { "id": "SCP-000088", "language": "Java", "framework": "Spring Boot", "title": "Rounding error in interest calculation", "description": "A Spring service uses binary floating point for money, causing rounding drift.", "owasp": "A04:2021 - Insecure Design", "owasp_api": "", "owasp_llm": "", "cwe": "CWE-682", "mitre_attack": "T1190 - Exploit Public-Facing Application", "severity": "Medium", "difficulty": "Intermediate", "vulnerable_code": ( "public BigDecimal interest(double principal, double rate) {\n" " // Vulnerable: double for currency\n" " return BigDecimal.valueOf(principal * rate);\n" "}\n" ), "secure_code": ( "public BigDecimal interest(BigDecimal principal, BigDecimal rate) {\n" " // Secure: BigDecimal throughout, explicit rounding\n" " return principal.multiply(rate)\n" " .setScale(2, RoundingMode.HALF_UP);\n" "}\n" ), "patch": ( "--- a/InterestService.java\n" "+++ b/InterestService.java\n" "@@ -1,4 +1,6 @@\n" "- return BigDecimal.valueOf(principal * rate);\n" "+ return principal.multiply(rate)\n" "+ .setScale(2, RoundingMode.HALF_UP);\n" ), "root_cause": "Binary floating point cannot represent decimal currency exactly, introducing drift.", "attack": "Repeated calculations accumulate cents of error, enabling arbitrage or loss.", "impact": "Incorrect balances, financial discrepancy.", "fix": "Use BigDecimal (or integer minor units) with explicit rounding for all money.", "guideline": "Never use float/double for currency; use BigDecimal with scale.", "tags": ["fintech", "spring", "java", "rounding"], "metadata": {"domain": "Banking", "input_source": "server", "auth_required": False}, }, { "id": "SCP-000089", "language": "Go", "framework": "Gin", "title": "Missing signature verification on webhook", "description": "A Gin webhook handler trusts the body without verifying the provider's HMAC signature.", "owasp": "A08:2021 - Software and Data Integrity Failures", "owasp_api": "API2:2023 - Broken Authentication", "owasp_llm": "", "cwe": "CWE-345", "mitre_attack": "T1190 - Exploit Public-Facing Application", "severity": "High", "difficulty": "Intermediate", "vulnerable_code": ( "func webhook(c *gin.Context) {\n" " body, _ := c.GetRawData()\n" " // Vulnerable: no signature check\n" " processEvent(json.RawMessage(body))\n" " c.Status(200)\n" "}\n" ), "secure_code": ( "func webhook(c *gin.Context) {\n" " body, _ := c.GetRawData()\n" " sig := c.GetHeader(\"X-Signature\")\n" " // Secure: verify HMAC\n" " mac := hmac.New(sha256.New, []byte(os.Getenv(\"WEBHOOK_SECRET\")))\n" " mac.Write(body)\n" " if !hmac.Equal([]byte(sig), []byte(hex.EncodeToString(mac.Sum(nil)))) {\n" " c.Status(401); return\n" " }\n" " processEvent(json.RawMessage(body))\n" " c.Status(200)\n" "}\n" ), "patch": ( "--- a/webhook.go\n" "+++ b/webhook.go\n" "@@ -2,5 +2,12 @@\n" "- processEvent(json.RawMessage(body))\n" "+ sig := c.GetHeader(\"X-Signature\")\n" "+ mac := hmac.New(sha256.New, []byte(os.Getenv(\"WEBHOOK_SECRET\")))\n" "+ mac.Write(body)\n" "+ if !hmac.Equal([]byte(sig), []byte(hex.EncodeToString(mac.Sum(nil)))) {\n" "+ c.Status(401); return\n" "+ }\n" "+ processEvent(json.RawMessage(body))\n" ), "root_cause": "Webhook authenticity is not verified, so anyone can forge events.", "attack": "Attacker posts fake 'payment succeeded' events to grant themselves credit.", "impact": "Fraud, unauthorized state changes.", "fix": "Verify the provider HMAC signature on every webhook before processing.", "guideline": "Always verify webhook signatures (HMAC) before acting on events.", "tags": ["fintech", "gin", "go", "webhook"], "metadata": {"domain": "Banking", "input_source": "request_body", "auth_required": False}, }, { "id": "SCP-000090", "language": "TypeScript", "framework": "NestJS", "title": "Client-side amount manipulation in checkout", "description": "A NestJS checkout trusts the price sent from the client instead of the server catalog.", "owasp": "A04:2021 - Insecure Design", "owasp_api": "API3:2023 - Broken Object Property Level Authorization", "owasp_llm": "", "cwe": "CWE-602", "mitre_attack": "T1190 - Exploit Public-Facing Application", "severity": "High", "difficulty": "Intermediate", "vulnerable_code": ( "@Post('checkout')\n" "checkout(@Body() b: { itemId: string; price: number }) {\n" " // Vulnerable: trusts client price\n" " return this.billing.charge(b.price);\n" "}\n" ), "secure_code": ( "@Post('checkout')\n" "async checkout(@Body() b: { itemId: string }) {\n" " // Secure: look up authoritative price server-side\n" " const item = await this.catalog.get(b.itemId);\n" " return this.billing.charge(item.price);\n" "}\n" ), "patch": ( "--- a/checkout.controller.ts\n" "+++ b/checkout.controller.ts\n" "@@ -1,5 +1,6 @@\n" "-checkout(@Body() b: { itemId: string; price: number }) {\n" "- return this.billing.charge(b.price);\n" "+async checkout(@Body() b: { itemId: string }) {\n" "+ const item = await this.catalog.get(b.itemId);\n" "+ return this.billing.charge(item.price);\n" ), "root_cause": "Price is taken from the client, so an attacker can set it to 0.01.", "attack": "Intercept the request and change price to 0.01 to buy at a discount.", "impact": "Revenue loss, fraud.", "fix": "Never trust client-supplied prices; derive totals server-side from the catalog.", "guideline": "Compute prices server-side from authoritative sources.", "tags": ["fintech", "nestjs", "typescript", "price-tampering"], "metadata": {"domain": "E-commerce", "input_source": "request_body", "auth_required": True}, }, { "id": "SCP-000091", "language": "Python", "framework": "Django", "title": "Reusable token (no expiry) for password reset", "description": "A Django reset token never expires and is stored in plaintext, enabling reuse.", "owasp": "A07:2021 - Identification and Authentication Failures", "owasp_api": "API2:2023 - Broken Authentication", "owasp_llm": "", "cwe": "CWE-640", "mitre_attack": "T1600 - Weaken Encryption", "severity": "High", "difficulty": "Intermediate", "vulnerable_code": ( "def issue_reset(user):\n" " token = secrets.token_urlsafe(16)\n" " # Vulnerable: no expiry, plaintext store\n" " Cache.set('reset:' + user.id, token)\n" " return token\n" ), "secure_code": ( "def issue_reset(user):\n" " token = secrets.token_urlsafe(32)\n" " # Secure: hash + short TTL\n" " Cache.set('reset:' + user.id, sha256(token), 900)\n" " return token\n" ), "patch": ( "--- a/auth.py\n" "+++ b/auth.py\n" "@@ -2,5 +2,6 @@\n" "- token = secrets.token_urlsafe(16)\n" "- Cache.set('reset:' + user.id, token)\n" "+ token = secrets.token_urlsafe(32)\n" "+ Cache.set('reset:' + user.id, sha256(token), 900)\n" ), "root_cause": "Reset tokens lack expiry and are stored reversibly, allowing indefinite reuse.", "attack": "Attacker who sees the token once can reset the password indefinitely.", "impact": "Persistent account takeover.", "fix": "Set short TTLs and store only token hashes; invalidate after use.", "guideline": "Reset tokens must expire and be single-use; store hashes only.", "tags": ["fintech", "django", "python", "auth"], "metadata": {"domain": "Authentication systems", "input_source": "server", "auth_required": False}, }, { "id": "SCP-000092", "language": "C#", "framework": "ASP.NET Core", "title": "Insecure direct object reference on bank account", "description": "An ASP.NET Core controller returns an account by id without verifying ownership.", "owasp": "A01:2021 - Broken Access Control", "owasp_api": "API1:2023 - Broken Object Level Authorization", "owasp_llm": "", "cwe": "CWE-639", "mitre_attack": "T1190 - Exploit Public-Facing Application", "severity": "Critical", "difficulty": "Beginner", "vulnerable_code": ( "[HttpGet(\"accounts/{id}\")]\n" "public Account Get(string id) => _repo.GetAccount(id); // Vulnerable: no owner check\n" ), "secure_code": ( "[HttpGet(\"accounts/{id}\")]\n" "public IActionResult Get(string id, [FromClaims] string userId)\n" "{\n" " var acc = _repo.GetAccount(id);\n" " if (acc == null || acc.OwnerId != userId) return NotFound();\n" " return Ok(acc);\n" "}\n" ), "patch": ( "--- a/AccountsController.cs\n" "+++ b/AccountsController.cs\n" "@@ -1,3 +1,7 @@\n" "-public Account Get(string id) => _repo.GetAccount(id);\n" "+public IActionResult Get(string id, [FromClaims] string userId) {\n" "+ var acc = _repo.GetAccount(id);\n" "+ if (acc == null || acc.OwnerId != userId) return NotFound();\n" "+ return Ok(acc); }\n" ), "root_cause": "Account lookup is keyed only by id, not by the authenticated owner.", "attack": "User enumerates account ids to read other customers' balances.", "impact": "Disclosure of financial data (PII).", "fix": "Scope lookups to the authenticated principal.", "guideline": "Enforce object-level authorization on financial records.", "tags": ["fintech", "aspnet", "csharp", "idor"], "metadata": {"domain": "Banking", "input_source": "path_param", "auth_required": True}, }, # ================================================================== FHIR / HEALTHCARE ================================================================== { "id": "SCP-000093", "language": "Java", "framework": "Spring Boot", "title": "FHIR resource IDOR across tenants", "description": "A Spring FHIR server returns a Patient resource by id without tenant scoping.", "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": "Critical", "difficulty": "Intermediate", "vulnerable_code": ( "@GetMapping(\"/fhir/Patient/{id}\")\n" "public Patient read(@PathVariable String id) {\n" " // Vulnerable: no tenant filter\n" " return fhirDao.read(Patient.class, id);\n" "}\n" ), "secure_code": ( "@GetMapping(\"/fhir/Patient/{id}\")\n" "public Patient read(@PathVariable String id, @TenantId String tenant) {\n" " // Secure: scope by tenant\n" " Patient p = fhirDao.read(Patient.class, id);\n" " if (!p.getTenant().equals(tenant)) throw new NotFoundException();\n" " return p;\n" "}\n" ), "patch": ( "--- a/FhirController.java\n" "+++ b/FhirController.java\n" "@@ -2,4 +2,7 @@\n" "- return fhirDao.read(Patient.class, id);\n" "+ Patient p = fhirDao.read(Patient.class, id);\n" "+ if (!p.getTenant().equals(tenant)) throw new NotFoundException();\n" "+ return p;\n" ), "root_cause": "FHIR reads are not scoped by tenant, so one clinic reads another's patients.", "attack": "Intercept and change Patient id to scrape PHI across tenants.", "impact": "HIPAA violation, mass PHI disclosure.", "fix": "Apply tenant scoping on every FHIR read/write.", "guideline": "Tenant-isolate all PHI resources; verify on every access.", "tags": ["fhir", "spring", "java", "healthcare"], "metadata": {"domain": "Healthcare", "input_source": "path_param", "auth_required": True}, }, { "id": "SCP-000094", "language": "Python", "framework": "FastAPI", "title": "Unvalidated FHIR Observation value", "description": "A FastAPI endpoint stores a FHIR Observation value without validating type/range, enabling injection.", "owasp": "A03:2021 - Injection", "owasp_api": "", "owasp_llm": "", "cwe": "CWE-20", "mitre_attack": "T1190 - Exploit Public-Facing Application", "severity": "Medium", "difficulty": "Intermediate", "vulnerable_code": ( "@app.post('/fhir/Observation')\n" "def obs(o: dict):\n" " # Vulnerable: stores arbitrary value\n" " db.observations.insert_one(o)\n" " return {'ok': True}\n" ), "secure_code": ( "@app.post('/fhir/Observation')\n" "def obs(o: ObservationModel):\n" " # Secure: pydantic validation of code/value/unit\n" " if not (0 <= o.valueQuantity.value <= 1000):\n" " raise HTTPException(422, 'out of range')\n" " db.observations.insert_one(o.dict())\n" " return {'ok': True}\n" ), "patch": ( "--- a/fhir_obs.py\n" "+++ b/fhir_obs.py\n" "@@ -1,5 +1,8 @@\n" "-def obs(o: dict):\n" "- db.observations.insert_one(o)\n" "+def obs(o: ObservationModel):\n" "+ if not (0 <= o.valueQuantity.value <= 1000):\n" "+ raise HTTPException(422, 'out of range')\n" "+ db.observations.insert_one(o.dict())\n" ), "root_cause": "Observation payload is stored without schema/range validation, allowing malformed or hostile data.", "attack": "Post an Observation with a script payload later rendered in a clinician dashboard (stored XSS).", "impact": "Data integrity loss, stored XSS in viewers.", "fix": "Validate FHIR resources against the profile (type, range, required fields).", "guideline": "Validate all FHIR resources server-side before persistence.", "tags": ["fhir", "fastapi", "python", "input-validation"], "metadata": {"domain": "Healthcare", "input_source": "request_body", "auth_required": True}, }, { "id": "SCP-000095", "language": "C#", "framework": "ASP.NET Core", "title": "Missing audit log on PHI access", "description": "An ASP.NET Core healthcare API reads PHI without writing an audit trail.", "owasp": "A09:2021 - Security Logging and Monitoring Failures", "owasp_api": "", "owasp_llm": "", "cwe": "CWE-778", "mitre_attack": "T1562.001 - Impair Defenses: Disable or Modify Tools", "severity": "Medium", "difficulty": "Beginner", "vulnerable_code": ( "[HttpGet(\"records/{id}\")]\n" "public Record Get(int id) {\n" " // Vulnerable: no audit log\n" " return _repo.Get(id);\n" "}\n" ), "secure_code": ( "[HttpGet(\"records/{id}\")]\n" "public Record Get(int id, ClaimsPrincipal user)\n" "{\n" " var r = _repo.Get(id);\n" " _audit.Log(new PhiAccess { User = user.Identity.Name, RecordId = id, At = DateTime.UtcNow });\n" " return r;\n" "}\n" ), "patch": ( "--- a/RecordsController.cs\n" "+++ b/RecordsController.cs\n" "@@ -1,4 +1,7 @@\n" "- return _repo.Get(id);\n" "+ var r = _repo.Get(id);\n" "+ _audit.Log(new PhiAccess { User = user.Identity.Name, RecordId = id, At = DateTime.UtcNow });\n" "+ return r;\n" ), "root_cause": "PHI access is not audited, failing compliance and incident response needs.", "attack": "An insider scrapes records with no trace, evading detection.", "impact": "Undetected PHI abuse; compliance failure (HIPAA).", "fix": "Emit immutable audit logs for every PHI read/write.", "guideline": "Audit all PHI access with user, record, and timestamp.", "tags": ["fhir", "aspnet", "csharp", "audit"], "metadata": {"domain": "Healthcare", "input_source": "path_param", "auth_required": True}, }, { "id": "SCP-000096", "language": "JavaScript", "framework": "Express", "title": "HL7v2 injection in message builder", "description": "An Express service builds HL7v2 messages by concatenating patient fields without escaping separators.", "owasp": "A03:2021 - Injection", "owasp_api": "", "owasp_llm": "", "cwe": "CWE-93", "mitre_attack": "T1190 - Exploit Public-Facing Application", "severity": "Medium", "difficulty": "Advanced", "vulnerable_code": ( "function hl7(patient) {\n" " // Vulnerable: unescaped field with pipe/newline\n" " return `PID|1|${patient.name}|${patient.dob}`;\n" "}\n" ), "secure_code": ( "function esc(s) { return String(s).replace(/[\\r\\n|]/g, ''); }\n" "function hl7(patient) {\n" " // Secure: strip HL7 field/segment separators\n" " return `PID|1|${esc(patient.name)}|${esc(patient.dob)}`;\n" "}\n" ), "patch": ( "--- a/hl7.js\n" "+++ b/hl7.js\n" "@@ -1,4 +1,6 @@\n" "+function esc(s) { return String(s).replace(/[\\r\\n|]/g, ''); }\n" " function hl7(patient) {\n" "- return `PID|1|${patient.name}|${patient.dob}`;\n" "+ return `PID|1|${esc(patient.name)}|${esc(patient.dob)}`;\n" ), "root_cause": "Patient fields containing HL7 separators corrupt the message or inject segments.", "attack": "name=EVN|1|admin sets a fake segment altering downstream routing.", "impact": "Message corruption, false data, misrouting.", "fix": "Escape HL7 separators and validate field contents.", "guideline": "Escape/encode structured-message separators before concatenation.", "tags": ["healthcare", "hl7", "express", "injection"], "metadata": {"domain": "Healthcare", "input_source": "request_body", "auth_required": False}, }, # ================================================================== KUBERNETES ================================================================== { "id": "SCP-000097", "language": "YAML", "framework": "Kubernetes", "title": "Container running as root with privileged", "description": "A Kubernetes Pod manifest runs as root with privileged: true, enabling host escape.", "owasp": "A05:2021 - Security Misconfiguration", "owasp_api": "", "owasp_llm": "", "cwe": "CWE-250", "mitre_attack": "T1611 - Escape to Host", "severity": "Critical", "difficulty": "Beginner", "vulnerable_code": ( "apiVersion: v1\n" "kind: Pod\n" "spec:\n" " containers:\n" " - name: app\n" " image: app:1.0\n" " securityContext:\n" " privileged: true # Vulnerable\n" " runAsUser: 0 # Vulnerable: root\n" ), "secure_code": ( "apiVersion: v1\n" "kind: Pod\n" "spec:\n" " securityContext:\n" " runAsNonRoot: true\n" " runAsUser: 1000\n" " seccompProfile:\n" " type: RuntimeDefault\n" " containers:\n" " - name: app\n" " image: app:1.0\n" " securityContext:\n" " allowPrivilegeEscalation: false\n" " readOnlyRootFilesystem: true\n" " capabilities:\n" " drop: [\"ALL\"]\n" ), "patch": ( "--- a/pod.yaml\n" "+++ b/pod.yaml\n" "@@ -3,7 +3,14 @@\n" "- securityContext:\n" "- privileged: true\n" "- runAsUser: 0\n" "+ securityContext:\n" "+ runAsNonRoot: true\n" "+ runAsUser: 1000\n" "+ seccompProfile:\n" "+ type: RuntimeDefault\n" "+ securityContext:\n" "+ allowPrivilegeEscalation: false\n" "+ readOnlyRootFilesystem: true\n" "+ capabilities: { drop: [\"ALL\"] }\n" ), "root_cause": "Privileged root containers can escape to the node via the kernel.", "attack": "A compromised container mounts /host and reads node secrets or pivots.", "impact": "Full node/cluster compromise.", "fix": "Run as non-root, drop capabilities, disable privilege escalation, use seccomp.", "guideline": "Apply Pod Security Standards; never run privileged/root in prod.", "tags": ["kubernetes", "privilege", "yaml", "container"], "metadata": {"domain": "Microservices", "input_source": "manifest", "auth_required": False}, }, { "id": "SCP-000098", "language": "YAML", "framework": "Kubernetes", "title": "Missing NetworkPolicy allows lateral movement", "description": "A namespace has no NetworkPolicy, so any pod can reach any other pod (including the DB).", "owasp": "A05:2021 - Security Misconfiguration", "owasp_api": "", "owasp_llm": "", "cwe": "CWE-923", "mitre_attack": "T1021 - Remote Services", "severity": "High", "difficulty": "Intermediate", "vulnerable_code": ( "# Vulnerable: no NetworkPolicy -> flat network\n" "apiVersion: v1\n" "kind: Service\n" "metadata:\n" " name: db\n" ), "secure_code": ( "apiVersion: networking.k8s.io/v1\n" "kind: NetworkPolicy\n" "metadata:\n" " name: default-deny\n" "spec:\n" " podSelector: {}\n" " policyTypes: [Ingress, Egress]\n" "---\n" "apiVersion: networking.k8s.io/v1\n" "kind: NetworkPolicy\n" "metadata:\n" " name: allow-app-to-db\n" "spec:\n" " podSelector:\n" " matchLabels: { app: db }\n" " ingress:\n" " - from:\n" " - podSelector:\n" " matchLabels: { app: api }\n" ), "patch": ( "--- a/networkpolicy.yaml\n" "+++ b/networkpolicy.yaml\n" "@@ -1,5 +1,23 @@\n" "+apiVersion: networking.k8s.io/v1\n" "+kind: NetworkPolicy\n" "+metadata: { name: default-deny }\n" "+spec:\n" "+ podSelector: {}\n" "+ policyTypes: [Ingress, Egress]\n" "+---\n" "+kind: NetworkPolicy\n" "+metadata: { name: allow-app-to-db }\n" "+spec:\n" "+ podSelector: { matchLabels: { app: db } }\n" "+ ingress:\n" "+ - from:\n" "+ - podSelector: { matchLabels: { app: api } }\n" ), "root_cause": "Absence of NetworkPolicy leaves pod-to-pod traffic unrestricted.", "attack": "A compromised web pod connects directly to the database pod.", "impact": "Lateral movement, data access.", "fix": "Apply default-deny and explicit allow policies between tiers.", "guideline": "Use NetworkPolicies to segment pod traffic by tier.", "tags": ["kubernetes", "network", "yaml", "segmentation"], "metadata": {"domain": "Microservices", "input_source": "manifest", "auth_required": False}, }, { "id": "SCP-000099", "language": "YAML", "framework": "Kubernetes", "title": "Image pulled from unpinned tag (latest)", "description": "A Deployment references an image by mutable :latest tag, enabling supply-chain drift.", "owasp": "A08:2021 - Software and Data Integrity Failures", "owasp_api": "", "owasp_llm": "", "cwe": "CWE-494", "mitre_attack": "T1195.001 - Supply Chain Compromise: Compromise Software Dependencies", "severity": "High", "difficulty": "Beginner", "vulnerable_code": ( "spec:\n" " containers:\n" " - name: app\n" " image: registry/app:latest # Vulnerable: mutable tag\n" ), "secure_code": ( "spec:\n" " containers:\n" " - name: app\n" " image: registry/app@sha256:9f86d0818... # Secure: digest-pinned\n" " imagePullPolicy: IfNotPresent\n" ), "patch": ( "--- a/deploy.yaml\n" "+++ b/deploy.yaml\n" "@@ -3,4 +3,5 @@\n" "- image: registry/app:latest\n" "+ image: registry/app@sha256:9f86d0818...\n" "+ imagePullPolicy: IfNotPresent\n" ), "root_cause": "Mutable image tags let an attacker-controlled rebuild run as the same deployment.", "attack": "Attacker pushes a malicious :latest; the next rollout runs it.", "impact": "Supply-chain compromise of workloads.", "fix": "Pin images by immutable digest and verify signatures (cosign).", "guideline": "Pin images by sha256 digest; sign and verify with cosign.", "tags": ["kubernetes", "supply-chain", "yaml", "image"], "metadata": {"domain": "Microservices", "input_source": "manifest", "auth_required": False}, }, { "id": "SCP-000100", "language": "Go", "framework": "Kubernetes Operator", "title": "Operator grants excessive RBAC", "description": "A Kubernetes operator's ClusterRole grants wildcard verbs/resources, violating least privilege.", "owasp": "A05:2021 - Security Misconfiguration", "owasp_api": "", "owasp_llm": "", "cwe": "CWE-269", "mitre_attack": "T1078 - Valid Accounts", "severity": "High", "difficulty": "Intermediate", "vulnerable_code": ( "rules:\n" "- apiGroups: [\"*\"]\n" " resources: [\"*\"] # Vulnerable: wildcard\n" " verbs: [\"*\"] # Vulnerable: all verbs\n" ), "secure_code": ( "rules:\n" "- apiGroups: [\"app.example.com\"]\n" " resources: [\"widgets\", \"widgets/status\"]\n" " verbs: [\"get\", \"list\", \"watch\", \"update\", \"patch\"]\n" ), "patch": ( "--- a/role.yaml\n" "+++ b/role.yaml\n" "@@ -1,5 +1,5 @@\n" "- resources: [\"*\"]\n" "- verbs: [\"*\"]\n" "+ resources: [\"widgets\", \"widgets/status\"]\n" "+ verbs: [\"get\", \"list\", \"watch\", \"update\", \"patch\"]\n" ), "root_cause": "Wildcard RBAC grants far more than the operator needs.", "attack": "A compromised operator can read secrets cluster-wide or delete workloads.", "impact": "Cluster-wide privilege escalation.", "fix": "Scope RBAC to specific API groups/resources/verbs; avoid wildcards.", "guideline": "Apply least-privilege RBAC; never use wildcard resources/verbs.", "tags": ["kubernetes", "rbac", "go", "least-privilege"], "metadata": {"domain": "Microservices", "input_source": "manifest", "auth_required": False}, }, { "id": "SCP-000101", "language": "Python", "framework": "Kubernetes Operator", "title": "Secret exposed in operator log", "description": "An operator logs the full resource spec including a Secret reference's literal value.", "owasp": "A09:2021 - Security Logging and Monitoring Failures", "owasp_api": "", "owasp_llm": "", "cwe": "CWE-532", "mitre_attack": "T1562.001 - Impair Defenses", "severity": "Medium", "difficulty": "Beginner", "vulnerable_code": ( "def reconcile(req):\n" " # Vulnerable: logs secret contents\n" " logging.info('spec=%s', req.obj['spec'])\n" ), "secure_code": ( "SENSITIVE = {'password', 'token', 'secret'}\n" "def _redact(spec):\n" " return {k: '***' if k.lower() in SENSITIVE else v for k, v in spec.items()}\n" "def reconcile(req):\n" " logging.info('spec=%s', _redact(req.obj['spec']))\n" ), "patch": ( "--- a/operator.py\n" "+++ b/operator.py\n" "@@ -1,3 +1,6 @@\n" "- logging.info('spec=%s', req.obj['spec'])\n" "+ def _redact(spec):\n" "+ return {k: '***' if k.lower() in SENSITIVE else v for k, v in spec.items()}\n" "+ logging.info('spec=%s', _redact(req.obj['spec']))\n" ), "root_cause": "Full resource specs containing secrets are written to logs.", "attack": "Anyone with log access reads secret values.", "impact": "Secret disclosure.", "fix": "Redact sensitive fields before logging; never log secrets.", "guideline": "Redact secrets in all logs; scrub sensitive keys.", "tags": ["kubernetes", "logging", "python", "secrets"], "metadata": {"domain": "Microservices", "input_source": "request_body", "auth_required": False}, }, # ================================================================== IoT ================================================================== { "id": "SCP-000102", "language": "C", "framework": "Embedded", "title": "Hardcoded WiFi credentials in firmware", "description": "An embedded IoT firmware stores WiFi credentials as string literals in flash.", "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 char *SSID = \"HomeNet\";\n" "const char *PSK = \"password123\"; // Vulnerable: hardcoded\n" ), "secure_code": ( "char ssid[33], psk[64];\n" "// Secure: load from secure element / provisioning at first boot\n" "if (load_credentials(ssid, psk) != 0) {\n" " enter_provisioning_mode();\n" "}\n" ), "patch": ( "--- a/wifi.c\n" "+++ b/wifi.c\n" "@@ -1,3 +1,6 @@\n" "-const char *SSID = \"HomeNet\";\n" "-const char *PSK = \"password123\";\n" "+char ssid[33], psk[64];\n" "+if (load_credentials(ssid, psk) != 0) {\n" "+ enter_provisioning_mode();\n" "+}\n" ), "root_cause": "Credentials compiled into firmware are recoverable by dumping flash.", "attack": "Attacker extracts the firmware and reads the WiFi PSK for network access.", "impact": "Network compromise via recovered credentials.", "fix": "Store credentials in a secure element; provision at first boot.", "guideline": "Never store secrets in firmware; use secure provisioning.", "tags": ["iot", "c", "secrets", "firmware"], "metadata": {"domain": "IoT", "input_source": "source_code", "auth_required": False}, }, { "id": "SCP-000103", "language": "C", "framework": "Embedded", "title": "Unauthenticated MQTT control topic", "description": "An IoT device subscribes to a control topic without auth, allowing remote actuation.", "owasp": "A01:2021 - Broken Access Control", "owasp_api": "", "owasp_llm": "", "cwe": "CWE-306", "mitre_attack": "T0883 - Internet Accessible Device", "severity": "Critical", "difficulty": "Intermediate", "vulnerable_code": ( "void on_message(char *topic, char *payload) {\n" " // Vulnerable: no auth on control topic\n" " if (strcmp(topic, \"device/cmd\") == 0) actuate(payload);\n" "}\n" ), "secure_code": ( "void on_message(char *topic, char *payload, mqtt_conn *c) {\n" " // Secure: require authenticated client + signed command\n" " if (!c->authenticated) return;\n" " if (strcmp(topic, \"device/cmd\") == 0 && verify_sig(payload, c->pubkey))\n" " actuate(payload);\n" "}\n" ), "patch": ( "--- a/mqtt.c\n" "+++ b/mqtt.c\n" "@@ -1,4 +1,7 @@\n" "- if (strcmp(topic, \"device/cmd\") == 0) actuate(payload);\n" "+ if (!c->authenticated) return;\n" "+ if (strcmp(topic, \"device/cmd\") == 0 && verify_sig(payload, c->pubkey))\n" "+ actuate(payload);\n" ), "root_cause": "Control commands are accepted from any client without authentication or integrity.", "attack": "Attacker publishes to device/cmd to unlock doors or change settings.", "impact": "Physical safety/security compromise.", "fix": "Require authenticated, signed commands over TLS MQTT.", "guideline": "Authenticate and sign IoT control commands; use MQTT over TLS.", "tags": ["iot", "c", "mqtt", "auth"], "metadata": {"domain": "IoT", "input_source": "network", "auth_required": True}, }, { "id": "SCP-000104", "language": "Python", "framework": "MicroPython", "title": "Telnet exposed without authentication on device", "description": "An IoT gateway starts a Telnet server with no auth, giving root shell access.", "owasp": "A07:2021 - Identification and Authentication Failures", "owasp_api": "", "owasp_llm": "", "cwe": "CWE-306", "mitre_attack": "T1021 - Remote Services", "severity": "Critical", "difficulty": "Beginner", "vulnerable_code": ( "import utelnet\n" "# Vulnerable: telnet with no auth\n" "utelnet.start(port=23, login=None, password=None)\n" ), "secure_code": ( "import ussl, socket\n" "# Secure: SSH/TLS with key auth only\n" "server = socket.socket()\n" "server = ussl.wrap_socket(server, keyfile='dev.key', certfile='dev.crt')\n" "server.bind(('', 22))\n" "server.listen(1)\n" ), "patch": ( "--- a/shell.py\n" "+++ b/shell.py\n" "@@ -1,4 +1,8 @@\n" "-utelnet.start(port=23, login=None, password=None)\n" "+server = socket.socket()\n" "+server = ussl.wrap_socket(server, keyfile='dev.key', certfile='dev.crt')\n" "+server.bind(('', 22))\n" "+server.listen(1)\n" ), "root_cause": "An unauthenticated Telnet server exposes a root shell on the LAN.", "attack": "Anyone on the network connects and gains full device control.", "impact": "Complete device compromise.", "fix": "Disable Telnet; use SSH/TLS with key-based auth.", "guideline": "Never expose unauthenticated shells; use SSH/TLS with keys.", "tags": ["iot", "python", "telnet", "auth"], "metadata": {"domain": "IoT", "input_source": "network", "auth_required": True}, }, { "id": "SCP-000105", "language": "C", "framework": "Embedded", "title": "Lack of firmware signature verification", "description": "An IoT bootloader flashes any uploaded firmware without verifying a signature.", "owasp": "A08:2021 - Software and Data Integrity Failures", "owasp_api": "", "owasp_llm": "", "cwe": "CWE-494", "mitre_attack": "T1195.002 - Supply Chain Compromise: Compromise Software Supply Chain", "severity": "Critical", "difficulty": "Advanced", "vulnerable_code": ( "void flash(const uint8_t *img, size_t len) {\n" " // Vulnerable: no signature check\n" " write_to_flash(img, len);\n" "}\n" ), "secure_code": ( "void flash(const uint8_t *img, size_t len) {\n" " // Secure: verify ECDSA signature with root public key\n" " if (!ecdsa_verify(ROOT_PUB, img, len - 64, img + len - 64))\n" " return;\n" " write_to_flash(img, len - 64);\n" "}\n" ), "patch": ( "--- a/bootloader.c\n" "+++ b/bootloader.c\n" "@@ -1,4 +1,7 @@\n" "- write_to_flash(img, len);\n" "+ if (!ecdsa_verify(ROOT_PUB, img, len - 64, img + len - 64))\n" "+ return;\n" "+ write_to_flash(img, len - 64);\n" ), "root_cause": "Firmware is flashed without verifying a trusted signature, enabling malicious images.", "attack": "Attacker uploads a trojaned firmware that persists on the device.", "impact": "Persistent device compromise, botnet recruitment.", "fix": "Verify firmware signatures (ECDSA) against a rooted public key before flashing.", "guideline": "Verify signed firmware; reject unsigned/modified images.", "tags": ["iot", "c", "firmware", "supply-chain"], "metadata": {"domain": "IoT", "input_source": "network", "auth_required": False}, }, { "id": "SCP-000106", "language": "Python", "framework": "IoT Gateway", "title": "Default credentials on management API", "description": "An IoT gateway API accepts a hardcoded default admin password.", "owasp": "A07:2021 - Identification and Authentication Failures", "owasp_api": "API2:2023 - Broken Authentication", "owasp_llm": "", "cwe": "CWE-1392", "mitre_attack": "T1078.001 - Valid Accounts: Default Accounts", "severity": "Critical", "difficulty": "Beginner", "vulnerable_code": ( "def login(u, p):\n" " # Vulnerable: default password\n" " if u == 'admin' and p == 'admin':\n" " return issue_token(u)\n" ), "secure_code": ( "def login(u, p):\n" " user = db.get_user(u)\n" " if user and argon2.verify(p, user.pw_hash):\n" " if not user.force_reset:\n" " return issue_token(u)\n" " return None\n" ), "patch": ( "--- a/auth.py\n" "+++ b/auth.py\n" "@@ -1,5 +1,7 @@\n" "- if u == 'admin' and p == 'admin':\n" "- return issue_token(u)\n" "+ user = db.get_user(u)\n" "+ if user and argon2.verify(p, user.pw_hash):\n" "+ return issue_token(u)\n" ), "root_cause": "A static default credential grants trivial admin access.", "attack": "Attacker logs in as admin with 'admin'/'admin'.", "impact": "Full device/gateway takeover.", "fix": "Store hashed credentials; force password change on first login; no defaults.", "guideline": "No default credentials; use hashed passwords and forced reset.", "tags": ["iot", "python", "default-creds", "auth"], "metadata": {"domain": "IoT", "input_source": "form_field", "auth_required": False}, }, { "id": "SCP-000107", "language": "C", "framework": "Embedded", "title": "Stack-based buffer overflow in HTTP header parse", "description": "An embedded web server copies a header value into a fixed stack buffer without bounds.", "owasp": "A03:2021 - Injection", "owasp_api": "", "owasp_llm": "", "cwe": "CWE-120", "mitre_attack": "T1203 - Exploitation for Client Execution", "severity": "Critical", "difficulty": "Advanced", "vulnerable_code": ( "void parse_header(char *line) {\n" " char val[64];\n" " // Vulnerable: strcpy from attacker input\n" " strcpy(val, strchr(line, ':') + 1);\n" "}\n" ), "secure_code": ( "void parse_header(char *line) {\n" " char val[64];\n" " char *v = strchr(line, ':') + 1;\n" " // Secure: bounded copy\n" " strncpy(val, v, sizeof(val) - 1);\n" " val[sizeof(val) - 1] = '\\0';\n" "}\n" ), "patch": ( "--- a/httpd.c\n" "+++ b/httpd.c\n" "@@ -3,4 +3,6 @@\n" "- strcpy(val, strchr(line, ':') + 1);\n" "+ char *v = strchr(line, ':') + 1;\n" "+ strncpy(val, v, sizeof(val) - 1);\n" "+ val[sizeof(val) - 1] = '\\0';\n" ), "root_cause": "strcpy into a fixed buffer allows overflow with a long header value.", "attack": "Send a huge header to overflow the stack and hijack execution.", "impact": "Remote code execution on the device.", "fix": "Use bounded copies (strncpy + NUL) or length-checked parsers.", "guideline": "Avoid strcpy; bound all copies; compile with stack protectors.", "tags": ["iot", "c", "buffer-overflow", "http"], "metadata": {"domain": "IoT", "input_source": "network", "auth_required": False}, }, { "id": "SCP-000108", "language": "C++", "framework": "Embedded", "title": "Unencrypted telemetry transmission", "description": "An IoT device sends sensor telemetry over plain HTTP, exposing it to interception.", "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": ( "void send_telemetry(const std::string& data) {\n" " // Vulnerable: plain HTTP\n" " http_post(\"http://collector/ingest\", data);\n" "}\n" ), "secure_code": ( "void send_telemetry(const std::string& data) {\n" " // Secure: HTTPS with cert pinning\n" " https_post(\"https://collector/ingest\", data, COLLECTOR_PINNED_CERT);\n" "}\n" ), "patch": ( "--- a/telemetry.cpp\n" "+++ b/telemetry.cpp\n" "@@ -2,4 +2,5 @@\n" "- http_post(\"http://collector/ingest\", data);\n" "+ https_post(\"https://collector/ingest\", data, COLLECTOR_PINNED_CERT);\n" ), "root_cause": "Telemetry is transmitted without transport encryption, exposing data in transit.", "attack": "On-path attacker reads sensor data or injects false telemetry.", "impact": "Data interception/modification.", "fix": "Use TLS with certificate pinning for all device communication.", "guideline": "Encrypt all device telemetry with TLS + cert pinning.", "tags": ["iot", "cpp", "tls", "telemetry"], "metadata": {"domain": "IoT", "input_source": "network", "auth_required": False}, }, ]