SQL Injection (SQLi)
Complete pentesting and interview preparation guide — concepts, major types, identification, impact, remediation, testing workflow, and practice questions.
1. What is SQL Injection?
SQL Injection (SQLi) is a vulnerability that occurs when an application incorporates untrusted user input into an SQL query without safely separating data from SQL code.
An attacker may manipulate the query's intended logic. Depending on the database permissions and application design, this can lead to authentication bypass, unauthorized data access, data modification, or deletion.
Example: vulnerable query
SELECT * FROM users
WHERE username = 'admin'
AND password = 'admin123';
Vulnerable PHP pattern:
$username = $_GET['username'];
$query = "SELECT * FROM users WHERE username = '$username'";
Potential impact
- Authentication or authorization bypass.
- Disclosure of sensitive database records.
- Unauthorized modification or deletion of data.
- Exposure of business or personal information.
- In some configurations, further compromise through excessive database privileges.
2. Major SQL Injection categories
Error-based and UNION-based
Boolean-based and time-based
For example, DNS or HTTP callbacks
Other important patterns include second-order SQLi and stacked queries. Numeric-based, string-based, and authentication-bypass SQLi describe contexts or patterns rather than equivalent top-level categories.
3. In-band SQL Injection
In-band SQLi uses the same communication channel to submit input and observe results.
A. Error-based SQL Injection
Definition: The application exposes database error messages that reveal details about query execution or the database environment.
Why it happens
- Verbose database errors shown to users.
- Improper exception handling.
- Untrusted input incorporated into dynamic SQL.
Illustrative test
Input: '
A vulnerable application might return a database syntax error, potentially revealing the database product or query context. An error alone is an indicator, not conclusive proof.
How to identify
- Identify parameters that may be used in database queries.
- Submit harmless unexpected characters in an authorized test.
- Compare normal and abnormal responses.
- Check whether database-specific errors are exposed.
- Reproduce and document the behaviour.
Impact
May disclose database type/version, query structure, table or column details, and—in some cases—sensitive records.
Remediation
- Use parameterized queries.
- Disable detailed database errors in production.
- Log diagnostic details internally and return generic errors.
- Use centralized exception handling.
B. UNION-based SQL Injection
Definition: The SQL UNION operator combines the result sets of two SELECT statements.
Illustrative SQL example
SELECT id, product FROM products
UNION
SELECT id, employee_name FROM employees;
For a UNION operation, the SELECT statements must return the same number of columns, and corresponding columns must have compatible data types.
How to identify
- Determine whether input can influence a database query.
- Observe errors or response changes when query structure is affected.
- In a controlled lab, verify whether secondary query results are reflected in the response.
Impact and remediation
Potential impact includes unauthorized disclosure of database information. Remediate with parameterized queries, least-privilege database accounts, and safe error handling.
4. Inferential (Blind) SQL Injection
Blind SQLi occurs when the application does not directly display database errors or query results. A tester infers query behaviour from response differences or timing.
A. Boolean-based Blind SQL Injection
Definition: The tester compares application behaviour for conditions that evaluate to TRUE and FALSE.
Illustrative TRUE condition: 1 = 1
Illustrative FALSE condition: 1 = 2
| Condition | Possible observation |
|---|---|
| TRUE | Normal result or one response pattern |
| FALSE | Different content, status, or no record |
Identification
- Establish a baseline response.
- Compare logically true and false test conditions in an authorized environment.
- Compare response body, status, and length.
- Repeat tests and rule out normal application variation.
Remediation
Use parameterized queries, enforce authorization server-side, validate expected input formats, and implement consistent error handling.
B. Time-based Blind SQL Injection
Definition: The tester observes whether a database operation causes a measurable delay, rather than relying on visible query output.
For example, some database engines provide delay functions such as MySQL's SLEEP(). A controlled lab can use a harmless delay to test whether a parameter influences query execution.
Identification
- Measure baseline response times.
- Compare requests with and without a controlled delay condition.
- Repeat measurements to account for network latency and server load.
- Correlate timing with the tested input.
Remediation
Use parameterized queries, restrict database permissions, monitor unusual query patterns, and apply appropriate query execution limits.
5. Out-of-band SQL Injection (OOB SQLi)
Definition: OOB SQLi occurs when a database interaction produces a signal or transfers data over a channel separate from the application's normal response—for example, a DNS or HTTP interaction.
Example scenario
- An application has an SQL Injection flaw.
- The database server has a feature capable of making an external network request.
- A controlled monitoring endpoint observes an unexpected DNS or HTTP callback.
- The tester correlates the callback with the test request.
How to identify
- Use only a controlled callback domain or endpoint.
- Monitor DNS/HTTP interactions.
- Correlate timestamps and test inputs.
- Check database outbound network access.
Impact
Potential information disclosure or data extraction, including where the application does not display query results.
Remediation
- Use parameterized SQL queries.
- Restrict outbound database network access.
- Disable unnecessary database network functionality.
- Apply least privilege and monitor outbound traffic.
6. Second-order SQL Injection
Definition: Second-order SQLi occurs when untrusted input is stored and later reused unsafely in another SQL query. The unsafe execution may happen in a later workflow, not when the input is first submitted.
Example scenario
- A user submits a profile field.
- The application stores the value in the database.
- Later, an administrative function retrieves that value.
- The retrieved value is concatenated into a new SQL statement without parameterization.
Why it happens
Developers may incorrectly assume that data already stored in their own database is trusted. Stored user input remains untrusted.
How to identify
- Map fields that persist user-controlled data.
- Trace where stored values are retrieved and reused.
- Test downstream workflows in an authorized environment.
- Review the relevant query construction and data flow.
Impact and remediation
Potential unauthorized data access or modification. Parameterize every query—including queries that use stored values—and validate data according to its intended use.
| First-order SQLi | Second-order SQLi |
|---|---|
| Input is executed during the initial request. | Input is stored and executed unsafely later. |
| Usually immediate. | Delayed and workflow-dependent. |
| Often easier to reproduce. | Requires tracing data flow across features. |
7. Stacked Queries SQL Injection
Definition: Stacked queries occur when an input can cause multiple SQL statements to be processed in one database interaction. Whether this is possible depends on the database, driver, and application configuration.
SELECT * FROM users WHERE id = 10;
SELECT * FROM products;
How to identify
- Understand the database engine and driver.
- Review whether multiple statements are enabled.
- Validate behaviour only in a controlled test environment.
Impact
Depending on permissions, additional statements could enable unauthorized data modification or deletion.
Remediation
- Use parameterized queries.
- Disable multi-statement execution when unnecessary.
- Apply least-privilege database permissions.
- Avoid dynamic SQL construction.
8. Other SQL Injection variations and contexts
| Variation | Explanation |
|---|---|
| Numeric-based SQLi | Injection context is a numeric parameter, such as an ID. |
| String-based SQLi | Injection context is a string parameter, such as a username or search term. |
| Authentication-bypass SQLi | Manipulation of login query logic may bypass authentication. |
| LIKE-based SQLi | Unsafe construction of a SQL LIKE expression. |
| ORM-related SQLi | Unsafe raw queries or dynamically constructed ORM expressions. |
| XML-derived SQLi | XML-derived input is unsafely incorporated into an SQL query. |
| DNS-based SQLi | An out-of-band technique using DNS interactions. |
These labels describe different input contexts, implementation patterns, or techniques. They are not all separate top-level SQLi categories.
9. Practical SQLi testing workflow
- Identify input parameters: URL parameters, request bodies, headers, cookies, search fields, login forms, and API parameters.
- Capture requests: Use Burp Suite to inspect requests and responses.
- Perform initial checks: Use harmless special-character and input variations in scope.
- Classify behaviour: Look for errors, reflected results, Boolean differences, timing differences, or controlled external callbacks.
- Validate: Reproduce the issue and eliminate false positives.
- Assess impact: Determine what data or operations are exposed, without exceeding authorization.
- Report: Include evidence, root cause, impact, severity, and remediation.
10. Tools used for SQL Injection testing
| Tool | Purpose |
|---|---|
| Burp Suite | Manual testing and HTTP request manipulation. |
| SQLmap | Automated detection and validation in authorized environments. |
| OWASP ZAP | Web application security testing and scanning. |
| Browser Developer Tools | Inspect application requests and responses. |
| Database logs | Investigate query execution and errors. |
| PortSwigger Web Security Academy | Practice SQLi concepts in intentionally vulnerable labs. |
11. How to prevent SQL Injection
1. Parameterized queries / prepared statements
Vulnerable PHP pattern:
$query = "SELECT * FROM users WHERE username = '$username'";
Safer PHP PDO example:
$stmt = $pdo->prepare(
"SELECT * FROM users WHERE username = :username"
);
$stmt->execute([
'username' => $username
]);
The query structure is defined separately from the supplied value. The database treats the username as data rather than SQL syntax.
2. Input validation
Validate according to expected format: IDs should be integers, quantities should be within valid ranges, and email fields should follow the application's requirements. Validation is useful but does not replace parameterized queries.
3. Least privilege
Give the application's database account only the permissions required for its tasks. A read-only feature should not have unnecessary UPDATE or DELETE permissions.
4. Secure error handling
Do not expose SQL statements, database credentials, stack traces, or internal database details to users. Log diagnostics securely on the server.
5. Avoid unsafe dynamic SQL
Do not concatenate untrusted values into SQL. For dynamic table or column identifiers—which usually cannot be bound as ordinary parameters—use strict allowlists.
12. Important SQL Injection interview questions
- What is SQL Injection?
- What is the root cause of SQL Injection?
- Explain the major types of SQL Injection.
- What is the difference between error-based and UNION-based SQLi?
- What is the difference between Boolean-based and time-based SQLi?
- What is out-of-band SQL Injection?
- What is second-order SQL Injection?
- What is the difference between first-order and second-order SQLi?
- What are stacked queries?
- What is the difference between UNION and UNION ALL?
- What is the difference between SQL Injection and NoSQL Injection?
- How do you test SQLi in REST APIs?
- How do you test SQLi in login functionality?
- Can SQL Injection happen through HTTP headers and cookies?
- Can SQL Injection occur in an application using an ORM?
- Does input validation completely prevent SQL Injection?
- How do prepared statements prevent SQL Injection?
- How would you report SQL Injection to a client?
- What is the business impact of SQL Injection?
- How would you test SQL Injection if database errors are disabled?
13. SQLi knowledge check
Choose an answer for each question, then submit to see your score and explanations.
Comments
Post a Comment