SQL Injection
SQL injection is an attack that slips database commands into user input so the application runs them against its own database.
What is SQL Injection?
SQL injection is an attack where someone types database commands into a place that should only accept data, such as a login box, a search field, or an API parameter, and the application runs those commands against its own database. It happens when code builds a query by joining user input straight into the SQL text.
For a business, one injectable parameter can expose an entire customer table. Attackers use it to read records they should never see, change or delete data, bypass login checks, and on some database configurations run operating system commands. The 2023 MOVEit Transfer breaches started with a SQL injection flaw in a file transfer product and ended with data stolen from more than a thousand organizations.
Security leaders should care for two reasons. The fix is known and cheap when applied during development. And an injectable query in production says something about the engineering process behind it: code review, testing, and secure defaults are probably missing in other places too.
How SQL Injection works
- The application accepts input, for example a product ID in a URL or an email address in a login form.
- The code builds a query by joining that input into a string, such as
"SELECT * FROM products WHERE id = '" + input + "'". - The attacker sends input that contains a quote and extra SQL. The quote closes the value the developer intended, and the rest becomes new query logic.
- The database receives one string and cannot tell which part came from the developer and which part came from the attacker. It parses and runs all of it.
- The attacker reads the result on the page, or infers it from error messages, page differences, or response delays when nothing is shown directly.
flowchart LR A["Attacker sends crafted input"] --> B["App joins input into SQL text"] B --> C["Database parses the whole string"] C --> D["Injected logic runs"] D --> E["Data returned, changed, or deleted"]
Under the hood
Why the database gets confused
A database turns query text into tokens before it runs anything. When input is concatenated into that text, the input takes part in parsing, so a quote or a keyword in the input changes the structure of the query. Parameterized queries fix this at the protocol level: the driver sends the query shape and the values separately, and the values are never parsed as SQL.
# Vulnerable: the email becomes part of the SQL text
cur.execute("SELECT id, email FROM users WHERE email = '" + email + "'")
# Safe: the driver sends the value separately from the query
cur.execute("SELECT id, email FROM users WHERE email = %s", (email,))
The main variants
- In-band: Results come back in the same response. Union-based injection appends rows from other tables with
UNION SELECT. Error-based injection pushes data into database error messages that the page displays. - Blind: Nothing is shown, so the attacker asks yes or no questions. Boolean-based injection watches for a page that changes when a condition is true. Time-based injection uses functions such as
SLEEP(),pg_sleep(), orWAITFOR DELAYand measures the response time. - Out-of-band: The database is tricked into making a DNS or HTTP request that carries the data to a server the attacker controls.
- Second-order: The payload is stored safely at first, then reused later by a different query that does concatenate it.
A classic manual probe is a single quote, or the string ' OR '1'='1 in a login field. Testers then use tools such as sqlmap to confirm and map the injection, but only on systems they are authorized to test.
What it leaves behind
Web server and WAF logs show quotes, comment markers (--, #, /*), UNION SELECT, sleep functions, and their URL-encoded forms in parameters. Application logs show bursts of database syntax errors from one client. Database audit logs show the web application account querying system catalogs such as information_schema.tables, which normal application code rarely touches. Time-based attacks show response times that jump by a fixed number of seconds.
Framework mapping
CWE-89 describes the coding weakness itself. ATT&CK technique T1190 describes how attackers use flaws like this one in internet-facing applications to get their first foothold.
Common attack scenarios
- An online retailer builds its product search query with string concatenation. A criminal uses union-based injection to pull the customer table, including password hashes, through the search results page.
- A file transfer appliance used by a logistics company has an injectable endpoint that needs no login. An extortion group automates the attack across every exposed appliance it can find on the internet and steals stored files.
- A hospital portal shows no errors and no results for bad input. An attacker uses time-based blind injection, one character at a time, to extract an administrator session token.
Framework mappings
Latest real-world attacks using this technique
News stories tagged with SQL Injection. This list updates on its own while the page is open.
- Info GitHub detects vulnerabilities in pull requestsHelp Net Security
- Medium WhatsApp fixes bug that let attackers fake messagesSecurity Affairs
- Medium WhatsApp patches Android flaw used by scammersSecurityWeek
- High Norwegian energy firms face cyberattacksSecurityWeek
- High Subnet Solutions PowerSYSTEM Center vulnerable to SQL InjectionCISA
- Critical Cl0p mass-exploits MOVEit Transfer SQL injection to steal files (CVE-2023-34362)CISA
Prevention, hardening and detection
Prevention and hardening
- Use parameterized queries or prepared statements for every query that includes outside data. Make this the only pattern allowed in code review.
- When you use an ORM, use its query builder. Treat every raw query feature as a high-risk spot and review it.
- Some parts of a query cannot be parameterized, such as column names and sort direction. Check those against a fixed allow-list in code.
- Give the application its own database account with only the rights it needs. It should not own the schema, read other databases, or run system procedures.
- Return generic error pages to users and keep database errors in server-side logs.
- Add static analysis to the build pipeline and dynamic scanning to test environments, so injectable code fails before release.
- A web application firewall can block common payloads while you patch. It is a temporary shield, because encoding and alternate syntax get past filters.
Detection
| Data source | What to look for | Example |
|---|---|---|
| Web server or WAF logs | SQL syntax and comment markers inside parameters, including encoded forms | id=1%27%20UNION%20SELECT%20NULL-- |
| Application logs | Bursts of database syntax errors from one client or session | 40 syntax errors in one minute from one IP |
| Database audit logs | The app account reading system catalogs or tables it never uses | SELECT on information_schema.tables |
| Response metrics | Response times or sizes that change in a fixed pattern on one endpoint | Requests to /search that take exactly 5 seconds |
Alert on the combination, not on one signal. A single quote in a search box is often a real customer. A single client that triggers errors, then catalog queries, then large responses is an attack in progress.
Frequently asked questions
Can a web application firewall stop SQL injection?
It blocks many common payloads and buys time after a new flaw is published. Attackers get around filters with encoding and alternate syntax, so the real fix is parameterized queries in the code.
Do ORMs prevent SQL injection?
Mostly, when you use their query builders. Raw query methods, string-built filters, and dynamic sort fields can still be injectable, so every place the ORM accepts raw SQL needs review.
What is blind SQL injection?
The application shows no query results or errors, so the attacker asks yes or no questions and watches for changes in the page or in response time. It is slower but can extract the same data.
Is SQL injection still a problem today?
Yes. Injection remains a category in the OWASP Top 10, and critical injection flaws keep appearing in commercial products such as file transfer tools and management consoles that sit on the internet.
References and further reading
- CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
- T1190: Exploit Public-Facing Application
- OWASP: SQL Injection
- OWASP SQL Injection Prevention Cheat Sheet
- PortSwigger Web Security Academy: SQL injection
- CISA advisory AA23-158A: Cl0p exploitation of MOVEit Transfer
- MITRE ATT&CK Enterprise matrix
- MITRE CWE list
- NIST Computer Security Resource Center glossary
Found a technical error in this entry? Tell us and we will fix it.