SQL Injection¶
SQL injection is a type of cyber attack where the attacker manipulates SQL queries to gain unauthorized access to a database or retrieve sensitive information.
How SQL Injection Works¶
When using a web application, SQL queries are typically pre-generated by the application, and the user only has control over the input fields. An attacker exploits this by providing specially crafted inputs to manipulate the SQL query.
Key Concepts¶
- User Input Control:
The attacker focuses on the user input fields to inject malicious SQL code. - Manipulating SQL Queries:
By injecting specific inputs, the attacker can manipulate the SQL query to always returnTRUE, bypassing authentication mechanisms.
Example of SQL Injection¶
Consider a login form where the SQL query is:
An attacker might input:
- Username:
admin' OR '1'='1 - Password:
anything
The resulting query becomes:
Since 1='1' is always true, the query bypasses authentication, granting unauthorized access.
Preventing SQL Injection¶
To mitigate SQL injection attacks:
- Use parameterized queries or prepared statements.
Avoid directly concatenating user inputs into SQL queries. For example, instead of:
Use parameterized queries or prepared statements, such as:
- Validate and sanitize user inputs.
- Employ web application firewalls (WAF).
- Regularly update and patch your database and application.
SQL Injection Types¶
Error Based SQL Injection¶
Attackers intentionally cause the database to throw errors by modifying the SQL query in a way that leads to a database exception. The goal is to gather valuable information from the error message, such as database structure, user information, or other sensitive data.
- UNION SQL Injection: The UNION operator is used to combine the results of the original query with the results from another SELECT query. Attackers can exploit this by adding a forged query to extract data from other tables.
Blind SQL Injection¶
Description: When error messages are not displayed or the attacker doesn't receive any feedback from the query, they must infer the result using boolean conditions or time delays. Blind SQLi can be categorized into:
-
Boolean-based Blind SQLi: Attackers use logical conditions (TRUE/FALSE) to determine if the query is returning true or false.
-
Time-Based Blind SQLi: Attackers use time delays (WAITFOR DELAY) to infer whether a query is true based on the delay in the server's response.
SQL Injection Methodology¶
- Information Gathering
- Launch SQL Injection Attacks
- Advanced SQL Injection
SQL injection is a critical vulnerability that can lead to severe consequences if not addressed properly. Always follow secure coding practices to protect your applications.