OWASP 2013 A1: SQL Injection
A bug described in 1998 is still the fastest way into a database.
SQL injection is a security vulnerability in which an application builds a database query out of user input, so the user can change what the query does. It is the most damaging form of Injection, which is number one on the 2013 OWASP Top 10. It was described publicly in 1998. It topped the list in 2010, it tops it again this year, and it still turns up in applications whose owners were sure they had fixed it years ago.
This piece is for the developer who has heard the term a hundred times and still has one query somewhere built out of strings. I want to show exactly how the attack works, what it has cost real companies, and why the fix is simpler than the folklore around it.
What the bug is
A SQL query is a program. When your application builds that program by gluing user input into it, the user is writing part of your program.
$sql = "SELECT id FROM users WHERE username = '" . $_POST['user'] .
"' AND password = '" . $_POST['pass'] . "'";
$result = mysql_query($sql);
The developer imagined input like alice and hunter2. The attacker sends this as the username:
' OR '1'='1' --
The query the database receives is:
SELECT id FROM users WHERE username = '' OR '1'='1' -- ' AND password = '...'
Everything after -- is a comment. '1'='1' is always true. The query returns the first user in the table, usually the administrator, and the application logs the attacker in as that user. No password needed.
That is the beginner’s version. The versions that matter use the same opening to read whole tables:
' UNION SELECT username, password_hash FROM users --
or to find out, one true-or-false question at a time, what the database contains even when the application never displays query results. Tools automate this. An attacker with a single injectable parameter and an afternoon can usually walk away with the entire database.
When the page shows nothing
Developers often tell me a form cannot be injectable because it never shows database output. It only says “Thank you” or “Not found”. That changes nothing for the attacker. It only changes how they ask.
Asking true or false questions. If the page behaves one way when the query finds a row and another way when it does not, the attacker can attach a condition and read the answer from the page:
/product.php?id=7 AND SUBSTRING((SELECT password_hash FROM users WHERE id=1),1,1)='a'
If product 7 still appears, the first character of the administrator’s hash is a. If not, try b. It sounds slow. A tool does it in minutes, one character at a time, with a binary search over each character.
Asking with time. If the page looks identical either way, the attacker makes the database wait when the answer is yes:
/product.php?id=7 AND IF(SUBSTRING(@@version,1,1)='5', SLEEP(5), 0)
On MySQL, a five second delay means version 5. SQL Server has WAITFOR DELAY and PostgreSQL has pg_sleep for the same purpose. There is no error to hide and no output to suppress. The response time is the output.
The point for defenders: hiding error messages is good practice, but it is not a defense against injection. It slows down the beginner and does nothing to the tool.
Three cases
Heartland Payment Systems, 2008. One of the largest card processors in the United States. Attackers used SQL injection on a web application to get a foothold, then moved into the network that handled card transactions. About 130 million card numbers were taken. The federal indictment filed in 2009 names SQL injection as the entry point not only for Heartland but for 7-Eleven and Hannaford as well. A web form was the front door to the payment network.
Sony Pictures, 2011. In June 2011, the group LulzSec said it had taken more than a million user records from Sony Pictures websites through a single SQL injection, and posted a large sample. The passwords were stored in plain text. Their statement at the time was blunt: a single injection in a web form had handed them everything. Two bugs compounded each other: the injection that opened the database, and the plaintext storage that made the contents immediately usable.
Yahoo Voices, 2012. In July 2012, about 450,000 usernames and passwords from Yahoo’s Voices service were posted publicly. The attackers used a union-based injection, the same technique as my second example above, and again the passwords were in plain text. The group that did it said they intended it as a warning. The accounts worked on other sites, because people reuse passwords, which is why a breach at one site is a breach at many.
In all three, the entry point was a web form that a developer had built by concatenating strings. Nothing exotic.
Why escaping is not the fix
The first thing most developers reach for is escaping: wrap the input in a function that adds backslashes before quotes.
$user = mysql_real_escape_string($_POST['user']);
$sql = "SELECT id FROM users WHERE username = '$user'";
This is better than nothing and it is still wrong, for three reasons.
It only works where the input is inside quotes. Numeric fields are usually not quoted:
$sql = "SELECT * FROM orders WHERE id = " . mysql_real_escape_string($_GET['id']);
Input of 1 OR 1=1 has no quotes to escape and the query returns every order.
It depends on the connection’s character set. There are documented cases where a multibyte character set lets an attacker smuggle a quote past the escaping function.
And it depends on every developer remembering, on every query, forever. One forgotten call and the whole database is open. A defense that fails when one person is tired is not a defense.
The fix
Parameterized queries. Also called prepared statements or bound parameters. The query is sent to the database with placeholders; the values are sent separately; the database never has a chance to confuse one for the other.
PHP, with PDO, its built-in database layer:
$stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? AND password_hash = ?");
$stmt->execute([$_POST['user'], $hash]);
$row = $stmt->fetch();
Java:
PreparedStatement ps = conn.prepareStatement(
"SELECT id FROM users WHERE username = ? AND password_hash = ?");
ps.setString(1, user);
ps.setString(2, hash);
ResultSet rs = ps.executeQuery();
Python, with psycopg2:
cur.execute("SELECT id FROM users WHERE username = %s AND password_hash = %s",
(user, hash))
Note the Python example: the %s is a placeholder handled by the driver, not string formatting. The moment someone writes "... %s" % user instead, the protection is gone. Same characters, opposite result.
An input of ' OR '1'='1 into a parameterized query is a username that happens to contain quotes. The database looks for a user literally named that, finds none, and returns nothing. The attack has nowhere to go.
Two things parameters cannot do, and where I still find bugs:
Table and column names cannot be parameters. If the application lets the user choose a sort column, map the input to a fixed list of allowed names in code; never put the raw value into the query.
Stored procedures are not automatically safe. A procedure that builds a query from its arguments with string concatenation is injectable from inside the database.
Second-order injection
This one survives code reviews, because the dangerous query looks like it uses trusted data.
A user registers with the name admin'--. The registration code uses a parameterized query, so the name is stored safely, exactly as typed. Weeks later, a password change feature reads the name back from the database and builds a new query with it:
$name = $row['username']; // came from our own database, so "safe"
$sql = "UPDATE users SET password_hash = '$newHash' WHERE username = '$name'";
The query the database receives is ... WHERE username = 'admin'--'. The comment cuts off the rest, and the attacker has just changed the administrator’s password.
Data from your own database is not trusted data. It is user input that has been resting. The rule is the same for every query: values go in as parameters, whatever their source.
The places it hides
Most teams fix the login form and the search box. These are the inputs I find still concatenated afterwards:
- Sort order and column names.
ORDER BYcannot take a parameter, so developers paste the value in. Map it to a fixed list instead. - Lists of IDs. A filter that takes several IDs is often built as
WHERE id IN (plus a joined string. Generate one placeholder per value. - Cookies and headers. Tracking code that logs the
User-Agentor a referral cookie into a table, built with string concatenation. - Admin and reporting screens. Internal pages get less review, and they usually run with a more powerful database account.
- Batch jobs. Imports that read a supplier’s file and insert each row with a built query. The file is user input too.
The layers around it
Parameterized queries end injection. The layers below reduce the damage if someone misses one.
Least privilege for the database account. The web application’s database user should be able to read and write the tables the application uses, and nothing else. No DROP, no access to other schemas, no file system functions. Many of the worst outcomes in the cases above came from an application account that could do anything.
Store passwords so that a stolen table is useless. Sony and Yahoo turned an injection into a catastrophe by storing passwords in plain text. A slow, salted hash (bcrypt, scrypt) means a stolen table still has to be cracked, one password at a time.
Do not rely on a web application firewall. A firewall in front of an injectable application is a filter that attackers test against until they find the encoding it does not understand. The firewall hides the bug from your scanner, not from the attacker. Fix the code.
Finding it in your own application
Search your code for the patterns. In PHP, any mysql_query, mysqli_query or $pdo->query call whose argument is built with . or string interpolation. In Java, any Statement (as opposed to PreparedStatement) with a + in the query. In Python, any execute whose first argument uses % or .format() on user input.
Then test, not just read. For each input the application takes, including hidden fields, cookies and HTTP headers, send a single quote and watch for a database error or a changed response. Automated scanners do this well, and so does a tester with a list of inputs and an afternoon.
The bug is fifteen years old. The fix has been in every major database driver for a decade. The only thing left to do is use it everywhere, with no exceptions, and to check.
Checklist
- Every query uses parameters for every value, whatever the source of the value.
- Table names, column names and sort orders come from a fixed list in code.
- The application’s database account can touch only the tables it needs.
- Passwords are stored with a slow, salted hash.
- Error pages show nothing about the database, and nobody counts that as the fix.
- Every input, including cookies, headers and hidden fields, has been tested with a single quote and a time delay.