Basic SQL Injection Tutorial
In my time I’ve seen a few pieces of insecure code. Considering what clients can pay for a bespoke eCommerce or CMS solution, you’d expect at least a basic level of security. Unfortunately there’s one oversight that crops up time and again. The SQL Injection vulnerability. Despite being a huge threat to your security, SQL injection holes are simple to prevent.
Trusting anything the client sends is a bad idea. ALWAYS assume the worst and sanitise GET or POST variables before using in an SQL call. Below is an example of some code that you may use when a user logs in:
1 2 3 4 5 6 7 8 | $username = $_POST['username']; $password = $_POST['password']; $sql = "SELECT id FROM users WHERE username='$username' AND password='$password' "; $query = mysql_query($sql); $id = mysql_fetch_array($query); if($id) {... |
The code above compares the username and password (submitted from a standard HTML form) to the database. If both match, then the script would go on to log the user in. The actual SQL call made to the database may look something like this:
1 | SELECT id FROM users WHERE username='johnsmith' AND password='mypass' |
Now, rather than ‘johnsmith’, should the username contain the following…
1 | johnsmith'# |
The entire SQL call made to the database would look like so…
1 | SELECT id FROM users WHERE username='johnsmith'#' AND password='mypass' |
Since MySQL treats everything after the hash (#) symbol as a comment, it’s actually only checking the username and not the password. The hacker can now log in as John without knowing the password! Even worse, the hacker need only guess the username of the administrator to log in as him too!
This is SQL injection in it’s most basic form. It can easily be worked on to spit out sensitive data to the screen, insert new rows (user accounts), delete data, edit data and more.
A simple solution to this problem would simply be to use PHP’s addslashes() function like so:
1 | $sql = "SELECT id FROM users WHERE username='". addslashes($username) ."' AND password='". addslashes($password) ."' "; |
Being the egotistical git I am, I wanted my phone to make a ‘kerching’ sound each time I made an affiliate sale. Nothing beats dozing off on a lazy Sunday evening and hearing your cash register ring out. Here’s how I made it happen…
If, like me, you spend all day staring at a Dreamweaver code screen, you may have given thought to your eyesight and the steps you take to preserve it.