Logging SQL Injections and XSS Through .htaccess

Posted by Jetlogs @ 10:12 am
Category: Web Development

I’ve recently found a very interesting and useful article from The Hacker Webzine on how to filter and log SQL Injections and Cross-site Scripting by using Apache’s .htaccess in this article.

From the article, you need to insert these lines to your .htaccess

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{QUERY_STRING} ("|%22).*(>|%3E|<|%3C).* [NC]
RewriteRule ^(.*)$ log.php [NC]
RewriteCond %{QUERY_STRING} (<|%3C).*script.*(>|%3E) [NC]
RewriteRule ^(.*)$ log.php [NC]
RewriteCond %{QUERY_STRING} (javascript:).*(;).* [NC]
RewriteRule ^(.*)$ log.php [NC]
RewriteCond %{QUERY_STRING} (;|'|"|%22).
*(union|select|insert|drop|update|md5|benchmark|or|and|if).* [NC]
RewriteRule ^(.*)$ log.php [NC]
RewriteRule (,|;|<|>|'|`) /log.php [NC]

What this basically does is that apache will redirect all URLs with unsafe request URI’s into your logging script. As for how you log these attempts, it is completely up to you. You can either store the details into a database, a flat text file, or mail the hack attempt (last resort, you don’t want to be mail bombed). But here is what a sample logging script might look like:

$agent = $_SERVER['HTTP_USER_AGENT'];
$uri = $_SERVER['REQUEST_URI'];
$ip = $_SERVER['REMOTE_ADDR'];
$referer = $_SERVER['HTTP_REFERER'] ? $_SERVER['HTTP_REFERER'] : "NONE";
$date = date('r');

$log =
"$date - IP: $ip | Agent: $agent  | URL: $uri | Referer: $referer \\n";

//Save to database assuming you are already connected to your database
$agent_clean = mysql_real_escape_string($agent, ENT_QUOTES);
$uri_clean = mysql_real_escape_string($uri, ENT_QUOTES);
$referer_clean = mysql_real_escape_string($referer, ENT_QUOTES);
$query = "INSERT INTO `logs`(date, IP, Agent, URL, Referer)
	VALUES('$date','$ip','$agent_clean','$uri_clean','$referer_clean')";

//Save to a flat file named log.txt
$handle = fopen("log.txt", "a");
fputs($handle, $log);
fclose($handle);

//mail to your email address

//if your email is going to be formatted as an HTML mail, use
//htmlentities() on the log message
mail("admin@site.com", "Injection Attempt", $log, "from:bot@site.com");

However, don’t be too confident in using this as your sole filter as this will only filter MOST vectors, but not all of them. Always remember that Web Security is a multi-tiered approach and care with inputs must always be done at each layer


No Comments »

No comments yet.

RSS Comment Feed Comments RSS |trackback TrackBack URI

Leave a comment

  • Archives

  • Donations

  • Social Bookmarks

  • Jetlogs.org
    Some Rights Reserved 2007
    Creative Commons License