=^.^=

Remote Controlled Netfilter with httpd, iptables and sudo

For a more secure and robust method of executing commands remotely, please see Part Six of my Mass Virtual Hosting series.

Is your web server behind a Linux firewall? Have you ever wanted to quickly make a ban at the firewall level from within your site? This extremely simple script will help you accomplish just that.

ClearOS users please see this article instead.

Requirements:

  • A linux router/firewall
  • Netfilter and iptables
  • An httpd capable of running PHP
  • PHP
  • Probably sudo

Selecting and configuring your httpd goes beyond the scope of this article. I recommend lighttpd but apache works just as well for a slightly higher memory footprint. For obvious reasons, make sure the web server is only reachable from the private network.

It's important to point out here that we're talking about exposing a service with root access to iptables on your firewall; this is not without great risk and you must take every precaution to secure and restrict access to the web daemon.

Once you have your httpd configured and running install riptables.php somewhere in the default host's document root. Load it in your web browser. If you get a '0' in the page body the script is running properly. In most cases you will need to add a line to sudoers that grants your httpd access to your iptables binary.  Open sudoers thus:

# visudo

and add this line, replacing apache with the account your httpd runs under and /sbin/iptables with the full path to your iptables binary (some systems, including ClearOS, replace /sbin/iptables with a shell script; use /sbin/iptables-bin instead):

apache ALL=(root) NOPASSWD: /sbin/iptables

Save sudoers and open riptables.php. Adjust the configuration variables to reflect your environment. Depending on your system you may need to seed the logfile to give your httpd write access:

# touch /var/log/riptables.log
# chown httpd: /var/log/riptables.log

where httpd is the account your web daemon runs under. Save the script and do a test run; from a root shell on your router type:

# iptables-save | grep "222.222.222.222"

You should see no results. Load the following URL into your browser, replacing the appropriate parts such as IP address:

http://192.168.0.1/riptables.php?action=deny&ip=222.222.222.222

If your browser loaded a '1' then the block was added successfully. Run the iptables-save line again. You should see:

-A INPUT -s 222.222.222.222 -j DROP
-A FORWARD -s 222.222.222.222 -j DROP
-A OUTPUT -d 222.222.222.222 -j DROP

If so everything is in working order. If not, check your log. Remove the block thus:

http://192.168.0.1/riptables.php?action=remove&ip=222.222.222.222

An additional mechanism for authentication, which comes in handy if the IP(s) you have granted access run multiple web apps, is the shared secred. Put a passphrase into the $shared_secret variable, then when you call the script from your webapp append the key variable with an md5'd hash of the secret.
The script can be called from within your web application by crafting a GET request or as simply as running wget:

exec("wget -O - 'http://$fw_address/riptables.php?action=$action&ip=$ip' >/dev/null 2>&1");

Download riptables.php here.

Note that IP chain rules are followed in order. If there is an ACCEPT rule for 0.0.0.0/0 before the rules this script adds they must be removed or it will not work.

< ?php
/*
           # Remote Controlled iptables
           # June 2010 http://foxpa.ws/
           # WTFPL v.2 http://foxpa.ws/wtfpl/

/// DOCUMENTATION

DANGER: This script requires sudo and an httpd in most environments.
        If you don't know why that's dangerous, you don't want to use this
        script.

DANGER: Improperly configured, this script could be used by an attacker to
        block legitimate traffic.

This script blocks, allows or removes an IP as passed to it through the GET
variables "ip" and "action." Valid action values are block, allow, remove.
The script will exit with a 0 on any error or a 1 on a successful execution.

To block an IP, one would GET request it thus:
   http://server-address/riptables.php?action=block&ip=222.222.222.222
On a successful block you would receive HTTP headers and a single 1 in the
body, or a 0 if the block was unsuccessful.

To grant httpd access to iptables you may need to edit sodoers to reflect:
apache ALL=(root) NOPASSWD: /sbin/iptables
where apache is whatever account your web daemon of choice runs under.

$whitelist is an array of IP addresses that should never be blocked
$allowed_clients should be an array of IP addresses allowed to have access to
this script. leave it blank to allow any host (not recommended).
$shared_secret is an optional key that can be passed to the script as an MD5
hash via GET var "key" to authenticate your application. Blank to disable.
$sudo_path should be the complete path to your sudo binary. Leave blank
if you do not require sudo.
$iptables_path should be set to reflect your system's configuration. Typical
locations include /sbin and /usr/sbin. Be sure to leave off the trailing slash.
$iptables_bin shoild be the name of your iptables binary, usually just iptables
except on systems where it has been replaced with a shell script.
$log_path should be the path to the specific file you would like to log actions
to. Blank to disable logging. Remember to update your log rotater's config.
*/

// CONFIGURATION
$whitelist = array();
$allowed_clients = array();
$shared_secret = '';
$sudo_path = '/usr/bin/sudo';
$iptables_path = '/sbin';
$iptables_bin = 'iptables';
$log_path = '/var/log/riptables.log';

