Midwest Web Development: Professional Web Developer's blog

 

SQL injection by example


 

SQL injection by example

Today I was working on a project for my day job which involved an ajax call to a database. A user inputs a zip code into a form text box and once 3 digits are entered, Javascript fires off a request to a PHP script which fires off a call to a MySQL database to see if there is a match.

I decided to look around the Internet for some example code to jump start. I found the following PHP code.  Seeing sample code like this makes me not only cringe, but makes me want to reach out and slap the developer that wrote it.

if(isset($_POST[queryString]))
{
  $queryString = $_POST[queryString];
  if(strlen($queryString) >0)
  {
    $query = "SELECT blog_tags FROM blog_entry WHERE blog_tags LIKE $queryString% LIMIT 10";
    $result = mysql_query($query) or die("There is an error in database please contact support");
    while($row = mysql_fetch_array($result))
    {
      echo $row[blog_tags];
    }
  }
}

This code would allow any attacker to inject SQL code into the query string, thus allowing them to run commands in your MySQL database.  They can do so simply by sending POST data like:

' OR 1; SELECT * FROM mysql.User

Scary, eh?  Using this code I can easily view all users in your MySQL database.

#1 Rule of Web Application Programming:  NEVER trust user input.
This includes POST data, GET data, COOKIES, etc --- basically anything that your script is reading from the client side.

SQL injection is simple to protect against.  PHP has built in functions to do so (addslashes(), mysql_real_escape_string(), etc.)  PHP also has the ability to use prepared statements, which automatically escape/filter any user input.

Simply put, if you take on the mindset that any one sending any sort of data to your program is a potential hacker, you will write more secure code.

More information on SQL injections can be found at OWASP's website
 

 

posted Tuesday, October 20, 2009 at 08:11:24 AM

Comments On This Entry   [ Add ]

Compose New Blog Comment



    required = required field         warning HTML and URL's are not allowed

[back to main]