How Does SQL Injection Work?
123
SQL Injection (SQLi) is a web security vulnerability that allows an attacker to interfere with the
queries that an application makes to its database. This can enable an attacker to view, modify,
or delete data that they are not normally able to access.
Mechanism of SQL Injection
SQL injection works by inserting or "injecting" malicious SQL code into an entry field for
execution. This can manipulate the database in unintended ways. Here’s a simplified example to
illustrate how SQL injection works:
Normal SQL Query
Consider a web application that allows users to log in with a username and password. The
application might use the following SQL query to check the credentials:
SELECT * FROM users WHERE username = 'user' AND password = 'pass';
If the user inputs valid credentials, the query returns the user details.
SQL Injection Attack
An attacker can exploit this by entering malicious input. For example, if the attacker
enters admin'-- as the username and leaves the password blank, the query becomes:
SELECT * FROM users WHERE username = 'admin'--' AND password = '';
The -- sequence is a comment in SQL, which means the rest of the query is ignored. This
effectively bypasses the password check and logs the attacker in as the admin.
Types of SQL Injection Attacks
Retrieving Hidden Data: Modify a query to return additional results. For example:
SELECT * FROM products WHERE category = 'Gifts' OR 1=1;
Subverting Application Logic: Change a query to interfere with the application's logic.
For example, bypassing login checks as shown above.
UNION Attacks: Retrieve data from different database tables. For example:
' UNION SELECT username, password FROM users--
Blind SQL Injection: Exploit SQL injection vulnerabilities where the results of the query
are not returned in the application's responses. Techniques include triggering time
delays or out-of-band network interactions.
Preventing SQL Injection
Parameterized Queries: Use prepared statements to ensure that user input is treated as
data and not executable code. For example, in Java:
PreparedStatement statement = [Link]("SELECT * FROM products
WHERE category = ?");
[Link](1, input);
ResultSet resultSet = [Link]();
Escaping User Input: Escape special characters in user input to prevent them from being
interpreted as SQL commands.
Stored Procedures: Use stored procedures to encapsulate SQL queries and limit the risk
of SQL injection.
Least Privilege: Limit database permissions to the minimum necessary for the
application to function.
By understanding how SQL injection works and implementing these preventive measures, you
can protect your applications from this common and dangerous vulnerability.