#!/usr/bin/php
<?php

/*

In neueren Versionen von fail2ban:
fail2ban-client set sasl unbanip 217.229.23.103

*/

$out = array();
exec('iptables -L -n', $out, $code);

if ($code != 0) {
	echo "Fehler in iptables -L -n (code $code)\n";
	exit(1);
}

/*
Chain fail2ban-vts-suhosin (1 references)
target     prot opt source               destination
DROP       all  --  119.188.46.42        0.0.0.0/0
DROP       all  --  94.223.182.126       0.0.0.0/0
*/

$cur_chain = '';

if (count($argv) == 1) {
	echo "Syntax: $argv[0] <ip> [<ip2> [...]]\n";
	exit(2);
}

array_shift($argv);

foreach ($argv as $ip) {
	$found = false;
	foreach ($out as $o) {
		if (preg_match("@Chain (.*) @U", $o, $m)) {
			$cur_chain = $m[1];
		} else if (preg_match("@DROP .* ".preg_quote($ip, '@').' @U', $o, $m)) {
			$found = true;
			echo "Sperre fuer $ip in chain $cur_chain entfernt: ";
			$out2 = array();
			exec('iptables -D '.escapeshellarg($cur_chain).' -s '.escapeshellarg($ip).' -j DROP', $out2, $code2);
			if ($code2 == 0) {
				echo "OK";
			} else {
				echo "Fehler (code $code2)";
			}
			echo "\n";
		}
	}
	if (!$found) {
		echo "IP $ip not listed as banned.\n";
	}
}

