SC: SQL Injection
Purpose
Detects SQL injection vulnerabilities in all forms: classic (error-based), blind (boolean and time-based), UNION-based, second-order, and ORM bypass patterns. Traces user input from HTTP request parameters through application logic to database query construction, identifying points where unsanitized data enters SQL statements.
Activation
Called by sc-orchestrator during Phase 2 (Vulnerability Hunting). Runs against all detected languages.
Phase 1: Discovery
File Patterns to Search
**/*.go, **/*.ts, **/*.js, **/*.py, **/*.php, **/*.java, **/*.kt, **/*.cs,
**/*.rb, **/routes/*, **/controllers/*, **/models/*, **/repositories/*,
**/dal/*, **/dao/*, **/*query*, **/*sql*, **/*database*, **/*db*
Keyword Patterns to Search
# Direct SQL construction
"SELECT.*FROM" # SQL SELECT statements
"INSERT INTO" # SQL INSERT
"UPDATE.*SET" # SQL UPDATE
"DELETE FROM" # SQL DELETE
"EXEC ", "EXECUTE " # Stored procedure execution
# String concatenation in queries
"+ .*query" # String concat with query variable
`${.*}`.*SELECT # Template literals in SQL
f"SELECT, f"INSERT # Python f-strings in SQL
"WHERE.*=.*'" + " # String concat in WHERE clause
".format(.*)".*SELECT # str.format() in SQL
# Language-specific database calls
"db.Query(", "db.Exec(" # Go database/sql
"sequelize.query(", ".rawQuery(" # Node.js Sequelize
"cursor.execute(", "connection.execute(" # Python DB-API
"$wpdb->query(", "->whereRaw(" # PHP WordPress/Laravel
"createNativeQuery(", "createQuery(" # Java JPA
"FromSqlRaw(", "ExecuteSqlRaw(" # C# Entity Framework
Semantic Patterns
- String concatenation — any variable concatenated into a string that is later passed to a database query function
- Template literal interpolation — variables embedded in SQL via template literals or f-strings
- ORM raw query methods — framework ORM methods that accept raw SQL strings
- Stored procedure calls — dynamic stored procedure name or parameter construction
- Query builder misuse — using
.where() with raw strings instead of parameterized objects
Data Flow Tracing (Source → Sink)
Sources (user input):
req.query.*, req.params.*, req.body.* (Express/Node)
request.GET, request.POST, request.data (Django)
$_GET, $_POST, $_REQUEST, $_COOKIE (PHP)
r.URL.Query(), r.FormValue(), r.PathValue() (Go)
@RequestParam, @PathVariable, @RequestBody (Spring)
[FromQuery], [FromRoute], [FromBody] (ASP.NET)
Sinks (database queries):
db.Query(), db.Exec(), db.QueryRow() (Go)
sequelize.query(), knex.raw(), prisma.$queryRaw() (Node)
cursor.execute(), RawSQL(), .extra(), .raw() (Python)
$pdo->query(), mysqli_query(), DB::select(DB::raw()) (PHP)
createNativeQuery(), session.createSQLQuery() (Java)
.FromSqlRaw(), .ExecuteSqlRaw() (C#)
Phase 2: Verification
For each candidate finding:
Exploitability Checklist
- Can user-controlled input reach the SQL query without modification?
- Is the input inserted into the SQL structure (not just values)?
- Can the attacker control the position of quotes, operators, or keywords?
- Is there a way to observe the result (error messages, data differences, timing)?
Sanitization Check
- Is input passed through a parameterized query / prepared statement?
- Is input cast to a specific type (integer, UUID) before use?
- Is input validated against an allowlist of expected values?
- Is input escaped using a database-specific escape function?
Framework Protection Check
- Django ORM:
.filter(), .get(), .exclude() are safe. .raw(), .extra(), RawSQL() are not.
- SQLAlchemy:
session.query() with model attributes is safe. text() with f-strings is not.
- ActiveRecord:
.where(hash) is safe. .where("string #{var}") is not.
- Prisma: All standard methods are safe.
$queryRaw with template literal (tagged) is safe. $queryRawUnsafe is not.
- GORM:
.Where(struct) is safe. .Where("name = " + input) is not.
- Entity Framework: LINQ queries are safe.
.FromSqlRaw(interpolated) is not.
- Hibernate: Criteria API is safe. HQL with concatenation is not.
Context-Aware False Positive Elimination
- Is the "query" actually a search query against a search engine (Elasticsearch), not SQL?
- Is the variable a constant/enum, not user input?
- Is the concatenation building a query that uses parameterized placeholders?
- Is the code in a migration file, seed file, or schema definition (not runtime)?
Severity Classification
- Critical: Direct SQL injection from HTTP parameter into database query with no sanitization, affecting authentication or data retrieval. User can read/write/delete arbitrary data.
- High: SQL injection that requires specific conditions (e.g., certain parameter values, authenticated user) or affects limited data scope.
- Medium: Second-order SQL injection (stored input used later in query), or injection in admin-only endpoints.
- Low: SQL injection in dead code, test code, or with strong compensating controls (WAF, input validation that limits exploitation).
Language-Specific Notes
Go
// VULNERABLE: String concatenation in query
query := "SELECT * FROM users WHERE id = " + r.URL.Query().Get("id")
rows, err := db.Query(query)
// SAFE: Parameterized query
rows, err := db.Query("SELECT * FROM users WHERE id = $1", r.URL.Query().Get("id"))
TypeScript/JavaScript
// VULNERABLE: Template literal in raw query
const users = await prisma.$queryRawUnsafe(`SELECT * FROM users WHERE name = '${req.query.name}'`)
// SAFE: Tagged template (Prisma parameterizes these)
const users = await prisma.$queryRaw`SELECT * FROM users WHERE name = ${req.query.name}`
Python
# VULNERABLE: f-string in SQL
cursor.execute(f"SELECT * FROM users WHERE id = {request.GET['id']}")
# SAFE: Parameterized query
cursor.execute("SELECT * FROM users WHERE id = %s", [request.GET['id']])
PHP
// VULNERABLE: Direct interpolation
$result = $pdo->query("SELECT * FROM users WHERE id = " . $_GET['id']);
// SAFE: Prepared statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$_GET['id']]);
Java
// VULNERABLE: String concatenation in JDBC
String query = "SELECT * FROM users WHERE id = " + request.getParameter("id");
ResultSet rs = stmt.executeQuery(query);
// SAFE: Prepared statement
PreparedStatement ps = conn.prepareStatement("SELECT * FROM users WHERE id = ?");
ps.setString(1, request.getParameter("id"));
ResultSet rs = ps.executeQuery();
C#
// VULNERABLE: String interpolation in raw SQL
var users = context.Users.FromSqlRaw($"SELECT * FROM Users WHERE Id = {id}").ToList();
// SAFE: Parameterized
var users = context.Users.FromSqlRaw("SELECT * FROM Users WHERE Id = {0}", id).ToList();
Output Format
Finding: SQLI-{NNN}
- Title: SQL Injection in {function/endpoint}
- Severity: Critical | High | Medium | Low
- Confidence: 0-100
- File: file/path:line
- Vulnerability Type: CWE-89 (SQL Injection)
- Description: User input from {source} is concatenated into SQL query at {sink} without parameterization.
- Proof of Concept: An attacker could supply
' OR 1=1 -- as the {parameter} to bypass the WHERE clause and retrieve all records.
- Impact: Unauthorized data access, data modification, authentication bypass, potential remote code execution via database features (xp_cmdshell, LOAD_FILE).
- Remediation: Use parameterized queries or prepared statements. Replace string concatenation with query placeholders.
- References: https://cwe.mitre.org/data/definitions/89.html, https://owasp.org/Top10/A03_2021-Injection/
Common False Positives
- ORM standard methods —
.filter(), .findOne(), LINQ queries are parameterized by default
- Prisma tagged templates —
prisma.$queryRaw\...`auto-parameterizes (but$queryRawUnsafe` does not)
- Search engine queries — Elasticsearch DSL, MongoDB queries are not SQL
- Schema/migration files — DDL statements in migration files are not user-input-driven
- Constants in queries —
"SELECT * FROM users WHERE role = 'admin'" with no variable input
- Query builders with safe API —
knex('users').where('id', input) parameterizes automatically
- Type-safe inputs — When input is guaranteed to be an integer via type casting before reaching query
1---
2name: sc-sqli
3description: SQL Injection detection across all variants — classic, blind, time-based, second-order, and UNION-based
4license: MIT
5metadata:
6 source: https://skillmd.com/skills/aibot88/sc-sqli
7 category: security
8 version: "1.0.0"
9---
10
11# SC: SQL Injection
12
13## Purpose
14
15Detects SQL injection vulnerabilities in all forms: classic (error-based), blind (boolean and time-based), UNION-based, second-order, and ORM bypass patterns. Traces user input from HTTP request parameters through application logic to database query construction, identifying points where unsanitized data enters SQL statements.
16
17## Activation
18
19Called by sc-orchestrator during Phase 2 (Vulnerability Hunting). Runs against all detected languages.
20
21## Phase 1: Discovery
22
23### File Patterns to Search
24```
25**/*.go, **/*.ts, **/*.js, **/*.py, **/*.php, **/*.java, **/*.kt, **/*.cs,
26**/*.rb, **/routes/*, **/controllers/*, **/models/*, **/repositories/*,
27**/dal/*, **/dao/*, **/*query*, **/*sql*, **/*database*, **/*db*
28```
29
30### Keyword Patterns to Search
31```
32# Direct SQL construction
33"SELECT.*FROM" # SQL SELECT statements
34"INSERT INTO" # SQL INSERT
35"UPDATE.*SET" # SQL UPDATE
36"DELETE FROM" # SQL DELETE
37"EXEC ", "EXECUTE " # Stored procedure execution
38
39# String concatenation in queries
40"+ .*query" # String concat with query variable
41`${.*}`.*SELECT # Template literals in SQL
42f"SELECT, f"INSERT # Python f-strings in SQL
43"WHERE.*=.*'" + " # String concat in WHERE clause
44".format(.*)".*SELECT # str.format() in SQL
45
46# Language-specific database calls
47"db.Query(", "db.Exec(" # Go database/sql
48"sequelize.query(", ".rawQuery(" # Node.js Sequelize
49"cursor.execute(", "connection.execute(" # Python DB-API
50"$wpdb->query(", "->whereRaw(" # PHP WordPress/Laravel
51"createNativeQuery(", "createQuery(" # Java JPA
52"FromSqlRaw(", "ExecuteSqlRaw(" # C# Entity Framework
53```
54
55### Semantic Patterns
561. **String concatenation** — any variable concatenated into a string that is later passed to a database query function
572. **Template literal interpolation** — variables embedded in SQL via template literals or f-strings
583. **ORM raw query methods** — framework ORM methods that accept raw SQL strings
594. **Stored procedure calls** — dynamic stored procedure name or parameter construction
605. **Query builder misuse** — using `.where()` with raw strings instead of parameterized objects
61
62### Data Flow Tracing (Source → Sink)
63
64**Sources (user input):**
65- `req.query.*`, `req.params.*`, `req.body.*` (Express/Node)
66- `request.GET`, `request.POST`, `request.data` (Django)
67- `$_GET`, `$_POST`, `$_REQUEST`, `$_COOKIE` (PHP)
68- `r.URL.Query()`, `r.FormValue()`, `r.PathValue()` (Go)
69- `@RequestParam`, `@PathVariable`, `@RequestBody` (Spring)
70- `[FromQuery]`, `[FromRoute]`, `[FromBody]` (ASP.NET)
71
72**Sinks (database queries):**
73- `db.Query()`, `db.Exec()`, `db.QueryRow()` (Go)
74- `sequelize.query()`, `knex.raw()`, `prisma.$queryRaw()` (Node)
75- `cursor.execute()`, `RawSQL()`, `.extra()`, `.raw()` (Python)
76- `$pdo->query()`, `mysqli_query()`, `DB::select(DB::raw())` (PHP)
77- `createNativeQuery()`, `session.createSQLQuery()` (Java)
78- `.FromSqlRaw()`, `.ExecuteSqlRaw()` (C#)
79
80## Phase 2: Verification
81
82For each candidate finding:
83
84### Exploitability Checklist
851. Can user-controlled input reach the SQL query without modification?
862. Is the input inserted into the SQL structure (not just values)?
873. Can the attacker control the position of quotes, operators, or keywords?
884. Is there a way to observe the result (error messages, data differences, timing)?
89
90### Sanitization Check
911. Is input passed through a parameterized query / prepared statement?
922. Is input cast to a specific type (integer, UUID) before use?
933. Is input validated against an allowlist of expected values?
944. Is input escaped using a database-specific escape function?
95
96### Framework Protection Check
97- **Django ORM:** `.filter()`, `.get()`, `.exclude()` are safe. `.raw()`, `.extra()`, `RawSQL()` are not.
98- **SQLAlchemy:** `session.query()` with model attributes is safe. `text()` with f-strings is not.
99- **ActiveRecord:** `.where(hash)` is safe. `.where("string #{var}")` is not.
100- **Prisma:** All standard methods are safe. `$queryRaw` with template literal (tagged) is safe. `$queryRawUnsafe` is not.
101- **GORM:** `.Where(struct)` is safe. `.Where("name = " + input)` is not.
102- **Entity Framework:** LINQ queries are safe. `.FromSqlRaw(interpolated)` is not.
103- **Hibernate:** Criteria API is safe. HQL with concatenation is not.
104
105### Context-Aware False Positive Elimination
1061. Is the "query" actually a search query against a search engine (Elasticsearch), not SQL?
1072. Is the variable a constant/enum, not user input?
1083. Is the concatenation building a query that uses parameterized placeholders?
1094. Is the code in a migration file, seed file, or schema definition (not runtime)?
110
111## Severity Classification
112
113- **Critical:** Direct SQL injection from HTTP parameter into database query with no sanitization, affecting authentication or data retrieval. User can read/write/delete arbitrary data.
114- **High:** SQL injection that requires specific conditions (e.g., certain parameter values, authenticated user) or affects limited data scope.
115- **Medium:** Second-order SQL injection (stored input used later in query), or injection in admin-only endpoints.
116- **Low:** SQL injection in dead code, test code, or with strong compensating controls (WAF, input validation that limits exploitation).
117
118## Language-Specific Notes
119
120### Go
121```go
122// VULNERABLE: String concatenation in query
123query := "SELECT * FROM users WHERE id = " + r.URL.Query().Get("id")
124rows, err := db.Query(query)
125
126// SAFE: Parameterized query
127rows, err := db.Query("SELECT * FROM users WHERE id = $1", r.URL.Query().Get("id"))
128```
129
130### TypeScript/JavaScript
131```typescript
132// VULNERABLE: Template literal in raw query
133const users = await prisma.$queryRawUnsafe(`SELECT * FROM users WHERE name = '${req.query.name}'`)
134
135// SAFE: Tagged template (Prisma parameterizes these)
136const users = await prisma.$queryRaw`SELECT * FROM users WHERE name = ${req.query.name}`
137```
138
139### Python
140```python
141# VULNERABLE: f-string in SQL
142cursor.execute(f"SELECT * FROM users WHERE id = {request.GET['id']}")
143
144# SAFE: Parameterized query
145cursor.execute("SELECT * FROM users WHERE id = %s", [request.GET['id']])
146```
147
148### PHP
149```php
150// VULNERABLE: Direct interpolation
151$result = $pdo->query("SELECT * FROM users WHERE id = " . $_GET['id']);
152
153// SAFE: Prepared statement
154$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
155$stmt->execute([$_GET['id']]);
156```
157
158### Java
159```java
160// VULNERABLE: String concatenation in JDBC
161String query = "SELECT * FROM users WHERE id = " + request.getParameter("id");
162ResultSet rs = stmt.executeQuery(query);
163
164// SAFE: Prepared statement
165PreparedStatement ps = conn.prepareStatement("SELECT * FROM users WHERE id = ?");
166ps.setString(1, request.getParameter("id"));
167ResultSet rs = ps.executeQuery();
168```
169
170### C#
171```csharp
172// VULNERABLE: String interpolation in raw SQL
173var users = context.Users.FromSqlRaw($"SELECT * FROM Users WHERE Id = {id}").ToList();
174
175// SAFE: Parameterized
176var users = context.Users.FromSqlRaw("SELECT * FROM Users WHERE Id = {0}", id).ToList();
177```
178
179## Output Format
180
181### Finding: SQLI-{NNN}
182- **Title:** SQL Injection in {function/endpoint}
183- **Severity:** Critical | High | Medium | Low
184- **Confidence:** 0-100
185- **File:** file/path:line
186- **Vulnerability Type:** CWE-89 (SQL Injection)
187- **Description:** User input from {source} is concatenated into SQL query at {sink} without parameterization.
188- **Proof of Concept:** An attacker could supply `' OR 1=1 --` as the {parameter} to bypass the WHERE clause and retrieve all records.
189- **Impact:** Unauthorized data access, data modification, authentication bypass, potential remote code execution via database features (xp_cmdshell, LOAD_FILE).
190- **Remediation:** Use parameterized queries or prepared statements. Replace string concatenation with query placeholders.
191- **References:** https://cwe.mitre.org/data/definitions/89.html, https://owasp.org/Top10/A03_2021-Injection/
192
193## Common False Positives
194
1951. **ORM standard methods** — `.filter()`, `.findOne()`, LINQ queries are parameterized by default
1962. **Prisma tagged templates** — `prisma.$queryRaw\`...\`` auto-parameterizes (but `$queryRawUnsafe` does not)
1973. **Search engine queries** — Elasticsearch DSL, MongoDB queries are not SQL
1984. **Schema/migration files** — DDL statements in migration files are not user-input-driven
1995. **Constants in queries** — `"SELECT * FROM users WHERE role = 'admin'"` with no variable input
2006. **Query builders with safe API** — `knex('users').where('id', input)` parameterizes automatically
2017. **Type-safe inputs** — When input is guaranteed to be an integer via type casting before reaching query