Friday, February 26, 2010

Active Apache Defense

Running a web-server that is publicly accessible will quickly get one familiar with the onslaught of attempts to find vulnerable web applications on that site. Whether they are individual attackers, scripted scans, or just someone poking around, it's traffic you dont need and a source that you want nothing to with.. or rather, you want them to have nothing to do with your system.

This method, which was created with some collaboration with a peer of mine at school (who solved a huge security hole in it.. that whole escaping shell commands thing, pretty important), uses the apache mod_rewrite engine and a php/shell script combo to dynamically add iptables rules when specified urls are loaded against your server, the vast majority of the time a potential attacker will be banned before they even realize what happened.

First, create the php script, this one is about three revisions of tweaking and seems to work quite effectively...

testBan.php:

$banme=$_SERVER['REMOTE_ADDR'];
$myFile="ban.txt";
$fh = fopen($myFile, 'a') or die("Can't Open File");
fwrite($fh, $banme);
fwrite($fh, "\n");
fclose($fh);
$e = escapeshellcmd($banme);
system("/var/www/localhost/htdocs/sec/ignore.sh $e");
echo "

Security Violation: The IP Address $banme has been logged and added to the blacklist";

The echo is really for debugging purposes, there is no real need to let someone know that they've been banned.


ignore.sh:
#!/bin/bash

for i in $(cat ignorefile); do
    if [ $1 == $i ]
    then exit
    fi
done

sudo iptables -A INPUT -s $1 -j APACHE
echo $1 >> ignorefile
 
That iptables rule sends the traffic to a chain called APACHE, I like to direct it there for logging purposes, you could just as easily drop or reject the traffic outright.
Next, create or add to a .htaccess file in your web root directory and create rewrite rules based on the kind of access attempts you notice to be common. Collecting a group of these common attempts is pretty easy, just grep your apache error log for " 404 " and you will see large groups of attempts to find things like roundcube or phpmyadmin.

a basic mod_rewrite setup for looks like this:

RewriteEngine On
RewriteRule ^phpmyadmin/ /sec/testBan.php [R=301,L]
RewriteRule ^roundcube/ /sec/testBan.php [R=301,L]
RewriteRule ^XMBforum/ /sec/testBan.php [R=301,L]
RewriteRule ^webmail/ /sec/testBan.php [R=301,L]


There are plenty of more complex regex based rewrites you could use to trap even more attempts, these are just a simple example. Make sure none of your rewrites match a legitimate site URL or you'll end up blocking welcome traffic accidentally.

0 comments:

Post a Comment