| |
| """SecureCodePairs v1.2.0 extension records (part 8): C++/Scala/Go/JS/TS deepen (SCP-000271+). |
| |
| Built with json-safe helpers (rec() with = kwargs). |
| """ |
| import json |
| from typing import List, Dict |
|
|
| L: List[Dict] = [] |
|
|
|
|
| def rec(**kw): |
| L.append(kw) |
|
|
|
|
| |
| rec(id="SCP-000271", language="C++", framework="Qt", |
| title="Command injection via QProcess", |
| description="A Qt app builds a QProcess command from 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='void run(QString f) {\n QProcess p;\n p.start("convert " + f); // Vulnerable: shell\n}', |
| secure_code='void run(QString f) {\n if (f.contains(QRegExp("[^A-Za-z0-9_./-]"))) return; // Secure: validate\n QProcess p;\n p.start("convert", QStringList() << f);\n}', |
| patch='--- a/run.cpp\n+++ b/run.cpp\n@@ -1,4 +1,6 @@\n- p.start("convert " + f);\n+ if (f.contains(QRegExp("[^A-Za-z0-9_./-]"))) return;\n+ QProcess p;\n+ p.start("convert", QStringList() << f);', |
| root_cause="Shell string from user input.", |
| attack="f=img.png;rm -rf / executes.", impact="Command injection.", |
| fix="Validate + arg list.", guideline="Avoid shell in QProcess.", |
| tags=["command-injection", "cpp", "qt", "rce"], |
| metadata={"domain": "IoT", "input_source": "argv", "auth_required": False}) |
|
|
| rec(id="SCP-000272", language="C++", framework="STD", |
| title="Buffer overflow in strcpy", |
| description="A C++ function copies with strcpy into a fixed buffer.", |
| owasp="A03:2021 - Injection", owasp_api="", owasp_llm="", |
| cwe="CWE-120", mitre_attack="T1203 - Exploitation for Client Execution", |
| severity="High", difficulty="Beginner", |
| vulnerable_code='void copy(std::string in) {\n char buf[32];\n strcpy(buf, in.c_str()); // Vulnerable\n}', |
| secure_code='void copy(std::string in) {\n std::vector<char> buf(in.size() + 1); // Secure: sized\n std::copy(in.begin(), in.end(), buf.begin());\n buf[in.size()] = \u002700\u0027;\n}', |
| patch='--- a/copy.cpp\n+++ b/copy.cpp\n@@ -1,4 +1,6 @@\n- char buf[32];\n- strcpy(buf, in.c_str());\n+ std::vector<char> buf(in.size() + 1);\n+ std::copy(in.begin(), in.end(), buf.begin());\n+ buf[in.size()] = \u002700\u0027;', |
| root_cause="Unbounded copy.", |
| attack="Long input overflows stack.", impact="RCE.", |
| fix="Use std::string/vector.", guideline="Prefer std::string.", |
| tags=["buffer-overflow", "cpp", "memory-safety"], |
| metadata={"domain": "IoT", "input_source": "argv", "auth_required": False}) |
|
|
| rec(id="SCP-000273", language="C++", framework="STD", |
| title="Format string in cout-free logging", |
| description="A C++ logger uses user input as a printf format.", |
| owasp="A03:2021 - Injection", owasp_api="", owasp_llm="", |
| cwe="CWE-134", mitre_attack="T1203 - Exploitation for Client Execution", |
| severity="Medium", difficulty="Intermediate", |
| vulnerable_code='void log(const char* m) {\n printf(m); // Vulnerable\n}', |
| secure_code='void log(const char* m) {\n printf("%s", m); // Secure\n}', |
| patch='--- a/log.cpp\n+++ b/log.cpp\n@@ -1,3 +1,3 @@\n- printf(m);\n+ printf("%s", m);', |
| root_cause="User input as format.", |
| attack="%x reads stack.", impact="Info leak.", |
| fix="Use %s positional.", guideline="Never format-user.", |
| tags=["format-string", "cpp", "logging"], |
| metadata={"domain": "IoT", "input_source": "argv", "auth_required": False}) |
|
|
| rec(id="SCP-000274", language="C++", framework="STD", |
| title="Use-after-free with raw pointer", |
| description="A C++ class returns a raw pointer to internal buffer after free.", |
| owasp="A03:2021 - Injection", owasp_api="", owasp_llm="", |
| cwe="CWE-416", mitre_attack="T1203 - Exploitation for Client Execution", |
| severity="High", difficulty="Advanced", |
| vulnerable_code='int* leak() {\n int* p = new int(1);\n delete p;\n return p; // Vulnerable: dangling\n}', |
| secure_code='std::unique_ptr<int> leak() {\n return std::make_unique<int>(1); // Secure: ownership\n}', |
| patch='--- a/leak.cpp\n+++ b/leak.cpp\n@@ -1,5 +1,3 @@\n-int* leak() {\n int* p = new int(1);\n delete p;\n return p;\n+std::unique_ptr<int> leak() {\n+ return std::make_unique<int>(1);', |
| root_cause="Returning freed pointer.", |
| attack="Heap confusion / RCE.", impact="Memory corruption.", |
| fix="Use smart pointers.", guideline="Prefer unique_ptr/shared_ptr.", |
| tags=["use-after-free", "cpp", "memory-safety"], |
| metadata={"domain": "IoT", "input_source": "internal", "auth_required": False}) |
|
|
| rec(id="SCP-000275", language="C++", framework="STD", |
| title="Integer overflow in size calculation", |
| description="A C++ allocation multiplies counts without overflow check.", |
| owasp="A03:2021 - Injection", owasp_api="", owasp_llm="", |
| cwe="CWE-190", mitre_attack="T1203 - Exploitation for Client Execution", |
| severity="High", difficulty="Advanced", |
| vulnerable_code='void* make(size_t n, size_t s) {\n return malloc(n * s); // Vulnerable: overflow\n}', |
| secure_code='void* make(size_t n, size_t s) {\n if (n != 0 && s > SIZE_MAX / n) return nullptr; // Secure\n return malloc(n * s);\n}', |
| patch='--- a/make.cpp\n+++ b/make.cpp\n@@ -1,3 +1,4 @@\n- return malloc(n * s);\n+ if (n != 0 && s > SIZE_MAX / n) return nullptr;\n+ return malloc(n * s);', |
| root_cause="Unchecked multiplication.", |
| attack="Small alloc then overflow.", impact="Memory corruption.", |
| fix="Check overflow.", guideline="Validate sizes.", |
| tags=["integer-overflow", "cpp", "memory-safety"], |
| metadata={"domain": "IoT", "input_source": "argv", "auth_required": False}) |
|
|
| rec(id="SCP-000276", language="C++", framework="STD", |
| title="SQL injection with string concat", |
| description="A C++ DB client concatenates user input into a query.", |
| owasp="A03:2021 - Injection", owasp_api="", owasp_llm="", |
| cwe="CWE-89", mitre_attack="T1190 - Exploit Public-Facing Application", |
| severity="High", difficulty="Intermediate", |
| vulnerable_code='std::string q = "SELECT * FROM u WHERE name=\u0027" + name + "\u0027";\ndb.query(q); // Vulnerable', |
| secure_code='std::string q = "SELECT * FROM u WHERE name = ?";\nstmt.bind(1, name); // Secure: prepared\nstmt.execute();', |
| patch='--- a/db.cpp\n+++ b/db.cpp\n@@ -1,3 +1,4 @@\n-std::string q = "SELECT * FROM u WHERE name=\u0027" + name + "\u0027";\n-db.query(q);\n+std::string q = "SELECT * FROM u WHERE name = ?";\n+stmt.bind(1, name);\n+stmt.execute();', |
| root_cause="String concat into SQL.", |
| attack="name=\u0027 OR 1=1 leaks rows.", impact="Data disclosure.", |
| fix="Use prepared statements.", guideline="Bind all SQL params.", |
| tags=["sqli", "cpp", "injection"], |
| metadata={"domain": "E-commerce", "input_source": "query_param", "auth_required": False}) |
|
|
| rec(id="SCP-000277", language="C++", framework="Qt", |
| title="Path traversal in file open", |
| description="A Qt app opens a file from a user-supplied relative 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='void open(QString p) {\n QFile f("/data/" + p); // Vulnerable: traversal\n f.open(QIODevice::ReadOnly);\n}', |
| secure_code='void open(QString p) {\n QFileInfo info(p);\n if (info.isAbsolute() || p.contains("..")) return; // Secure\n QFile f("/data/" + p);\n f.open(QIODevice::ReadOnly);\n}', |
| patch='--- a/open.cpp\n+++ b/open.cpp\n@@ -1,4 +1,6 @@\n- QFile f("/data/" + p);\n- f.open(QIODevice::ReadOnly);\n+ QFileInfo info(p);\n+ if (info.isAbsolute() || p.contains("..")) return;\n+ QFile f("/data/" + p);\n+ f.open(QIODevice::ReadOnly);', |
| root_cause="Unsanitized path.", |
| attack="p=../../etc/passwd reads file.", impact="File disclosure.", |
| fix="Reject absolute/.. paths.", guideline="Confine file paths.", |
| tags=["path-traversal", "cpp", "qt", "file-read"], |
| metadata={"domain": "Backend", "input_source": "query_param", "auth_required": False}) |
|
|
| rec(id="SCP-000278", language="C++", framework="STD", |
| title="Hardcoded API key in source", |
| description="A C++ client embeds a secret string.", |
| 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* KEY = "sk_live_9f8e7d6c"; // Vulnerable', |
| secure_code='std::string get_key() {\n const char* e = std::getenv("API_KEY"); // Secure: env\n return e ? e : "";\n}', |
| patch='--- a/client.cpp\n+++ b/client.cpp\n@@ -1,2 +1,4 @@\n-const char* KEY = "sk_live_9f8e7d6c";\n+std::string get_key() {\n+ const char* e = std::getenv("API_KEY");\n+ return e ? e : "";\n+}', |
| root_cause="Secret in binary.", |
| attack="Extract from binary.", impact="Key compromise.", |
| fix="Load from env/secret.", guideline="Externalize secrets.", |
| tags=["secrets", "cpp", "config"], |
| metadata={"domain": "Banking", "input_source": "source_code", "auth_required": False}) |
|
|
| rec(id="SCP-000279", language="C++", framework="STD", |
| title="Weak random for session token", |
| description="A C++ service uses rand() 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='std::string tok() {\n return std::to_string(rand()); // Vulnerable: weak\n}', |
| secure_code='#include <random>\nstd::string tok() {\n std::random_device rd; // Secure: CSPRNG\n std::mt19937 gen(rd());\n return std::to_string(gen());\n}', |
| patch='--- a/tok.cpp\n+++ b/tok.cpp\n@@ -1,3 +1,5 @@\n-std::string tok() {\n return std::to_string(rand());\n+#include <random>\n+std::string tok() {\n+ std::random_device rd;\n+ std::mt19937 gen(rd());', |
| root_cause="Non-CSPRNG token.", |
| attack="Predict token.", impact="Session hijack.", |
| fix="Use random_device.", guideline="Use CSPRNG for tokens.", |
| tags=["crypto", "cpp", "tokens"], |
| metadata={"domain": "Authentication systems", "input_source": "server", "auth_required": False}) |
|
|
| rec(id="SCP-000280", language="C++", framework="STD", |
| title="Uninitialized variable use", |
| description="A C++ function uses a variable before initialization.", |
| owasp="A03:2021 - Injection", owasp_api="", owasp_llm="", |
| cwe="CWE-457", mitre_attack="T1203 - Exploitation for Client Execution", |
| severity="Medium", difficulty="Beginner", |
| vulnerable_code='int compute(int x) {\n int r; // Vulnerable: uninitialized\n if (x > 0) r = x * 2;\n return r; // may be garbage\n}', |
| secure_code='int compute(int x) {\n int r = 0; // Secure: initialize\n if (x > 0) r = x * 2;\n return r;\n}', |
| patch='--- a/compute.cpp\n+++ b/compute.cpp\n@@ -1,4 +1,4 @@\n-int r; // Vulnerable: uninitialized\n+int r = 0; // Secure: initialize\n if (x > 0) r = x * 2;', |
| root_cause="Use before init.", |
| attack="Read uninitialized stack data.", impact="Info leak / bug.", |
| fix="Initialize variables.", guideline="Always initialize.", |
| tags=["uninitialized", "cpp", "memory-safety"], |
| metadata={"domain": "IoT", "input_source": "internal", "auth_required": False}) |
|
|
| rec(id="SCP-000281", language="C++", framework="STD", |
| title="Double free via raw pointer", |
| description="A C++ function frees a raw pointer twice.", |
| owasp="A03:2021 - Injection", owasp_api="", owasp_llm="", |
| cwe="CWE-415", mitre_attack="T1203 - Exploitation for Client Execution", |
| severity="High", difficulty="Advanced", |
| vulnerable_code='void run() {\n int* p = new int(1);\n delete p; delete p; // Vulnerable: double free\n}', |
| secure_code='void run() {\n auto p = std::make_unique<int>(1); // Secure: RAII\n} // freed once', |
| patch='--- a/run.cpp\n+++ b/run.cpp\n@@ -1,4 +1,2 @@\n- int* p = new int(1);\n- delete p; delete p;\n+ auto p = std::make_unique<int>(1);', |
| root_cause="Freeing same pointer twice.", |
| attack="Heap corruption.", impact="Memory corruption.", |
| fix="Use smart pointers.", guideline="Avoid manual delete.", |
| tags=["double-free", "cpp", "memory-safety"], |
| metadata={"domain": "IoT", "input_source": "internal", "auth_required": False}) |
|
|
| rec(id="SCP-000282", language="C++", framework="STD", |
| title="Insecure temp file (tmpnam)", |
| description="A C++ program creates a temp file with a predictable name.", |
| owasp="A01:2021 - Broken Access Control", owasp_api="", owasp_llm="", |
| cwe="CWE-377", mitre_attack="T1190 - Exploit Public-Facing Application", |
| severity="Medium", difficulty="Intermediate", |
| vulnerable_code='void save(std::string d) {\n char* name = std::tmpnam(nullptr); // Vulnerable: predictable\n std::ofstream f(name); f << d;\n}', |
| secure_code='#include <filesystem>\nvoid save(std::string d) {\n auto p = std::filesystem::temp_directory_path() / "appXXXXXX"; // Secure\n std::ofstream f(p); f << d;\n}', |
| patch='--- a/save.cpp\n+++ b/save.cpp\n@@ -1,4 +1,5 @@\n- char* name = std::tmpnam(nullptr);\n- std::ofstream f(name); f << d;\n+#include <filesystem>\n+ auto p = std::filesystem::temp_directory_path() / "appXXXXXX";\n+ std::ofstream f(p); f << d;', |
| root_cause="Predictable temp name.", |
| attack="Pre-create / symlink.", impact="File tampering.", |
| fix="Use unique temp paths.", guideline="Avoid tmpnam.", |
| tags=["temp-file", "cpp", "file-write"], |
| metadata={"domain": "IoT", "input_source": "internal", "auth_required": False}) |
|
|
| rec(id="SCP-000283", language="C++", framework="STD", |
| title="Race condition on shared counter", |
| description="A C++ counter increments without atomic/lock.", |
| owasp="A01:2021 - Broken Access Control", owasp_api="", owasp_llm="", |
| cwe="CWE-362", mitre_attack="T1203 - Exploitation for Client Execution", |
| severity="Medium", difficulty="Intermediate", |
| vulnerable_code='int counter = 0;\nvoid inc() { counter++; } // Vulnerable: data race', |
| secure_code='#include <atomic>\nstd::atomic<int> counter{0};\nvoid inc() { counter++; } // Secure: atomic', |
| patch='--- a/cnt.cpp\n+++ b/cnt.cpp\n@@ -1,3 +1,3 @@\n-int counter = 0;\n-void inc() { counter++; }\n+#include <atomic>\n+std::atomic<int> counter{0};\n+void inc() { counter++; }', |
| root_cause="Non-atomic shared mutation.", |
| attack="Lost updates / logic error.", impact="Inconsistent state.", |
| fix="Use atomics/locks.", guideline="Protect shared state.", |
| tags=["race-condition", "cpp", "concurrency"], |
| metadata={"domain": "Backend", "input_source": "internal", "auth_required": False}) |
|
|
| rec(id="SCP-000284", language="C++", framework="STD", |
| title="Null pointer dereference", |
| description="A C++ function dereferences a pointer that may be null.", |
| owasp="A03:2021 - Injection", owasp_api="", owasp_llm="", |
| cwe="CWE-476", mitre_attack="T1203 - Exploitation for Client Execution", |
| severity="Medium", difficulty="Beginner", |
| vulnerable_code='void show(User* u) {\n std::cout << u->name; // Vulnerable: u may be null\n}', |
| secure_code='void show(User* u) {\n if (!u) return; // Secure: null check\n std::cout << u->name;\n}', |
| patch='--- a/show.cpp\n+++ b/show.cpp\n@@ -1,3 +1,4 @@\n- std::cout << u->name;\n+ if (!u) return;\n+ std::cout << u->name;', |
| root_cause="Missing null check.", |
| attack="Pass null to crash.", impact="DoS.", |
| fix="Check before deref.", guideline="Null-check inputs.", |
| tags=["null-deref", "cpp", "memory-safety"], |
| metadata={"domain": "IoT", "input_source": "argv", "auth_required": False}) |
|
|
| rec(id="SCP-000285", language="C++", framework="STD", |
| title="Improper TLS certificate verification", |
| description="A C++ TLS client disables peer 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='ctx->set_verify_mode(boost::asio::ssl::verify_none); // Vulnerable', |
| secure_code='ctx->set_verify_mode(boost::asio::ssl::verify_peer); // Secure\nctx->set_default_verify_paths();', |
| patch='--- a/tls.cpp\n+++ b/tls.cpp\n@@ -1,2 +1,3 @@\n-ctx->set_verify_mode(boost::asio::ssl::verify_none);\n+ctx->set_verify_mode(boost::asio::ssl::verify_peer);\n+ctx->set_default_verify_paths();', |
| root_cause="Verification disabled.", |
| attack="MITM intercepts TLS.", impact="Credential/data theft.", |
| fix="Enable peer verify.", guideline="Always verify TLS.", |
| tags=["tls", "cpp", "mitm"], |
| metadata={"domain": "Banking", "input_source": "network", "auth_required": False}) |
|
|
| rec(id="SCP-000286", language="C++", framework="Qt", |
| title="XSS via QLabel rich text", |
| description="A Qt QLabel renders user text as rich text (HTML).", |
| 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='label->setTextFormat(Qt::RichText);\nlabel->setText(userInput); // Vulnerable: HTML', |
| secure_code='label->setTextFormat(Qt::PlainText); // Secure: no HTML\nlabel->setText(userInput);', |
| patch='--- a/ui.cpp\n+++ b/ui.cpp\n@@ -1,3 +1,3 @@\n-label->setTextFormat(Qt::RichText);\n-label->setText(userInput);\n+label->setTextFormat(Qt::PlainText);\n+label->setText(userInput);', |
| root_cause="Rich text renders HTML.", |
| attack="<script> runs in WebEngine.", impact="XSS.", |
| fix="Use PlainText.", guideline="Avoid RichText for user input.", |
| tags=["xss", "cpp", "qt", "template"], |
| metadata={"domain": "E-commerce", "input_source": "db", "auth_required": False}) |
|
|
| rec(id="SCP-000287", language="C++", framework="STD", |
| title="Out-of-bounds read in loop", |
| description="A C++ loop reads past a container boundary.", |
| owasp="A03:2021 - Injection", owasp_api="", owasp_llm="", |
| cwe="CWE-125", mitre_attack="T1203 - Exploitation for Client Execution", |
| severity="Medium", difficulty="Intermediate", |
| vulnerable_code='for (size_t i = 0; i <= v.size(); i++) { // Vulnerable: <= off-by-one\n use(v[i]);\n}', |
| secure_code='for (size_t i = 0; i < v.size(); i++) { // Secure: < not <=\n use(v[i]);\n}', |
| patch='--- a/loop.cpp\n+++ b/loop.cpp\n@@ -1,3 +1,3 @@\n-for (size_t i = 0; i <= v.size(); i++) {\n+for (size_t i = 0; i < v.size(); i++) {\n use(v[i]);', |
| root_cause="Off-by-one bound.", |
| attack="Read past buffer.", impact="Info leak.", |
| fix="Correct bounds.", guideline="Audit loop bounds.", |
| tags=["out-of-bounds", "cpp", "memory-safety"], |
| metadata={"domain": "IoT", "input_source": "internal", "auth_required": False}) |
|
|
| rec(id="SCP-000288", language="C++", framework="STD", |
| title="LDAP injection in filter", |
| description="A C++ LDAP client builds a filter 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='std::string f = "(uid=" + user + ")"; // Vulnerable: inject\nldap_search(f);', |
| secure_code='std::string f = "(uid=" + escape_ldap(user) + ")"; // Secure: escape\nldap_search(f);', |
| patch='--- a/ldap.cpp\n+++ b/ldap.cpp\n@@ -1,3 +1,3 @@\n-std::string f = "(uid=" + user + ")";\n-std_ldap_search(f);\n+std::string f = "(uid=" + escape_ldap(user) + ")";\n+ldap_search(f);', |
| root_cause="Unescaped LDAP filter.", |
| attack="user=*)(|(uid=* bypasses.", impact="Auth bypass / disclosure.", |
| fix="Escape LDAP specials.", guideline="Sanitize LDAP input.", |
| tags=["ldap-injection", "cpp", "injection"], |
| metadata={"domain": "Authentication systems", "input_source": "query_param", "auth_required": False}) |
|
|
| rec(id="SCP-000289", language="C++", framework="STD", |
| title="Business logic: negative price order", |
| description="A C++ checkout accepts a negative price 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='void add(Order& o, double price) {\n o.total += price; // Vulnerable: negative allowed\n}', |
| secure_code='void add(Order& o, double price) {\n if (price <= 0 || price > 1e6) throw std::invalid_argument("bad"); // Secure\n o.total += price;\n}', |
| patch='--- a/order.cpp\n+++ b/order.cpp\n@@ -1,3 +1,4 @@\n- o.total += price;\n+ if (price <= 0 || price > 1e6) throw std::invalid_argument("bad");\n+ o.total += price;', |
| root_cause="Client price not validated.", |
| attack="price=-100 => negative total.", impact="Revenue loss.", |
| fix="Validate server-side.", guideline="Validate business values.", |
| tags=["business-logic", "cpp", "ecommerce"], |
| metadata={"domain": "E-commerce", "input_source": "request_body", "auth_required": True}) |
|
|
| rec(id="SCP-000290", language="C++", framework="STD", |
| title="Insecure deserialization (boost)", |
| description="A C++ app deserializes untrusted bytes with boost::serialization.", |
| 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='std::istringstream iss(data);\nboost::archive::text_iarchive ia(iss);\nia >> obj; // Vulnerable: untrusted bytes', |
| secure_code='// Use a schema-validated JSON/Protobuf with strict parsing\nauto obj = parse_json_strict(data); // Secure', |
| patch='--- a/load.cpp\n+++ b/load.cpp\n@@ -1,4 +1,3 @@\n-std::istringstream iss(data);\n-boost::archive::text_iarchive ia(iss);\n-ia >> obj;\n+auto obj = parse_json_strict(data);', |
| root_cause="Native deserialization of untrusted data.", |
| attack="Craft malicious archive for RCE.", impact="Remote code execution.", |
| fix="Use safe serialization.", guideline="Validate deserialized data.", |
| tags=["deserialization", "cpp", "rce"], |
| metadata={"domain": "Microservices", "input_source": "request_body", "auth_required": False}) |
|
|
| |
| rec(id="SCP-000291", language="Scala", framework="Play", |
| title="SQL injection via string interp", |
| description="A Play/Slick query interpolates user input.", |
| owasp="A03:2021 - Injection", owasp_api="", owasp_llm="", |
| cwe="CWE-89", mitre_attack="T1190 - Exploit Public-Facing Application", |
| severity="High", difficulty="Intermediate", |
| vulnerable_code='def search(q: String) = sql"SELECT * FROM u WHERE name = ${q}".as[User] // Vulnerable: raw interp', |
| secure_code='def search(q: String) = sql"SELECT * FROM u WHERE name = $q".as[User] // Secure: bound param', |
| patch='--- a/UserRepo.scala\n+++ b/UserRepo.scala\n@@ -1,2 +1,2 @@\n-def search(q: String) = sql"SELECT * FROM u WHERE name = ${q}".as[User]\n+def search(q: String) = sql"SELECT * FROM u WHERE name = $q".as[User]', |
| root_cause="Raw string interpolation into SQL.", |
| attack="q=' OR 1=1 dumps table.", impact="Data disclosure.", |
| fix="Use bound parameters.", guideline="Bind all SQL params.", |
| tags=["sqli", "scala", "play", "injection"], |
| metadata={"domain": "E-commerce", "input_source": "query_param", "auth_required": False}) |
|
|
| rec(id="SCP-000292", language="Scala", framework="Play", |
| title="XSS in Twirl template", |
| description="A Play Twirl template renders user input 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='<div>@Html(comment)</div> <!-- Vulnerable: unescaped -->', |
| secure_code='<div>@comment</div> <!-- Secure: escaped -->', |
| patch='--- a/show.scala.html\n+++ b/show.scala.html\n@@ -1,2 +1,2 @@\n-<div>@Html(comment)</div>\n+<div>@comment</div>', |
| root_cause="Html() disables escaping.", |
| attack="comment=<script>steal()</script> runs.", impact="XSS.", |
| fix="Use default escaping.", guideline="Avoid @Html on user input.", |
| tags=["xss", "scala", "play", "template"], |
| metadata={"domain": "E-commerce", "input_source": "db", "auth_required": False}) |
|
|
| rec(id="SCP-000293", language="Scala", framework="Akka HTTP", |
| title="Path traversal in static route", |
| description="An Akka HTTP route serves files 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='path("files" / Segment) { name =>\n getFromFile("/data/" + name) // Vulnerable: traversal\n}', |
| secure_code='path("files" / Segment) { name =>\n val safe = Paths.get("/data").resolve(name).normalize()\n if (!safe.startsWith(Paths.get("/data"))) reject else getFromFile(safe.toFile) // Secure\n}', |
| patch='--- a/StaticRoutes.scala\n+++ b/StaticRoutes.scala\n@@ -1,3 +1,5 @@\n- getFromFile("/data/" + name)\n+ val safe = Paths.get("/data").resolve(name).normalize()\n+ if (!safe.startsWith(Paths.get("/data"))) reject\n+ else getFromFile(safe.toFile)', |
| 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", "scala", "akka", "file-read"], |
| metadata={"domain": "Backend", "input_source": "path_param", "auth_required": False}) |
|
|
| rec(id="SCP-000294", language="Scala", framework="Play", |
| title="Missing authorization on admin action", |
| description="A Play admin action has no role 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='def deleteUser = Action { req =>\n repo.delete(req.queryString("id").get) // Vulnerable: no role\n}', |
| secure_code='def deleteUser = Action { implicit req =>\n if (!req.session.get("role").contains("admin")) Forbidden else repo.delete(...) // Secure\n}', |
| patch='--- a/Admin.scala\n+++ b/Admin.scala\n@@ -1,3 +1,4 @@\n-def deleteUser = Action { req =>\n repo.delete(req.queryString("id").get)\n+ if (!req.session.get("role").contains("admin")) Forbidden\n+ else repo.delete(...)', |
| root_cause="No role check.", |
| attack="Any user deletes accounts.", impact="Privilege escalation.", |
| fix="Enforce role.", guideline="Authorize admin actions.", |
| tags=["authorization", "scala", "play", "broken-access-control"], |
| metadata={"domain": "Authentication systems", "input_source": "query_param", "auth_required": True}) |
|
|
| rec(id="SCP-000295", language="Scala", framework="Play", |
| title="Command injection via Process", |
| description="A Play 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='import sys.process._\ndef run(host: String) = s"ping -c1 $host".! // Vulnerable: shell', |
| secure_code='def run(host: String) = {\n require(host.matches("[\\w.-]+")) // Secure: validate\n Seq("ping", "-c1", host).! // arg array\n}', |
| patch='--- a/Ping.scala\n+++ b/Ping.scala\n@@ -1,3 +1,4 @@\n-def run(host: String) = s"ping -c1 $host".!\n+ require(host.matches("[\\w.-]+"))\n+ Seq("ping", "-c1", host).!', |
| root_cause="Shell interpolation.", |
| attack="host=;rm -rf / executes.", impact="Command injection.", |
| fix="Validate + Seq arg array.", guideline="Avoid shell interpolation.", |
| tags=["command-injection", "scala", "play", "rce"], |
| metadata={"domain": "IoT", "input_source": "query_param", "auth_required": False}) |
|
|
| rec(id="SCP-000296", language="Scala", framework="Play", |
| title="Open redirect", |
| description="A Play action 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='def go = Action { req =>\n Redirect(req.getQueryString("url").getOrElse("/")) // Vulnerable\n}', |
| secure_code='def go = Action { req =>\n val u = req.getQueryString("url").filter(_.startsWith("/"))\n Redirect(u.getOrElse("/")) // Secure\n}', |
| patch='--- a/Links.scala\n+++ b/Links.scala\n@@ -1,3 +1,4 @@\n-def go = Action { req =>\n Redirect(req.getQueryString("url").getOrElse("/"))\n+ val u = req.getQueryString("url").filter(_.startsWith("/"))\n+ Redirect(u.getOrElse("/"))', |
| root_cause="Unvalidated redirect.", |
| attack="url=//evil.com phishing.", impact="Phishing.", |
| fix="Allowlist relative.", guideline="Validate redirects.", |
| tags=["open-redirect", "scala", "play", "phishing"], |
| metadata={"domain": "Authentication systems", "input_source": "query_param", "auth_required": False}) |
|
|
| rec(id="SCP-000297", language="Scala", framework="Play", |
| title="Insecure JWT verification (none alg)", |
| description="A Play JWT verifier accepts the none 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='def verify(t: String) = JwtJson4s("secret").decodeJson(t) // Vulnerable if none allowed', |
| secure_code='def verify(t: String) = JwtJson4s("secret", JwtAlgorithm.HS256).decodeJson(t) // Secure: pin alg', |
| patch='--- a/Auth.scala\n+++ b/Auth.scala\n@@ -1,2 +1,2 @@\n-def verify(t: String) = JwtJson4s("secret").decodeJson(t)\n+def verify(t: String) = JwtJson4s("secret", JwtAlgorithm.HS256).decodeJson(t)', |
| root_cause="No algorithm pinning.", |
| attack="Forge alg=none token.", impact="Auth bypass.", |
| fix="Pin algorithm.", guideline="Forbid none algorithm.", |
| tags=["jwt", "scala", "play", "auth"], |
| metadata={"domain": "Authentication systems", "input_source": "header", "auth_required": True}) |
|
|
| rec(id="SCP-000298", language="Scala", framework="Akka HTTP", |
| title="No rate limit on login", |
| description="An Akka HTTP 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='path("login") { post { entity(as[Login]) { l => complete(auth(l)) } } } // Vulnerable: no throttle', |
| secure_code='path("login") { post { throttle(5, 1.minute) { // Secure\n entity(as[Login]) { l => complete(auth(l)) } } } }', |
| patch='--- a/LoginRoute.scala\n+++ b/LoginRoute.scala\n@@ -1,3 +1,4 @@\n-path("login") { post { entity(as[Login]) { l => complete(auth(l)) } } }\n+path("login") { post { throttle(5, 1.minute) {\n+ entity(as[Login]) { l => complete(auth(l)) } } } }', |
| root_cause="No throttle on auth.", |
| attack="Brute force credentials.", impact="Account takeover.", |
| fix="Throttle login.", guideline="Rate limit auth.", |
| tags=["rate-limiting", "scala", "akka", "auth"], |
| metadata={"domain": "Authentication systems", "input_source": "request_body", "auth_required": False}) |
|
|
| rec(id="SCP-000299", language="Scala", framework="Play", |
| title="Hardcoded secret in conf", |
| description="A Play application.conf contains a static secret.", |
| 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='play.http.secret.key = "changeme123456" # Vulnerable', |
| secure_code='play.http.secret.key = ${?SECRET_KEY} # Secure: from env', |
| patch='--- a/conf/application.conf\n+++ b/conf/application.conf\n@@ -1,2 +1,2 @@\n-play.http.secret.key = "changeme123456"\n+play.http.secret.key = ${?SECRET_KEY}', |
| root_cause="Static secret in config.", |
| attack="Forge signed sessions.", impact="Auth bypass.", |
| fix="Load from env.", guideline="Externalize secrets.", |
| tags=["secrets", "scala", "play", "config"], |
| metadata={"domain": "Backend", "input_source": "source_code", "auth_required": False}) |
|
|
| rec(id="SCP-000300", language="Scala", framework="Play", |
| title="IDOR on resource read", |
| description="A Play action returns a resource by id without 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="High", difficulty="Beginner", |
| vulnerable_code='def show(id: Long) = Action { repo.find(id).map(Ok(_)).getOrElse(NotFound) } // Vulnerable: no owner', |
| secure_code='def show(id: Long) = Action { req =>\n repo.findOwned(id, req.user.id).map(Ok(_)).getOrElse(NotFound) // Secure\n}', |
| patch='--- a/Resource.scala\n+++ b/Resource.scala\n@@ -1,2 +1,3 @@\n-def show(id: Long) = Action { repo.find(id).map(Ok(_)).getOrElse(NotFound) }\n+def show(id: Long) = Action { req =>\n+ repo.findOwned(id, req.user.id).map(Ok(_)).getOrElse(NotFound) }', |
| root_cause="No ownership scoping.", |
| attack="Enumerate others resources.", impact="PII disclosure.", |
| fix="Scope by owner.", guideline="Authorize reads by owner.", |
| tags=["idor", "scala", "play", "access-control"], |
| metadata={"domain": "E-commerce", "input_source": "path_param", "auth_required": True}) |
|
|
| rec(id="SCP-000301", language="Scala", framework="Play", |
| title="XML external entity in XML parsing", |
| description="A Play controller parses XML with a vulnerable parser.", |
| 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='val xml = scala.xml.XML.loadString(body) // Vulnerable: XXE in some setups', |
| secure_code='import scala.xml.factory.XMLLoader\nval loader = new XMLLoader { override def adapter = new scala.xml.parsing.NoBindingFactoryAdapter { override def resolveEntity(...) = null } }\nval xml = loader.loadString(body) // Secure: disable external', |
| patch='--- a/XmlCtrl.scala\n+++ b/XmlCtrl.scala\n@@ -1,2 +1,4 @@\n-val xml = scala.xml.XML.loadString(body)\n+val loader = new XMLLoader { override def adapter = new NoBindingFactoryAdapter { override def resolveEntity(...) = null } }\n+val xml = loader.loadString(body)', |
| root_cause="Parser may resolve external entities.", |
| attack="DOCTYPE reads local files / SSRF.", impact="File disclosure.", |
| fix="Disable external entities.", guideline="Harden XML parsing.", |
| tags=["xxe", "scala", "play", "xml"], |
| metadata={"domain": "REST API", "input_source": "request_body", "auth_required": False}) |
|
|
| rec(id="SCP-000302", language="Scala", framework="Akka HTTP", |
| title="CORS allow-all with credentials", |
| description="An Akka HTTP 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='corsSettings = CorsSettings.defaultSettings.withAllowOrigin(_ => true).withAllowCredentials(true) // Vulnerable', |
| secure_code='corsSettings = CorsSettings.defaultSettings.withAllowedOrigins("https://app.example.com").withAllowCredentials(true) // Secure', |
| patch='--- a/Cors.scala\n+++ b/Cors.scala\n@@ -1,2 +1,2 @@\n-corsSettings = CorsSettings.defaultSettings.withAllowOrigin(_ => true).withAllowCredentials(true)\n+corsSettings = CorsSettings.defaultSettings.withAllowedOrigins("https://app.example.com").withAllowCredentials(true)', |
| root_cause="Wildcard origin + credentials.", |
| attack="Malicious site reads responses with cookies.", impact="Cross-origin theft.", |
| fix="Pin origins.", guideline="Restrict CORS.", |
| tags=["cors", "scala", "akka", "config"], |
| metadata={"domain": "E-commerce", "input_source": "header", "auth_required": True}) |
|
|
| rec(id="SCP-000303", language="Scala", framework="Play", |
| title="Mass assignment via case class binding", |
| description="A Play form binds all fields 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='def update = Action { implicit req =>\n userForm.bindFromRequest.fold(_ => BadRequest, u => repo.update(u)) // Vulnerable: role bound\n}', |
| secure_code='def update = Action { implicit req =>\n val f = userForm.bindFromRequest.filterNot(_._1 == "role")\n f.fold(_ => BadRequest, u => repo.update(u.copy(role = currentUser.role))) // Secure\n}', |
| patch='--- a/UserCtrl.scala\n+++ b/UserCtrl.scala\n@@ -1,3 +1,4 @@\n-def update = Action { implicit req =>\n userForm.bindFromRequest.fold(_ => BadRequest, u => repo.update(u))\n+ val f = userForm.bindFromRequest.filterNot(_._1 == "role")\n+ f.fold(_ => BadRequest, u => repo.update(u.copy(role = currentUser.role)))', |
| root_cause="All fields bound from request.", |
| attack="POST role=admin escalates.", impact="Privilege escalation.", |
| fix="Whitelist fields.", guideline="Use form whitelists.", |
| tags=["mass-assignment", "scala", "play", "auth"], |
| metadata={"domain": "E-commerce", "input_source": "request_body", "auth_required": True}) |
|
|
| rec(id="SCP-000304", language="Scala", framework="Play", |
| title="Weak password hashing (MD5)", |
| description="A Play auth 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='def hashPw(pw: String) = MessageDigest.getInstance("MD5").digest(pw.getBytes) // Vulnerable', |
| secure_code='import java.security.SecureRandom\nimport org.mindrot.jbcrypt.BCrypt\ndef hashPw(pw: String) = BCrypt.hashpw(pw, BCrypt.gensalt(12)) // Secure', |
| patch='--- a/Auth.scala\n+++ b/Auth.scala\n@@ -1,2 +1,3 @@\n-def hashPw(pw: String) = MessageDigest.getInstance("MD5").digest(pw.getBytes)\n+import org.mindrot.jbcrypt.BCrypt\n+def hashPw(pw: String) = BCrypt.hashpw(pw, BCrypt.gensalt(12))', |
| root_cause="MD5 unsalted/fast.", |
| attack="Crack passwords.", impact="Credential compromise.", |
| fix="Use bcrypt/argon2.", guideline="Slow salted KDFs.", |
| tags=["crypto", "scala", "play", "passwords"], |
| metadata={"domain": "Authentication systems", "input_source": "request_body", "auth_required": False}) |
|
|
| rec(id="SCP-000305", language="Scala", framework="Akka HTTP", |
| title="Insecure random for token", |
| description="A Scala service uses scala.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='def token = Random.alphanumeric.take(16).mkString // Vulnerable: predictable', |
| secure_code='import java.security.SecureRandom\ndef token = { val r = new SecureRandom(); (1 to 24).map(_ => r.nextInt(36)).map(...).mkString } // Secure: CSPRNG', |
| patch='--- a/Token.scala\n+++ b/Token.scala\n@@ -1,2 +1,3 @@\n-def token = Random.alphanumeric.take(16).mkString\n+import java.security.SecureRandom\n+def token = { val r = new SecureRandom(); ... }', |
| root_cause="Non-CSPRNG token.", |
| attack="Predict token sequence.", impact="Token forgery.", |
| fix="Use SecureRandom.", guideline="Use CSPRNG for tokens.", |
| tags=["crypto", "scala", "akka", "tokens"], |
| metadata={"domain": "Authentication systems", "input_source": "server", "auth_required": False}) |
|
|
| |
| rec(id="SCP-000306", language="Go", framework="Gin", |
| title="SQL injection in raw query", |
| description="A Gin handler builds a SQL query by string 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='q := fmt.Sprintf("SELECT * FROM u WHERE name = \u0027%s\u0027", name)\nrows, _ := db.Query(q) // Vulnerable', |
| secure_code='rows, _ := db.Query("SELECT * FROM u WHERE name = $1", name) // Secure: bound', |
| patch='--- a/handler.go\n+++ b/handler.go\n@@ -1,3 +1,2 @@\n-q := fmt.Sprintf("SELECT * FROM u WHERE name = \u0027%s\u0027", name)\n-rows, _ := db.Query(q)\n+rows, _ := db.Query("SELECT * FROM u WHERE name = $1", name)', |
| root_cause="String formatting into SQL.", |
| attack="name=\u0027 OR 1=1 dumps rows.", impact="Data disclosure.", |
| fix="Use bound parameters.", guideline="Bind all SQL params.", |
| tags=["sqli", "go", "gin", "injection"], |
| metadata={"domain": "E-commerce", "input_source": "query_param", "auth_required": False}) |
|
|
| rec(id="SCP-000307", language="Go", framework="Gin", |
| title="Command injection via exec.Command", |
| description="A Gin handler passes user input to a shell.", |
| 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, _ := exec.Command("sh", "-c", "ping -c1 "+host).Output() // Vulnerable', |
| secure_code='if !validHost(host) { c.AbortWithStatus(400); return }\nout, _ := exec.Command("ping", "-c1", host).Output() // Secure: arg array', |
| patch='--- a/ping.go\n+++ b/ping.go\n@@ -1,3 +1,4 @@\n-out, _ := exec.Command("sh", "-c", "ping -c1 "+host).Output()\n+if !validHost(host) { c.AbortWithStatus(400); return }\n+out, _ := exec.Command("ping", "-c1", 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", "go", "gin", "rce"], |
| metadata={"domain": "IoT", "input_source": "query_param", "auth_required": False}) |
|
|
| rec(id="SCP-000308", language="Go", framework="Gin", |
| title="Path traversal in file serve", |
| description="A Gin 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='c.File("/data/" + c.Query("name")) // Vulnerable: traversal', |
| secure_code='name := filepath.Base(c.Query("name"))\npath := filepath.Join("/data", name)\nif !strings.HasPrefix(path, "/data") { c.AbortWithStatus(403); return } // Secure\nc.File(path)', |
| patch='--- a/files.go\n+++ b/files.go\n@@ -1,2 +1,5 @@\n-c.File("/data/" + c.Query("name"))\n+name := filepath.Base(c.Query("name"))\n+path := filepath.Join("/data", name)\n+if !strings.HasPrefix(path, "/data") { c.AbortWithStatus(403); return }\n+c.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", "go", "gin", "file-read"], |
| metadata={"domain": "Backend", "input_source": "query_param", "auth_required": False}) |
|
|
| rec(id="SCP-000309", language="Go", framework="Gin", |
| title="Missing authorization on admin route", |
| description="A Gin admin route has no role 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='r.DELETE("/admin/user/:id", deleteUser) // Vulnerable: no authz', |
| secure_code='r.DELETE("/admin/user/:id", requireAdmin(), deleteUser) // Secure: middleware', |
| patch='--- a/routes.go\n+++ b/routes.go\n@@ -1,2 +1,2 @@\n-r.DELETE("/admin/user/:id", deleteUser)\n+r.DELETE("/admin/user/:id", requireAdmin(), deleteUser)', |
| root_cause="No authz middleware.", |
| attack="Any authenticated user deletes accounts.", impact="Privilege escalation.", |
| fix="Add role middleware.", guideline="Enforce admin authz.", |
| tags=["authorization", "go", "gin", "broken-access-control"], |
| metadata={"domain": "Authentication systems", "input_source": "path_param", "auth_required": True}) |
|
|
| rec(id="SCP-000310", language="Go", framework="Gin", |
| title="Hardcoded secret in source", |
| description="A Gin 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 apiKey = "sk_live_5a4b3c2d" // Vulnerable', |
| secure_code='var apiKey = os.Getenv("PAYMENT_API_KEY") // Secure: env', |
| patch='--- a/config.go\n+++ b/config.go\n@@ -1,2 +1,2 @@\n-const apiKey = "sk_live_5a4b3c2d"\n+var apiKey = os.Getenv("PAYMENT_API_KEY")', |
| root_cause="Secret in source.", |
| attack="Repo access reveals key.", impact="Payment fraud.", |
| fix="Use env/secret.", guideline="Externalize secrets.", |
| tags=["secrets", "go", "gin", "config"], |
| metadata={"domain": "Banking", "input_source": "source_code", "auth_required": False}) |
|
|
| rec(id="SCP-000311", language="Go", framework="Gin", |
| title="XSS via template unescaped", |
| description="A Gin template renders user input with template.HTML.", |
| 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='c.HTML(200, "post.tmpl", gin.H{"comment": template.HTML(comment)}) // Vulnerable: unescaped', |
| secure_code='c.HTML(200, "post.tmpl", gin.H{"comment": comment}) // Secure: auto-escaped', |
| patch='--- a/post.go\n+++ b/post.go\n@@ -1,2 +1,2 @@\n-c.HTML(200, "post.tmpl", gin.H{"comment": template.HTML(comment)})\n+c.HTML(200, "post.tmpl", gin.H{"comment": comment})', |
| root_cause="template.HTML disables escaping.", |
| attack="comment=<script>steal()</script> runs.", impact="XSS.", |
| fix="Use default escaping.", guideline="Avoid template.HTML on user input.", |
| tags=["xss", "go", "gin", "template"], |
| metadata={"domain": "E-commerce", "input_source": "db", "auth_required": False}) |
|
|
| rec(id="SCP-000312", language="Go", framework="Gin", |
| title="No rate limit on login", |
| description="A Gin login 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='r.POST("/login", login) // Vulnerable: no throttle', |
| secure_code='r.POST("/login", rateLimiter(5, time.Minute), login) // Secure: middleware', |
| patch='--- a/routes.go\n+++ b/routes.go\n@@ -1,2 +1,2 @@\n-r.POST("/login", login)\n+r.POST("/login", rateLimiter(5, time.Minute), login)', |
| root_cause="No throttle on auth.", |
| attack="Brute force credentials.", impact="Account takeover.", |
| fix="Rate limit login.", guideline="Throttle auth endpoints.", |
| tags=["rate-limiting", "go", "gin", "auth"], |
| metadata={"domain": "Authentication systems", "input_source": "request_body", "auth_required": False}) |
|
|
| rec(id="SCP-000313", language="Go", framework="Gin", |
| title="Insecure JWT verification (none alg)", |
| description="A Go JWT verifier allows the none 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='token, _ := jwt.Parse(t, func(t *jwt.Token) (interface{}, error) { return key, nil }) // Vulnerable: any alg', |
| secure_code='token, _ := jwt.Parse(t, func(t *jwt.Token) (interface{}, error) {\n if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("bad") } // Secure: pin\n return key, nil\n})', |
| patch='--- a/auth.go\n+++ b/auth.go\n@@ -1,3 +1,5 @@\n-token, _ := jwt.Parse(t, func(t *jwt.Token) (interface{}, error) { return key, nil })\n+token, _ := jwt.Parse(t, func(t *jwt.Token) (interface{}, error) {\n+ if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("bad") }\n+ return key, nil\n+})', |
| root_cause="No algorithm pinning.", |
| attack="Forge alg=none token.", impact="Auth bypass.", |
| fix="Pin algorithm.", guideline="Forbid none.", |
| tags=["jwt", "go", "gin", "auth"], |
| metadata={"domain": "Authentication systems", "input_source": "header", "auth_required": True}) |
|
|
| rec(id="SCP-000314", language="Go", framework="Gin", |
| title="IDOR on invoice read", |
| description="A Gin handler returns an invoice 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='r.GET("/invoice/:id", func(c *gin.Context) {\n inv := repo.FindInvoice(c.Param("id")); c.JSON(200, inv) // Vulnerable: no owner\n})', |
| secure_code='r.GET("/invoice/:id", func(c *gin.Context) {\n inv := repo.FindInvoiceOwned(c.Param("id"), c.MustGet("uid").(string)) // Secure: scoped\n c.JSON(200, inv)\n})', |
| patch='--- a/invoice.go\n+++ b/invoice.go\n@@ -1,4 +1,5 @@\n-r.GET("/invoice/:id", func(c *gin.Context) {\n inv := repo.FindInvoice(c.Param("id")); c.JSON(200, inv)\n+r.GET("/invoice/:id", func(c *gin.Context) {\n+ inv := repo.FindInvoiceOwned(c.Param("id"), c.MustGet("uid").(string))\n+ c.JSON(200, inv)', |
| root_cause="No ownership scoping.", |
| attack="Enumerate others invoices.", impact="PII disclosure.", |
| fix="Scope by owner.", guideline="Authorize reads by owner.", |
| tags=["idor", "go", "gin", "access-control"], |
| metadata={"domain": "E-commerce", "input_source": "path_param", "auth_required": True}) |
|
|
| rec(id="SCP-000315", language="Go", framework="Gin", |
| title="Open redirect via ReturnURL", |
| description="A Gin login redirects to ReturnURL 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='c.Redirect(302, c.Query("ReturnURL")) // Vulnerable', |
| secure_code='u := c.Query("ReturnURL")\nif !strings.HasPrefix(u, "/") || strings.HasPrefix(u, "//") { u = "/" } // Secure\nc.Redirect(302, u)', |
| patch='--- a/login.go\n+++ b/login.go\n@@ -1,2 +1,4 @@\n-c.Redirect(302, c.Query("ReturnURL"))\n+u := c.Query("ReturnURL")\n+if !strings.HasPrefix(u, "/") || strings.HasPrefix(u, "//") { u = "/" }\n+c.Redirect(302, u)', |
| root_cause="Unvalidated redirect.", |
| attack="ReturnURL=//evil.com phishing.", impact="Phishing.", |
| fix="Allowlist relative.", guideline="Validate redirects.", |
| tags=["open-redirect", "go", "gin", "phishing"], |
| metadata={"domain": "Authentication systems", "input_source": "query_param", "auth_required": False}) |
|
|
| rec(id="SCP-000316", language="Go", framework="Gin", |
| title="Business logic: negative quantity", |
| description="A Go cart handler accepts a negative quantity.", |
| 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='type Cart struct{ Qty int }\njson.NewDecoder(r.Body).Decode(&cart) // Vulnerable: negative qty', |
| secure_code='type Cart struct{ Qty int `json:"qty" binding="required,gt=0,lte=100"` }\nif err := c.ShouldBindJSON(&cart); err != nil { c.AbortWithStatus(400); return } // Secure', |
| patch='--- a/cart.go\n+++ b/cart.go\n@@ -1,3 +1,4 @@\n-type Cart struct{ Qty int }\n-json.NewDecoder(r.Body).Decode(&cart)\n+type Cart struct{ Qty int `json:"qty" binding="required,gt=0,lte=100"` }\n+if err := c.ShouldBindJSON(&cart); err != nil { c.AbortWithStatus(400); return }', |
| root_cause="Client qty not bounded.", |
| attack="qty=-5 => negative charge.", impact="Revenue loss.", |
| fix="Validate with binding tags.", guideline="Validate business values.", |
| tags=["business-logic", "go", "gin", "ecommerce"], |
| metadata={"domain": "E-commerce", "input_source": "request_body", "auth_required": True}) |
|
|
| rec(id="SCP-000317", language="Go", framework="Gin", |
| title="Insecure random for CSRF token", |
| description="A Go handler uses math/rand for CSRF tokens.", |
| owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="", |
| cwe="CWE-338", mitre_attack="T1600 - Weaken Encryption", |
| severity="High", difficulty="Intermediate", |
| vulnerable_code='func csrf() string { return strconv.Itoa(rand.Int()) } // Vulnerable: predictable', |
| secure_code='func csrf() string { b := make([]byte, 32); rand.Read(b); return hex.EncodeToString(b) } // Secure: crypto/rand', |
| patch='--- a/csrf.go\n+++ b/csrf.go\n@@ -1,2 +1,3 @@\n-func csrf() string { return strconv.Itoa(rand.Int()) }\n+func csrf() string { b := make([]byte, 32); rand.Read(b); return hex.EncodeToString(b) }', |
| root_cause="Non-CSPRNG token.", |
| attack="Predict token.", impact="CSRF bypass.", |
| fix="Use crypto/rand.", guideline="Use CSPRNG for tokens.", |
| tags=["crypto", "go", "gin", "tokens"], |
| metadata={"domain": "E-commerce", "input_source": "server", "auth_required": False}) |
|
|
| rec(id="SCP-000318", language="Go", framework="Gin", |
| title="CORS allow-all with credentials", |
| description="A Gin 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='c.Writer.Header().Set("Access-Control-Allow-Origin", "*") // Vulnerable\nc.Writer.Header().Set("Access-Control-Allow-Credentials", "true")', |
| secure_code='c.Writer.Header().Set("Access-Control-Allow-Origin", "https://app.example.com") // Secure\nc.Writer.Header().Set("Access-Control-Allow-Credentials", "true")', |
| patch='--- a/cors.go\n+++ b/cors.go\n@@ -1,3 +1,3 @@\n-c.Writer.Header().Set("Access-Control-Allow-Origin", "*")\n-c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")\n+c.Writer.Header().Set("Access-Control-Allow-Origin", "https://app.example.com")\n+c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")', |
| root_cause="Wildcard origin + credentials.", |
| attack="Cross-origin read with cookies.", impact="Data theft.", |
| fix="Pin origins.", guideline="Restrict CORS.", |
| tags=["cors", "go", "gin", "config"], |
| metadata={"domain": "E-commerce", "input_source": "header", "auth_required": True}) |
|
|
| rec(id="SCP-000319", language="Go", framework="Gin", |
| title="Deserialization of untrusted JSON with reflection", |
| description="A Go handler decodes JSON into an interface{} 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='var data interface{}\njson.Unmarshal(body, &data) // Vulnerable: loose typing', |
| secure_code='var data StrictDTO\nif err := json.Unmarshal(body, &data); err != nil { c.AbortWithStatus(400); return } // Secure: typed', |
| patch='--- a/handler.go\n+++ b/handler.go\n@@ -1,3 +1,4 @@\n-var data interface{}\n-json.Unmarshal(body, &data)\n+var data StrictDTO\n+if err := json.Unmarshal(body, &data); err != nil { c.AbortWithStatus(400); return }', |
| root_cause="Untyped JSON decode.", |
| attack="Type confusion in downstream logic.", impact="Logic abuse.", |
| fix="Use strict DTOs.", guideline="Type all JSON input.", |
| tags=["deserialization", "go", "gin", "injection"], |
| metadata={"domain": "Microservices", "input_source": "request_body", "auth_required": False}) |
|
|
| rec(id="SCP-000320", language="Go", framework="Gin", |
| title="Unsafe reflection by name", |
| description="A Go handler instantiates a type from a request param.", |
| owasp="A03:2021 - Injection", owasp_api="", owasp_llm="", |
| cwe="CWE-470", mitre_attack="T1190 - Exploit Public-Facing Application", |
| severity="High", difficulty="Advanced", |
| vulnerable_code='typ := reflect.TypeOf(structs[req.FormValue("t")]) // Vulnerable: arbitrary\nobj := reflect.New(typ).Interface()', |
| secure_code='ALLOWED := map[string]bool{"A": true, "B": true}\nif !ALLOWED[req.FormValue("t")] { c.AbortWithStatus(400); return } // Secure', |
| patch='--- a/handler.go\n+++ b/handler.go\n@@ -1,3 +1,4 @@\n-typ := reflect.TypeOf(structs[req.FormValue("t")])\n-obj := reflect.New(typ).Interface()\n+ALLOWED := map[string]bool{"A": true, "B": true}\n+if !ALLOWED[req.FormValue("t")] { c.AbortWithStatus(400); return }', |
| root_cause="Unrestricted reflection.", |
| attack="Pick unexpected type for abuse.", impact="Logic abuse / RCE.", |
| fix="Allowlist reflectable types.", guideline="Restrict reflection.", |
| tags=["injection", "go", "gin", "reflection"], |
| metadata={"domain": "Backend", "input_source": "form_field", "auth_required": False}) |
|
|
| rec(id="SCP-000321", language="Go", framework="Gin", |
| title="Race condition on balance update", |
| description="A Go handler updates a balance without locking.", |
| 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="High", difficulty="Advanced", |
| vulnerable_code='acc.Balance -= amount // Vulnerable: data race (concurrent requests)', |
| secure_code='acc.mu.Lock(); defer acc.mu.Unlock()\nif acc.Balance < amount { return errInsufficient }\nacc.Balance -= amount // Secure: locked', |
| patch='--- a/account.go\n+++ b/account.go\n@@ -1,3 +1,5 @@\n-acc.Balance -= amount\n+acc.mu.Lock(); defer acc.mu.Unlock()\n+if acc.Balance < amount { return errInsufficient }\n+acc.Balance -= amount', |
| root_cause="Unlocked shared mutation.", |
| attack="Double-spend via concurrent requests.", impact="Financial loss.", |
| fix="Use mutex/atomic.", guideline="Protect shared state.", |
| tags=["race-condition", "go", "gin", "concurrency"], |
| metadata={"domain": "Banking", "input_source": "request_body", "auth_required": True}) |
|
|
| rec(id="SCP-000322", language="Go", framework="Gin", |
| title="Verbose error leak in response", |
| description="A Go handler returns raw error messages including internals.", |
| 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='c.JSON(500, gin.H{"error": err.Error()}) // Vulnerable: leaks internals', |
| secure_code='c.JSON(500, gin.H{"error": "internal_error"}) // Secure: generic\nlog.Printf("err: %v", err)', |
| patch='--- a/handler.go\n+++ b/handler.go\n@@ -1,2 +1,3 @@\n-c.JSON(500, gin.H{"error": err.Error()})\n+c.JSON(500, gin.H{"error": "internal_error"})\n+log.Printf("err: %v", err)', |
| root_cause="Raw error to client.", |
| attack="Extract stack/paths from errors.", impact="Info disclosure.", |
| fix="Generic errors to client.", guideline="Log detailed, return generic.", |
| tags=["info-leak", "go", "gin", "error-handling"], |
| metadata={"domain": "Backend", "input_source": "server", "auth_required": False}) |
|
|
| rec(id="SCP-000323", language="Go", framework="Gin", |
| title="Insecure file upload (no type check)", |
| description="A Go handler stores any uploaded file.", |
| 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='file, _ := c.FormFile("file")\nc.SaveUploadedFile(file, "/uploads/"+file.Filename) // Vulnerable: any type', |
| secure_code='if ct := file.Header.Get("Content-Type"); ct != "image/png" && ct != "image/jpeg" { c.AbortWithStatus(400); return }\nname := uuid.New().String() + ".png"\nc.SaveUploadedFile(file, "/uploads/"+name) // Secure: validate + randomize', |
| patch='--- a/upload.go\n+++ b/upload.go\n@@ -1,3 +1,5 @@\n-file, _ := c.FormFile("file")\n-c.SaveUploadedFile(file, "/uploads/"+file.Filename)\n+if ct := file.Header.Get("Content-Type"); ct != "image/png" && ct != "image/jpeg" { c.AbortWithStatus(400); return }\n+name := uuid.New().String() + ".png"\n+c.SaveUploadedFile(file, "/uploads/"+name)', |
| root_cause="No content-type validation.", |
| attack="Upload .go webshell.", impact="RCE.", |
| fix="Allowlist types; randomize name.", guideline="Validate uploads.", |
| tags=["file-upload", "go", "gin", "rce"], |
| metadata={"domain": "E-commerce", "input_source": "form_field", "auth_required": True}) |
|
|
| rec(id="SCP-000324", language="Go", framework="Gin", |
| title="LDAP injection in filter", |
| description="A Go LDAP client 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='filter := fmt.Sprintf("(uid=%s)", user)\nsearchReq.Filter = filter // Vulnerable', |
| secure_code='filter := fmt.Sprintf("(uid=%s)", ldap.EscapeFilter(user)) // Secure: escape', |
| patch='--- a/ldap.go\n+++ b/ldap.go\n@@ -1,3 +1,3 @@\n-filter := fmt.Sprintf("(uid=%s)", user)\n-searchReq.Filter = filter\n+filter := fmt.Sprintf("(uid=%s)", ldap.EscapeFilter(user))\n+searchReq.Filter = filter', |
| root_cause="Unescaped LDAP filter.", |
| attack="user=*)(|(uid=* bypasses.", impact="Auth bypass.", |
| fix="Escape LDAP specials.", guideline="Sanitize LDAP input.", |
| tags=["ldap-injection", "go", "gin", "injection"], |
| metadata={"domain": "Authentication systems", "input_source": "query_param", "auth_required": False}) |
|
|
| rec(id="SCP-000325", language="Go", framework="Gin", |
| title="Missing CSRF protection on state change", |
| description="A Go form POST has no CSRF token check.", |
| 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='r.POST("/transfer", transfer) // Vulnerable: no CSRF', |
| secure_code='r.POST("/transfer", csrfProtect(), transfer) // Secure: token check', |
| patch='--- a/routes.go\n+++ b/routes.go\n@@ -1,2 +1,2 @@\n-r.POST("/transfer", transfer)\n+r.POST("/transfer", csrfProtect(), transfer)', |
| root_cause="No CSRF token on POST.", |
| attack="Cross-site POST forges transfer.", impact="Unauthorized transfer.", |
| fix="Add CSRF token check.", guideline="Protect state changes.", |
| tags=["csrf", "go", "gin", "config"], |
| metadata={"domain": "Banking", "input_source": "form_field", "auth_required": True}) |
|
|
| RECORDS_EXT8 = L |
|
|