#!/usr/bin/env python3 """SecureCodePairs v1.2.0 extension records (part 6): Java deep pack (SCP-000231+). Brings Java to a deeper pack, built with json-safe helpers. """ import json from typing import List, Dict L: List[Dict] = [] def rec(**kw): L.append(kw) # 1. SQL injection via concatenated PreparedStatement rec(id="SCP-000231", language="Java", framework="Spring Boot", title="SQL injection via concatenated PreparedStatement", description="A Spring repository builds a PreparedStatement query by 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='String sql = "SELECT * FROM u WHERE name=\'" + name + "\'";\nPreparedStatement ps = c.prepareStatement(sql); // Vulnerable', secure_code='String sql = "SELECT * FROM u WHERE name = ?";\nPreparedStatement ps = c.prepareStatement(sql);\nps.setString(1, name); // Secure', patch='--- a/Repo.java\n+++ b/Repo.java\n@@ -1,3 +1,4 @@\n-String sql = "SELECT * FROM u WHERE name=\'" + name + "\'";\n-PreparedStatement ps = c.prepareStatement(sql);\n+String sql = "SELECT * FROM u WHERE name = ?";\n+PreparedStatement ps = c.prepareStatement(sql);\n+ps.setString(1, name);', root_cause="Query string built by concatenation then prepared.", attack="name=' OR '1'='1 bypasses auth.", impact="Data disclosure.", fix="Use bound parameters only.", guideline="Always bind parameters; never concat into SQL.", tags=["sqli", "spring", "java", "injection"], metadata={"domain": "E-commerce", "input_source": "query_param", "auth_required": False}) # 2. ObjectInputStream deserialization rec(id="SCP-000232", language="Java", framework="Spring Boot", title="Insecure Java deserialization (ObjectInputStream)", description="A Spring endpoint reads a serialized Java object from the request.", 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='ObjectInputStream ois = new ObjectInputStream(req.getInputStream());\nObject o = ois.readObject(); // Vulnerable: gadget chains -> RCE', secure_code='MyDto o = objectMapper.readValue(req.getInputStream(), MyDto.class); // Secure: JSON DTO', patch='--- a/Ctrl.java\n+++ b/Ctrl.java\n@@ -1,3 +1,3 @@\n-ObjectInputStream ois = new ObjectInputStream(req.getInputStream());\n-Object o = ois.readObject();\n+MyDto o = objectMapper.readValue(req.getInputStream(), MyDto.class);', root_cause="Native Java deserialization of untrusted bytes.", attack="Send a gadget-chain payload for RCE.", impact="Remote code execution.", fix="Avoid native deserialization; use JSON DTOs.", guideline="Never deserialize untrusted Java objects.", tags=["deserialization", "spring", "java", "rce"], metadata={"domain": "Microservices", "input_source": "request_body", "auth_required": False}) # 3. XMLDecoder RCE rec(id="SCP-000233", language="Java", framework="Spring Boot", title="XMLDecoder remote code execution", description="A Spring endpoint uses XMLDecoder to parse client XML.", 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='XMLDecoder d = new XMLDecoder(inputStream);\nObject o = d.readObject(); // Vulnerable: executes ', secure_code='JAXBContext ctx = JAXBContext.newInstance(Dto.class);\nDto o = (Dto) ctx.createUnmarshaller().unmarshal(safeSource); // Secure', patch='--- a/Ctrl.java\n+++ b/Ctrl.java\n@@ -1,3 +1,3 @@\n-XMLDecoder d = new XMLDecoder(inputStream);\n-Object o = d.readObject();\n+JAXBContext ctx = JAXBContext.newInstance(Dto.class);\n+Dto o = (Dto) ctx.createUnmarshaller().unmarshal(safeSource);', root_cause="XMLDecoder evaluates method elements as code.", attack="Craft payload for RCE.", impact="Remote code execution.", fix="Replace XMLDecoder with JAXB/JSON DTOs.", guideline="Never use XMLDecoder on untrusted XML.", tags=["deserialization", "spring", "java", "rce"], metadata={"domain": "Backend", "input_source": "request_body", "auth_required": False}) # 4. Path traversal in FileSystem rec(id="SCP-000234", language="Java", framework="Spring Boot", title="Path traversal in file servlet", description="A Spring controller reads a file using a raw request 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='@GetMapping("/file")\npublic Resource file(@RequestParam String p) {\n return new FileSystemResource("/data/" + p); // Vulnerable: traversal\n}', secure_code='@GetMapping("/file")\npublic Resource file(@RequestParam String p) {\n Path base = Paths.get("/data").toRealPath();\n Path full = base.resolve(p).normalize();\n if (!full.startsWith(base)) throw new ResponseStatusException(FORBIDDEN); // Secure\n return new FileSystemResource(full);\n}', patch='--- a/FileCtrl.java\n+++ b/FileCtrl.java\n@@ -1,4 +1,7 @@\n- return new FileSystemResource("/data/" + p);\n+ Path base = Paths.get("/data").toRealPath();\n+ Path full = base.resolve(p).normalize();\n+ if (!full.startsWith(base)) throw new ResponseStatusException(FORBIDDEN);\n+ return new FileSystemResource(full);', root_cause="Unsanitized path joined to base dir.", attack="p=../../etc/passwd reads arbitrary file.", impact="File disclosure.", fix="Resolve and confine to base dir.", guideline="Confine file paths to a base directory.", tags=["path-traversal", "spring", "java", "file-read"], metadata={"domain": "Backend", "input_source": "query_param", "auth_required": False}) # 5. Missing @PreAuthorize on admin rec(id="SCP-000235", language="Java", framework="Spring Boot", title="Missing method-level authorization (IDOR/admin)", description="A Spring admin endpoint lacks @PreAuthorize, allowing any user.", 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='@DeleteMapping("/admin/user/{id}")\npublic void delete(@PathVariable Long id) { // Vulnerable: no role check\n repo.delete(id);\n}', secure_code='@PreAuthorize("hasRole(\'ADMIN\')") // Secure\n@DeleteMapping("/admin/user/{id}")\npublic void delete(@PathVariable Long id) {\n repo.delete(id);\n}', patch='--- a/AdminCtrl.java\n+++ b/AdminCtrl.java\n@@ -1,4 +1,5 @@\n+@PreAuthorize("hasRole(\'ADMIN\')")\n @DeleteMapping("/admin/user/{id}")\n public void delete(@PathVariable Long id) {\n repo.delete(id);\n }', root_cause="No method-level authorization on admin route.", attack="Any authenticated user deletes any account.", impact="Privilege escalation.", fix="Add @PreAuthorize role checks.", guideline="Enforce role checks on sensitive methods.", tags=["authorization", "spring", "java", "broken-access-control"], metadata={"domain": "Authentication systems", "input_source": "path_param", "auth_required": True}) # 6. Hardcoded API key rec(id="SCP-000236", language="Java", framework="Spring Boot", title="Hardcoded API key in source", description="A Spring service hardcodes a third-party 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='private static final String KEY = "sk_live_1a2b3c4d"; // Vulnerable', secure_code='@Value("${PAYMENT_API_KEY}") // Secure: from env/secret\nprivate String key;', patch='--- a/Payment.java\n+++ b/Payment.java\n@@ -1,2 +1,2 @@\n-private static final String KEY = "sk_live_1a2b3c4d";\n+@Value("${PAYMENT_API_KEY}")\n+private String key;', root_cause="Secret in source.", attack="Repo access reveals the key.", impact="Payment fraud.", fix="Use env/secret manager.", guideline="Externalize secrets.", tags=["secrets", "spring", "java", "config"], metadata={"domain": "Banking", "input_source": "source_code", "auth_required": False}) # 7. XSS in Thymeleaf unescaped rec(id="SCP-000237", language="Java", framework="Spring Boot", title="XSS via Thymeleaf th:utext", description="A Thymeleaf template renders user input with th:utext (unescaped).", 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='
', secure_code='
', patch='--- a/post.html\n+++ b/post.html\n@@ -1,2 +1,2 @@\n-
\n+
', root_cause="Unescaped output in template.", attack="comment= runs.", impact="XSS.", fix="Use th:text (escaped).", guideline="Escape all user output in templates.", tags=["xss", "spring", "java", "template"], metadata={"domain": "E-commerce", "input_source": "db", "auth_required": False}) # 8. No rate limit on login rec(id="SCP-000238", language="Java", framework="Spring Boot", title="No rate limit on authentication", description="A Spring login endpoint has no rate limiting, enabling brute force.", 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='@PostMapping("/login")\npublic String login(String u, String p) { // Vulnerable: no throttle\n auth(u, p); return "ok";\n}', secure_code='@PostMapping("/login")\n@RateLimiter(key = "#u", limit = 5, duration = 60) // Secure\npublic String login(String u, String p) {\n auth(u, p); return "ok";\n}', patch='--- a/AuthCtrl.java\n+++ b/AuthCtrl.java\n@@ -1,4 +1,5 @@\n- auth(u, p); return "ok";\n+@RateLimiter(key = "#u", limit = 5, duration = 60)\n+public String login(String u, String p) {\n+ auth(u, p); return "ok";', root_cause="No throttling on auth.", attack="Credential stuffing / brute force.", impact="Account takeover.", fix="Rate limit login attempts.", guideline="Throttle authentication endpoints.", tags=["rate-limiting", "spring", "java", "auth"], metadata={"domain": "Authentication systems", "input_source": "request_body", "auth_required": False}) # 9. Unsafe reflection rec(id="SCP-000239", language="Java", framework="Spring Boot", title="Arbitrary class instantiation via reflection", description="A Spring handler instantiates a class whose name comes from the request.", owasp="A03:2021 - Injection", owasp_api="", owasp_llm="", cwe="CWE-470", mitre_attack="T1190 - Exploit Public-Facing Application", severity="High", difficulty="Advanced", vulnerable_code='String cls = req.getParameter("cls");\nObject o = Class.forName(cls).getDeclaredConstructor().newInstance(); // Vulnerable', secure_code='private static final Set ALLOWED = Set.of("com.app.A", "com.app.B");\nString cls = req.getParameter("cls");\nif (!ALLOWED.contains(cls)) throw new IllegalArgumentException("bad cls"); // Secure\nObject o = Class.forName(cls).getDeclaredConstructor().newInstance();', patch='--- a/Ctrl.java\n+++ b/Ctrl.java\n@@ -1,3 +1,5 @@\n-String cls = req.getParameter("cls");\n-Object o = Class.forName(cls).getDeclaredConstructor().newInstance();\n+private static final Set ALLOWED = Set.of("com.app.A", "com.app.B");\n+if (!ALLOWED.contains(cls)) throw new IllegalArgumentException("bad cls");\n+Object o = Class.forName(cls).getDeclaredConstructor().newInstance();', root_cause="Unrestricted reflection on user input.", attack="cls=java.lang.Runtime loads attacker-chosen class.", impact="Arbitrary code / RCE.", fix="Allowlist reflectable classes.", guideline="Allowlist classes for reflection.", tags=["injection", "spring", "java", "reflection"], metadata={"domain": "Backend", "input_source": "query_param", "auth_required": False}) # 10. CORS wildcard with credentials rec(id="SCP-000240", language="Java", framework="Spring Boot", title="CORS allow-all with credentials", description="A Spring CORS config permits any origin together 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='config.setAllowedOriginPatterns(Arrays.asList("*")); // Vulnerable\nconfig.setAllowCredentials(true);', secure_code='config.setAllowedOrigins(Arrays.asList("https://app.example.com")); // Secure\nconfig.setAllowCredentials(true);', patch='--- a/Cors.java\n+++ b/Cors.java\n@@ -1,3 +1,3 @@\n-config.setAllowedOriginPatterns(Arrays.asList("*"));\n+config.setAllowedOrigins(Arrays.asList("https://app.example.com"));', root_cause="Wildcard origin with credentials.", attack="Malicious site reads responses with victim cookies.", impact="Cross-origin data theft.", fix="Pin origins; never * with credentials.", guideline="Restrict CORS origins.", tags=["cors", "spring", "java", "config"], metadata={"domain": "E-commerce", "input_source": "header", "auth_required": True}) RECORDS_EXT6 = L