SQL Injection
SQL injection, or SQLi, is a web vulnerability that allows an attacker to interfere with the database queries an application makes.
It usually happens when user input is inserted into SQL queries without safe handling. This can allow attackers to bypass authentication, read sensitive data, modify records, or in severe cases interact with the underlying server.
Warning
Test SQL injection only in authorized labs, bug bounty scopes, or approved assessments.
Overview
Web applications often use databases to store:
- User accounts
- Password hashes
- Sessions
- Orders
- Messages
- Products
- Permissions
- Logs
- Application settings
Applications communicate with relational databases using SQL.
Example query:
SQL injection happens when attacker-controlled input changes the intended query logic.
How Web Apps Use SQL
A login form might accept:
The application may build a query:
If a matching row exists, the application logs the user in.
The problem appears when input is concatenated directly into the query instead of being handled safely.
Authentication Bypass Example
Attacker input:
Possible resulting query:
Why this works in vulnerable logic:
| Part | Purpose |
|---|---|
' |
Closes the original string |
OR 1=1 |
Adds a condition that is always true |
-- - |
Comments out the rest of the query |
The database may return a valid row because 1=1 is always true.
Common SQLi Indicators
SQL injection may be present when input causes database errors or changes behavior unexpectedly.
Signs to look for:
- SQL error messages
- Different responses after adding
' - Login bypass behavior
- Unexpected empty or full result sets
- Time delays after sleep payloads
- Different HTTP status codes
- Different content length
- Database-specific error text
Example test characters:
Note
Error messages are helpful in labs, but real applications may suppress errors. SQLi can still exist without visible errors.
Common Injection Points
SQLi can appear anywhere user input reaches a database query.
Common locations:
| Location | Example |
|---|---|
| URL query parameters | /product?id=1 |
| POST body | username=alice&password=test |
| JSON API body | { "id": 1 } |
| Cookies | TrackingId=abc123 |
| HTTP headers | User-Agent, X-Forwarded-For |
| Search fields | /search?q=laptop |
| Sort parameters | sort=price |
| Filters | category=books |
SQL Comments
Comments are often used to ignore the rest of the original query.
Common SQL comment styles:
| Syntax | Notes |
|---|---|
-- |
Common SQL comment |
-- - |
Often used to ensure spacing |
# |
MySQL comment |
/* comment */ |
Inline block comment |
Example:
Boolean-Based SQLi
Boolean-based SQLi checks whether true and false conditions change the response.
Example true condition:
Example false condition:
If the page behaves differently, the input may be injectable.
Union-Based SQLi
UNION can combine results from another query into the original response.
Conceptual example:
SELECT name, price FROM products WHERE category = 'books'
UNION
SELECT username, password FROM users;
Requirements:
- Same number of columns
- Compatible data types
- Output reflected in the response
Basic testing pattern:
Error-Based SQLi
Error-based SQLi relies on database error messages to reveal information.
Useful errors may disclose:
- Database type
- Table names
- Column names
- Query structure
- Type mismatch details
Example issue:
Warning
Production systems should not expose detailed database errors to users.
Blind SQLi
Blind SQLi occurs when the application does not show query results or useful errors, but behavior still changes based on injected conditions.
Types:
| Type | Description |
|---|---|
| Boolean-based blind | Response changes based on true/false logic |
| Time-based blind | Response delay confirms query execution |
| Out-of-band | Database triggers external interaction |
Time-based example concept:
If the response is delayed, the query may be injectable.
Impact
SQL injection can have serious impact.
Possible outcomes:
- Authentication bypass
- Reading sensitive data
- Dumping user tables
- Modifying records
- Deleting data
- Accessing password hashes
- Bypassing business logic
- Reading database metadata
- Gaining administrative access
- Remote code execution in some configurations
Database Enumeration Concepts
After confirming SQLi in an authorized lab, enumeration often follows this order:
- Identify database type.
- List databases.
- List tables.
- List columns.
- Extract selected data.
- Validate impact safely.
Common database metadata locations:
| DBMS | Metadata Source |
|---|---|
| MySQL | information_schema |
| PostgreSQL | information_schema, pg_catalog |
| MSSQL | information_schema, sys |
| Oracle | all_tables, all_tab_columns |
| SQLite | sqlite_master |
Prevention
The main defense is parameterized queries, also called prepared statements.
Unsafe pattern:
Safer conceptual pattern:
The query structure is separated from user-controlled values.
Defensive Practices
Use multiple layers of defense:
- Parameterized queries
- Server-side input validation
- Least-privilege database accounts
- Safe error handling
- Avoid dynamic SQL where possible
- Strong password hashing
- Logging and monitoring
- Web application firewall as defense-in-depth
- Secure ORM usage
- Regular testing
Important
Manual escaping is not a replacement for parameterized queries.
Testing Checklist
When testing for SQLi:
- Identify inputs that may reach the database.
- Test with quotes and special characters.
- Compare normal, true, and false conditions.
- Watch for errors, redirects, content-length changes, and timing differences.
- Test GET, POST, JSON, cookies, and headers.
- Use tools carefully after manual confirmation.
- Avoid destructive payloads.
- Document exact request and response evidence.
Quick Reference
| Goal | Example Concept |
|---|---|
| Break string | ' |
| Always true condition | ' OR 1=1-- - |
| Boolean true test | ' AND 1=1-- - |
| Boolean false test | ' AND 1=2-- - |
| Column count testing | UNION SELECT NULL... |
| Time delay testing | SLEEP(5) |
| Main defense | Parameterized queries |
Notes to Remember
- SQLi changes the logic of database queries.
- Authentication bypass is a common beginner example.
- SQLi can affect GET, POST, JSON, cookies, and headers.
- Visible errors are helpful but not required.
- Blind SQLi relies on behavior or timing.
- SQLMap can automate testing but must be used carefully.
- Parameterized queries are the primary defense.
- Database users should follow least privilege.