What is SQL injection?
SQL injection is an attack that allows malicious actors to inject malicious code in the database commands run by an SQL server. This commonly occurs because the vulnerable server fails to "sanitize" the inputs for special characters, which allows user input to be interpreted as code.
Why is it dangerous?
Because the vulnerability allows the malicious actor to execute any code they wish, this allows them to bypass login processes, steal stored data, tamper with the data, or delete the data altogether.
How does it work under the hood?
When you try to log in on the server, it runs a query on its database looking for a match. If such a match exists, you are logged in. For example, if you were to login with u5ername:pAssw0rd as your credentials, the query would be:
SELECT * FROM logins WHERE
username = 'u5ername' AND password = 'pAssw0rd'
(For easier comprehension, user input is marked in bold and underlined, strings are in green, SQL keywords in blue, and SQL operators in brown, SQL comments are marked in grey.)
The query shown above would only evaluate to true if there is a user called u5ername
with password pAssw0rd
in the user database. As useful as it is for the user, it does very little for us, the attackers.
So, how to exploit it?
The first challenge starts easy: the server is defenseless against SQL injection. This allows us to showcase the classic SQL injection (SQLi) attack: commenting. When a user attempts to log in, the server does a query looking for a user with a matching username and password given by the user. By commenting out part of the query as demonstrated below, the attacker can remove the requirement of a matching password by commenting it out.
By using the username u5ername/*'
and an empty password, we get the query
SELECT * FROM logins WHERE
username =
'u5ername'/* ' ' AND password = ''
As shown above, the greyed out part is commented out by the /*
. This causes the rest of the query to be ignored, and thus the query matches any user with the username u5ername
and does not check the password. As an attacker that does not know the password, this attack allows us to log in regardless as the user u5ername
.