Introduction to SQL Injection (SQLi)¶
SQL Injection (SQLi) is a code injection technique used to attack data-driven applications. It occurs when an attacker inserts or "injects" a malicious SQL query via the input data from the client to the application.
A successful SQLi exploit can read sensitive data from the database, modify database data (Insert/Update/Delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file present on the DBMS file system, and in some cases, issue commands to the operating system.
Core Cause¶
SQLi vulnerabilities are primarily caused by the insecure practice of concatenating user-supplied input directly into SQL statements.
Vulnerable Code Example (PHP):
<?php
$userId = $_GET['id']; // User-controlled input
$query = "SELECT * FROM users WHERE id = '" . $userId . "';"; // Direct concatenation
$result = mysqli_query($conn, $query);
?>
1' OR '1'='1, the query becomes SELECT * FROM users WHERE id = '1' OR '1'='1';, which will return all users. Types of SQL Injection¶
SQLi attacks are broadly categorized based on the method used to exfiltrate data.
-
In-Band SQLi (Classic SQLi): The attacker uses the same communication channel to launch the attack and gather results.
- Error-Based SQLi
- Union-Based SQLi
-
Inferential SQLi (Blind SQLi): The attacker sends data payloads and observes the web application's response and behavior to learn about the structure of the database.
- Boolean-Based Blind SQLi
- Time-Based Blind SQLi
-
Out-of-Band SQLi: The attacker can only exfiltrate data through a different channel (e.g., DNS or HTTP requests to an external server). This is covered in Advanced SQLi.