Nov
20

Test Your Protection Against SQL Injection with PHP

AddThis Social Bookmark Button

As we discussed in previous articles, an important part of keeping your scripts secure is to test them for protection against possible vulnerabilities.

The best way to make certain that you have protected yourself against injection is to try it yourself, creating tests that attempt to inject SQL code. For help and guidance in this task, you will probably find it useful to consult the amusing and revealing detailed instructions on just how to carry out an injection exploit, which can be found at http://www.issadvisor.com/columns/SqlInjection3/sql-injection-3-exploit-tables_files/frame.htm and http://www.imperva.com/application_defense_center/white_papers/blind_sql_server_injection.html. Here we present a sample of such a test, in this case testing for protection against injection into a SELECT statement.

  1. <?php
  2.    // protection function to be tested
  3.    function safe( $string ) {
  4.    return "’" . mysql_real_escape_string( $string ) . "’"
  5.    }
  6.    // connect to the database
  7.    ///////////////////////
  8.    // attempt an injection
  9.    ///////////////////////
  10.    $exploit = "lemming’ AND 1=1;";
  11.    // sanitize it
  12.  $safe = safe( $exploit );
  13.  $query = "SELECT * FROM animals WHERE name = $safe";
  14.  $result = mysql_query( $query );
  15.  // test whether the protection has been sufficient
  16.  if ( $result &amp;&amp; mysql_num_rows( $result ) == 1 ) {
  17.  exitt "Protection succeeded:\n
  18. exploit $exploit was neutralized.";
  19.  }
  20.  else {
  21.  exit( "Protection failed:\n
  22. exploit $exploit was able to retrieve all rows." );
  23.  }
  24. ?>

If you were to create a suite of such tests, trying different kinds of injection with different SQL commands, you would quickly detect any holes in your sanitizing strategies. Once those were fixed, you could be sure that you have real protection against the threat of injection.

AddThis Social Bookmark Button

1 Comment

Comments RSS Feed   TrackBack URL

Sorry, the comment form is closed at this time.