SQL Injection

SQL injection vulnerabilities are one of the most common and most damaging vulnerabilities out there. A small opening would enable an attacker to extract every piece of data in the database. It is a subset of a vulnerabilities associated with unsanitised user inputs. The idea is to get the server to run SQL that has been specially crafted by the attacker.

Here’s a good kit to practice. Follow the instructions and you’ll be able to perform the attack without any special tools. Just some basic understanding on the web and you’re good to go.

Further reading:

How it works

The root cause is always the same move: building a SQL statement by gluing strings together, so data supplied by the user ends up inside the code the database executes. A login form that does this:

SELECT * FROM users WHERE username = '$user' AND password = '$pass'

stops checking passwords the moment someone types ' OR '1'='1 into the username field, because the statement the database now runs is:

SELECT * FROM users WHERE username = '' OR '1'='1' AND password = '...'

'1'='1' is true for every row, so the query matches a user and the login passes. The attacker never needed a password, they needed quotes.

Reading data out works the same way. An UNION SELECT bolted onto a query lets the attacker append their own columns to the result set, and the information_schema tables describe every table and column in the database, so the attacker can walk the schema first and then pull the rows they want, one query at a time. The PentesterLab exercise above walks you from one injected quote all the way to a shell on the box.

The fix

Separate code from data. Prepared statements send the SQL and the values in two pieces, so the database parses the statement before the values exist and there is nothing left to inject:

db.exec_params("SELECT * FROM users WHERE username = $1 AND password = $2", [user, pass])

An ORM does this for you as long as you stay off its raw query escape hatches. Give the application’s database user the least privilege it can live with, because when a query does slip through, an account that can read one schema turns a total compromise into a bad afternoon.