Last Updated on 25 August 2023 by Daniel

SQL injection is a type of cyber attack where malicious SQL code is inserted into a query, allowing unauthorized access to a database or manipulation of its data. It occurs when user input is not properly sanitized or validated before being used in SQL queries. Here are some examples of SQL injection:
- Classic SQL Injection: Suppose you have a login form with fields for username and password. An attacker might input something like this as the username:bash
‘ OR ‘1’=’1
If the input is not properly sanitized, the resulting SQL query could become:
SELECT * FROM users WHERE username = ” OR ‘1’=’1′ AND password = ‘…’
Since '1'='1'
is always true, this query would allow the attacker to log in without knowing a valid username or password.
Union-based SQL Injection: In cases where the application displays data from the database, an attacker might use a UNION-based attack to retrieve unauthorized data. For instance:
‘ UNION SELECT null, username, password FROM users —
The injected SQL adds a second query that retrieves the username and password from the users
table.
Blind SQL Injection: In this scenario, the attacker doesn’t receive direct data from the database, but can infer information based on application responses. For example:
‘ OR 1=1; — (if application behaves differently when an error occurs) ‘ AND 1=2; — (if application behaves differently when a valid condition is met)
Time-Based Blind SQL Injection: Attackers might induce delays in the application’s response to infer whether the injected condition is true or false. For example:
‘ OR IF(1=1, SLEEP(5), 0); — ‘ OR IF(1=2, SLEEP(5), 0); —
- Second-Order SQL Injection: In this case, the malicious code doesn’t directly affect the database when first injected, but later it is used in a query, causing the injection to execute. This might happen when user input is stored in the database and then used in a query without proper validation.
- Out-of-Band SQL Injection: Attackers might use techniques that rely on out-of-band communication (such as DNS requests or HTTP requests) to extract information from the database.
It’s important to note that SQL injection can have serious consequences, including unauthorized access to sensitive data, data manipulation, and potentially full control over a database. To prevent SQL injection, always validate, sanitize, and use parameterized queries or prepared statements when interacting with databases.