Skip to content

Instantly share code, notes, and snippets.

@yllus
Last active August 29, 2015 14:09
Show Gist options
  • Select an option

  • Save yllus/db7060cebb1277e66013 to your computer and use it in GitHub Desktop.

Select an option

Save yllus/db7060cebb1277e66013 to your computer and use it in GitHub Desktop.

SQL String Escaping

Here's an example of using grep to find all instances of the word "insert" (ignoring case):

ssyed@server:~$ cd /var/www/ 
ssyed@server:/var/www$ grep -Ri insert . 
... a whole bunch of results ...
./folder_button/jsinclude_server_com_ccare.php:$query = "INSERT INTO log VALUES(NULL, '$ip', '$hostname', '". $_SERVER['HTTP_REFERER'] ."', '". $data['queue_id'] ."', '". $data['status_id'] ."','". $_SERVER['HTTP_USER_AGENT'] ."');";	
... a whole bunch more results ...

We've identified that the file ./folder_button/jsinclude_server_com_ccare.php contains an INSERT query; let's now wrap that in a sprintf() statement and use mysql_real_escape_string() to ensure all data being entered into that INSERT SQL statement is properly escaped:

$query = sprintf("INSERT INTO log VALUES(NULL, '%s', '%s', '%s', '%s', '%s','%s')",
  mysql_real_escape_string($ip),
  mysql_real_escape_string($hostname), 
  mysql_real_escape_string($_SERVER['HTTP_REFERER']), 
  mysql_real_escape_string($data['queue_id']), 
  mysql_real_escape_string($data['status_id']), 
);

This will work for any type of SQL statement: SELECT, INSERT, UPDATE or DELETE. To find where those queries are being run, you can use grep on each word:

ssyed@server:/var/www$ grep -Ri select . 
ssyed@server:/var/www$ grep -Ri insert . 
ssyed@server:/var/www$ grep -Ri update . 
ssyed@server:/var/www$ grep -Ri delete . 

General Input Sanitation

Here's an example of using grep to find all instances of the word "_server" (ignoring case):

ssyed@server:~$ cd /var/www/ 
ssyed@server:/var/www$ grep -Ri _server . 
... a whole bunch of results ...
./folder_button/jsinclude_server_com_ccare.php:   $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
... a whole bunch more results ...

We've identified that the file ./folder_button/jsinclude_server_com_ccare.php sets the variable $ip to the raw input value of $_SERVER["HTTP_X_FORWARDED_FOR"]; let's instead update that to do the same thing but run through PHP's built in input validation function:

$ip = filter_input(INPUT_SERVER, 'HTTP_X_FORWARDED_FOR', FILTER_SANITIZE_STRING);

You can also filter $_GET and $_POST variables in almost the example same manner (changing just the first parameter for filter_input):

$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_STRING);
$url = filter_input(INPUT_POST, 'url', FILTER_SANITIZE_STRING);

You can actually go a bit further and sanitize more specifically using the other sanitize filters in PHP (see http://php.net/manual/en/filter.filters.sanitize.php ).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment