This tutorial aims to provide an understanding of Time-Based Blind SQL Injections, a subset of SQL Injection vulnerabilities that can affect web applications.
By the end of this tutorial, you will be able to:
Before proceeding with this tutorial, you should:
A Time-Based Blind SQL Injection is a type of SQL Injection attack where an attacker can make queries to a database by forcing the application to wait for a specified amount of time, then return a result. The waiting time allows the attacker to infer if the payload used returned true or false, even though no data from the database is returned.
Parameterized Queries: This is a best practice for preventing SQL Injection. It involves pre-compiling SQL statements so that user input is treated as a string literal instead of part of the SQL command.
Input Validation: This is another best practice where user inputs are checked against a set of rules before being processed.
If an application has a SQL Injection vulnerability, an attacker can inject a SQL command like the following:
SELECT * FROM users WHERE username='' OR SLEEP(5)=''; --'
In this scenario, if the application waits for 5 seconds before responding, this indicates that it is vulnerable to time-based blind SQL injection.
To prevent SQL Injection, use parameterized queries. Here is an example using PHP and MySQLi:
$user = $_POST['user'];
$pass = $_POST['pass'];
$stmt = $conn->prepare('SELECT * FROM users WHERE username = ? AND password = ?');
$stmt->bind_param('ss', $user, $pass);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// process rows
}
In this code:
prepare
function is used to compile the SQL statement.bind_param
function is used to bind the user inputs to the SQL statement.execute
function is used to execute the prepared statement.In this tutorial:
To continue your learning, consider studying other types of SQL Injection attacks, as well as other web application vulnerabilities.
Can you identify if the following PHP code is vulnerable to time-based blind SQL injection?
$user = $_POST['user'];
$pass = $_POST['pass'];
$sql = "SELECT * FROM users WHERE username = '$user' AND password = '$pass'";
$result = mysqli_query($conn, $sql);
Rewrite the above PHP code snippet to use parameterized queries.
Yes, the code is vulnerable to time-based blind SQL injection. It directly includes user inputs in the SQL query.
Here is the code rewritten to use parameterized queries:
$user = $_POST['user'];
$pass = $_POST['pass'];
$stmt = $conn->prepare('SELECT * FROM users WHERE username = ? AND password = ?');
$stmt->bind_param('ss', $user, $pass);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// process rows
}
Continue practicing by identifying vulnerable code snippets and rewriting them to use parameterized queries.