Pin Me

SQL Injection

written by: Strobe•edited by: Michele McDonough•updated: 11/15/2008

When programming a script that accesses a database, it’s important to keep security in mind. SQL injection attacks are one of the most common attacks on SQL databases such as MSSQL and MySQL.

  • slide 1 of 1

    For an attacker to overtake a website with an SQL injection attack, all he or she may need is a web browser and a hand crafted URL typed in to do loads of damage to a web server. Because the attack is relatively simple, it is often used excessively by not so experienced crackers.

    An SQL Injection attacks happens because variables that are passed across scripts are not filtered properly. These variables are then used in a database call and are stored as an SQL statement. Once this takes place the vulnerable script executes the SQL statement and sends the parameters that were entered in the URL field to the database. Look at the following examples for more clarification:

    http://www.mysite.com/login.php?user=tom&pass=none

    Now in a normal situation, this would try and login the user “tom” with the password “none”. Now our SQL statement would look similar to this:

    $sql = “SELECT * FROM `users` WHERE `user` = ‘“ . $user . “’ AND `pass` = ‘“ . $pass .”’ “ ;

    or

    $sql = “SELECT * FROM `users` WHERE `user` = ‘tom’ AND `pass`=’none’”;

    Now in this statement we don’t do any sort of checking to make sure that the variables actually held the expected values which are a user name and password. What if our URL looked like this:

    http://www.mysite.com/login.php?user=tammy&pass=’%20OR%201=1

    Now our statement would like this once the variables are parsed:

    $sql = “SELECT * FROM `users` WHERE `user` = ‘tammy’ AND `pass` =’’ OR 1=1”;

    Now in this example, no matter what the user entered as their username or password, the SQL statement will return true because we included the 1=1, which is pretty straight forward, one does equal one.

    While the SQL examples shown are very simple and would probably not work on any scripts written in the past few years, the concept of SQL injections stays the same. A malicious user can hack a website with just entering text in the URL field. Imagine if we included a DELETE command on the SQL statement without a LIMIT argument? The entire database would be erased without warning. SQL injection attacks can also be used to gain administrator access to a website.

    It’s important when you are programming, that you take extra care with user input. Not filtering user input is one of the main reasons why SQL injection attacks succeed. There are many other ways SQL injection attacks take place with other characters and such, but the main thing to remember with these attacks is they all have one common denominator. And that is that user input was not filtered correctly. So filter user input in your scripts for security.