Security skill · Find and fix
SQL injection: find and fix.
Find SQL injection in application code by tracing untrusted input to query construction, confirm it safely against a test database, and fix it with parameterized queries, allowlists for identifiers, and least-privilege database roles. Use when reviewing code, a pull request, or a web API for SQL injection (CWE-89).
Facts
- Category
- Find and fix
- License
- MIT
- Tags
- Code review
- Version
- 1.0.0
- Last updated
- 2026-12-02
- Folder
sql-injection-find-and-fix/- MCP resource
skill://sql-injection-find-and-fix/SKILL.md- Files
- SKILL.md
- LICENSE
- references/patterns.md
- Standards
- A05:2025
- CWE-89
Original Saasment content. Saasment is in early access; this skill does not require joining it.
Install via MCP or as files
Connect your client to https://www.saasment.com/api/mcp (see client setup) and call get_skill:
{
"name": "get_skill",
"arguments": {
"slug": "sql-injection-find-and-fix"
}
}Or download the .zip and unpack it into your agent's skills directory:
Terminal, from your project root (user-level: ~/.cursor/skills)
mkdir -p .cursor/skills
curl -fsSL https://www.saasment.com/ai-security/skills/sql-injection-find-and-fix/download.zip -o /tmp/sql-injection-find-and-fix.zip
unzip -o /tmp/sql-injection-find-and-fix.zip -d .cursor/skills
# result: .cursor/skills/sql-injection-find-and-fix/SKILL.mdReview SKILL.md before enabling a skill. Skills are instructions your agent will follow.
SKILL.md
---
name: sql-injection-find-and-fix
description: Find SQL injection in application code by tracing untrusted input to query construction, confirm it safely against a test database, and fix it with parameterized queries, allowlists for identifiers, and least-privilege database roles. Use when reviewing code, a pull request, or a web API for SQL injection (CWE-89).
license: MIT
metadata:
author: Saasment
version: "1.0.0"
category: both
tags: "code-review"
---
# SQL injection: find and fix
License: MIT. Copyright (c) 2026 Saasment. Source: https://www.saasment.com/ai-security/skills/sql-injection-find-and-fix
SQL injection occurs when untrusted input changes the structure of a SQL statement. The reliable fix is to keep data and SQL separate with parameterized queries. Escaping by hand and blocklists of keywords are fragile and should not be the main control.
## When to use
- You review code that builds queries for a relational database (including raw queries inside an ORM, query builders, stored procedures, and text-to-SQL features).
- You have a web API or form and want to check whether inputs reach SQL.
- You want to fix a reported SQL injection finding and prove the fix.
## Safe by default
- Only test applications and databases you own or are authorized to test.
- Test against a local or staging copy with synthetic data and a database account that cannot drop tables. Never run injection probes against production.
- Use probes that read or error, not probes that modify or delete. Do not use stacked statements that write data, and do not extract real customer records to prove impact. A single synthetic row or an error message is enough evidence.
- Avoid automated scanners at high rates on shared infrastructure. Keep request rates low.
## Procedure
1. **Find query construction sites.** Search for SQL keywords and database calls, then look for string concatenation, interpolation, or formatting near them. Patterns by language are in `references/patterns.md`. Include raw-query escape hatches in ORMs and any dynamic `ORDER BY`, `LIMIT`, column, or table names, which cannot be parameterized as values.
2. **Trace inputs.** For each site, follow the variables back to their source: query string, path, body, headers, cookies, uploaded files, message queues, and data stored earlier by users (second-order injection).
3. **Classify each site:**
- Vulnerable: untrusted data is concatenated or interpolated into the statement text.
- Needs allowlist: identifier or keyword position (sort column, direction, table).
- Safe: values are bound as parameters, and the statement text is a constant.
4. **Confirm safely.** In the test environment, send a single quote or a harmless boolean variation to the suspect parameter and compare responses: a database error, a changed result count, or a timing difference suggests injection. Record request and observed difference. Stop once the issue is confirmed.
5. **Fix by pattern:**
- Values: use parameterized queries or prepared statements (placeholders such as `?`, `$1`, `%s` with a driver that binds, or named parameters). Pass values separately from the statement.
- Dynamic identifiers and keywords: map user choices to a fixed allowlist in code (for example `{"price": "price", "name": "name"}`) and reject everything else. Never quote user input into an identifier.
- `LIKE` patterns: bind the pattern as a parameter and escape wildcard characters if the user should not control them.
- `IN (...)` lists: generate the right number of placeholders and bind each value.
- ORM raw queries: use the ORM's bound-parameter API, not formatted strings.
- Stored procedures: do not build dynamic SQL inside them from parameters without binding.
6. **Reduce impact (defense in depth).** Use a least-privilege database account for the app: no DDL, only the tables and operations it needs, a separate read-only role for reporting. Do not return raw database errors to clients. Set statement timeouts.
7. **Add tests.** Write unit or integration tests that send quote characters, SQL comment markers, and boolean variations as data, and assert they are stored or matched literally and that sort or filter allowlists reject unexpected values.
8. **Add guardrails.** Enable a linter or static analysis rule that flags string-built SQL, and require review for any new raw query.
## Verification
- Re-send the confirmation request from step 4 and verify there is no error, no changed result, and no timing difference.
- Run the new tests; verify they fail against the old code (use a scratch branch) and pass against the fix.
- Re-run a static analysis rule for string-built SQL and verify the finding is gone with no new ones.
- Check the database logs in the test environment: the statement text should be identical for different input values, with values shown as bound parameters.
## Reporting
For each finding: file and line, input source, vulnerable construction, fix, test added. Note any remaining dynamic SQL and its allowlist.
## References
- CWE-89: https://cwe.mitre.org/data/definitions/89.html
- OWASP Top 10 web, Injection category: https://owasp.org/Top10/
- OWASP SQL Injection Prevention Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html
- Companion skills: `insecure-output-handling-review`, `authz-idor-review`.
Helper files
LICENSE
MIT License Copyright (c) 2026 Saasment Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
references/patterns.md
# SQL injection patterns by language
License: MIT. Copyright (c) 2026 Saasment.
Each pair shows a vulnerable construction and a safe replacement. Use your driver's current documentation for exact placeholder syntax.
## JavaScript / TypeScript (node-postgres, mysql2)
```js
// Vulnerable: input becomes part of the statement text
const rows = await client.query(`SELECT * FROM users WHERE email = '${email}'`);
// Safe: bound parameter (node-postgres)
const rows = await client.query("SELECT * FROM users WHERE email = $1", [email]);
// Safe: bound parameter (mysql2)
const [rows] = await pool.execute("SELECT * FROM users WHERE email = ?", [email]);
```
Search terms: template literals or `+` near `SELECT`, `INSERT`, `UPDATE`, `DELETE`, `.query(`, `.raw(`, `$queryRawUnsafe`, `sequelize.query`.
## Python (psycopg, SQLAlchemy, sqlite3, Django)
```python
# Vulnerable
cur.execute(f"SELECT * FROM users WHERE email = '{email}'")
cur.execute("SELECT * FROM users WHERE email = '%s'" % email)
# Safe: driver binds the parameter (psycopg uses %s as a placeholder, not string formatting)
cur.execute("SELECT * FROM users WHERE email = %s", (email,))
# Safe: SQLAlchemy text with bound parameters
conn.execute(text("SELECT * FROM users WHERE email = :email"), {"email": email})
# Django: avoid string-formatted raw(); pass params
User.objects.raw("SELECT * FROM auth_user WHERE email = %s", [email])
```
Search terms: `f"SELECT`, `% ` or `.format(` near SQL, `.raw(`, `.extra(`, `RawSQL(`, `cursor.execute(` with a built string.
## Java (JDBC, JPA)
```java
// Vulnerable
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM users WHERE email = '" + email + "'");
// Safe
PreparedStatement ps = conn.prepareStatement("SELECT * FROM users WHERE email = ?");
ps.setString(1, email);
ResultSet rs = ps.executeQuery();
// JPA: named parameter
em.createQuery("SELECT u FROM User u WHERE u.email = :email", User.class)
.setParameter("email", email);
```
Search terms: `createStatement`, `executeQuery(` with `+`, `createQuery(` or `createNativeQuery(` with concatenation.
## Go (database/sql)
```go
// Vulnerable
rows, err := db.Query("SELECT * FROM users WHERE email = '" + email + "'")
rows, err := db.Query(fmt.Sprintf("SELECT * FROM users WHERE email = '%s'", email))
// Safe (placeholder syntax depends on the driver: $1 for pgx/lib/pq, ? for MySQL)
rows, err := db.Query("SELECT * FROM users WHERE email = $1", email)
```
## PHP (PDO)
```php
// Vulnerable
$pdo->query("SELECT * FROM users WHERE email = '$email'");
// Safe
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(['email' => $email]);
```
Also set `PDO::ATTR_EMULATE_PREPARES` to `false` where the driver supports real prepared statements.
## C# (.NET)
```csharp
// Vulnerable
var cmd = new SqlCommand($"SELECT * FROM Users WHERE Email = '{email}'", conn);
// Safe
var cmd = new SqlCommand("SELECT * FROM Users WHERE Email = @email", conn);
cmd.Parameters.AddWithValue("@email", email);
```
Entity Framework: prefer `FromSqlInterpolated` (parameterized) over `FromSqlRaw` with string concatenation.
## Ruby (ActiveRecord)
```ruby
# Vulnerable
User.where("email = '#{email}'")
# Safe
User.where("email = ?", email)
User.where(email: email)
```
## Dynamic identifiers (all languages)
Placeholders bind values, not identifiers. For sort columns or table names, use an allowlist:
```python
ALLOWED_SORT = {"name": "name", "created": "created_at"}
column = ALLOWED_SORT.get(request_sort)
if column is None:
raise ValueError("invalid sort")
direction = "DESC" if request_dir == "desc" else "ASC"
query = f"SELECT id, name FROM items ORDER BY {column} {direction}" # both pieces come from constants
```
## Safe confirmation probes (test environment only)
- Add a single quote to a string parameter and watch for a database error or changed response.
- Compare `value` against `value' AND '1'='1` and `value' AND '1'='2` (read-only boolean variation) for a differing result count.
- Stop as soon as the behavior difference is clear. Do not extract data or run write statements.
Related
Companion skills
Questions
How do I install the SQL injection: find and fix skill?
Download https://www.saasment.com/ai-security/skills/sql-injection-find-and-fix/download.zip and unzip it into your agent's skills directory (for example .cursor/skills, .claude/skills, .agents/skills, or .github/skills) so that sql-injection-find-and-fix/SKILL.md exists. Or connect to https://www.saasment.com/api/mcp and call the get_skill tool with the slug sql-injection-find-and-fix.
What license is the SQL injection: find and fix skill under?
It is original Saasment content under the MIT license, stated in the SKILL.md frontmatter and in the LICENSE file in the skill folder.
Is it safe to run this skill?
A skill is a set of instructions your agent follows, so read SKILL.md first. It tells the agent to test only systems you own or are authorized to test, to use test environments and synthetic data, and to avoid destructive probes. Downloading it does not run any code on your machine.