A “SQL injection” (SQLI) attack is an exploit that takes advantage of poor web development techniques and, typically combined with, faulty database security. The result of a successful attack can range from impersonating a user account to a complete compromise of the respective database or server. Unlike a DDoS attack, an SQLI attack is completely and easily preventable if a web application is appropriately programmed.
Executing the attack
Whenever you login to a web site and enter your user name and password, in order to test your credentials the web application may run a query like the following:
SELECT UserID FROM Users WHERE UserName='myuser' AND Password='mypass';
Note: string values in a SQL query must be enclosed in single quotes which is why they appear around the user entered values.
So the combination of the entered user name (myuser) and password (mypass) must match an entry in the Users table in order for a UserID to be returned. If there is no match, no UserID is returned so the login credentials are invalid. While a particular implementation may differ, the mechanics are pretty standard.
So now let’s look at a template authentication query which we can substitute the values the user enters on the web form:
SELECT UserID FROM Users WHERE UserName='[user]’ AND Password='[pass]’
At first glance this may seem like a straightforward and logical step for easily validating users, however if a simple substitution of the user entered values is performed on this template, it is susceptible to an SQLI attack.
For example, suppose “myuser’–” is entered in the user name field and “wrongpass” is entered in the password. Using simple substitution in our template query, we would get this:
SELECT UserID FROM Users WHERE UserName='myuser'--' AND Password='wrongpass'
A key to this statement is the inclusion of the two dashes (--)
. This is the begin comment token for SQL statements, so anything appearing after the two dashes (inclusive) will be ignored. Essentially, the above query is executed by the database as:
SELECT UserID FROM Users WHERE UserName='myuser'
The glaring omission here is the lack of the password check. By including the two dashes as part of the user field, we completely bypassed the password check condition and were able to login as “myuser” without knowing the respective password. This act of manipulating the query to produce unintended results is a SQL injection attack.