Skip to content

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:

SELECT *
FROM users
WHERE username = 'alice';

SQL injection happens when attacker-controlled input changes the intended query logic.


How Web Apps Use SQL

A login form might accept:

Username: John
Password: Un@detectable444

The application may build a query:

SELECT *
FROM users
WHERE username = 'John'
AND password = 'Un@detectable444';

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:

Username: John
Password: abc' OR 1=1;-- -

Possible resulting query:

SELECT *
FROM users
WHERE username = 'John'
AND password = 'abc' OR 1=1;-- -';

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:

' OR 1=1-- -

Boolean-Based SQLi

Boolean-based SQLi checks whether true and false conditions change the response.

Example true condition:

' AND 1=1-- -

Example false condition:

' AND 1=2-- -

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:

' UNION SELECT NULL-- -
' UNION SELECT NULL,NULL-- -
' UNION SELECT NULL,NULL,NULL-- -

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:

You have an error in your SQL syntax near...

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:

' OR SLEEP(5)-- -

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:

  1. Identify database type.
  2. List databases.
  3. List tables.
  4. List columns.
  5. Extract selected data.
  6. 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:

SELECT *
FROM users
WHERE username = '$username'
AND password = '$password';

Safer conceptual pattern:

SELECT *
FROM users
WHERE username = ?
AND password = ?;

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.