<?php

/*

iptables stats
by Eric O'Callaghan

You need to have GeoIP working with PHP:
http://www.maxmind.com/app/php

This just shows what country (using GeoIP) and destination ports are most popular in iptables.log

This cron job should make an IP:PORT text file from your iptables.log every 10 minutes, so that this PHP script can read it
0,10,20,30,40,50 * * * * cat /var/log/iptables.log | grep TCP | awk {'print $9 $19'} | sed 's/SRC=//' | sed 's/DPT=/:/' | grep -v WINDOW | sort -n > /var/www/iptables.txt

This is strictly for IPv4; IPv6 is not supported
UDP traffic from iptables.log is not counted at all
If logrotate or whatever swaps out the iptables.log, it's obviously going to affect your stats

*/

// Get the GeoIP class going
require_once "Net/GeoIP.php";
$geoip Net_GeoIP::getInstance("/usr/share/GeoIP/GeoIP.dat");

// Set filename of logged connections
$file "/var/www/iptables.txt";

// Throw a fatal error if the file can't be opened
if (@is_readable($file)) {
    
$fh fopen($file"r");
    
$data file($file);
} else {
    die(
"cannot read $file");
}

// Get the date the file was last edited
$asof date("Y-m-d @ g:i:s A T"filemtime($file));

// Loop through each line of the file
for ($n 0$n count($data); $n++) {

    
// Pull apart the IP address and port number
    
$line explode("\n"$data[$n]);
    
$conn explode(":"$line[0]);
    
$ip $conn[0];
    
$port $conn[1];

    
// Get the country that corresponds to the IP address
    
$country $geoip->lookupCountryName($ip);

    
// Count up the values per country/port in two arrays
    
$ccount["$country"]++;
    
$pcount["$port"]++;
}

// Close the log file
fclose($fh);

// Sort the IP and port counter arrays
arsort($ccount);
arsort($pcount);

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>iptables stats</title>
</head>
<body>
<table width="100%">
<tr>
<td align="left"><big><code>iptables stats</code></big></td>
<td align="right"><code><?php echo $asof?></code></td>
</tr>
</table>
<hr>
<table align="center" width="50%">
<tr>
<td align="left">
<table border="1">
<tr>
<td><b>Country</b></td>
<td><b>Total</b></td>
</tr>
<?php

// Loop through and show a table row for each country
foreach ($ccount as $key => $value) {
        echo 
"<tr>\n<td>$key</td>\n<td>$value</td>\n</tr>\n";
}

?>
</table>
</td>
<td align="right">
<table border="1">
<tr>
<td><b>Port Number</b></td>
<td><b>Total</b></td>
</tr>
<?php

// Loop through and show a table row for each port number
foreach ($pcount as $key => $value) {
        echo 
"<tr>\n<td>$key</td>\n<td>$value</td>\n</tr>\n";
}

?>
</table>
</td>
</tr>
</table><br>
<hr>
<table align="center">
<tr>
<td align="center"><code>Total: <?php echo $n?></code></td>
</tr>
</table>
</body>
</html>