// FUNCTIONS
function log_action($line)
{
	global $log_path, $remote_addr;
	if(!empty($log_path))
	{
		$fh = fopen($log_path, 'a');
		$date = date("Y-m-d H:i:s", time());
		fwrite($fh, "$date $remote_addr - $line\n");
		fclose($fh);
	}
}

function ip_deny($ip)	// This function drops all packets from an IP
{
	global $sudo_path, $iptables_path, $iptables_bin;
	$string1 = "$sudo_path $iptables_path/$iptables_bin -A INPUT -s $ip -j DROP";
	$string2 = "$sudo_path $iptables_path/$iptables_bin -A FORWARD -s $ip -j DROP";
	$string3 = "$sudo_path $iptables_path/$iptables_bin -A OUTPUT -d $ip -j DROP";
	exec($string1, $output1, $return1);
	exec($string2, $output2, $return2);
	exec($string3, $coutput3, $return3);
	if($return1 != 0 or $return2 != 0 or $return3 != 0) // Check for non-zero exit status
	{
		log_action("Attempted to block $ip but failed. Error:\nString1: $string1\nOutput1: {$output1[0]}\nString2: $string2\nOutput2: {$output2[0]}\nString3: $string3\nOutput3: {$output3[0]}\n");
		return 0;
	}
	else
	{
		log_action("$ip was blocked.");
		return 1;
	}
}

function ip_accept($ip) // This function explicitly allows an address, useful where DROP is default
{
	global $sudo_path, $iptables_path, $iptables_bin;
	$string1 = "$sudo_path $iptables_path/$iptables_bin -A INPUT -s $ip -j ACCEPT";
	$string2 = "$sudo_path $iptables_path/$iptables_bin -A FORWARD -s $ip -j ACCEPT";
	$string3 = "$sudo_path $iptables_path/$iptables_bin -A OUTPUT -d $ip -j ACCEPT";
	exec($string1, $output1, $return1);
	exec($string2, $output2, $return2);
	exec($string3, $coutput3, $return3);
	if($return1 != 0 or $return2 != 0 or $return3 != 0) // Check for non-zero exit status
	{
		log_action("Attempted to accept $ip but failed. Error:\nString1: $string1\nOutput1: {$output1[0]}\nString2: $string2\nOutput2: {$output2[0]}\nString3: $string3\nOutput3: {$output3[0]}\n");
		return 0;
	}
	else
	{
		log_action("$ip was accepted.");
		return 1;
	}
}

function ip_remove($ip) // This function undelicately removes a block or explicit accept from an IP
{
	global $sudo_path, $iptables_path, $iptables_bin;
	exec("$sudo_path $iptables_path/$iptables_bin -D INPUT -s $ip -j DROP");
	exec("$sudo_path $iptables_path/$iptables_bin -D FORWARD -s $ip -j DROP");
	exec("$sudo_path $iptables_path/$iptables_bin -D OUTPUT -d $ip -j DROP");
	exec("$sudo_path $iptables_path/$iptables_bin -D INPUT -s $ip -j ACCEPT");
	exec("$sudo_path $iptables_path/$iptables_bin -D FORWARD -s $ip -j ACCEPT");
	exec("$sudo_path $iptables_path/$iptables_bin -D OUTPUT -d $ip -j ACCEPT");
	log_action("$ip was removed.");
	return 1;
}

// SANITY CHECKING
if(!empty($_GET['ip']))
	$ip = $_GET['ip'];
else
	die('0');
$remote_addr = $_SERVER['REMOTE_ADDR'];
$octets = explode('.', $ip);
foreach($octets as $octet)
{
	if($octet > 255 or $octet < 0)
	{
		log_action("Invalid IP Address $ip");
		die('0');
	}
}
$ip = escapeshellcmd($ip);
if(!empty($shared_secret) and $_GET['key'] != md5($shared_secret))
{
	log_action("DANGER Invalid shared secret. Remember to encrypt your key variable with MD5.");
	die('0');
}
if(!empty($allowed_clients[0]))
{
	$valid = false;
	foreach($allowed_clients as $allowed)
	{
		if($allowed = $remote_addr)
			$valid = true;
	}
	if(!$valid)
	{
		log_action("DANGER Client is not in \$allowed_hosts array. This could be a sign of exposure.");
		die('0');
	}
}

// THE BRAINS
if($_GET['action'] == 'deny')
{
	foreach($whitelist as $whiteip)
	{
		if($ip == $whiteip)
			die('0');
	}
	ip_remove($ip);
	print(ip_deny($ip));
}
elseif($_GET['action'] == 'accept')
{
	ip_remove($ip);
	print(ip_accept($ip));
}
elseif($_GET['action'] == 'remove')
{
	ip_remove($ip);
	print('1');
}
else
{
	log_action('Invalid action parameter.');
	die('0');
}

?>

Comments

[...] my last post I shared a scriptlet that could be used to remote block access to your network with apache, sudo and iptables. This [...]