├── .gitattributes ├── www ├── .htaccess ├── foot.php ├── header.php ├── mindate.php ├── head.php ├── head-r.php ├── charthitsperhour.php ├── chartblocksperhour.php ├── chartblocksperday.php ├── ipmap.php ├── charttotalblocksperday.php ├── head-gr.php ├── mapdata.php ├── charthitsperdaycombined.php ├── blocks-ps.php ├── head-g.php ├── ptr.php ├── dialtodayblocks.php ├── dialtodayrepeats.php ├── charthitsperday.php ├── datepicker.php ├── reban-country.php ├── reban-br.php ├── dialtodayhits.php ├── release-country.php ├── config.php ├── release-br.php ├── release-date.php ├── reban-date.php ├── safe-unmark.php ├── release-ip.php ├── duplicates.php ├── safe-mark.php ├── stylesheet.css ├── reban-ip.php ├── blocks.php ├── repeats-ip-day.php ├── release-country-view.php ├── reban-br-view.php ├── ids.php ├── reban-country-view.php ├── repeats-ip.php ├── release-br-view.php ├── blocks-view.php ├── release-date-view.php ├── reban-date-view.php ├── repeats-date.php ├── release-iprange.php ├── reban-iprange.php ├── repeats.php ├── repeats-view.php ├── search-date.php ├── release.php ├── charthitsperweekcombined.php ├── reban.php ├── search.php └── functions.php ├── Events ├── CommonCode.vbs └── Config.INI ├── hmsRetroAddPTR.ps1 ├── hmsRetroConsolidateRules.ps1 ├── hmsRetroAddBlocksIPTable.ps1 ├── hmsRetroAddRuleName.ps1 ├── Config.ps1 ├── hmsFirewallBanDBSetup.ps1 ├── hmsConsolidateRules.ps1 ├── hmsDuplicateRuleFinder.ps1 ├── BlockCount.ps1 └── hmsConsolidateRulesMonthly.ps1 /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /www/.htaccess: -------------------------------------------------------------------------------- 1 | order deny,allow 2 | deny from all 3 | allow from 127.0.0.1 4 | allow from 192.168.1 -------------------------------------------------------------------------------- /www/foot.php: -------------------------------------------------------------------------------- 1 | 2 |

3 | 4 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /www/header.php: -------------------------------------------------------------------------------- 1 |
2 | 3 | 8 |
9 | -------------------------------------------------------------------------------- /www/mindate.php: -------------------------------------------------------------------------------- 1 | prepare(" 7 | SELECT 8 | ".DBCastDateTimeFieldAsDate('timestamp')." AS date 9 | FROM hm_fwban 10 | ".DBLimitRowsWithOffset(DBCastDateTimeFieldAsDate('timestamp'),'ASC',0,0,0,1) 11 | ); 12 | $sql->execute(); 13 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 14 | echo "'".$row['date']."',"; 15 | } 16 | ?> -------------------------------------------------------------------------------- /Events/CommonCode.vbs: -------------------------------------------------------------------------------- 1 | Function IsMySQL() : IsMySQL = False 2 | If ConfigIni.GetKeyValue("hMailServer","DatabaseType") = "MySQL" Then 3 | IsMySQL = True 4 | End If 5 | End Function 6 | 7 | Function IsMSSQL() : IsMSSQL = False 8 | If ConfigIni.GetKeyValue("hMailServer","DatabaseType") = "MSSQL" Then 9 | IsMSSQL = True 10 | End If 11 | End Function 12 | 13 | Function DBGetCurrentDateTime() 14 | DBGetCurrentDateTime = "" 15 | If (IsMySQL() = True) Then 16 | DBGetCurrentDateTime = "NOW()" 17 | Elseif (IsMSSQL() = True) Then 18 | DBGetCurrentDateTime = "GETDATE()" 19 | End if 20 | End Function -------------------------------------------------------------------------------- /www/head.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | hMailServer Firewall Ban 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
-------------------------------------------------------------------------------- /www/head-r.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | hMailServer Firewall Ban 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
-------------------------------------------------------------------------------- /www/charthitsperhour.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 22 | -------------------------------------------------------------------------------- /www/chartblocksperhour.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 22 | -------------------------------------------------------------------------------- /www/chartblocksperday.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 27 | -------------------------------------------------------------------------------- /www/ipmap.php: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /www/charttotalblocksperday.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 27 | -------------------------------------------------------------------------------- /www/head-gr.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | hMailServer Firewall Ban 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 |
-------------------------------------------------------------------------------- /www/mapdata.php: -------------------------------------------------------------------------------- 1 | prepare(" 6 | SELECT 7 | COUNT(DISTINCT(country)) AS count 8 | FROM hm_fwban 9 | "); 10 | $sql->execute(); 11 | $countcountries = $sql->fetchColumn(); 12 | 13 | echo "data.addRows(".$countcountries.");"; 14 | echo "data.addColumn('string', 'Country');"; 15 | echo "data.addColumn('number', 'Blocked IPs');"; 16 | 17 | $sql = $pdo->prepare(" 18 | SELECT 19 | country, 20 | COUNT(country) AS count 21 | FROM hm_fwban 22 | GROUP BY country 23 | "); 24 | $sql->execute(); 25 | $N=0; 26 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 27 | if (($row['country']===NULL)||($row['country']=="")||($row['country']=="NOT FOUND")) { 28 | echo "data.setValue(".$N.", 0, 'Nowhereland".$N."');"; 29 | echo "data.setValue(".$N.", 1, 0);"; 30 | } else { 31 | echo "data.setValue(".$N.", 0, '".$row['country']."');"; 32 | echo "data.setValue(".$N.", 1, ".$row['count'].");"; 33 | } 34 | $N++; 35 | } 36 | ?> 37 | -------------------------------------------------------------------------------- /www/charthitsperdaycombined.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 34 | -------------------------------------------------------------------------------- /Events/Config.INI: -------------------------------------------------------------------------------- 1 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 2 | ; _ _ _ _ _ _ _ ____ ____ ____ _ _ ____ ____ ; 3 | ; |__| |\/| /_\ | | [__ |___ |__/ | | |___ |__/ ; 4 | ; | | | |/ \| |___ ___] |___ | \ \/ |___ | \ ; 5 | ; ____ _ ____ ____ _ _ _ _ _ _ ___ _ _ _ ; 6 | ; |___ | |__/ |___ | | | /_\ | | |__] /_\ |\ | ; 7 | ; | | | \ |___ |_|_|/ \|___ |___ |__]/ \| \| ; 8 | ; ; 9 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 10 | ; ; 11 | ; ############# USER VARIABLES ############## ; 12 | ; ; 13 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 14 | 15 | [hMailServer] 16 | AdminUser=Administrator 17 | AdminPassword=supersecretpassword 18 | EventDir=C:\Program Files (x86)\hMailServer\Events 19 | LogDir=C:\Program Files (x86)\hMailServer\Logs 20 | TempDir=C:\Program Files (x86)\hMailServer\Temp 21 | idsTable=hm_ids 22 | DatabaseType=MySQL -------------------------------------------------------------------------------- /www/blocks-ps.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 |
5 |

Block List Analyzer

6 | 7 |
"; 13 | echo "
"; 14 | echo " "; 15 | echo "
"; 16 | } elseif(isset($_POST["submit"])) { 17 | $script_command = "Powershell.exe -ExecutionPolicy Bypass -File ".$PowershellScriptDir."BlockCount.ps1"; 18 | pclose(popen("start /B ". $script_command, "r")); 19 | 20 | echo "Script execution initiated. You may continue browsing the web admin. You will receive an email with the results shortly.

"; 21 | echo "Script Location: ".$PowershellScriptDir."BlockCount.ps1"; 22 | } else { 23 | echo "Script running. Please check your email in a few minutes."; 24 | } 25 | ?> 26 | 27 |
-------------------------------------------------------------------------------- /www/head-g.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | hMailServer Firewall Ban 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
-------------------------------------------------------------------------------- /www/ptr.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | hMailServer Firewall Ban 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 |
15 | 16 | prepare(" 23 | SELECT 24 | ".DBCastDateTimeFieldAsDate('timestamp')." AS dateptr, 25 | ban_reason, 26 | helo, 27 | ptr 28 | FROM hm_fwban 29 | WHERE ipaddress = '$ip' 30 | "); 31 | $sql->execute(); 32 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 33 | echo "IP: ".$ip."
"; 34 | echo "PTR: ".$row['ptr']."
"; 35 | echo "HELO: ".$row['helo']."
"; 36 | echo "Ban Reason: ".$row['ban_reason']."
"; 37 | echo "Ban Date: ".$row['dateptr']."
"; 38 | } 39 | ?> 40 | 41 |
42 |
43 | 44 | 45 | -------------------------------------------------------------------------------- /www/dialtodayblocks.php: -------------------------------------------------------------------------------- 1 | 50 | -------------------------------------------------------------------------------- /www/dialtodayrepeats.php: -------------------------------------------------------------------------------- 1 | 50 | -------------------------------------------------------------------------------- /www/charthitsperday.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 44 | -------------------------------------------------------------------------------- /www/datepicker.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /www/reban-country.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 |
";} 21 | else { 22 | $sqlcount = $pdo->prepare(" 23 | SELECT 24 | COUNT(id) AS value_occurrence 25 | FROM hm_fwban 26 | WHERE country LIKE '%{$country}%' AND (flag=1 OR flag=2) 27 | "); 28 | $sqlcount->execute(); 29 | $total_rows = $sqlcount->fetchColumn(); 30 | if ($total_rows > 0) { 31 | echo "
".number_format($total_rows)." hits for ".$country." have been re-banned the firewall.
"; 32 | $sql = $pdo->prepare(" 33 | SELECT id 34 | FROM hm_fwban 35 | WHERE country LIKE '%{$country}%' AND (flag=1 OR flag=2) 36 | "); 37 | $sql->execute(); 38 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 39 | $sql_update = $pdo->exec(" 40 | UPDATE hm_fwban SET flag=3 WHERE id = ".$row['id'] 41 | ); 42 | } 43 | } else { 44 | echo "
Error: No released records for \"".$country."\". Please search release status or check the spelling and try again."; 45 | } 46 | } 47 | ?> 48 |
49 | 50 | -------------------------------------------------------------------------------- /www/reban-br.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 |
";} else { 21 | 22 | $sqlcount = $pdo->prepare(" 23 | SELECT 24 | COUNT(id) AS value_occurrence 25 | FROM hm_fwban 26 | WHERE ban_reason LIKE '{$ban_reason}' AND (flag=1 OR flag=2) 27 | "); 28 | $sqlcount->execute(); 29 | $total_rows = $sqlcount->fetchColumn(); 30 | if ($total_rows > 0) { 31 | echo "
".number_format($total_rows)." hits for ".$ban_reason." have been re-banned to the firewall.
"; 32 | $sql = $pdo->prepare(" 33 | SELECT 34 | id 35 | FROM hm_fwban 36 | WHERE ban_reason LIKE '{$ban_reason}' AND (flag=1 OR flag=2) 37 | "); 38 | $sql->execute(); 39 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 40 | $sql_update = $pdo->exec(" 41 | UPDATE hm_fwban SET flag=3 WHERE id = ".$row['id'] 42 | ); 43 | } 44 | } else { 45 | echo "
Error: No previously released records for \"".$ban_reason."\". Try searching for released records for ".$ban_reason."."; 46 | } 47 | } 48 | ?> 49 |
50 | 51 | -------------------------------------------------------------------------------- /www/dialtodayhits.php: -------------------------------------------------------------------------------- 1 | 62 | -------------------------------------------------------------------------------- /www/release-country.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 |
";} 21 | else { 22 | 23 | $sqlcount = $pdo->prepare(" 24 | SELECT 25 | COUNT(id) AS value_occurrence 26 | FROM hm_fwban 27 | WHERE country LIKE '%{$country}%' AND (flag IS NULL OR flag=3) 28 | "); 29 | $sqlcount->execute(); 30 | $total_rows = $sqlcount->fetchColumn(); 31 | if ($total_rows > 0) { 32 | if($total_rows == 1){$singular="";}else{$singular="s";} 33 | if($total_rows == 1){$singpos="has";}else{$singpos="have";} 34 | echo "
".number_format($total_rows)." hit".$singular." for ".$country." ".$singpos." been released from the firewall.
"; 35 | $sql = $pdo->prepare(" 36 | SELECT 37 | id 38 | FROM hm_fwban 39 | WHERE country LIKE '%{$country}%' AND (flag IS NULL OR flag=3) 40 | "); 41 | $sql->execute(); 42 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 43 | $sql_update = $pdo->exec(" 44 | UPDATE hm_fwban SET flag=2 WHERE id=".$row['id'] 45 | ); 46 | } 47 | } else { 48 | echo "
Error: No unreleased records for \"".$country."\". Please search release status or check the spelling and try again."; 49 | } 50 | } 51 | ?> 52 |
53 | 54 | -------------------------------------------------------------------------------- /www/config.php: -------------------------------------------------------------------------------- 1 | 'mysql', 24 | 'host' => 'localhost', 25 | 'username' => 'hmailserver', 26 | 'password' => 'supersecretpassword', 27 | 'dbname' => 'hmailserver', 28 | 'driver' => 'mysql', 29 | 'port' => '3306', 30 | 'dsn' => 'MariaDB ODBC 3.0 Driver' 31 | ); 32 | 33 | 34 | /* GeoLite2MySQL - GeoIP Database Using MaxMind Data 35 | https://github.com/palinkas-jo-reggelt/GeoLite2MySQL 36 | 37 | Database Variables follow the same rules as above. 38 | 39 | If GeoLite2MySQL is in use, set 'use_geoip' to 'true'. 40 | 41 | Using a database vs calling ip-api.com for geoip requests will 42 | prevent rate limiting in situations where there are a large number 43 | of calls. Eg. manually banning a /24 IP range with 256 individual 44 | bans - calling 256 geoip requests - exceeding the 150/minute 45 | rate limit at ip-api.com. 46 | 47 | */ 48 | 49 | $GeoIPDatabase = array ( 50 | 'use_geoip' => 'false', 51 | 'dbtype' => 'mysql', 52 | 'host' => 'localhost', 53 | 'username' => 'geoip', 54 | 'password' => 'supersecretpassword', 55 | 'dbname' => 'geoip', 56 | 'driver' => 'mysql', 57 | 'port' => '3306', 58 | 'dsn' => 'MariaDB ODBC 3.0 Driver' 59 | ); 60 | 61 | 62 | /* PowershellScriptDir - Location of project powershell files. */ 63 | 64 | $PowershellScriptDir = "C:\\scripts\\hmailserver\\FWBan\\"; 65 | 66 | ?> -------------------------------------------------------------------------------- /www/release-br.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 |
";} 21 | else { 22 | $sqlcount = $pdo->prepare(" 23 | SELECT 24 | COUNT(id) AS value_occurrence 25 | FROM hm_fwban 26 | WHERE ban_reason LIKE '{$ban_reason}' AND (flag IS NULL OR flag=3) 27 | "); 28 | $sqlcount->execute(); 29 | $total_rows = $sqlcount->fetchColumn(); 30 | if ($total_rows > 0) { 31 | if($total_rows == 1){$singular="";}else{$singular="s";} 32 | if($total_rows == 1){$singpos="has";}else{$singpos="have";} 33 | echo "
".number_format($total_rows)." hit".$singular." for ".$ban_reason." ".$singpos." been released from the firewall.
"; 34 | $sql = $pdo->prepare(" 35 | SELECT 36 | id 37 | FROM hm_fwban 38 | WHERE ban_reason LIKE '{$ban_reason}' AND (flag IS NULL OR flag=3) 39 | "); 40 | $sql->execute(); 41 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 42 | $sql_update = $pdo->exec(" 43 | UPDATE hm_fwban SET flag=2 WHERE id = ".$row['id'] 44 | ); 45 | } 46 | } else { 47 | echo "
Error: No unreleased records for \"".$ban_reason."\". Please search release status or check the spelling and try again."; 48 | } 49 | } 50 | ?> 51 |
52 | 53 | -------------------------------------------------------------------------------- /www/release-date.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 |
";} 22 | elseif (empty($dateTo)){echo "Error: Date range empty. Please see administrator.

";} 23 | else { 24 | $sqlcount = $pdo->prepare(" 25 | SELECT 26 | COUNT(id) AS value_occurrence 27 | FROM hm_fwban 28 | WHERE timestamp BETWEEN '{$dateFrom} 00:00:00' AND '{$dateTo} 23:59:59' AND (flag IS NULL OR flag=3) 29 | "); 30 | $sqlcount->execute(); 31 | $total_rows = $sqlcount->fetchColumn(); 32 | if ($total_rows > 0) { 33 | if($total_rows == 1){$singular="";}else{$singular="s";} 34 | if($total_rows == 1){$singpos="has";}else{$singpos="have";} 35 | echo "
".number_format($total_rows)." hit".$singular." for date range \"".$dateFrom."\" to \"".$dateTo."\" ".$singpos." been released from the firewall.
"; 36 | $sql = $pdo->prepare(" 37 | SELECT 38 | id 39 | FROM hm_fwban 40 | WHERE timestamp BETWEEN '{$dateFrom} 00:00:00' AND '{$dateTo} 23:59:59' AND (flag IS NULL OR flag=3) 41 | "); 42 | $sql->execute(); 43 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 44 | $sql_update = $pdo->exec(" 45 | UPDATE hm_fwban SET flag=2 WHERE id=".$row['id'] 46 | ); 47 | } 48 | } else { 49 | echo "
Error: Date range \"".$dateFrom."\" to \"".$dateTo."\" contains no entries in database. Please try again."; 50 | } 51 | } 52 | 53 | ?> 54 |
55 | 56 | -------------------------------------------------------------------------------- /www/reban-date.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 |
"; 23 | } elseif (empty($dateTo)){ 24 | echo "You did not put in an ending date. Both beginning and ending dates are required for date range release even if the range is a single day.

"; 25 | } else { 26 | 27 | $sqlcount = $pdo->prepare(" 28 | SELECT 29 | COUNT(id) AS value_occurrence 30 | FROM hm_fwban 31 | WHERE timestamp BETWEEN '{$dateFrom} 00:00:00' AND '{$dateTo} 23:59:59' AND (flag=1 OR flag=2) 32 | "); 33 | $sqlcount->execute(); 34 | $total_rows = $sqlcount->fetchColumn(); 35 | if ($total_rows > 0) { 36 | echo "
".number_format($total_rows)." hits for date range \"".$dateFrom."\" to \"".$dateTo."\" have been marked for re-BAN to the firewall.
"; 37 | $sql = $pdo->prepare(" 38 | SELECT 39 | id 40 | FROM hm_fwban 41 | WHERE timestamp BETWEEN '{$dateFrom} 00:00:00' AND '{$dateTo} 23:59:59' AND (flag=1 OR flag=2) 42 | "); 43 | $sql->execute(); 44 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 45 | $sql_update = $pdo->exec(" 46 | UPDATE hm_fwban SET flag=3 WHERE id = ".$row['id'] 47 | ); 48 | } 49 | } else { 50 | echo "
Error: Date range \"".$dateFrom."\" to \"".$dateTo."\" contains no entries in database that were previously released. Please try again."; 51 | } 52 | } 53 | ?> 54 |
55 | 56 | -------------------------------------------------------------------------------- /www/safe-unmark.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | Ban IP Range"; 40 | echo $ipRange." : IP Range

"; 41 | echo $iplo." : Network Address
"; 42 | echo $iphi." : Broadcast Address
"; 43 | echo $ip_count." : Number of IPs in range

"; 44 | echo "Begin Update:

"; 45 | 46 | 47 | if (empty($ipRange)){ 48 | echo "Error: IP range empty. Please see administrator.

"; 49 | } else { 50 | 51 | $start = ip2long($iplo); 52 | for ($i = 0; $i < $ip_count; $i++) { 53 | 54 | $ip = long2ip($start + $i); 55 | 56 | $sql_existing = $pdo->prepare(" 57 | SELECT 58 | id, 59 | ipaddress, 60 | flag 61 | FROM hm_fwban 62 | WHERE ".DBIpStringToIntField('ipaddress')." = ".DBIpStringToIntValue($ip)." 63 | "); 64 | $sql_existing->execute(); 65 | while($row = $sql_existing->fetch(PDO::FETCH_ASSOC)){ 66 | 67 | $ipaddressdb = $row['ipaddress']; 68 | $flag = $row['flag']; 69 | $id = $row['id']; 70 | } 71 | if ($flag=6) { 72 | $sql_rem_safe_six = $pdo->exec(" 73 | UPDATE hm_fwban SET flag=1 WHERE id=".$id 74 | ); 75 | echo "IP ".$ip." removed from SAFE list and updated to RELEASED
"; 76 | } else if ($flag=5) { 77 | $sql_rem_safe_six = $pdo->exec(" 78 | UPDATE hm_fwban SET flag=2 WHERE id=".$id 79 | ); 80 | echo "IP ".$ip." removed from SAFE list and updated to RELEASED status for firewall rule removal
"; 81 | } 82 | $ipaddressdb = ""; 83 | $flag = ""; 84 | $id = ""; 85 | } 86 | } 87 | ?> 88 |
89 | 90 | -------------------------------------------------------------------------------- /www/release-ip.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | Release IP Range"; 40 | echo $ipRange." : IP Range

"; 41 | echo $iplo." : Network Address
"; 42 | echo $iphi." : Broadcast Address
"; 43 | echo $ip_count." : Number of IPs in range

"; 44 | echo "Begin Update:

"; 45 | 46 | 47 | if (empty($ipRange)){ 48 | echo "Error: IP range empty. Please see administrator.

"; 49 | } else { 50 | 51 | $start = ip2long($iplo); 52 | for ($i = 0; $i < $ip_count; $i++) { 53 | 54 | $ip = long2ip($start + $i); 55 | 56 | $sql = $pdo->prepare(" 57 | SELECT 58 | id, 59 | ipaddress, 60 | flag 61 | FROM hm_fwban 62 | WHERE INET_ATON(ipaddress) = INET_ATON('".$ip."') 63 | "); 64 | $sql->execute(); 65 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 66 | $ipaddressdb = $row['ipaddress']; 67 | $flag = $row['flag']; 68 | $id = $row['id']; 69 | } 70 | if (!empty($ipaddressdb)){ 71 | if (!(($flag==1)||($flag==2)||($flag==5)||($flag==6))){ 72 | $sql_update_manban = $pdo->exec(" 73 | UPDATE hm_fwban SET flag=2 WHERE id=".$id 74 | ); 75 | echo "IP ".$ip." marked for release - added to list for firewall rule removal
"; 76 | } else if ($flag==5||$flag=6){ 77 | echo "IP ".$ip." marked SAFE - no action neccessary
"; 78 | } else { 79 | echo "IP ".$ip." previously released - no action neccessary
"; 80 | } 81 | } 82 | $ipaddressdb = ""; 83 | $flag = ""; 84 | $id = ""; 85 | } 86 | } 87 | ?> 88 |
89 | 90 | -------------------------------------------------------------------------------- /hmsRetroAddPTR.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | _ _ _ _ _ _ _ ____ ____ ____ _ _ ____ ____ 3 | |__| |\/| /_\ | | [__ |___ |__/ | | |___ |__/ 4 | | | | |/ \| |___ ___] |___ | \ \/ |___ | \ 5 | ____ _ ____ ____ _ _ _ _ _ _ ___ _ _ _ 6 | |___ | |__/ |___ | | | /_\ | | |__] /_\ |\ | 7 | | | | \ |___ |_|_|/ \|___ |___ |__]/ \| \| 8 | 9 | .SYNOPSIS 10 | Retroactively insert PTR records into database. 11 | 12 | .DESCRIPTION 13 | Adds column "ptr" to database, then checks PTR for each IP in the database and inserts record. 14 | 15 | .FUNCTIONALITY 16 | 1) Fill in user variables 17 | 2) Run script 18 | 19 | .NOTES 20 | Takes a while to run if you have lots of bans in the database. Includes email report. 21 | 22 | .EXAMPLE 23 | 24 | #> 25 | 26 | # Include required files 27 | Try { 28 | .("$PSScriptRoot\Config.ps1") 29 | .("$PSScriptRoot\CommonCode.ps1") 30 | } 31 | Catch { 32 | Write-Output "$((get-date).ToString(`"yy/MM/dd HH:mm:ss.ff`")) : ERROR : Unable to load supporting PowerShell Scripts : $query `n$Error[0]" | out-file "$PSScriptRoot\PSError.log" -append 33 | } 34 | 35 | # Set start time 36 | $StartTime = (Get-Date -f G) 37 | 38 | # Add "ptr" column to hm_fwban 39 | $Query = "ALTER TABLE hm_fwban ADD ptr VARCHAR(192) NULL;" 40 | RunSQLQuery($Query) 41 | 42 | $Query = "SELECT COUNT(ID) AS countnull FROM hm_fwban WHERE ptr IS NULL" 43 | RunSQLQuery($Query) | ForEach { 44 | $CountBeg = $_.countnull 45 | } 46 | 47 | $Query = "SELECT ID, ipaddress FROM hm_fwban WHERE ptr IS NULL" 48 | RunSQLQuery($Query) | ForEach { 49 | $IP = $_.ipaddress 50 | $ID = $_.ID 51 | 52 | Try { 53 | $ErrorActionPreference = 'Stop' 54 | $PTR = [System.Net.Dns]::GetHostEntry($IP).HostName 55 | } 56 | Catch { 57 | $PTR = 'No.PTR.Record' 58 | } 59 | 60 | $Query = "UPDATE hm_fwban SET ptr = '$PTR' WHERE ID = '$ID'" 61 | RunSQLQuery($Query) 62 | } 63 | 64 | $Query = "SELECT COUNT(ID) AS countnull FROM hm_fwban WHERE ptr IS NULL" 65 | RunSQLQuery($Query) | ForEach { 66 | $CountEnd = $_.countnull 67 | } 68 | 69 | If (($CountBeg - $CountEnd) -gt 0){ 70 | $CountRes = "$(($CountBeg - $CountEnd).ToString('#,##0')) PTR records failed insert into database. Check error log." 71 | } Else { 72 | $CountRes = "All $(($CountBeg).ToString('#,##0')) PTR records inserted successfully." 73 | } 74 | 75 | $EndTime = (Get-Date -f G) 76 | $OperationTime = New-Timespan $StartTime $EndTime 77 | If (($Duration).Hours -eq 1) {$sh = ""} Else {$sh = "s"} 78 | If (($Duration).Minutes -eq 1) {$sm = ""} Else {$sm = "s"} 79 | If (($Duration).Seconds -eq 1) {$ss = ""} Else {$ss = "s"} 80 | 81 | $EmailBody = ("Retroactive PTR update complete.`n`nResults: $CountRes `n`nUpdate completed in {0:%h} hour$sh {0:%m} minute$sm {0:%s} second$ss" -f $OperationTime) 82 | EmailResults -------------------------------------------------------------------------------- /www/duplicates.php: -------------------------------------------------------------------------------- 1 | 2 |
3 | prepare(" 16 | SELECT 17 | count(*) AS duplicate_count 18 | FROM ( 19 | SELECT 20 | ipaddress 21 | FROM hm_fwban 22 | GROUP BY ipaddress 23 | HAVING COUNT(ipaddress) > 1 24 | ) AS t 25 | "); 26 | $total_pages_sql->execute(); 27 | $total_rows = $total_pages_sql->fetchColumn(); 28 | $total_pages = ceil($total_rows / $no_of_records_per_page); 29 | 30 | $sql = $pdo->prepare(" 31 | SELECT 32 | ipaddress, 33 | COUNT(ipaddress) AS dupip, 34 | ".DBFormatDate('timestamp', '%Y/%m/%d %T')." AS dupdate, 35 | country, 36 | helo 37 | FROM hm_fwban 38 | GROUP BY ipaddress, ".DBFormatDate('timestamp', '%Y/%m/%d %T').", country, helo 39 | HAVING COUNT(ipaddress) > 1 40 | ".DBLimitRowsWithOffset('dupdate','DESC','dupip','DESC',$offset,$no_of_records_per_page) 41 | ); 42 | $sql->execute(); 43 | 44 | if ($total_rows == 0){ 45 | echo "
No duplicate entries found."; 46 | } else { 47 | echo "
".number_format($total_rows)." Duplicate IP Reports (Page: ".number_format($page)." of ".number_format($total_pages) . ")
"; 48 | echo " 49 | 50 | 51 | 52 | 53 | 54 | 55 | "; 56 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 57 | echo ""; 58 | echo ""; 59 | echo ""; 60 | echo ""; 61 | echo ""; 62 | echo ""; 63 | echo ""; 64 | } 65 | echo "
Last SeenIP AddressCountryHELODuplicates
" . $row['dupdate'] . "".$row['ipaddress']."".$row['country']."".$row['helo']."" . $row['dupip'] . "
"; 66 | if ($total_pages < 2){ 67 | echo ""; 68 | } else { 69 | echo "
    "; 70 | if($page <= 1){echo "
  • First
  • ";} else {echo "
  • First
  • ";} 71 | if($page <= 1){echo "
  • Prev
  • ";} else {echo "
  • Prev
  • ";} 72 | if($page >= $total_pages){echo "
  • Next
  • ";} else {echo "
  • Next
  • ";} 73 | if($page >= $total_pages){echo "
  • Last
  • ";} else {echo "
  • Last
  • ";} 74 | echo "
"; 75 | echo "

"; 76 | } 77 | } 78 | ?> 79 |
80 | -------------------------------------------------------------------------------- /www/safe-mark.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | Release IP Range"; 40 | echo $ipRange." : IP Range

"; 41 | echo $iplo." : Network Address
"; 42 | echo $iphi." : Broadcast Address
"; 43 | echo $ip_count." : Number of IPs in range

"; 44 | echo "Begin Update:

"; 45 | 46 | 47 | if (empty($ipRange)){ 48 | echo "Error: IP range empty. Please see administrator.

"; 49 | } else { 50 | 51 | $start = ip2long($iplo); 52 | for ($i = 0; $i < $ip_count; $i++) { 53 | 54 | $ip = long2ip($start + $i); 55 | 56 | $sql = $pdo->prepare(" 57 | SELECT 58 | id, 59 | ipaddress, 60 | flag 61 | FROM hm_fwban 62 | WHERE ".DBIpStringToIntField('ipaddress')." = ".DBIpStringToIntValue($ip)." 63 | "); 64 | $sql->execute(); 65 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 66 | $ipaddressdb = $row['ipaddress']; 67 | $flag = $row['flag']; 68 | $id = $row['id']; 69 | } 70 | if (!empty($ipaddressdb)){ 71 | if (!(($flag==1)||($flag==2)||($flag==5)||($flag==6))){ 72 | $sql_update_bansafe = $pdo->exec(" 73 | UPDATE hm_fwban SET flag=5 WHERE id=".$id 74 | ); 75 | echo "IP ".$ip." marked banned - updated to SAFE and added to list for firewall rule removal
"; 76 | } else if ($flag==5||$flag=6){ 77 | echo "IP ".$ip." marked SAFE - no action neccessary
"; 78 | } else { 79 | $sql_update_relsafe = $pdo->exec(" 80 | UPDATE hm_fwban SET flag=5 WHERE id=".$id 81 | ); 82 | echo "IP ".$ip." previously released - updated to SAFE status
"; 83 | } 84 | } 85 | $ipaddressdb = ""; 86 | $flag = ""; 87 | $id = ""; 88 | } 89 | } 90 | ?> 91 |
92 | 93 | -------------------------------------------------------------------------------- /www/stylesheet.css: -------------------------------------------------------------------------------- 1 | body { 2 | background: #fefefe; 3 | font-family: "Roboto"; 4 | font-size: 12pt; 5 | } 6 | 7 | a:link, a:active, a:visited { 8 | color: #FF0000; 9 | text-transform: underline; 10 | } 11 | 12 | a:hover { 13 | color: #FF0000; 14 | text-transform: none; 15 | } 16 | 17 | .header { 18 | position: fixed; 19 | top: 0; 20 | left: 0; 21 | width: 100%; 22 | color: #000; 23 | background: #fefefe; 24 | z-index: 1; 25 | overflow: hidden; 26 | text-align:center; 27 | } 28 | 29 | .header h1 { 30 | font-size:25px; 31 | font-weight:normal; 32 | margin:0 auto; 33 | } 34 | 35 | .header h2 { 36 | font-size:15px; 37 | font-weight:normal; 38 | margin:0 auto; 39 | } 40 | 41 | .wrapper { 42 | max-width: 920px; 43 | position: relative; 44 | margin: 30px auto 30px auto; 45 | padding-top: 20px; 46 | } 47 | 48 | .clear { 49 | clear: both; 50 | } 51 | 52 | .banner { 53 | width: 100%; 54 | } 55 | 56 | .headlinks { 57 | max-width: 720px; 58 | position:relative; 59 | margin: 0px auto; 60 | } 61 | 62 | .headlinkwidth { 63 | width: 100%; 64 | min-width: 300px; 65 | position:relative; 66 | margin: 0 auto; 67 | } 68 | 69 | .headlinks a:link, a:active, a:visited { 70 | color: #FF0000; 71 | text-transform: underline; 72 | } 73 | 74 | .headlinks a:hover { 75 | color: #FF0000; 76 | text-transform: none; 77 | } 78 | 79 | .section { 80 | padding: 5px 0 15px 0; 81 | margin: 0; 82 | } 83 | 84 | .section h2 { 85 | font-size:16px; 86 | font-weight:bold; 87 | text-align:left; 88 | } 89 | 90 | .section h3 { 91 | font-size:16px; 92 | font-weight:bold; 93 | } 94 | 95 | .secleft { 96 | float: left; 97 | width: 49%; 98 | padding-right: 3px; 99 | } 100 | 101 | .secright { 102 | float: right; 103 | width: 49%; 104 | padding-left: 3px; 105 | } 106 | 107 | .secmap { 108 | float: none; 109 | width: 920px; 110 | height: 600px; 111 | padding: 0 0 10px 0; 112 | text-align: center; 113 | } 114 | 115 | table.section { 116 | border-collapse: collapse; 117 | border: 1px solid black; 118 | width: 100%; 119 | font-size: 10pt; 120 | } 121 | 122 | table.section tr:nth-child(even) { 123 | background-color: #F8F8F8; 124 | } 125 | 126 | table.section th, table.section td { 127 | border: 1px solid black; 128 | } 129 | 130 | .footer { 131 | width: 100%; 132 | text-align: center; 133 | } 134 | 135 | ul { 136 | list-style-type: none; 137 | padding: 0; 138 | } 139 | 140 | li { 141 | padding: 0; 142 | display: inline; 143 | } 144 | 145 | @media only screen and (max-width: 629px) { 146 | .secleft { 147 | float: none; 148 | width: 100%; 149 | padding: 0 0 10px 0; 150 | text-align: left; 151 | } 152 | .secright { 153 | float: none ; 154 | width: 100% ; 155 | } 156 | .secmap { 157 | float: none; 158 | width: 95%; 159 | height: 220px; 160 | padding: 0 0 10px 0; 161 | text-align: center; 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /www/reban-ip.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | Ban IP Range"; 41 | echo $ipRange." : IP Range

"; 42 | echo $iplo." : Network Address
"; 43 | echo $iphi." : Broadcast Address
"; 44 | echo $ip_count." : Number of IPs in range

"; 45 | echo "Begin Update:

"; 46 | 47 | 48 | if (empty($ipRange)){ 49 | echo "Error: IP range empty. Please see administrator.

"; 50 | } else { 51 | 52 | $start = ip2long($iplo); 53 | for ($i = 0; $i < $ip_count; $i++) { 54 | 55 | $ip = long2ip($start + $i); 56 | 57 | $sql_existing = $pdo->prepare(" 58 | SELECT 59 | id, 60 | ipaddress, 61 | flag 62 | FROM hm_fwban 63 | WHERE ".DBIpStringToIntField('ipaddress')." = ".DBIpStringToIntValue($ip)." 64 | "); 65 | $sql_existing->execute(); 66 | while($row = $sql_existing->fetch(PDO::FETCH_ASSOC)){ 67 | 68 | $ipaddressdb = $row['ipaddress']; 69 | $flag = $row['flag']; 70 | $id = $row['id']; 71 | } 72 | if (empty($ipaddressdb)){ 73 | $sql_new_cidr_ban = $pdo->exec(" 74 | INSERT INTO hm_fwban (timestamp,ipaddress,ban_reason,country) VALUES (".DBGetCurrentDateTime().",'".$ip."','Manual','".$country."')" 75 | ); 76 | echo "IP ".$ip." added to ban list for firewall rule insertion
"; 77 | } else { 78 | if (($flag==1)||($flag==2)){ 79 | $sql_update_manban = $pdo->exec(" 80 | UPDATE hm_fwban SET flag=3 WHERE id=".$id 81 | ); 82 | echo "IP ".$ip." previously released - updating and added to list for firewall rule insertion
"; 83 | } else if (($flag==5)||($flag==6)){ 84 | echo "IP ".$ip." marked SAFE - no action taken
"; 85 | } else { 86 | echo "IP ".$ip." already banned - no action necessary
"; 87 | } 88 | } 89 | $ipaddressdb = ""; 90 | $flag = ""; 91 | $id = ""; 92 | $country = ""; 93 | } 94 | } 95 | ?> 96 |
97 | 98 | -------------------------------------------------------------------------------- /www/blocks.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 |
5 |

Block List Analyzer

6 | Counts the number of Banned IPs that returned and were subsequently blocked by the firewall for a given number of distinct days.

7 | Choose the number of days to run out below. Execution time is high, so start with no more than 10 days before attempting to proceed beyond that. If you run into "exceeded max execution time" errors then run BlockCount.ps1 instead.

8 | How many days to input? 9 |
10 | 23 | 24 |
25 | 26 | prepare(" 34 | SELECT 35 | COUNT(DISTINCT(ipaddress)) 36 | FROM hm_fwban 37 | "); 38 | $tsql->execute(); 39 | $TotalIPs = $tsql->fetchColumn(); 40 | 41 | $nsql = $pdo->prepare(" 42 | SELECT 43 | COUNT(DISTINCT(ipaddress)) 44 | FROM hm_fwban_rh 45 | "); 46 | $nsql->execute(); 47 | $AllReturnIPs = $nsql->fetchColumn(); 48 | 49 | $NeverIPs = ($TotalIPs - $AllReturnIPs); 50 | $PercentNever = sprintf("%.2f%%", ($NeverIPs / $TotalIPs) * 100); 51 | 52 | echo "

"; 53 | echo "Total Number of Firewall Bans: ".number_format($TotalIPs)."

"; 54 | echo "Number of Firewall Bans that have never returned: ".number_format($NeverIPs)." (".$PercentNever.")

"; 55 | 56 | echo " 57 | 58 | 59 | 60 | 61 | "; 62 | 63 | $a = 0; 64 | 65 | If ($days == 0){ 66 | echo ""; 67 | } Else { 68 | do{ 69 | $sql = $pdo->prepare(" 70 | SELECT COUNT(*) AS countips 71 | FROM ( 72 | SELECT 73 | ipaddress, 74 | COUNT(DISTINCT(".DBCastDateTimeFieldAsDate('timestamp').")) AS countdate 75 | FROM hm_fwban_rh 76 | GROUP BY ipaddress 77 | HAVING COUNT(DISTINCT(".DBCastDateTimeFieldAsDate('timestamp').")) > ".$a." 78 | ) AS returnhits 79 | "); 80 | $sql->execute(); 81 | $ReturnIPs = $sql->fetchColumn(); 82 | $PercentReturns = sprintf("%.2f%%", ($ReturnIPs / $TotalIPs) * 100); 83 | echo ""; 84 | echo ""; 85 | echo ""; 86 | If ($a == 0){$sd = "";} Else {$sd = "s";} 87 | echo ""; 88 | echo ""; 89 | 90 | $a++; 91 | 92 | } while($a < $days); 93 | } 94 | 95 | echo "
Number of IPsPercent ReturnsReturned At Least
".number_format($ReturnIPs)."".$PercentReturns."".($a + 1)." day".$sd."
"; 96 | 97 | ?> 98 |
99 | -------------------------------------------------------------------------------- /hmsRetroConsolidateRules.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | _ _ _ _ _ _ _ ____ ____ ____ _ _ ____ ____ 3 | |__| |\/| /_\ | | [__ |___ |__/ | | |___ |__/ 4 | | | | |/ \| |___ ___] |___ | \ \/ |___ | \ 5 | ____ _ ____ ____ _ _ _ _ _ _ ___ _ _ _ 6 | |___ | |__/ |___ | | | /_\ | | |__] /_\ |\ | 7 | | | | \ |___ |_|_|/ \|___ |___ |__]/ \| \| 8 | 9 | .SYNOPSIS 10 | Powershell script to retroactively consolidate firewall rules 11 | 12 | .DESCRIPTION 13 | Consolidates rules from one firewall rule per IP to one firewall rule per day containing all IPs for the queried day 14 | 15 | .FUNCTIONALITY 16 | * Queries database for each day's bans (active firewall rules) 17 | * Creates new firewall rule for each day containing all banned IPs for that day 18 | * Deletes all one-IP-per firewall rules 19 | 20 | .NOTES 21 | * FOR RETROACTIVE USE ONLY - RUN ONLY ONCE 22 | * TO BE USED ONLY ON ACTIVE FIREWALL BAN INSTALLATIONS 23 | * Do not run on fresh installations 24 | * Automatically selects first day through yesterday 25 | 26 | .EXAMPLE 27 | 28 | #> 29 | 30 | # Include required files 31 | Try { 32 | .("$PSScriptRoot\Config.ps1") 33 | .("$PSScriptRoot\CommonCode.ps1") 34 | } 35 | Catch { 36 | Write-Output "$((get-date).ToString(`"yy/MM/dd HH:mm:ss.ff`")) : ERROR : Unable to load supporting PowerShell Scripts : $query `n$Error[0]" | out-file "$PSScriptRoot\PSError.log" -append 37 | } 38 | 39 | # Set start time 40 | $StartTime = (Get-Date -f G) 41 | 42 | $ConsFolder = "$PSScriptRoot\ConsolidateRules" 43 | 44 | # Create ConsolidateRules folder if it doesn't exist 45 | If (-not(Test-Path $ConsFolder)) { 46 | md $ConsFolder 47 | } 48 | 49 | # Delete all files in the Consolidated Rules folder before beginning 50 | Get-ChildItem -Path $ConsFolder -Include * | foreach { $_.Delete()} 51 | 52 | # Find earliest ban date 53 | $Query = "SELECT MIN(timestamp) AS mindate FROM hm_fwban WHERE flag IS NULL" 54 | RunSQLQuery $Query | ForEach { 55 | $MinDate = (Get-Date -date $_.mindate) 56 | } 57 | 58 | $A = 0 59 | 60 | Do { 61 | $BanDate = $MinDate.AddDays($A).ToString("yyyy-MM-dd") 62 | $ConsRules = "$ConsFolder\hMS FWBan $BanDate.csv" 63 | 64 | $Query = " 65 | SELECT 66 | id, 67 | ipaddress 68 | FROM hm_fwban 69 | WHERE $(DBCastDateTimeFieldAsDate('timestamp')) LIKE '$BanDate%' AND flag IS NULL 70 | " 71 | RunSQLQuery $Query | Export-CSV $ConsRules 72 | 73 | Import-CSV $ConsRules | ForEach { 74 | Write-Output $_.ipaddress 75 | } | Out-File "$ConsRules.txt" 76 | 77 | $NL = [System.Environment]::NewLine 78 | $Content=[String] $Template= [System.IO.File]::ReadAllText("$ConsRules.txt") 79 | $Content.Replace($NL,",") | Out-File "$ConsRules.rule.txt" 80 | (Get-Content -Path "$ConsRules.rule.txt") -Replace ',$','' | Set-Content -Path "$ConsRules.rule.txt" 81 | 82 | & netsh advfirewall firewall add rule name="hMS FWBan $BanDate" description="FWB Rules for $BanDate" dir=in interface=any action=block remoteip=$(Get-Content "$ConsRules.rule.txt") 83 | 84 | Import-CSV $ConsRules | ForEach { 85 | $IP = $_.ipaddress 86 | & netsh advfirewall firewall delete rule name=`"$IP`" 87 | } 88 | 89 | $A++ 90 | 91 | } Until ($BanDate -match $((Get-Date).AddDays(-1).ToString("yyyy-MM-dd"))) 92 | 93 | $Query = "SELECT COUNT(ID) AS countnull FROM hm_fwban WHERE ptr IS NULL" 94 | RunSQLQuery($Query) | ForEach { 95 | $CountEnd = $_.countnull 96 | } 97 | 98 | $EndTime = (Get-Date -f G) 99 | $OperationTime = New-Timespan $StartTime $EndTime 100 | If (($Duration).Hours -eq 1) {$sh = ""} Else {$sh = "s"} 101 | If (($Duration).Minutes -eq 1) {$sm = ""} Else {$sm = "s"} 102 | If (($Duration).Seconds -eq 1) {$ss = ""} Else {$ss = "s"} 103 | 104 | $EmailBody = ("Retroactive Rule Consolidation complete.`n`nUpdate completed in {0:%h} hour$sh {0:%m} minute$sm {0:%s} second$ss" -f $OperationTime) 105 | EmailResults -------------------------------------------------------------------------------- /www/repeats-ip-day.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | prepare(" 25 | SELECT 26 | COUNT(ipaddress) 27 | FROM ( 28 | SELECT * 29 | FROM hm_fwban_rh 30 | WHERE '".$date." 00:00:00' <= timestamp 31 | ) AS A 32 | WHERE timestamp <= '".$date." 23:59:59' AND ipaddress = '{$repeatIP}' 33 | "); 34 | $total_pages_sql->execute(); 35 | $total_rows = $total_pages_sql->fetchColumn(); 36 | $total_pages = ceil($total_rows / $no_of_records_per_page); 37 | 38 | $sql = $pdo->prepare(" 39 | SELECT 40 | a.TimeStamp, 41 | a.ipaddress, 42 | b.ban_reason, 43 | b.country 44 | FROM 45 | ( 46 | SELECT 47 | ipaddress, 48 | ".DBFormatDate('timestamp', '%y/%m/%d %T')." as TimeStamp 49 | FROM ( 50 | SELECT * 51 | FROM hm_fwban_rh 52 | WHERE '".$date." 00:00:00' <= timestamp 53 | ) AS X 54 | WHERE timestamp <= '".$date." 23:59:59' AND ipaddress = '{$repeatIP}' 55 | ) AS a 56 | JOIN 57 | ( 58 | SELECT 59 | ipaddress, 60 | country, 61 | ban_reason 62 | FROM hm_fwban 63 | ) AS b 64 | ON a.ipaddress = b.ipaddress 65 | ".DBLimitRowsWithOffset('a.TimeStamp','DESC',0,0,$offset,$no_of_records_per_page) 66 | ); 67 | $sql->execute(); 68 | 69 | if ($total_rows == 1){$singular = '';} else {$singular= 's';} 70 | 71 | if ($total_rows == 0){ 72 | echo "

There are no repeat dropped IPs to report."; 73 | } else { 74 | echo "IP ".$repeatIP." denied access ".number_format($total_rows)." time".$singular." on ".$date.". (Page: ".number_format($page)." of ".number_format($total_pages).")
"; 75 | echo " 76 | 77 | 78 | 79 | 80 | 81 | "; 82 | 83 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 84 | echo ""; 85 | echo ""; 86 | echo ""; 87 | echo ""; 88 | echo ""; 89 | echo ""; 90 | } 91 | echo "
DateIP AddressReasonCountry
".$row['TimeStamp']."".$row['ipaddress']."".$row['ban_reason']."".$row['country']."
"; 92 | 93 | if ($total_pages < 2){ 94 | echo "

"; 95 | } else { 96 | echo "
    "; 97 | if($page <= 1){echo "
  • First
  • ";} else {echo "
  • First
  • ";} 98 | if($page <= 1){echo "
  • Prev
  • ";} else {echo "
  • Prev
  • ";} 99 | if($page >= $total_pages){echo "
  • Next
  • ";} else {echo "
  • Next
  • ";} 100 | if($page >= $total_pages){echo "
  • Last
  • ";} else {echo "
  • Last
  • ";} 101 | echo "
"; 102 | } 103 | if ($total_pages > 0){ 104 | echo "FB = Firewall Blocks
105 | RS = Released Status
"; 106 | } 107 | } 108 | 109 | echo "
"; 110 | ?> 111 |
112 | 113 | -------------------------------------------------------------------------------- /hmsRetroAddBlocksIPTable.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | _ _ _ _ _ _ _ ____ ____ ____ _ _ ____ ____ 3 | |__| |\/| /_\ | | [__ |___ |__/ | | |___ |__/ 4 | | | | |/ \| |___ ___] |___ | \ \/ |___ | \ 5 | ____ _ ____ ____ _ _ _ _ _ _ ___ _ _ _ 6 | |___ | |__/ |___ | | | /_\ | | |__] /_\ |\ | 7 | | | | \ |___ |_|_|/ \|___ |___ |__]/ \| \| 8 | 9 | .SYNOPSIS 10 | Powershell script to retroactively create hm_fwban_blocks_ip table and fill it. 11 | 12 | .DESCRIPTION 13 | 14 | .FUNCTIONALITY 15 | 16 | .NOTES 17 | Includes email notification when complete. 18 | 19 | .EXAMPLE 20 | 21 | #> 22 | 23 | # Include required files 24 | Try { 25 | .("$PSScriptRoot\Config.ps1") 26 | .("$PSScriptRoot\CommonCode.ps1") 27 | } 28 | Catch { 29 | Write-Output "$((get-date).ToString(`"yy/MM/dd HH:mm:ss.ff`")) : ERROR : Unable to load supporting PowerShell Scripts : $query `n$Error[0]" | out-file "$PSScriptRoot\PSError.log" -append 30 | } 31 | 32 | # Set start time 33 | $StartTime = (Get-Date -f G) 34 | if ($DatabaseType -eq "MYSQL"){ 35 | $Query = " 36 | CREATE TABLE IF NOT EXISTS hm_fwban_blocks_ip ( 37 | id INT(22) NOT NULL AUTO_INCREMENT, 38 | ipaddress varchar(15) NOT NULL UNIQUE, 39 | hits INT(8), 40 | lasttimestamp datetime NOT NULL, 41 | PRIMARY KEY (id) 42 | UNIQUE KEY ipaddress (ipaddress) 43 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 44 | COMMIT; 45 | " 46 | } elseif ($DatabaseType -eq "MSSQL") { 47 | $Query = " 48 | IF NOT EXISTS (SELECT 1 FROM SYSOBJECTS WHERE NAME='hm_fwban_blocks_ip') 49 | CREATE TABLE hm_fwban_blocks_ip ( 50 | id INT IDENTITY PRIMARY KEY, 51 | ipaddress varchar(15) NOT NULL UNIQUE, 52 | hits INT, 53 | lasttimestamp DATETIME NOT NULL, 54 | ) 55 | " 56 | } 57 | RunSQLQuery $Query 58 | if ($DatabaseType -eq "MYSQL"){ 59 | $Query = "ALTER TABLE hm_fwban_rh DROP id;" 60 | } elseif ($DatabaseType -eq "MSSQL") { 61 | $Query = "ALTER TABLE hm_fwban_rh DROP COLUMN id;" 62 | } 63 | RunSQLQuery $Query 64 | 65 | if ($DatabaseType -eq "MYSQL"){ 66 | $Query = "ALTER TABLE hm_fwban_rh ADD ipid INT(22) NULL;" 67 | } elseif ($DatabaseType -eq "MSSQL") { 68 | $Query = "ALTER TABLE hm_fwban_rh ADD ipid INT NULL;" 69 | } 70 | RunSQLQuery $Query 71 | 72 | $Query = " 73 | SELECT 74 | timestamp, 75 | ipaddress 76 | FROM hm_fwban_rh 77 | WHERE timestamp > '2020-02-14 06:22:00' 78 | " 79 | RunSQLQuery $Query | foreach { 80 | $timestamp = (Get-Date $_.timestamp).ToString("yyyy-MM-dd HH:mm:ss") 81 | $ipaddress = $_.ipaddress 82 | if ($DatabaseType -eq "MYSQL"){ 83 | $Query = "INSERT INTO hm_fwban_blocks_ip (ipaddress, hits, lasttimestamp) VALUES ('$ipaddress',1,'$timestamp') ON DUPLICATE KEY UPDATE hits=(hits+1),lasttimestamp='$timestamp';" 84 | } elseif ($DatabaseType -eq "MSSQL") { 85 | $Query = "IF NOT EXISTS (SELECT 1 FROM hm_fwban_blocks_ip WHERE ipaddress='$ipaddress') INSERT INTO hm_fwban_blocks_ip (ipaddress, hits, lasttimestamp) VALUES ('$ipaddress',1,'$timestamp') ELSE UPDATE hm_fwban_blocks_ip SET hits=(hits+1),lasttimestamp='$timestamp' WHERE ipaddress='$ipaddress';" 86 | } 87 | RunSQLQuery $Query 88 | } 89 | 90 | $Query = " 91 | SELECT 92 | id, 93 | ipaddress 94 | FROM hm_fwban_blocks_ip 95 | " 96 | RunSQLQuery $Query | foreach { 97 | $id = $_.id 98 | $ipaddress = $_.ipaddress 99 | $Query = "UPDATE hm_fwban_rh SET ipid='$id' WHERE ipaddress='$ipaddress';" 100 | RunSQLQuery $Query 101 | } 102 | 103 | $EndTime = (Get-Date -f G) 104 | $OperationTime = New-Timespan $StartTime $EndTime 105 | If (($OperationTime).Hours -eq 1) {$sh = ""} Else {$sh = "s"} 106 | If (($OperationTime).Minutes -eq 1) {$sm = ""} Else {$sm = "s"} 107 | If (($OperationTime).Seconds -eq 1) {$ss = ""} Else {$ss = "s"} 108 | 109 | $EmailBody = ("Retroactive hm_fwban_blocks_ip fill script compete.`n`nUpdate completed in {0:%h} hour$sh {0:%m} minute$sm {0:%s} second$ss" -f $OperationTime) 110 | Write-Host $EmailBody 111 | #EmailResults -------------------------------------------------------------------------------- /www/release-country-view.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 |
"; 23 | } else { 24 | 25 | $no_of_records_per_page = 20; 26 | $offset = ($page-1) * $no_of_records_per_page; 27 | $total_pages_sql = $pdo->prepare(" 28 | SELECT 29 | Count( * ) AS count 30 | FROM hm_fwban 31 | WHERE country LIKE '%{$country}%' AND (flag IS NULL OR flag=3) 32 | "); 33 | $total_pages_sql->execute(); 34 | $total_rows = $total_pages_sql->fetchColumn(); 35 | $total_pages = ceil($total_rows / $no_of_records_per_page); 36 | 37 | $sql = $pdo->prepare(" 38 | SELECT 39 | id, 40 | ".DBFormatDate('timestamp', '%y/%m/%d %T')." as TimeStamp, 41 | ipaddress, 42 | ban_reason, 43 | country, 44 | flag 45 | FROM hm_fwban 46 | WHERE country LIKE '%{$country}%' AND (flag IS NULL OR flag=3) 47 | ".DBLimitRowsWithOffset('TimeStamp','DESC',0,0,$offset,$no_of_records_per_page) 48 | ); 49 | $sql->execute(); 50 | 51 | if ($total_rows == 1){$singular = '';} else {$singular= 's';} 52 | if ($total_rows == 0){ 53 | echo "No unreleased results for \"".$country."\""; 54 | } else { 55 | echo "

What would you like to release?

"; 56 | echo "Click \"NO\" under column \"RS\" to release a single address.

"; 57 | echo "Click here to release all.
"; 58 | echo "

"; 59 | echo "Results for \"".$country."\": ".number_format($total_rows)." IP".$singular." (Page: ".number_format($page)." of ".number_format($total_pages).")
"; 60 | echo " 61 | 62 | 63 | 64 | 65 | 66 | 67 | "; 68 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 69 | echo ""; 70 | 71 | echo ""; 72 | echo ""; 73 | echo ""; 74 | echo ""; 75 | if($row['flag'] === NULL || $row['flag'] == 3) echo ""; 76 | else echo ""; 77 | 78 | echo ""; 79 | } 80 | echo "
TimestampIP AddressReasonCountryRS
" . $row['TimeStamp'] . "".$row['ipaddress']."" . $row['ban_reason'] . "".$row['country']."NoYES
"; 81 | 82 | if ($total_pages == 1){ 83 | echo ""; 84 | } else { 85 | echo "
    "; 86 | if($page <= 1){echo "
  • First
  • ";} else {echo "
  • First
  • ";} 87 | if($page <= 1){echo "
  • Prev
  • ";} else {echo "
  • Prev
  • ";} 88 | if($page >= $total_pages){echo "
  • Next
  • ";} else {echo "
  • Next
  • ";} 89 | if($page >= $total_pages){echo "
  • Last
  • ";} else {echo "
  • Last
  • ";} 90 | echo "
"; 91 | } 92 | } 93 | } 94 | echo "
"; 95 | ?> 96 |
97 | 98 | -------------------------------------------------------------------------------- /www/reban-br-view.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 |
Error: No IP entries for ban reason ".$ban_reason."

"; 22 | } else { 23 | 24 | $no_of_records_per_page = 20; 25 | $offset = ($page-1) * $no_of_records_per_page; 26 | $total_pages_sql = $pdo->prepare(" 27 | SELECT 28 | Count( * ) AS count 29 | FROM hm_fwban 30 | WHERE ban_reason LIKE '{$ban_reason}' AND (flag=1 OR flag=2) 31 | "); 32 | $total_pages_sql->execute(); 33 | $total_rows = $total_pages_sql->fetchColumn(); 34 | $total_pages = ceil($total_rows / $no_of_records_per_page); 35 | 36 | $sql = $pdo->prepare(" 37 | SELECT 38 | id, 39 | ".DBFormatDate('timestamp', '%y/%m/%d %T')." as TimeStamp, 40 | ipaddress, 41 | ban_reason, 42 | country, 43 | flag, 44 | helo 45 | FROM hm_fwban 46 | WHERE ban_reason LIKE '{$ban_reason}' AND (flag=1 OR flag=2) 47 | ".DBLimitRowsWithOffset('TimeStamp','DESC',0,0,$offset,$no_of_records_per_page) 48 | ); 49 | $sql->execute(); 50 | 51 | if ($total_rows == 1){$singular = '';} else {$singular= 's';} 52 | if ($total_rows == 0){ 53 | echo "

No previously released results for ban reason \"".$ban_reason."\""; 54 | } else { 55 | echo "

What would you like to ban?

"; 56 | echo "Click \"YES\" under column \"RS\" to re-ban a single address.

"; 57 | echo "Click here to re-ban all.
"; 58 | echo "

"; 59 | echo "Results for released IPs for ban reason \"".$ban_reason."\": ".number_format($total_rows)." IP".$singular." (Page: ".number_format($page)." of ".number_format($total_pages).")
"; 60 | echo " 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | "; 69 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 70 | echo ""; 71 | 72 | echo ""; 73 | echo ""; 74 | echo ""; 75 | echo ""; 76 | echo ""; 77 | if($row['flag'] == 1 || $row['flag'] == 2) echo ""; 78 | else echo ""; 79 | 80 | echo ""; 81 | } 82 | echo "
TimestampIP AddressReasonCountryHELORS
".$row['TimeStamp']."".$row['ipaddress']."".$row['ban_reason']."" . $row['country'] . "".$row['helo']."YESNO
"; 83 | 84 | echo "
    "; 85 | if($page <= 1){echo "
  • First
  • ";} else {echo "
  • First
  • ";} 86 | if($page <= 1){echo "
  • Prev
  • ";} else {echo "
  • Prev
  • ";} 87 | if($page >= $total_pages){echo "
  • Next
  • ";} else {echo "
  • Next
  • ";} 88 | if($page >= $total_pages){echo "
  • Last
  • ";} else {echo "
  • Last
  • ";} 89 | echo "
"; 90 | } 91 | } 92 | echo "
"; 93 | ?> 94 |
95 | 96 | -------------------------------------------------------------------------------- /www/ids.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | \"".$search."\"";} 26 | if ($search=="") {$search_all="All ";} else {$search_all="";} 27 | 28 | $no_of_records_per_page = 20; 29 | $offset = ($page-1) * $no_of_records_per_page; 30 | $total_pages_sql = $pdo->prepare(" 31 | SELECT 32 | COUNT(ipaddress) 33 | FROM hm_ids".$search_sql 34 | ); 35 | $total_pages_sql->execute(); 36 | $total_rows = $total_pages_sql->fetchColumn(); 37 | $total_pages = ceil($total_rows / $no_of_records_per_page); 38 | 39 | $sql = $pdo->prepare(" 40 | SELECT 41 | ipaddress, 42 | ".DBFormatDate('timestamp', '%y/%m/%d %T')." AS TimeStamp, 43 | country, 44 | hits 45 | FROM hm_ids ".$search_sql." 46 | GROUP BY ipaddress, ".DBFormatDate('timestamp', '%y/%m/%d %T').", country, hits 47 | ".DBLimitRowsWithOffset('timestamp','DESC',0,0,$offset,$no_of_records_per_page)); 48 | $sql->execute(); 49 | 50 | if ($total_rows == 1){$singular = '';} else {$singular= 's';} 51 | if ($total_rows == 0){ 52 | if ($search == ""){ 53 | echo "
There are no IDS entries to report."; 54 | } else { 55 | echo "
There are no IDS entries to report for search term \"".$search."\". Please enter only IP address or date."; 56 | } 57 | } else { 58 | echo $search_all."".number_format($total_rows)." IP".$singular." hit by IDS".$search_list.". (Page: ".number_format($page)." of ".number_format($total_pages).")
"; 59 | echo " 60 | 61 | 62 | 63 | 64 | 65 | "; 66 | 67 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 68 | echo ""; 69 | echo ""; 70 | echo ""; 71 | echo ""; 72 | echo ""; 73 | echo ""; 74 | } 75 | echo "
TimestampIP AddressCountryHits
".$row['TimeStamp']."".$row['ipaddress']."".$row['country']."".$row['hits']."
"; 76 | 77 | if ($total_pages < 2){ 78 | echo "

"; 79 | } else { 80 | echo "
    "; 81 | if($page <= 1){echo "
  • First
  • ";} else {echo "
  • First
  • ";} 82 | if($page <= 1){echo "
  • Prev
  • ";} else {echo "
  • Prev
  • ";} 83 | if($page >= $total_pages){echo "
  • Next
  • ";} else {echo "
  • Next
  • ";} 84 | if($page >= $total_pages){echo "
  • Last
  • ";} else {echo "
  • Last
  • ";} 85 | echo "
"; 86 | } 87 | } 88 | 89 | echo "
90 | IDS = Intrusion Detection System.

91 | Records connections that either a) were not rejected and did not successfully send a message or b) were not rejected and did not successfully log in. After 3 such connections within an interval of a specified number of hours (declared in Config.ps1), the IP is banned. If an IP is recorded less than 3 times within the interval period, it is expired from the IDS table."; 92 | ?> 93 |
94 | 95 | -------------------------------------------------------------------------------- /www/reban-country-view.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 |
Error: No country selected. Please see administrator.

"; 23 | } else { 24 | 25 | $no_of_records_per_page = 20; 26 | $offset = ($page-1) * $no_of_records_per_page; 27 | $total_pages_sql = $pdo->prepare(" 28 | SELECT 29 | Count( * ) AS count 30 | FROM hm_fwban 31 | WHERE country LIKE '{$country}' AND (flag=1 OR flag=2) 32 | "); 33 | $total_pages_sql->execute(); 34 | $total_rows = $total_pages_sql->fetchColumn(); 35 | $total_pages = ceil($total_rows / $no_of_records_per_page); 36 | 37 | $sql = $pdo->prepare(" 38 | SELECT 39 | id, 40 | ".DBFormatDate('timestamp', '%y/%m/%d %T')." as TimeStamp, 41 | ipaddress, 42 | ban_reason, 43 | country, 44 | flag, 45 | helo 46 | FROM hm_fwban 47 | WHERE country LIKE '{$country}' AND (flag=1 OR flag=2) 48 | ".DBLimitRowsWithOffset('TimeStamp','DESC',0,0,$offset,$no_of_records_per_page) 49 | ); 50 | $sql->execute(); 51 | 52 | if ($total_rows == 1){$singular = '';} else {$singular= 's';} 53 | if ($total_rows == 0){ 54 | echo "

No previously released results for \"".$country."\""; 55 | } else { 56 | echo "

What would you like to ban?

"; 57 | echo "Click \"YES\" under column \"RS\" to re-ban a single address.

"; 58 | echo "Click here to re-ban all.
"; 59 | echo "

"; 60 | echo "Results for released IPs for \"".$country."\": ".number_format($total_rows)." IP".$singular." (Page: ".number_format($page)." of ".number_format($total_pages).")
"; 61 | echo " 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | "; 70 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 71 | echo ""; 72 | 73 | echo ""; 74 | echo ""; 75 | echo ""; 76 | echo ""; 77 | echo ""; 78 | if($row['flag'] == 1 || $row['flag'] == 2) echo ""; 79 | else echo ""; 80 | 81 | echo ""; 82 | } 83 | echo "
TimestampIP AddressReasonCountryHELORS
".$row['TimeStamp']."".$row['ipaddress']."".$row['ban_reason']."" . $row['country'] . "".$row['helo']."YESNO
"; 84 | 85 | echo "
    "; 86 | if($page <= 1){echo "
  • First
  • ";} else {echo "
  • First
  • ";} 87 | if($page <= 1){echo "
  • Prev
  • ";} else {echo "
  • Prev
  • ";} 88 | if($page >= $total_pages){echo "
  • Next
  • ";} else {echo "
  • Next
  • ";} 89 | if($page >= $total_pages){echo "
  • Last
  • ";} else {echo "
  • Last
  • ";} 90 | echo "
"; 91 | echo "
RS = Released Status (removal from firewall). Clicking on \"YES\" will re-ban the IP.

"; 92 | } 93 | } 94 | echo "
"; 95 | ?> 96 |
97 | -------------------------------------------------------------------------------- /www/repeats-ip.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | prepare(" 23 | SELECT 24 | COUNT(DISTINCT(".DBCastDateTimeFieldAsDate('timestamp').")) 25 | FROM hm_fwban_rh 26 | WHERE ipaddress='{$repeatIP}' 27 | "); 28 | $total_pages_sql->execute(); 29 | $total_rows = $total_pages_sql->fetchColumn(); 30 | $total_pages = ceil($total_rows / $no_of_records_per_page); 31 | 32 | $total_hits_sql = $pdo->prepare(" 33 | SELECT 34 | COUNT(ipaddress) 35 | FROM hm_fwban_rh 36 | WHERE ipaddress='{$repeatIP}' 37 | "); 38 | $total_hits_sql->execute(); 39 | $total_hits = $total_hits_sql->fetchColumn(); 40 | 41 | $sql = $pdo->prepare(" 42 | SELECT 43 | a.day, 44 | a.ipaddress, 45 | b.ban_reason, 46 | b.country, 47 | a.countip 48 | FROM 49 | ( 50 | SELECT 51 | ipaddress, 52 | COUNT(ipaddress) AS countip, 53 | ".DBFormatDate(DBCastDateTimeFieldAsDate('timestamp'), '%y/%m/%d')." AS day 54 | FROM hm_fwban_rh 55 | WHERE ipaddress = '{$repeatIP}' 56 | GROUP BY ".DBFormatDate(DBCastDateTimeFieldAsDate('timestamp'), '%y/%m/%d').", ipaddress 57 | ) AS a 58 | JOIN 59 | ( 60 | SELECT 61 | ipaddress, 62 | country, 63 | ban_reason 64 | FROM hm_fwban 65 | ) AS b 66 | ON a.ipaddress = b.ipaddress 67 | GROUP BY a.day, a.ipaddress, b.ban_reason, b.country, a.countip 68 | ".DBLimitRowsWithOffset('a.day','DESC',0,0,$offset,$no_of_records_per_page) 69 | ); 70 | $sql->execute(); 71 | 72 | if ($total_rows == 1){$singular = '';} else {$singular= 's';} 73 | 74 | if ($total_rows == 0){ 75 | echo "

There are no repeat dropped IPs to report."; 76 | } else { 77 | echo "IP ".$repeatIP." denied access ".number_format($total_hits)." times over ".number_format($total_rows)." day".$singular.". (Page: ".number_format($page)." of ".number_format($total_pages).")
"; 78 | echo " 79 | 80 | 81 | 82 | 83 | 84 | 85 | "; 86 | 87 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 88 | echo ""; 89 | echo ""; 90 | echo ""; 91 | echo ""; 92 | echo ""; 93 | echo ""; 94 | echo ""; 95 | } 96 | echo "
DateIP AddressReasonCountryFB
".$row['day']."".$row['ipaddress']."".$row['ban_reason']."".$row['country']."".number_format($row['countip'])."
"; 97 | 98 | if ($total_pages < 2){ 99 | echo "

"; 100 | } else { 101 | echo "
    "; 102 | if($page <= 1){echo "
  • First
  • ";} else {echo "
  • First
  • ";} 103 | if($page <= 1){echo "
  • Prev
  • ";} else {echo "
  • Prev
  • ";} 104 | if($page >= $total_pages){echo "
  • Next
  • ";} else {echo "
  • Next
  • ";} 105 | if($page >= $total_pages){echo "
  • Last
  • ";} else {echo "
  • Last
  • ";} 106 | echo "
"; 107 | } 108 | if ($total_pages > 0){ 109 | echo "FB = Firewall Blocks
110 | RS = Released Status
"; 111 | } 112 | } 113 | echo "
"; 114 | ?> 115 |
116 | 117 | -------------------------------------------------------------------------------- /www/release-br-view.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 |
"; 22 | } else { 23 | $no_of_records_per_page = 20; 24 | $offset = ($page-1) * $no_of_records_per_page; 25 | $total_pages_sql = $pdo->prepare(" 26 | SELECT 27 | Count( * ) AS count 28 | FROM hm_fwban 29 | WHERE ban_reason LIKE '{$ban_reason}' AND (flag IS NULL OR flag=3) 30 | "); 31 | $total_pages_sql->execute(); 32 | $total_rows = $total_pages_sql->fetchColumn(); 33 | $total_pages = ceil($total_rows / $no_of_records_per_page); 34 | 35 | $sql = $pdo->prepare(" 36 | SELECT 37 | id, 38 | ".DBFormatDate('timestamp', '%y/%m/%d %T')." as TimeStamp, 39 | ipaddress, 40 | ban_reason, 41 | country, 42 | helo, 43 | flag 44 | FROM hm_fwban 45 | WHERE ban_reason LIKE '{$ban_reason}' AND (flag IS NULL OR flag=3) 46 | ".DBLimitRowsWithOffset('TimeStamp','DESC',0,0,$offset,$no_of_records_per_page) 47 | ); 48 | $sql->execute(); 49 | 50 | if ($total_rows == 1){$singular = '';} else {$singular= 's';} 51 | if ($total_rows == 0){ 52 | echo "No unreleased results for ban reason \"".$ban_reason."\"."; 53 | } else { 54 | echo "

What would you like to release?

"; 55 | echo "Click \"NO\" under column \"RS\" to release a single address.

"; 56 | echo "Click here to release all.
"; 57 | echo "

"; 58 | echo "Results for ban reason \"".$ban_reason."\": ".number_format($total_rows)." IP".$singular." (Page: ".number_format($page)." of ".number_format($total_pages).")
"; 59 | echo " 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | "; 68 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 69 | echo ""; 70 | 71 | echo ""; 72 | echo ""; 73 | echo ""; 74 | echo ""; 75 | echo ""; 76 | if($row['flag'] === NULL || $row['flag'] == 3) echo ""; 77 | else echo ""; 78 | 79 | echo ""; 80 | } 81 | echo "
TimestampIP AddressReasonCountryHELORS
" . $row['TimeStamp'] . "" . $row['ipaddress'] . "" . $row['ban_reason'] . "" . $row['country'] . "" . $row['helo'] . "NoYES
"; 82 | 83 | if ($total_pages == 1){ 84 | echo ""; 85 | } else { 86 | echo "
    "; 87 | if($page <= 1){echo "
  • First
  • ";} else {echo "
  • First
  • ";} 88 | if($page <= 1){echo "
  • Prev
  • ";} else {echo "
  • Prev
  • ";} 89 | if($page >= $total_pages){echo "
  • Next
  • ";} else {echo "
  • Next
  • ";} 90 | if($page >= $total_pages){echo "
  • Last
  • ";} else {echo "
  • Last
  • ";} 91 | echo "
"; 92 | } 93 | if ($total_pages > 0){ 94 | echo "
95 | RS = Release Status

"; 96 | } 97 | } 98 | } 99 | echo "
"; 100 | ?> 101 |
102 | 103 | -------------------------------------------------------------------------------- /www/blocks-view.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 |

Repeat Hits (Connections Dropped at Firewall)

5 | 6 | prepare(" 30 | SELECT COUNT(*) AS countips 31 | FROM ( 32 | SELECT 33 | a.ipaddress, 34 | b.ban_reason, 35 | b.country, 36 | a.countip 37 | FROM 38 | ( 39 | SELECT 40 | ipaddress, 41 | COUNT(ipaddress) AS countip, 42 | COUNT(DISTINCT(".DBCastDateTimeFieldAsDate('timestamp').")) AS countdate 43 | FROM hm_fwban_rh 44 | GROUP BY ipaddress 45 | HAVING COUNT(DISTINCT(".DBCastDateTimeFieldAsDate('timestamp').")) > ".($days - 1)." 46 | ) AS a 47 | LEFT JOIN 48 | ( 49 | SELECT 50 | ipaddress, 51 | country, 52 | ban_reason 53 | FROM hm_fwban 54 | ) AS b 55 | ON a.ipaddress = b.ipaddress 56 | ) AS returnhits 57 | "); 58 | $total_pages_sql->execute(); 59 | $total_rows = $total_pages_sql->fetchColumn(); 60 | $total_pages = ceil($total_rows / $no_of_records_per_page); 61 | 62 | $sql = $pdo->prepare(" 63 | SELECT 64 | a.ipaddress, 65 | b.ban_reason, 66 | b.country, 67 | a.countip 68 | FROM 69 | ( 70 | SELECT 71 | ipaddress, 72 | COUNT(ipaddress) AS countip, 73 | COUNT(DISTINCT(".DBCastDateTimeFieldAsDate('timestamp').")) AS countdate 74 | FROM hm_fwban_rh 75 | GROUP BY ipaddress 76 | HAVING COUNT(DISTINCT(".DBCastDateTimeFieldAsDate('timestamp').")) > ".($days - 1)." 77 | ) AS a 78 | LEFT JOIN 79 | ( 80 | SELECT 81 | ipaddress, 82 | country, 83 | ban_reason 84 | FROM hm_fwban 85 | ) AS b 86 | ON a.ipaddress = b.ipaddress 87 | ".DBLimitRowsWithOffset('countip','DESC',0,0,$offset,$no_of_records_per_page) 88 | ); 89 | $sql->execute(); 90 | 91 | if ($total_rows == 1){$singular = '';} else {$singular= 's';} 92 | if ($total_rows == 0){ 93 | echo "
There are no IPs repeatedly dropped at the firewall at least ".$days." days."; 94 | } else { 95 | echo number_format($total_rows)." IP".$singular." repeatedly dropped at firewall on at least ".$days." distinct days. (Page: ".number_format($page)." of ".number_format($total_pages).")
"; 96 | echo " 97 | 98 | 99 | 100 | 101 | 102 | "; 103 | 104 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 105 | echo ""; 106 | echo ""; 107 | echo ""; 108 | echo ""; 109 | if($row['countip']==0){echo "";} 110 | else{echo "";} 111 | echo ""; 112 | } 113 | echo "
IP AddressReasonCountryBlocks
".$row['ipaddress']."".$row['ban_reason']."".$row['country']."0".number_format($row['countip'])."
"; 114 | 115 | if ($total_pages < 2){ 116 | echo "

"; 117 | } else { 118 | echo "
    "; 119 | if($page <= 1){echo "
  • First
  • ";} else {echo "
  • First
  • ";} 120 | if($page <= 1){echo "
  • Prev
  • ";} else {echo "
  • Prev
  • ";} 121 | if($page >= $total_pages){echo "
  • Next
  • ";} else {echo "
  • Next
  • ";} 122 | if($page >= $total_pages){echo "
  • Last
  • ";} else {echo "
  • Last
  • ";} 123 | echo "
"; 124 | } 125 | } 126 | 127 | echo "
"; 128 | ?> 129 |
130 | 131 | -------------------------------------------------------------------------------- /hmsRetroAddRuleName.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | _ _ _ _ _ _ _ ____ ____ ____ _ _ ____ ____ 3 | |__| |\/| /_\ | | [__ |___ |__/ | | |___ |__/ 4 | | | | |/ \| |___ ___] |___ | \ \/ |___ | \ 5 | ____ _ ____ ____ _ _ _ _ _ _ ___ _ _ _ 6 | |___ | |__/ |___ | | | /_\ | | |__] /_\ |\ | 7 | | | | \ |___ |_|_|/ \|___ |___ |__]/ \| \| 8 | 9 | .SYNOPSIS 10 | Powershell script to retroactively add firewall rule names 11 | 12 | .DESCRIPTION 13 | Adds column "rulename" to database, queries firewall for rules, extracts IP scope from rules and inserts rule name into database for each IP. 14 | 15 | .FUNCTIONALITY 16 | 1) Fill in user variables 17 | 2) Run script 18 | 19 | .NOTES 20 | Includes email notification when complete. Also includes a search for bans with no rules to bring the firewall up to match the database. 21 | 22 | .EXAMPLE 23 | 24 | #> 25 | 26 | # Include required files 27 | Try { 28 | .("$PSScriptRoot\Config.ps1") 29 | .("$PSScriptRoot\CommonCode.ps1") 30 | } 31 | Catch { 32 | Write-Output "$((get-date).ToString(`"yy/MM/dd HH:mm:ss.ff`")) : ERROR : Unable to load supporting PowerShell Scripts : $query `n$Error[0]" | out-file "$PSScriptRoot\PSError.log" -append 33 | } 34 | 35 | # Set start time 36 | $StartTime = (Get-Date -f G) 37 | 38 | # Create folder if it doesn't exist 39 | If (-not(Test-Path "$PSScriptRoot\RetroAddRuleName")) { 40 | md "$PSScriptRoot\RetroAddRuleName" 41 | } 42 | 43 | # Add "rulename" column to hm_fwban 44 | $Query = "ALTER TABLE hm_fwban ADD rulename VARCHAR(192) NULL;" 45 | RunSQLQuery($Query) 46 | 47 | # Count IPs that should get rulenames 48 | $Query = " 49 | SELECT 50 | COUNT(rulename) AS countnull 51 | FROM hm_fwban 52 | WHERE flag IS NULL 53 | " 54 | RunSQLQuery($Query) | ForEach { 55 | [int]$CountStart = $_.countnull 56 | } 57 | 58 | $NewLine = [System.Environment]::NewLine 59 | $RegexIP = '(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' 60 | $RegexDateName = '(hmsFWBRule\-|hMS\sFWBan\s)(20\d{2}\-\d{2}\-\d{2})(_\d{3})?$' 61 | $RegexIPName = '^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$' 62 | $RegexFileName = 'hms\sFWBan\s20[0-9][0-9]\-[0-9][0-9]\-[0-9][0-9].txt$' 63 | $Location = "$PSScriptRoot\RetroAddRuleName" 64 | 65 | Get-NetshFireWallrule ("all") | ForEach { 66 | If (($_.RuleName -match $RegexDateName) -or ($_.RuleName -match $RegexIPName)){ 67 | $RuleName = $_.RuleName 68 | Get-NetshFireWallrule ("$RuleName") | ForEach { 69 | $RemoteIP = $_.RemoteIP 70 | $ReplaceCIDR = ($RemoteIP).Replace("/32", "") 71 | $ReplaceNL = ($ReplaceCIDR).Replace(",", $NewLine) 72 | Write-Output $ReplaceNL 73 | } | Out-File "$Location\$RuleName.txt" 74 | } 75 | } 76 | 77 | Get-ChildItem $Location | Where-Object {$_.name -match $RegexFileName} | ForEach { 78 | $RuleFileName = $_.name 79 | $SQLRuleName = ($RuleFileName).Replace(".txt", "") 80 | Get-Content -Path "$Location\$RuleFileName" | ForEach { 81 | If ($_ -match $RegexIP){ 82 | $IP = $_ 83 | $Query = "UPDATE hm_fwban SET rulename = '$SQLRuleName' WHERE ipaddress = '$IP'" 84 | RunSQLQuery($Query) 85 | } 86 | } 87 | } 88 | 89 | # Pick up any missed entries (bans without firewall rules) 90 | $Query = "SELECT ipaddress, id FROM hm_fwban WHERE flag IS NULL AND rulename IS NULL" 91 | RunSQLQuery $Query | foreach { 92 | $ID = $_.id 93 | $IP = $_.ipaddress 94 | & netsh advfirewall firewall add rule name="$IP" description="Rule added $((get-date).ToString('MM/dd/yy'))" dir=in interface=any action=block remoteip=$IP 95 | $Query = "UPDATE hm_fwban SET rulename='$IP' WHERE id='$ID'" 96 | RunSQLQuery $Query 97 | } 98 | 99 | # Count Results 100 | $Query = " 101 | SELECT 102 | COUNT(rulename) AS countrulename 103 | FROM hm_fwban 104 | WHERE rulename IS NOT NULL AND flag IS NULL 105 | " 106 | RunSQLQuery($Query) | ForEach { 107 | [int]$CountEnd = $_.countrulename 108 | } 109 | 110 | $ResultCount = $CountStart - $CountEnd 111 | If ($ResultCount -eq 0){ 112 | $ResultMsg = "Successfully added $($CountEnd)ToString.('#,###') rulenames" 113 | } Else { 114 | $ResultMsg = "UPDATE FAILED to add $(($CountStart - $CountEnd)ToString.('#,###')) rulenames - check DB Error Logs for more info" 115 | } 116 | 117 | $EndTime = (Get-Date -f G) 118 | $OperationTime = New-Timespan $StartTime $EndTime 119 | If (($Duration).Hours -eq 1) {$sh = ""} Else {$sh = "s"} 120 | If (($Duration).Minutes -eq 1) {$sm = ""} Else {$sm = "s"} 121 | If (($Duration).Seconds -eq 1) {$ss = ""} Else {$ss = "s"} 122 | 123 | $EmailBody = ("Retroactive RuleName update complete `n`nResults: $ResultMsg`n`nUpdate completed in {0:%h} hour$sh {0:%m} minute$sm {0:%s} second$ss" -f $OperationTime) 124 | EmailResults -------------------------------------------------------------------------------- /Config.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | _ _ _ _ _ _ _ ____ ____ ____ _ _ ____ ____ 3 | |__| |\/| /_\ | | [__ |___ |__/ | | |___ |__/ 4 | | | | |/ \| |___ ___] |___ | \ \/ |___ | \ 5 | ____ _ ____ ____ _ _ _ _ _ _ ___ _ _ _ 6 | |___ | |__/ |___ | | | /_\ | | |__] /_\ |\ | 7 | | | | \ |___ |_|_|/ \|___ |___ |__]/ \| \| 8 | 9 | .SYNOPSIS 10 | Config File 11 | 12 | .DESCRIPTION 13 | Config File 14 | 15 | .FUNCTIONALITY 16 | 17 | .NOTES 18 | 19 | .EXAMPLE 20 | 21 | #> 22 | 23 | ### MYSQL VARIABLES ################################################################ 24 | # # 25 | $DatabaseType = 'MYSQL' #<-- Options: "MYSQL" or "MSSQL" # 26 | $SQLAdminUserName = 'hmailserver' # 27 | $SQLAdminPassword = 'supersecretpassword' # 28 | $SQLDatabase = 'hmailserver' # 29 | $SQLHost = '127.0.0.1' # 30 | $SQLPort = 3306 # 31 | $SQLSSL = 'none' # 32 | # # 33 | ### MySQL SSL OPTIONS ############################################################## 34 | # # 35 | # Set to 'none' if Powershell and MySQL on same machine (seems to be MySQL bug) # 36 | # # 37 | # None - Do not use SSL. # 38 | # Preferred - Use SSL if the server supports it, but allow connection in all cases. # 39 | # Required - Always use SSL. Deny connection if server does not support SSL. # 40 | # VerifyCA - Always use SSL. Validate the CA but tolerate name mismatch. # 41 | # VerifyFull - Always use SSL. Fail if the host name is not correct. # 42 | # # 43 | ### FIREWALL VARIABLES ############################################################# 44 | # # 45 | $LANSubnet = '192.168.1' # <-- 3 octets only, please # 46 | $MailPorts = '25|465|587|110|995|143|993' # <-- add custom ports if in use # 47 | $FirewallLog = 'C:\scripts\hmailserver\FWBan\Firewall\pfirewall.log' # 48 | # # 49 | ### INTERVAL VARIABLES ############################################################# 50 | # # 51 | $Interval = 5 # <-- (minutes) must match the frequency of Win Sched Task # 52 | $IDSExpire = 12 # <-- (hours) expire IDS entries that have not resulted in ban # 53 | # # 54 | ### PHP VARIABLES ################################################################## 55 | # # 56 | $wwwFolder = "C:\xampp\htdocs\mydomain\fwban" # <-- www folder location # 57 | $wwwURI = "https://firewallban.dynu.net" # <-- no trailing slash, please # 58 | # # 59 | ### EMAIL VARIABLES ################################################################ 60 | # # 61 | $FromAddress = 'notifier.account@gmail.com' # 62 | $Recipient = 'me@mydomain.com' # 63 | $SMTPServer = 'smtp.gmail.com' # 64 | $SMTPAuthUser = 'notifier.account@gmail.com' # 65 | $SMTPAuthPass = 'supersecretpassword' # 66 | $SMTPPort = 587 # 67 | $SSL = 'True' # 68 | # # 69 | ######################################################################################## -------------------------------------------------------------------------------- /hmsFirewallBanDBSetup.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | _ _ _ _ _ _ _ ____ ____ ____ _ _ ____ ____ 3 | |__| |\/| /_\ | | [__ |___ |__/ | | |___ |__/ 4 | | | | |/ \| |___ ___] |___ | \ \/ |___ | \ 5 | ____ _ ____ ____ _ _ _ _ _ _ ___ _ _ _ 6 | |___ | |__/ |___ | | | /_\ | | |__] /_\ |\ | 7 | | | | \ |___ |_|_|/ \|___ |___ |__]/ \| \| 8 | 9 | .SYNOPSIS 10 | Database Setup 11 | 12 | .DESCRIPTION 13 | 14 | .FUNCTIONALITY 15 | 16 | .NOTES 17 | 18 | .EXAMPLE 19 | 20 | #> 21 | 22 | # Include required files 23 | 24 | Try { 25 | .("$PSScriptRoot\Config.ps1") 26 | .("$PSScriptRoot\CommonCode.ps1") 27 | } 28 | Catch { 29 | Write-Output "Error while loading supporting PowerShell Scripts" | Out-File -Path "$PSScriptRoot\PSError.log" 30 | } 31 | 32 | If ($DatabaseType -eq "MSSQL") { 33 | 34 | # Create hm_fwban table if it doesn't exist 35 | $Query = " 36 | IF NOT EXISTS (SELECT 1 FROM SYSOBJECTS WHERE NAME = 'hm_fwban') 37 | BEGIN 38 | CREATE TABLE hm_fwban ( 39 | ID int IDENTITY(1,1) NOT NULL PRIMARY KEY, 40 | ipaddress varchar(15) NOT NULL, 41 | timestamp datetime NOT NULL, 42 | ban_reason varchar(192) DEFAULT NULL, 43 | country varchar(192) DEFAULT NULL, 44 | flag int DEFAULT NULL, 45 | helo varchar(192) DEFAULT NULL, 46 | ptr varchar(192) DEFAULT NULL, 47 | rulename varchar(192) DEFAULT NULL 48 | ) 49 | END; 50 | " 51 | RunSQLQuery $Query 52 | 53 | # Create hm_fwban_rh table if it doesn't exist 54 | $Query = " 55 | IF NOT EXISTS (SELECT 1 FROM SYSOBJECTS WHERE NAME = 'hm_fwban_rh') 56 | BEGIN 57 | CREATE TABLE hm_fwban_rh ( 58 | id int IDENTITY(1,1) NOT NULL PRIMARY KEY, 59 | timestamp datetime NOT NULL, 60 | ipaddress varchar(15) NOT NULL 61 | ipid int DEFAULT NULL, 62 | ) 63 | END; 64 | " 65 | RunSQLQuery $Query 66 | 67 | # Create hm_fwban_blocks_ip table if it doesn't exist 68 | $Query = " 69 | IF NOT EXISTS (SELECT 1 FROM SYSOBJECTS WHERE NAME = 'hm_fwban_blocks_ip') 70 | BEGIN 71 | CREATE TABLE hm_fwban_blocks_ip ( 72 | id INT IDENTITY(1,1) NOT NULL, 73 | ipaddress varchar(15) NOT NULL UNIQUE, 74 | hits INT, 75 | lasttimestamp datetime NOT NULL, 76 | PRIMARY KEY (id) 77 | ) 78 | END; 79 | " 80 | RunSQLQuery $Query 81 | 82 | # Create hm_ids table if it doesn't exist 83 | $Query = " 84 | IF NOT EXISTS (SELECT 1 FROM SYSOBJECTS WHERE NAME = 'hm_ids') 85 | BEGIN 86 | CREATE TABLE hm_ids ( 87 | timestamp datetime NOT NULL, 88 | ipaddress varchar(15) NOT NULL PRIMARY KEY, 89 | hits int NOT NULL, 90 | country varchar(64) DEFAULT NULL, 91 | helo varchar(128) DEFAULT NULL 92 | ) 93 | END; 94 | " 95 | RunSQLQuery $Query 96 | } 97 | 98 | If ($DatabaseType -eq "MYSQL") { 99 | 100 | # Create hm_fwban table if it doesn't exist 101 | $Query = " 102 | CREATE TABLE IF NOT EXISTS hm_fwban ( 103 | ID int(11) NOT NULL AUTO_INCREMENT, 104 | ipaddress varchar(192) NOT NULL, 105 | timestamp datetime NOT NULL, 106 | ban_reason varchar(192) DEFAULT NULL, 107 | country varchar(192) DEFAULT NULL, 108 | flag int(1) DEFAULT NULL, 109 | helo varchar(192) DEFAULT NULL, 110 | ptr varchar(192) DEFAULT NULL, 111 | rulename varchar(192) DEFAULT NULL, 112 | PRIMARY KEY (ID), 113 | KEY ipaddress (ipaddress) 114 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 115 | COMMIT; 116 | " 117 | RunSQLQuery $Query 118 | 119 | # Create hm_fwban_rh table if it doesn't exist 120 | $Query = " 121 | CREATE TABLE IF NOT EXISTS hm_fwban_rh ( 122 | id int(24) NOT NULL AUTO_INCREMENT, 123 | ipid INT(22) NULL, 124 | timestamp datetime NOT NULL, 125 | ipaddress varchar(15) NOT NULL, 126 | PRIMARY KEY (id), 127 | KEY timestamp (timestamp) 128 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 129 | COMMIT; 130 | " 131 | RunSQLQuery $Query 132 | 133 | # Create hm_fwban_blocks_ip table if it doesn't exist 134 | $Query = " 135 | CREATE TABLE IF NOT EXISTS hm_fwban_blocks_ip ( 136 | id INT(22) NOT NULL AUTO_INCREMENT, 137 | ipaddress varchar(15) NOT NULL UNIQUE, 138 | hits INT(8), 139 | lasttimestamp datetime NOT NULL, 140 | PRIMARY KEY (id) 141 | UNIQUE KEY ipaddress (ipaddress) 142 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 143 | COMMIT; 144 | " 145 | RunSQLQuery $Query 146 | 147 | # Create hm_ids table if it doesn't exist 148 | $Query = " 149 | CREATE TABLE IF NOT EXISTS hm_ids ( 150 | timestamp datetime NOT NULL, 151 | ipaddress varchar(15) NOT NULL, 152 | hits int(8) NOT NULL, 153 | country varchar(64) DEFAULT NULL, 154 | PRIMARY KEY (ipaddress), 155 | UNIQUE KEY ipaddress (ipaddress) 156 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 157 | COMMIT; 158 | " 159 | RunSQLQuery $Query 160 | } 161 | -------------------------------------------------------------------------------- /www/release-date-view.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 |
"; 24 | } elseif (empty($dateTo)){ 25 | echo "You did not put in an ending date. Both beginning and ending dates are required for date range release even if the range is a single day.

"; 26 | } else { 27 | 28 | $no_of_records_per_page = 20; 29 | $offset = ($page-1) * $no_of_records_per_page; 30 | $total_pages_sql = $pdo->prepare(" 31 | SELECT 32 | Count( * ) AS count 33 | FROM hm_fwban 34 | WHERE timestamp BETWEEN '{$dateFrom} 00:00:00' AND '{$dateTo} 23:59:59' AND (flag IS NULL OR flag=3) 35 | "); 36 | $total_pages_sql->execute(); 37 | $total_rows = $total_pages_sql->fetchColumn(); 38 | $total_pages = ceil($total_rows / $no_of_records_per_page); 39 | 40 | $sql = $pdo->prepare(" 41 | SELECT 42 | id, 43 | ".DBFormatDate('timestamp', '%y/%m/%d %T')." as TimeStamp, 44 | ipaddress, 45 | ban_reason, 46 | country, 47 | flag 48 | FROM hm_fwban 49 | WHERE timestamp BETWEEN '{$dateFrom} 00:00:00' AND '{$dateTo} 23:59:59' AND (flag IS NULL OR flag=3) 50 | ".DBLimitRowsWithOffset('TimeStamp','DESC',0,0,$offset,$no_of_records_per_page) 51 | ); 52 | $sql->execute(); 53 | 54 | if ($total_rows == 1){$singular = '';} else {$singular= 's';} 55 | if ($total_rows == 0){ 56 | echo "

No unreleased results for date range \"".$dateFrom."\" to \"".$dateTo."\""; 57 | } else { 58 | echo "

What would you like to release?

"; 59 | echo "Click \"NO\" under column \"RS\" to release a single address.

"; 60 | echo "Click here to release all.
"; 61 | echo "

"; 62 | echo "Results for date range \"".$dateFrom."\" to \"".$dateTo."\": ".number_format($total_rows)." IP".$singular." (Page: ".number_format($page)." of ".number_format($total_pages).")
"; 63 | echo " 64 | 65 | 66 | 67 | 68 | 69 | 70 | "; 71 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 72 | echo ""; 73 | 74 | echo ""; 75 | echo ""; 76 | echo ""; 77 | echo ""; 78 | if($row['flag'] === NULL || $row['flag'] == 3) echo ""; 79 | else echo ""; 80 | 81 | echo ""; 82 | } 83 | echo "
TimestampIP AddressReasonCountryRS
" . $row['TimeStamp'] . "" . $row['ipaddress'] . "" . $row['ban_reason'] . "" . $row['country'] . "NoYES
"; 84 | 85 | if ($total_pages == 1){ 86 | echo ""; 87 | } else { 88 | echo "
    "; 89 | if($page <= 1){echo "
  • First
  • ";} else {echo "
  • First
  • ";} 90 | if($page <= 1){echo "
  • Prev
  • ";} else {echo "
  • Prev
  • ";} 91 | if($page >= $total_pages){echo "
  • Next
  • ";} else {echo "
  • Next
  • ";} 92 | if($page >= $total_pages){echo "
  • Last
  • ";} else {echo "
  • Last
  • ";} 93 | echo "
"; 94 | } 95 | } 96 | } 97 | echo "
"; 98 | ?> 99 | 100 |
101 | 102 | -------------------------------------------------------------------------------- /www/reban-date-view.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 |
You did not put in a beginning date. Both beginning and ending dates are required for date range release even if the range is a single day.

"; 24 | } elseif (empty($dateTo)){ 25 | echo "

You did not put in an ending date. Both beginning and ending dates are required for date range release even if the range is a single day.

"; 26 | } else { 27 | 28 | $no_of_records_per_page = 20; 29 | $offset = ($page-1) * $no_of_records_per_page; 30 | $total_pages_sql = $pdo->prepare(" 31 | SELECT 32 | Count( * ) AS count 33 | FROM hm_fwban 34 | WHERE timestamp BETWEEN '{$dateFrom} 00:00:00' AND '{$dateTo} 23:59:59' AND (flag=1 OR flag=2) 35 | "); 36 | $total_pages_sql->execute(); 37 | $total_rows = $total_pages_sql->fetchColumn(); 38 | $total_pages = ceil($total_rows / $no_of_records_per_page); 39 | 40 | $sql = $pdo->prepare(" 41 | SELECT 42 | id, 43 | ".DBFormatDate('timestamp', '%y/%m/%d %T')." as TimeStamp, 44 | ipaddress, 45 | ban_reason, 46 | country, 47 | flag, 48 | helo 49 | FROM hm_fwban 50 | WHERE timestamp BETWEEN '{$dateFrom} 00:00:00' AND '{$dateTo} 23:59:59' AND (flag=1 OR flag=2) 51 | ".DBLimitRowsWithOffset('TimeStamp','DESC',0,0,$offset,$no_of_records_per_page) 52 | ); 53 | $sql->execute(); 54 | 55 | if ($total_rows == 1){$singular = '';} else {$singular= 's';} 56 | if ($total_rows == 0){ 57 | echo "

No previously released results for date range \"".$dateFrom."\" to \"".$dateTo."\""; 58 | } else { 59 | echo "

What would you like to ban?

"; 60 | echo "Click \"YES\" under column \"RS\" to re-ban a single address.

"; 61 | echo "Click here to re-ban all.
"; 62 | echo "

"; 63 | echo "Results for released IPs in date range \"".$dateFrom."\" to \"".$dateTo."\": ".number_format($total_rows)." IP".$singular." (Page: ".number_format($page)." of ".number_format($total_pages).")
"; 64 | echo " 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | "; 73 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 74 | 75 | echo ""; 76 | 77 | echo ""; 78 | echo ""; 79 | echo ""; 80 | echo ""; 81 | echo ""; 82 | if($row['flag'] == 1 || $row['flag'] == 2) echo ""; 83 | else echo ""; 84 | 85 | echo ""; 86 | } 87 | echo "
TimestampIP AddressReasonCountryHELORS
".$row['TimeStamp']."".$row['ipaddress']."".$row['ban_reason']."" . $row['country'] . "".$row['helo']."YESNO
"; 88 | 89 | echo "
    "; 90 | if($page <= 1){echo "
  • First
  • ";} else {echo "
  • First
  • ";} 91 | if($page <= 1){echo "
  • Prev
  • ";} else {echo "
  • Prev
  • ";} 92 | if($page >= $total_pages){echo "
  • Next
  • ";} else {echo "
  • Next
  • ";} 93 | if($page >= $total_pages){echo "
  • Last
  • ";} else {echo "
  • Last
  • ";} 94 | echo "
"; 95 | echo "
RS = Released Status (removal from firewall). Clicking on \"YES\" will re-ban the IP.

"; 96 | } 97 | } 98 | echo "
"; 99 | ?> 100 |
101 | -------------------------------------------------------------------------------- /hmsConsolidateRules.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | _ _ _ _ _ _ _ ____ ____ ____ _ _ ____ ____ 3 | |__| |\/| /_\ | | [__ |___ |__/ | | |___ |__/ 4 | | | | |/ \| |___ ___] |___ | \ \/ |___ | \ 5 | ____ _ ____ ____ _ _ _ _ _ _ ___ _ _ _ 6 | |___ | |__/ |___ | | | /_\ | | |__] /_\ |\ | 7 | | | | \ |___ |_|_|/ \|___ |___ |__]/ \| \| 8 | 9 | .SYNOPSIS 10 | Powershell script to consolidate firewall rules 11 | 12 | .DESCRIPTION 13 | Consolidates rules from one firewall rule per IP to one firewall rule per day containing all IPs for the previous day 14 | 15 | .FUNCTIONALITY 16 | * Queries database for previous day's bans 17 | * Creates new firewall containing all of previous day's banned IPs 18 | * Deletes all of previous day's one-IP-per firewall rules 19 | 20 | .NOTES 21 | * Create scheduled task to run once per day at 12:01 am 22 | 23 | .EXAMPLE 24 | 25 | #> 26 | 27 | # Include required files 28 | Try { 29 | .("$PSScriptRoot\Config.ps1") 30 | .("$PSScriptRoot\CommonCode.ps1") 31 | } 32 | Catch { 33 | Write-Output "$((get-date).ToString(`"yy/MM/dd HH:mm:ss.ff`")) : ERROR : Unable to load supporting PowerShell Scripts : $query `n$Error[0]" | out-file "$PSScriptRoot\PSError.log" -append 34 | } 35 | 36 | $ConsFolder = "$PSScriptRoot\ConsolidateRules" 37 | 38 | # Create ConsolidateRules folder if it doesn't exist 39 | If (-not(Test-Path $ConsFolder)) { 40 | md $ConsFolder 41 | } 42 | 43 | # Delete all files in the Consolidated Rules folder before beginning 44 | Get-ChildItem -Path $ConsFolder -Include * | foreach { $_.Delete()} 45 | 46 | # Get BanDate (Yesterday) and establish csv 47 | $BanDate = (Get-Date).AddDays(-1).ToString("yyyy-MM-dd") 48 | 49 | $Query = "SELECT COUNT(id) AS countid FROM hm_fwban WHERE $(DBCastDateTimeFieldAsDate('timestamp')) LIKE '$BanDate%' AND flag IS NULL" 50 | RunSQLQuery $Query | ForEach { 51 | [int]$CountIP = $_.countid 52 | } 53 | 54 | $N = 0 55 | $Rows = 400 56 | $Limit = [math]::ceiling($CountIP / $Rows) 57 | 58 | If ($Limit -eq 0){ 59 | Exit 60 | } 61 | ElseIf ($Limit -eq 1){ 62 | $ConsRules = "$ConsFolder\hMS FWBan "+$BanDate+".csv" 63 | $Query = " 64 | SELECT 65 | ipaddress 66 | FROM hm_fwban 67 | WHERE $(DBCastDateTimeFieldAsDate('timestamp')) LIKE '$BanDate%' AND flag IS NULL 68 | ORDER BY timestamp DESC 69 | $(DBLimitRowsWithOffset $($N * $Rows) $Rows) 70 | " 71 | RunSQLQuery $Query | Export-CSV $ConsRules 72 | } 73 | Else { 74 | Do { 75 | $X = ($N).ToString("0") 76 | $ConsRules = "$ConsFolder\hMS FWBan "+$BanDate+"_"+$X+".csv" 77 | $Query = " 78 | SELECT 79 | ipaddress 80 | FROM hm_fwban 81 | WHERE $(DBCastDateTimeFieldAsDate('timestamp')) LIKE '$BanDate%' AND flag IS NULL 82 | ORDER BY timestamp DESC 83 | $(DBLimitRowsWithOffset $($N * $Rows) $Rows) 84 | " 85 | RunSQLQuery $Query | Export-CSV $ConsRules 86 | 87 | $N++ 88 | } 89 | Until ($N -eq $Limit) 90 | } 91 | 92 | $RegexName = '^hMS\sFWBan\s202[0-9]\-[0-9]{2}\-[0-9]{2}(_[0-9]{1,3})?\.csv$' 93 | $RegexIP = '(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' 94 | Get-ChildItem $ConsFolder | Where-Object {$_.name -match "hMS FWBan $BanDate"} | ForEach { 95 | $FileName = $_.name 96 | $FilePathName = "$ConsFolder\$FileName" 97 | $RuleName = ($FileName).Replace(".csv", "") 98 | import-csv -Path $FilePathName | ForEach { 99 | $IP = $_.ipaddress 100 | $Query = "UPDATE hm_fwban SET rulename = '$RuleName' WHERE ipaddress = '$IP'" 101 | RunSQLQuery($Query) 102 | Write-Output $IP 103 | } | Out-File "$FilePathName.txt" 104 | 105 | # Make sure txt file path exists 106 | If (Test-Path "$FilePathName.txt"){ 107 | $RuleData = Get-Content "$FilePathName.txt" | Select-Object -First 1 108 | # Make sure txt file is populated with IP data (if not, you'll have a rule banning all local and all remote IPs) 109 | If ($RuleData -match $RegexIP){ 110 | 111 | # Replace all newlines and last comma in order to create a single string that can be used to populate firewall rule remoteaddress 112 | $NL = [System.Environment]::NewLine 113 | $Content=[String] $Template= [System.IO.File]::ReadAllText("$FilePathName.txt") 114 | $Content.Replace($NL,",") | Out-File "$FilePathName.rule.txt" 115 | (Get-Content -Path "$FilePathName.rule.txt") -Replace ',$','' | Set-Content -Path "$FilePathName.rule.txt" 116 | 117 | # Add firewall rule with string containing all IPs from yesterday's bans 118 | & netsh advfirewall firewall add rule name="$RuleName" description="FWB Rules for $BanDate" dir=in interface=any action=block remoteip=$(Get-Content "$FilePathName.rule.txt") 119 | 120 | # Read csv and delete each of yesterday's individual IP firewall rules 121 | Import-CSV $FilePathName | ForEach { 122 | $IP = $_.ipaddress 123 | & netsh advfirewall firewall delete rule name=`"$IP`" 124 | } 125 | } 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /hmsDuplicateRuleFinder.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | _ _ _ _ _ _ _ ____ ____ ____ _ _ ____ ____ 3 | |__| |\/| /_\ | | [__ |___ |__/ | | |___ |__/ 4 | | | | |/ \| |___ ___] |___ | \ \/ |___ | \ 5 | ____ _ ____ ____ _ _ _ _ _ _ ___ _ _ _ 6 | |___ | |__/ |___ | | | /_\ | | |__] /_\ |\ | 7 | | | | \ |___ |_|_|/ \|___ |___ |__]/ \| \| 8 | 9 | .SYNOPSIS 10 | Deduplicate + De-Orphan Firewall Rules 11 | 12 | .DESCRIPTION 13 | Removes duplicate firewall rules and orphans (rules that should have been deleted upon release) 14 | 15 | .FUNCTIONALITY 16 | * Reads firewall rules & selects only ones named as IP (will not select consolidated date rules) 17 | * Finds duplicates in list and deletes them 18 | * Finds orphans and deletes them 19 | 20 | .NOTES 21 | * Create scheduled task to run daily 22 | * Best time to run scheduled task is immediately after running hmsConsolidateRules.ps1 23 | 24 | .EXAMPLE 25 | 26 | #> 27 | 28 | # Include required files 29 | Try { 30 | .("$PSScriptRoot\Config.ps1") 31 | .("$PSScriptRoot\CommonCode.ps1") 32 | } 33 | Catch { 34 | Write-Output "Error while loading supporting PowerShell Scripts" | Out-File -Path "$PSScriptRoot\PSError.log" 35 | } 36 | 37 | # Establish Duplicate Rules Folder 38 | $DupFolder = "$PSScriptRoot\DuplicateRules" 39 | 40 | # Create ConsolidateRules folder if it doesn't exist 41 | If (-not(Test-Path $DupFolder)) { 42 | md $DupFolder 43 | } 44 | 45 | # Delete all files in the Duplicate Rules Folder - don't want to confuse rule creation 46 | Get-ChildItem -Path $DupFolder -Include * | foreach { $_.Delete()} 47 | 48 | # Establish files and regex 49 | $FWRuleList = "$DupFolder\fwrulelist.txt" 50 | $DupList = "$DupFolder\fwduplist.txt" 51 | $RegexIP = '(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' 52 | $RegexConsName = 'hMS\sFWBan\s20[0-9]{2}\-[0-9]{2}\-[0-9]{2}(_[0-9]{2})?' 53 | $NL = [System.Environment]::NewLine 54 | 55 | # Read rules from firewall and output only ones with IP name (unconsolidated rules) 56 | Get-NetshFireWallrule ("all") | ForEach { 57 | If (($_.RuleName -match $RegexIP) -or ($_.RuleName -match $RegexConsName)){ 58 | Write-Output $_.RuleName 59 | } 60 | } | out-file $FWRuleList 61 | 62 | # Find duplicates and output as list 63 | $A = Get-Content $FWRuleList 64 | $HT = @{} 65 | $A | ForEach {$HT["$_"] += 1} 66 | # For each duplicate, get RemoteIPs and delete firewall ALL duplicate rules 67 | $HT.Keys | Where {$HT["$_"] -gt 1} | ForEach { 68 | $RuleName = $_ 69 | $RuleNameFile = "$DupFolder\$RuleName.txt" 70 | Get-NetshFireWallrule $RuleName | ForEach { 71 | Write-Output $_.RemoteIP 72 | } | Out-File $RuleNameFile 73 | & netsh advfirewall firewall delete rule name=`"$RuleName`" 74 | } 75 | 76 | # Look in Duplicate Rules folder and massage the data 77 | Get-ChildItem $DupFolder | Where-Object {($_.name -match "$RegexIP.txt") -or ($_.name -match "$RegexConsName.txt")} | ForEach { 78 | $RuleNameFileIP = $_.name 79 | $RuleData = Get-Content -Path "$DupFolder\$RuleNameFileIP" | Select-Object -First 1 80 | # Make sure txt file is populated with IP data (if not, you'll have a rule banning all local and all remote IPs) 81 | If ($RuleData -match $RegexIP){ 82 | # Remove duplicate RemoteIP strings, remove /32 from RemoteIP, remove NewLines, remove comma at end of RemoteIP string, then add one firewall rule to replace duplicates 83 | Get-Content -Path "$DupFolder\$RuleNameFileIP" | Select -First 1 | Out-File "$DupFolder\$RuleNameFileIP.ip.txt" 84 | (Get-Content -Path "$DupFolder\$RuleNameFileIP.ip.txt") -Replace '\/32','' | Set-Content -Path "$DupFolder\$RuleNameFileIP.ip.txt" 85 | (Get-Content -Path "$DupFolder\$RuleNameFileIP.ip.txt") -Replace $NL,'' | Set-Content -Path "$DupFolder\$RuleNameFileIP.ip.txt" 86 | (Get-Content -Path "$DupFolder\$RuleNameFileIP.ip.txt") -Replace ',$','' | Set-Content -Path "$DupFolder\$RuleNameFileIP.ip.txt" 87 | # Duplicate rule could be either today's IP name or consolidated date name. 88 | If ($RuleNameFileIP -match $RegexIP){ 89 | $FWRNIP = $RuleNameFileIP.Split(".") 90 | $FWRN = $FWRNIP[0]+"."+$FWRNIP[1]+"."+$FWRNIP[2]+"."+$FWRNIP[3] 91 | } Else { 92 | $FWRN = $RuleNameFileIP.Split(".")[0] 93 | } 94 | # Double check rule has RemoteIP data in case something went wrong with naming scheme 95 | If ((Get-Content -Path "$DupFolder\$RuleNameFileIP") -match $RegexIP){ 96 | & netsh advfirewall firewall add rule name="$FWRN" description="Rule added $((get-date).ToString('MM/dd/yy')) - DUP" dir=in interface=any action=block remoteip=$(Get-Content -Path "$DupFolder\$FWRN.txt.ip.txt") 97 | } Else { 98 | $EmailBody = "Warning! hmsDuplicateRuleFinder attempting to create rule $FWRN which has NO remote IP! Can result in blocking 100% of inbound traffic - locking you OUT. Contact developer at https://github.com/palinkas-jo-reggelt/hMailServer-Firewall-Ban/issues for solution." 99 | EmailResults 100 | } 101 | } 102 | } -------------------------------------------------------------------------------- /BlockCount.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | _ _ _ _ __ _ _ ____ ____ ____ _ _ ____ ____ 3 | |__| |\/| /__\ | | [__ |___ |__/ | | |___ |__/ 4 | | | | |/ \| |___ ___] |___ | \ \/ |___ | \ 5 | 6 | ____ _ ____ ____ _ _ _ __ _ _ ___ __ _ _ 7 | |___ | |__/ |___ | | | /__\ | | |__] /__\ |\ | 8 | | | | \ |___ |_|_|/ \|___ |___ |__]/ \| \| 9 | 10 | .SYNOPSIS 11 | Analysis of Blocked IPs (firewall log drops) 12 | 13 | .DESCRIPTION 14 | Counts number of firewall drops for a given number of days 15 | 16 | .FUNCTIONALITY 17 | Run whenever you're curious 18 | 19 | .NOTES 20 | Script runs until there are 0 firewall drops for a given number of days 21 | 22 | .EXAMPLE 23 | 24 | #> 25 | 26 | # Include required files 27 | Try { 28 | .("$PSScriptRoot\Config.ps1") 29 | .("$PSScriptRoot\CommonCode.ps1") 30 | } 31 | Catch { 32 | Write-Output "$((get-date).ToString(`"yy/MM/dd HH:mm:ss.ff`")) : ERROR : Unable to load supporting PowerShell Scripts : $query `n$Error[0]" | out-file "$PSScriptRoot\PSError.log" -append 33 | } 34 | 35 | $EmailBody = "$PSScriptRoot\BlockCountEmailBody.txt" 36 | 37 | # Delete old files if exist 38 | If (Test-Path $EmailBody) {Remove-Item -Force -Path $EmailBody} 39 | 40 | Write-Output ' 41 | 42 | 43 | 44 | hMailServer Firewall Ban 45 | 46 | 47 | 48 | 49 | 50 |
51 | ' | Out-File $EmailBody -append 52 | 53 | Write-Output ' 54 | 55 | hMailServer Firewall Ban Project
56 | Block Count
57 | Count repeat drops from firewall log

58 | 59 | ' | out-file $EmailBody -append 60 | 61 | $StartTime = get-date 62 | 63 | Write-Output "Run : $(Get-Date -f g)

" | out-file $EmailBody -append 64 | 65 | # Find oldest database entry and count days. 66 | $Query = "Select MIN(timestamp) AS mints FROM hm_fwban" 67 | MySQLQuery($Query) | ForEach { 68 | $Oldest = $_.mints 69 | } 70 | $NumDays = (New-TimeSpan $Oldest $(Get-Date)).Days 71 | 72 | Write-Output ("{0,7} : Number of days data in database

" -f ($NumDays).ToString("#,###")) | out-file $EmailBody -append 73 | 74 | # Count number of bans in firewall ban database 75 | $Query = "Select COUNT(ipaddress) AS countip from hm_fwban WHERE flag IS NULL" 76 | MySQLQuery($Query) | ForEach { 77 | $TotalRules = $_.countip 78 | } 79 | Write-Output ("{0,7} : Total number of IPs banned

" -f ($TotalRules).ToString("#,###")) | out-file $EmailBody -append 80 | 81 | # Count number of distinct IPs recorded in repeat hit database 82 | $Query = "Select COUNT(DISTINCT(ipaddress)) AS totalreturnips, COUNT(ipaddress) AS totalhits FROM hm_fwban_rh" 83 | MySQLQuery($Query) | ForEach { 84 | $TotalReturnIPs = $_.totalreturnips 85 | } 86 | 87 | # Subtract distinct IPs in RH database from number of bans in FWB database to derive number of FWBans that never returned 88 | $PercentReturns = ([int]$TotalReturnIPs / [int]$TotalRules).ToString("P") 89 | $NeverBlocked = ([int]$TotalRules - [int]$TotalReturnIPs) 90 | $PercentNever = ([int]$NeverBlocked / [int]$TotalRules).ToString("P") 91 | Write-Output ("{0,7} : {1,6} : Number of banned IPs that never returned

" -f ($NeverBlocked).ToString("#,###"), $PercentNever) | out-file $EmailBody -append 92 | 93 | # Find number of distinct IPs that were blocked for a given number of days and continue until no results are found 94 | $a = 0 95 | Write-Output " 96 | 97 | " | out-file $EmailBody -append 98 | Do { 99 | $Query = "SELECT COUNT(*) AS countips FROM (SELECT ipaddress, COUNT(DISTINCT(DATE(timestamp))) AS countdate FROM hm_fwban_rh GROUP BY ipaddress HAVING countdate > $a) AS returnhits" 100 | MySQLQuery($Query) | ForEach { 101 | $ReturnIPs = $_.countips 102 | } 103 | $PercentReturns = ($ReturnIPs / $TotalRules) 104 | If ($ReturnIPs -lt 1) { 105 | Write-Output "
No. of banned IPsPercent ReturnsReturned at least

No more results

" | out-file $EmailBody -append 106 | $TimeElapsed = (New-TimeSpan $StartTime $(get-date)) 107 | If (($TimeElapsed).Minutes -eq 1) {$sm = ""} Else {$sm = "s"} 108 | If (($TimeElapsed).Seconds -eq 1) {$ss = ""} Else {$ss = "s"} 109 | Write-Output ("Time Elapsed: {0:%m} minute$sm {0:%s} second$ss" -f $TimeElapsed) | out-file $EmailBody -append 110 | } Else { 111 | If ($a -eq 0) {$sd = ""} Else {$sd = "s"} 112 | Write-Output (" {0,7} {1,6} $($a + 1) day$sd" -f ($ReturnIPs).ToString("#,###"), $PercentReturns.ToString("P")) | out-file $EmailBody -append 113 | } 114 | $a++ 115 | } Until ($ReturnIPs -lt 1) 116 | 117 | Write-Output ' 118 | 119 |

120 | 121 |
122 | 123 | 124 | ' | Out-File $EmailBody -append 125 | 126 | $HTML = 'True' 127 | EmailResults $HTML -------------------------------------------------------------------------------- /www/repeats-date.php: -------------------------------------------------------------------------------- 1 | 2 | "; 20 | echo "

Search a date range for connections blocked by firewall:

"; 21 | echo "Enter start & end dates and click to search.

"; 22 | echo "
"; 23 | echo ""; 24 | echo ""; 25 | echo ""; 26 | echo ""; 27 | echo "
Starting Date:
Ending Date:
"; 28 | echo "
"; 29 | echo "
"; 30 | echo "
"; 31 | 32 | if (empty($dateFrom)){ 33 | echo "Note: Range can be a single day, but start and end dates must both be filled in.

"; 34 | } elseif (empty($dateTo)){ 35 | echo "You did not put in an ending date. Both beginning and ending dates are required for date range release even if the range is a single day.

"; 36 | } else { 37 | 38 | $no_of_records_per_page = 20; 39 | $offset = ($page-1) * $no_of_records_per_page; 40 | 41 | $total_pages_sql = $pdo->prepare(" 42 | SELECT 43 | COUNT(DISTINCT(ipaddress)) 44 | FROM ( 45 | SELECT * 46 | FROM hm_fwban_rh 47 | WHERE '".$dateFrom." 00:00:00' <= timestamp 48 | ) AS A 49 | WHERE timestamp <= '".$dateTo." 23:59:59' 50 | "); 51 | $total_pages_sql->execute(); 52 | $total_rows = $total_pages_sql->fetchColumn(); 53 | $total_pages = ceil($total_rows / $no_of_records_per_page); 54 | 55 | $sql = $pdo->prepare(" 56 | SELECT 57 | a.TimeStamp, 58 | a.ipaddress, 59 | b.ban_reason, 60 | b.country, 61 | a.countip 62 | FROM 63 | ( 64 | SELECT 65 | ipaddress, 66 | COUNT(ipaddress) AS countip, 67 | ".DBFormatDate('timestamp', '%y/%m/%d')." as TimeStamp 68 | FROM ( 69 | SELECT * 70 | FROM hm_fwban_rh 71 | WHERE '".$dateFrom." 00:00:00' <= timestamp 72 | ) AS A 73 | WHERE timestamp <= '".$dateTo." 23:59:59' 74 | GROUP BY ipaddress 75 | ) AS a 76 | JOIN 77 | ( 78 | SELECT 79 | ipaddress, 80 | country, 81 | ban_reason 82 | FROM hm_fwban 83 | ) AS b 84 | ON a.ipaddress = b.ipaddress 85 | GROUP BY a.ipaddress 86 | ".DBLimitRowsWithOffset('a.TimeStamp','DESC',0,0,$offset,$no_of_records_per_page) 87 | ); 88 | $sql->execute(); 89 | 90 | if ($total_rows == 1){$singular = '';} else {$singular= 's';} 91 | if ($total_rows == 0){ 92 | echo "

No results for date range \"".$dateFrom."\" to \"".$dateTo."\"".$RSres; 93 | } else { 94 | echo "Results for date range \"".$dateFrom."\" to \"".$dateTo."\": ".number_format($total_rows)." IP".$singular." (Page: ".number_format($page)." of ".number_format($total_pages).")
"; 95 | echo " 96 | 97 | 98 | 99 | 100 | 101 | 102 | "; 103 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 104 | echo ""; 105 | echo ""; 106 | echo ""; 107 | echo ""; 108 | echo ""; 109 | echo ""; 110 | echo ""; 111 | } 112 | echo "
TimestampIP AddressReasonCountryRH
".$row['TimeStamp']."".$row['ipaddress']."".$row['ban_reason']."".$row['country']."".number_format($row['countip'])."
"; 113 | 114 | if ($total_pages < 2){ 115 | echo "

"; 116 | } else { 117 | echo "
    "; 118 | if($page <= 1){echo "
  • First
  • ";} else {echo "
  • First
  • ";} 119 | if($page <= 1){echo "
  • Prev
  • ";} else {echo "
  • Prev
  • ";} 120 | if($page >= $total_pages){echo "
  • Next
  • ";} else {echo "
  • Next
  • ";} 121 | if($page >= $total_pages){echo "
  • Last
  • ";} else {echo "
  • Last
  • ";} 122 | echo "
"; 123 | } 124 | if ($total_pages > 0){ 125 | echo "RH = Repeat Hits
126 | RS = Released Status
"; 127 | } 128 | } 129 | } 130 | echo "
"; 131 | echo "
"; 132 | ?> 133 | 134 | -------------------------------------------------------------------------------- /www/release-iprange.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | - no IP range specified or
- malformed IP range/CIDR or
- CIDR outside program bounds of /22 to /32"; 32 | } else { 33 | 34 | $ips = ipRangeFinder($ipRange); 35 | $iplo = $ips[0]; 36 | $iphi = $ips[1]; 37 | 38 | $range = explode("/", $ipRange); 39 | $rcidr = $range[1]; 40 | $ip_count = 1 << (32 - $rcidr); 41 | 42 | $no_of_records_per_page = 20; 43 | $offset = ($page-1) * $no_of_records_per_page; 44 | $total_pages_sql = $pdo->prepare(" 45 | SELECT COUNT(*) AS count 46 | FROM hm_fwban 47 | WHERE INET_ATON(ipaddress) BETWEEN INET_ATON('".$iplo."') AND INET_ATON('".$iphi."') 48 | ORDER BY INET_ATON(ipaddress) ASC 49 | "); 50 | $total_pages_sql->execute(); 51 | $total_rows = $total_pages_sql->fetchColumn(); 52 | $total_pages = ceil($total_rows / $no_of_records_per_page); 53 | 54 | $sql = $pdo->prepare(" 55 | SELECT 56 | id, 57 | ".DBFormatDate('timestamp', '%y/%m/%d %T')." as TimeStamp, 58 | ipaddress, 59 | ban_reason, 60 | country, 61 | flag 62 | FROM hm_fwban 63 | WHERE INET_ATON(ipaddress) BETWEEN INET_ATON('".$iplo."') AND INET_ATON('".$iphi."') 64 | ".DBLimitRowsWithOffset('TimeStamp','DESC',0,0,$offset,$no_of_records_per_page) 65 | ); 66 | $sql->execute(); 67 | 68 | if ($total_rows == 1){$singular = '';} else {$singular= 's';} 69 | 70 | echo "

IP Range Information

"; 71 | echo " 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 |
IP RangeNetwork AddressBroadcast AddressIPs in range
".$ipRange."".$iplo."".$iphi."".$ip_count."


"; 85 | 86 | echo "

What would you like to release?

"; 87 | echo "Click \"NO\" under column \"RS\" to release a single address.

"; 88 | echo "Click here to release all ".number_format($total_rows)." IPs in range.
"; 89 | echo "

"; 90 | if ($total_pages == 0) { 91 | echo "No results from Firewall Ban found within IP range ".$ipRange; 92 | } else { 93 | echo "Firewall Ban results for IP range \"".$ipRange."\": ".number_format($total_rows)." IP".$singular." (Page: ".number_format($page)." of ".number_format($total_pages).")
"; 94 | echo " 95 | 96 | 97 | 98 | 99 | 100 | 101 | "; 102 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 103 | 104 | echo ""; 105 | 106 | echo ""; 107 | echo ""; 108 | echo ""; 109 | echo ""; 110 | if($row['flag']==NULL||$row['flag']==3||$row['flag']==4||$row['flag']==7) echo ""; 111 | elseif($row['flag'] == 1 || $row['flag'] == 2) echo ""; 112 | elseif($row['flag'] == 6 || $row['flag'] == 5) echo ""; 113 | else echo ""; 114 | 115 | echo ""; 116 | } 117 | echo "
TimestampIP AddressReasonCountryRS
".$row['TimeStamp']."".$row['ipaddress']."".$row['ban_reason']."".$row['country']."NOYESSAFERR
"; 118 | 119 | if ($total_pages < 2){ 120 | echo ""; 121 | } else { 122 | echo "
    "; 123 | if($page <= 1){echo "
  • First
  • ";} else {echo "
  • First
  • ";} 124 | if($page <= 1){echo "
  • Prev
  • ";} else {echo "
  • Prev
  • ";} 125 | if($page >= $total_pages){echo "
  • Next
  • ";} else {echo "
  • Next
  • ";} 126 | if($page >= $total_pages){echo "
  • Last
  • ";} else {echo "
  • Last
  • ";} 127 | echo "
"; 128 | } 129 | } 130 | } 131 | 132 | ?> 133 | 134 |
135 | 136 | -------------------------------------------------------------------------------- /www/reban-iprange.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | - no IP range specified or
- malformed IP range/CIDR or
- CIDR outside program bounds of /22 to /32"; 32 | } else { 33 | 34 | $ips = ipRangeFinder($ipRange); 35 | $iplo = $ips[0]; 36 | $iphi = $ips[1]; 37 | 38 | $range = explode("/", $ipRange); 39 | $rcidr = $range[1]; 40 | $ip_count = 1 << (32 - $rcidr); 41 | 42 | $no_of_records_per_page = 20; 43 | $offset = ($page-1) * $no_of_records_per_page; 44 | 45 | $total_pages_sql = $pdo->prepare(" 46 | SELECT COUNT(*) AS count 47 | FROM hm_fwban 48 | WHERE ".DBIpStringToIntField('ipaddress')." BETWEEN ".DBIpStringToIntValue($iplo)." AND ".DBIpStringToIntValue($iphi)." 49 | "); 50 | $total_pages_sql->execute(); 51 | $total_rows = $total_pages_sql->fetchColumn(); 52 | $total_pages = ceil($total_rows / $no_of_records_per_page); 53 | 54 | 55 | $sql = $pdo->prepare(" 56 | SELECT 57 | id, 58 | ".DBFormatDate('timestamp', '%y/%m/%d %T')." as TimeStamp, 59 | ipaddress, 60 | ban_reason, 61 | country, 62 | flag 63 | FROM hm_fwban 64 | WHERE ".DBIpStringToIntField('ipaddress')." BETWEEN ".DBIpStringToIntValue($iplo)." AND ".DBIpStringToIntValue($iphi)." 65 | ".DBLimitRowsWithOffset('TimeStamp','DESC',0,0,$offset,$no_of_records_per_page) 66 | ); 67 | $sql->execute(); 68 | 69 | if ($total_rows == 1){$singular = '';} else {$singular= 's';} 70 | 71 | echo "

IP Range Information

"; 72 | echo " 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 |
IP RangeNetwork AddressBroadcast AddressIPs in range
".$ipRange."".$iplo."".$iphi."".$ip_count."


"; 86 | 87 | echo "

What would you like to ban?

"; 88 | echo "Click \"YES\" under column \"RS\" to reban a single address (if previously released).

"; 89 | echo "Click here to ban all ".number_format($ip_count)." IPs in range. Duplicates will be deleted from the database prior to adding firewall rules.
"; 90 | echo "

"; 91 | if ($total_pages == 0) { 92 | echo "No existing results from Firewall Ban found within IP range ".$ipRange.""; 93 | } else { 94 | echo "Firewall Ban results for IP range \"".$ipRange."\": ".number_format($total_rows)." IP".$singular." (Page: ".number_format($page)." of ".number_format($total_pages).")
"; 95 | echo " 96 | 97 | 98 | 99 | 100 | 101 | 102 | "; 103 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 104 | 105 | echo ""; 106 | 107 | echo ""; 108 | echo ""; 109 | echo ""; 110 | echo ""; 111 | if($row['flag'] == 1 || $row['flag'] == 2) echo ""; 112 | elseif($row['flag']==NULL||$row['flag']==3||$row['flag']==4||$row['flag']==7) echo ""; 113 | elseif($row['flag'] == 6 || $row['flag'] == 5) echo ""; 114 | else echo ""; 115 | 116 | echo ""; 117 | } 118 | echo "
TimestampIP AddressReasonCountryRS
".$row['TimeStamp']."".$row['ipaddress']."".$row['ban_reason']."".$row['country']."YESNOSAFERR
"; 119 | 120 | if ($total_pages < 2){ 121 | echo ""; 122 | } else { 123 | echo "
    "; 124 | if($page <= 1){echo "
  • First
  • ";} else {echo "
  • First
  • ";} 125 | if($page <= 1){echo "
  • Prev
  • ";} else {echo "
  • Prev
  • ";} 126 | if($page >= $total_pages){echo "
  • Next
  • ";} else {echo "
  • Next
  • ";} 127 | if($page >= $total_pages){echo "
  • Last
  • ";} else {echo "
  • Last
  • ";} 128 | echo "
"; 129 | } 130 | } 131 | } 132 | 133 | // } 134 | ?> 135 |
136 | 137 | -------------------------------------------------------------------------------- /www/repeats.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 |
5 |

IPs blocked per day from inception:

6 |
7 |
8 |
9 |

Average blocks per hour from inception:

10 |
11 |
12 |
13 |
14 | 15 | 16 |
17 |
18 |

This Week's Daily Blocks:

19 | 20 | prepare(" 37 | SELECT 38 | COUNT(DISTINCT(ipaddress)) AS ipsblocked, 39 | COUNT(*) AS totalblocks 40 | FROM ( 41 | SELECT * 42 | FROM hm_fwban_rh 43 | WHERE '{$today} 00:00:00' <= timestamp 44 | ) AS A 45 | WHERE timestamp <= '{$today} 23:59:50' 46 | "); 47 | $sql->execute(); 48 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 49 | echo "".number_format($row['ipsblocked'])." IPs blocked Today attemtpting access ".number_format($row['totalblocks'])." times
"; 50 | } 51 | echo $dailyblocks; 52 | ?> 53 |
54 |
55 | 56 |
57 |

This Year's Monthly Blocks:

58 | 59 | prepare(" 65 | SELECT 66 | COUNT(DISTINCT(ipaddress)) AS ipsblocked, 67 | COUNT(*) AS totalblocks 68 | FROM ( 69 | SELECT * 70 | FROM hm_fwban_rh 71 | WHERE '{$thismonth}-01 00:00:00' <= timestamp 72 | ) AS A 73 | WHERE timestamp <= ".DBGetCurrentDateTime() 74 | ); 75 | $sql->execute(); 76 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 77 | echo "".number_format($row['ipsblocked'])." IPs blocked in ".date("F", strtotime($thismonth))." attemtpting access ".number_format($row['totalblocks'])." times
"; 78 | } 79 | 80 | echo $monthlyblocks; 81 | ?> 82 |
83 |
84 |
85 |
86 | 87 |
88 |
89 |

Search for Repeat Blocks by IP:

90 |
91 | 92 | 93 |
94 |
95 |
96 | 97 |
98 |

Search for Repeat Blocks by Date Range:

99 |
100 | 101 | 102 | 103 | 104 |
Starting Date:
Ending Date:
105 |
106 |
107 |
108 |
109 |
110 | 111 | 112 |
113 |
114 |

Mark an IP / IP Range Safe:

115 | Permanently release an IP range and mark it safe from future bans.

116 |
117 | 118 | 119 |
120 |
IP Ranges MUST be in:
121 | 255.255.255.255 OR
122 | 255.255.255.255/24 format.

123 | Single IPs will be automatically converted to /32 CIDR for search purposes. Netmask /22 - /32 only.
124 |
125 | 126 |
127 |

Disable IP Safe Status:

128 | Remove safe status from an IP and reban.

129 |
130 | 131 | 132 |
133 |
IP Ranges MUST be in:
134 | 255.255.255.255 OR
135 | 255.255.255.255/24 format.

136 | Single IPs will be automatically converted to /32 CIDR for search purposes. Netmask /22 - /32 only.
137 |
138 |
139 |
140 | 141 | 142 |
143 |
144 |

Blocks Analyzer

145 | See how many IPs have returned for a given number of days.

146 | Blocks Analyzer 147 |
148 | 149 |
150 |
151 |
152 |
153 | 154 | 155 |
156 | -------------------------------------------------------------------------------- /www/repeats-view.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 |

Search Repeat Hits (Connections Dropped at Firewall)

5 | 6 | ".$search.""; 35 | $ipdate = "IP"; 36 | } elseif (preg_match("/^20[0-9]{2}-[0-9]{2}$/", $search)) { 37 | $search_sql = " 38 | FROM ( 39 | SELECT * 40 | FROM hm_fwban_rh 41 | WHERE '".date('Y-m-d',(strtotime($search)))." 00:00:00' <= timestamp 42 | ) AS x 43 | WHERE timestamp <= '".date('Y-m-t',(strtotime($search)))." 23:59:59' 44 | "; 45 | $search_list = "matching month: ".date('F Y',(strtotime($search))).""; 46 | $ipdate = "Date"; 47 | } elseif (preg_match("/^20[0-9]{2}-[0-9]{2}\-[0-9]{2}$/", $search)) { 48 | $search_sql = " 49 | FROM ( 50 | SELECT * 51 | FROM hm_fwban_rh 52 | WHERE '".date('Y-m-d',(strtotime($search)))." 00:00:00' <= timestamp 53 | ) AS x 54 | WHERE timestamp <= '".date('Y-m-d',(strtotime($search)))." 23:59:59' 55 | "; 56 | $search_list = "matching date: ".date('Y-m-d',(strtotime($search))).""; 57 | $ipdate = "Date"; 58 | } elseif ((!empty($search)) && (empty($ipdate))) { 59 | echo "You must enter a valid IP or date (format: YYYY-MM or YYYY-MM-DD). Showing all results."; 60 | $search_sql = "FROM hm_fwban_rh"; 61 | $search_list = ""; 62 | } else { 63 | $search_sql = "FROM hm_fwban_rh"; 64 | $search_list = ""; 65 | } 66 | 67 | if ($search==""){$search_page="";}else{$search_page="&search=".$search;} 68 | if ($search==""){$search_all="All ";}else{$search_all="";} 69 | if ($ipdate==""){$ipdate_page="";}else{$ipdate_page="&ipdate=".$ipdate;} 70 | 71 | echo "
"; 72 | echo "
"; 73 | echo ""; 74 | echo " "; 75 | echo ""; 76 | echo "
"; 77 | echo "
"; 78 | echo "
"; 79 | 80 | $no_of_records_per_page = 20; 81 | $offset = ($page-1) * $no_of_records_per_page; 82 | $total_pages_sql = $pdo->prepare(" 83 | SELECT 84 | COUNT(DISTINCT(ipaddress)) 85 | ".$search_sql 86 | ); 87 | $total_pages_sql->execute(); 88 | $total_rows = $total_pages_sql->fetchColumn(); 89 | $total_pages = ceil($total_rows / $no_of_records_per_page); 90 | 91 | $sql = $pdo->prepare(" 92 | SELECT 93 | a.TimeStamp, 94 | a.ipaddress, 95 | b.ban_reason, 96 | b.country, 97 | a.countip 98 | FROM 99 | ( 100 | SELECT 101 | DISTINCT(ipaddress), 102 | COUNT(ipaddress) AS countip, 103 | ".DBFormatDate('MAX(timestamp)', '%y/%m/%d %T')." as TimeStamp 104 | ".$search_sql." 105 | GROUP BY ipaddress 106 | ) AS a 107 | JOIN 108 | ( 109 | SELECT 110 | ipaddress, 111 | country, 112 | ban_reason 113 | FROM hm_fwban 114 | ) AS b 115 | ON a.ipaddress = b.ipaddress 116 | ".DBLimitRowsWithOffset('a.TimeStamp','DESC',0,0,$offset,$no_of_records_per_page) 117 | ); 118 | $sql->execute(); 119 | 120 | if ($total_rows == 1){$singular = '';} else {$singular= 's';} 121 | if ($total_rows == 0){ 122 | echo "
There are no repeat drops to report ".$search_list.". Please enter only IP address or date."; 123 | } else { 124 | echo $search_all."".number_format($total_rows)." IP".$singular." repeatedly dropped at firewall ".$search_list.". (Page: ".number_format($page)." of ".number_format($total_pages).")
"; 125 | echo " 126 | 127 | 128 | 129 | 130 | 131 | 132 | "; 133 | 134 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 135 | echo ""; 136 | echo ""; 137 | echo ""; 138 | echo ""; 139 | echo ""; 140 | if($row['countip']==0){echo "";} 141 | else{echo "";} 142 | echo ""; 143 | } 144 | echo "
Last HitIP AddressReasonCountryFB
".$row['TimeStamp']."".$row['ipaddress']."".$row['ban_reason']."".$row['country']."0".number_format($row['countip'])."
"; 145 | 146 | if ($total_pages < 2){ 147 | echo "

"; 148 | } else { 149 | echo "
    "; 150 | if($page <= 1){echo "
  • First
  • ";} else {echo "
  • First
  • ";} 151 | if($page <= 1){echo "
  • Prev
  • ";} else {echo "
  • Prev
  • ";} 152 | if($page >= $total_pages){echo "
  • Next
  • ";} else {echo "
  • Next
  • ";} 153 | if($page >= $total_pages){echo "
  • Last
  • ";} else {echo "
  • Last
  • ";} 154 | echo "
"; 155 | } 156 | if ($total_pages > 0){ 157 | echo "FB = Firewall Blocks
158 | RS = Released Status
"; 159 | } 160 | } 161 | echo "
"; 162 | 163 | ?> 164 |
165 | 166 | -------------------------------------------------------------------------------- /hmsConsolidateRulesMonthly.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | _ _ _ _ _ _ _ ____ ____ ____ _ _ ____ ____ 3 | |__| |\/| /_\ | | [__ |___ |__/ | | |___ |__/ 4 | | | | |/ \| |___ ___] |___ | \ \/ |___ | \ 5 | ____ _ ____ ____ _ _ _ _ _ _ ___ _ _ _ 6 | |___ | |__/ |___ | | | /_\ | | |__] /_\ |\ | 7 | | | | \ |___ |_|_|/ \|___ |___ |__]/ \| \| 8 | 9 | .SYNOPSIS 10 | Powershell script to consolidate daily firewall rules into monthly firewall rules 11 | 12 | .DESCRIPTION 13 | Powershell script to consolidate daily firewall rules into monthly firewall rules 14 | 15 | .FUNCTIONALITY 16 | * Queries firewall for previous month's rules 17 | * Creates new firewall rules containing all of previous month's banned IPs 18 | * Deletes all of previous month's daily firewall rules 19 | 20 | .NOTES 21 | * Create scheduled task to run once per day at 12:01 am (will run only on the first of the month) 22 | 23 | .EXAMPLE 24 | 25 | #> 26 | # Include required files 27 | Try { 28 | .("$PSScriptRoot\Config.ps1") 29 | .("$PSScriptRoot\CommonCode.ps1") 30 | } 31 | Catch { 32 | Write-Output "$((get-date).ToString(`"yy/MM/dd HH:mm:ss.ff`")) : ERROR : Unable to load supporting PowerShell Scripts : $query `n$Error[0]" | out-file "$PSScriptRoot\PSError.log" -append 33 | } 34 | 35 | # Run nightly but only trigger on the first of the month 36 | If ((Get-Date).ToString("dd") -notmatch '01') { Exit } 37 | 38 | $ConsFolder = "$PSScriptRoot\ConsolidateRulesMonthly" 39 | $EmailBody = "$PSScriptRoot\ConsolidateRulesMonthly\EmailBody.txt" 40 | 41 | # Create ConsolidateRules folder if it doesn't exist 42 | If (-not(Test-Path $ConsFolder)) { 43 | md $ConsFolder 44 | } 45 | 46 | # Delete all files in the Consolidated Rules folder before beginning 47 | Get-ChildItem -Path $ConsFolder -Include * | foreach { $_.Delete()} 48 | 49 | # Get BanDate (last month) and establish csv 50 | $BanDate = (Get-Date).AddMonths(-1).ToString("yyyy-MM") 51 | 52 | # Set up email result 53 | Write-Output "hMailServer Firewall Ban `n`nMonthly Rule Consolidation `n`n" | Out-File $EmailBody -Append 54 | 55 | # Establish files and regex 56 | $FWRuleList = "$ConsFolder\fwrulelist.txt" 57 | $RemoteIPList = "$ConsFolder\remoteiplist.txt" 58 | $RegexConsName = 'hMS\sFWBan\s20[0-9]{2}\-[0-9]{2}\-[0-9]{2}(_[0-9]{2})?' 59 | $NL = [System.Environment]::NewLine 60 | 61 | # Read rules from firewall and output only ones from last month 62 | Get-NetshFireWallrule ("all") | ForEach { 63 | If (($_.RuleName -match $RegexConsName) -and ($_.RuleName -match $BanDate)){ 64 | Write-Output $_.RuleName 65 | } 66 | } | Out-File $FWRuleList 67 | 68 | # Get list of rulenames, read RemoteIP from each rule, then output to a single list 69 | Get-Content -Path $FWRuleList | ForEach { 70 | $RuleDay = $_ 71 | Get-NetshFireWallrule ($RuleDay) | ForEach { 72 | $RemoteIP = $_.RemoteIP 73 | $ReplaceCIDR = ($RemoteIP).Replace("/32", "") 74 | Write-Output $ReplaceCIDR 75 | } 76 | } | Out-File $RemoteIPList 77 | 78 | # convert list to single string 79 | (Get-Content -Path $RemoteIPList) -Replace '$',',' | Set-Content -NoNewline -Path $RemoteIPList 80 | (Get-Content -Path $RemoteIPList) -Replace ',$','' | Set-Content -NoNewline -Path $RemoteIPList 81 | 82 | # Create new list for the purpose of updating rulename in database 83 | (Get-Content -Path $RemoteIPList) -Replace ',',$NL | Out-File "$RemoteIPList.updater.txt" 84 | $CountRemoteIPs = (Get-Content -Path "$RemoteIPList.updater.txt").Count 85 | Write-Output "There are $CountRemoteIPs IPs contained in $((Get-Content $FWRuleList).Count) firewall rules in the month of $((Get-Date $BanDate).ToString("MMMM")) $((Get-Date $BanDate).ToString("yyyy"))`n`n" | Out-File $EmailBody -Append 86 | 87 | $N = 0 88 | $Rows = 400 89 | $Limit = [math]::ceiling($CountRemoteIPs / $Rows) 90 | 91 | If ($Limit -eq 0){ 92 | Write-Output "WARNING - there are no rules to consolidate `n`nExiting operation - Bye..." | Out-File $EmailBody -Append 93 | EmailResults 94 | Exit 95 | } 96 | ElseIf ($Limit -eq 1){ 97 | # Add rule for last month 98 | $MonthRuleName = "hMS FWBan $BanDate" 99 | & netsh advfirewall firewall add rule name="$MonthRuleName" description="FWB Rules for $BanDate" dir=in interface=any action=block remoteip=$(Get-Content $RemoteIPList) 100 | Write-Output "Creating firewall rule : $MonthRuleName" | Out-File $EmailBody -Append 101 | 102 | # Delete last month's rules 103 | Get-Content -Path $FWRuleList | ForEach { 104 | $RuleToDelete = $_ 105 | & netsh advfirewall firewall delete rule name=`"$RuleToDelete`" 106 | Write-Output "Deleting firewall rule : $RuleToDelete" | Out-File $EmailBody -Append 107 | } 108 | 109 | # Update rulenames in database 110 | Get-Content -Path "$RemoteIPList.updater.txt" | ForEach { 111 | $IP = $_ 112 | $Query = "UPDATE hm_fwban SET rulename='$MonthRuleName' WHERE ipaddress='$IP'" 113 | RunSQLQuery $Query 114 | } 115 | } 116 | Else { 117 | Do { 118 | # Split up IPs into chunks for multiple rule creation 119 | $X = ($N).ToString("00") 120 | Get-Content "$RemoteIPList.updater.txt" | select -first $Rows -skip $($N * $Rows) | Out-File "$RemoteIPList.IPBatchForRemoteIP_$X.txt" 121 | (Get-Content "$RemoteIPList.IPBatchForRemoteIP_$X.txt") -Replace '$',',' | Set-Content -NoNewline -Path "$RemoteIPList.IPBatchForRuleCreation_$X.txt" 122 | (Get-Content "$RemoteIPList.IPBatchForRuleCreation_$X.txt") -Replace ',$','' | Set-Content -Path "$RemoteIPList.IPBatchForRuleCreation_$X.txt" 123 | 124 | # Create chunk rule 125 | $MonthRuleName = "hMS FWBan "+$BanDate+"_"+$X 126 | & netsh advfirewall firewall add rule name="$MonthRuleName" description="FWB Rules for $BanDate" dir=in interface=any action=block remoteip=$(Get-Content "$RemoteIPList.IPBatchForRuleCreation_$X.txt") 127 | Write-Output "Creating firewall rule : $MonthRuleName" | Out-File $EmailBody -Append 128 | 129 | # Update rulenames in database 130 | Get-Content "$RemoteIPList.IPBatchForRemoteIP_$X.txt" | ForEach { 131 | $IP = $_ 132 | $Query = "UPDATE hm_fwban SET rulename='$MonthRuleName' WHERE ipaddress='$IP'" 133 | RunSQLQuery $Query 134 | } 135 | 136 | $N++ 137 | } 138 | Until ($N -eq $Limit) 139 | 140 | # Delete last month's rules 141 | Get-Content -Path $FWRuleList | ForEach { 142 | $RuleToDelete = $_ 143 | & netsh advfirewall firewall delete rule name=`"$RuleToDelete`" 144 | Write-Output "Deleting firewall rule : $RuleToDelete" | Out-File $EmailBody -Append 145 | } 146 | } 147 | 148 | EmailResults -------------------------------------------------------------------------------- /www/search-date.php: -------------------------------------------------------------------------------- 1 | 2 | "; 20 | echo "

Search a date range:

"; 21 | echo "Enter start & end dates and click to search.

"; 22 | echo "
"; 23 | echo ""; 24 | echo ""; 25 | echo ""; 26 | echo ""; 32 | echo ""; 33 | echo "
Starting Date:
Ending Date:
Release Status: 27 |
"; 34 | echo "
"; 35 | echo "
"; 36 | echo "
"; 37 | 38 | if (empty($dateFrom)){ 39 | echo "Note: Range can be a single day, but start and end dates must both be filled in.

"; 40 | } elseif (empty($dateTo)){ 41 | echo "You did not put in an ending date. Both beginning and ending dates are required for date range release even if the range is a single day.

"; 42 | } else { 43 | 44 | $no_of_records_per_page = 20; 45 | $offset = ($page-1) * $no_of_records_per_page; 46 | 47 | if ($RS=="NO"){$RS_SQL = " AND (flag IS NULL OR flag=3)";} 48 | elseif ($RS=="YES"){$RS_SQL = " AND (flag=1 OR flag=2)";} 49 | else {$RS_SQL = "";} 50 | 51 | $total_pages_sql = $pdo->prepare(" 52 | SELECT 53 | Count(*) AS count 54 | FROM hm_fwban 55 | WHERE timestamp BETWEEN '{$dateFrom} 00:00:00' AND '{$dateTo} 23:59:59'".$RS_SQL 56 | ); 57 | $total_pages_sql->execute(); 58 | $total_rows = $total_pages_sql->fetchColumn(); 59 | $total_pages = ceil($total_rows / $no_of_records_per_page); 60 | 61 | $sql = $pdo->prepare(" 62 | SELECT 63 | a.tsf, 64 | a.ipaddress, 65 | a.ban_reason, 66 | a.country, 67 | a.flag, 68 | a.helo, 69 | a.ptr, 70 | b.returnhits 71 | FROM 72 | ( 73 | SELECT 74 | ".DBFormatDate('timestamp', '%y/%m/%d %T')." AS tsf, 75 | timestamp, 76 | ipaddress, 77 | ban_reason, 78 | country, 79 | flag, 80 | helo, 81 | ptr 82 | FROM hm_fwban 83 | WHERE timestamp BETWEEN '{$dateFrom} 00:00:00' AND '{$dateTo} 23:59:59'".$RS_SQL." 84 | ) AS a 85 | LEFT JOIN 86 | ( 87 | SELECT 88 | COUNT(ipaddress) AS returnhits, 89 | ipaddress 90 | FROM hm_fwban_rh 91 | ) AS b 92 | ON a.ipaddress = b.ipaddress 93 | ".DBLimitRowsWithOffset('a.tsf','DESC',0,0,$offset,$no_of_records_per_page) 94 | ); 95 | $sql->execute(); 96 | 97 | if ($RS=="YES"){$RSres=" with release status \"YES\"";} 98 | elseif ($RS=="NO"){$RSres=" with release status \"NO\"";} 99 | else {$RSres = "";} 100 | if ($total_rows == 1){$singular = '';} else {$singular= 's';} 101 | if ($total_rows == 0){ 102 | echo "

No results for date range \"".$dateFrom."\" to \"".$dateTo."\"".$RSres; 103 | } else { 104 | echo "Results for date range \"".$dateFrom."\" to \"".$dateTo."\"".$RSres.": ".number_format($total_rows)." IP".$singular." (Page: ".number_format($page)." of ".number_format($total_pages).")
"; 105 | echo " 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | "; 115 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 116 | echo ""; 117 | 118 | echo ""; 119 | echo ""; 120 | echo ""; 121 | echo ""; 122 | echo ""; 123 | if ($row['returnhits']===NULL){echo "";} 124 | else {echo "";} 125 | if($row['flag'] === NULL || $row['flag'] == 3 || $row['flag'] == 7) echo ""; 126 | elseif($row['flag'] == 1 || $row['flag'] == 2) echo ""; 127 | elseif($row['flag'] == 4) echo ""; 128 | elseif($row['flag'] == 6 || $row['flag'] == 5) echo ""; 129 | else echo ""; 130 | 131 | echo ""; 132 | } 133 | echo "
TimestampIP AddressReasonCountryHELORHRS
".$row['tsf']."".$row['ipaddress']."".$row['ban_reason']."".$row['country']."".$row['helo']."0".number_format($row['returnhits'])."NoYESNEWSAFERR
"; 134 | if ($total_pages < 2){echo "";} 135 | else { 136 | echo "
    "; 137 | if($page <= 1){echo "
  • First
  • ";} else {echo "
  • First
  • ";} 138 | if($page <= 1){echo "
  • Prev
  • ";} else {echo "
  • Prev
  • ";} 139 | if($page >= $total_pages){echo "
  • Next
  • ";} else {echo "
  • Next
  • ";} 140 | if($page >= $total_pages){echo "
  • Last
  • ";} else {echo "
  • Last
  • ";} 141 | echo "
"; 142 | } 143 | if ($total_pages > 0){ 144 | echo "
145 | RH = Repeat Hits
146 | RS = Release Status

"; 147 | } 148 | } 149 | } 150 | echo "
"; 151 | echo "
"; 152 | ?> 153 | 154 | -------------------------------------------------------------------------------- /www/release.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 15 | 16 |
17 |
18 |

Release a date range:

19 | Enter start & end dates and click to review.

20 |
21 | 22 | 23 | 24 | 25 | 26 |
Starting Date:
Ending Date:
27 |
28 |
Note: Range can be a single day, but start and end dates must both be filled in.
29 |
30 | 31 |
32 |

Release a recent day:

33 | Unreleased IPs over the past five days. Click below to review.

34 | 35 | prepare(" 40 | SELECT 41 | COUNT(id) AS value_occurrence 42 | FROM hm_fwban 43 | WHERE timestamp BETWEEN '{$today} 00:00:00' AND '{$today} 23:59:59' AND (flag=3 OR flag IS NULL) 44 | "); 45 | $sql->execute(); 46 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 47 | if ($row['value_occurrence'] == 1){$singular='';}else{$singular='s';} 48 | echo "".number_format($row['value_occurrence'])." Hit".$singular." Today
"; 49 | } 50 | 51 | $sql = $pdo->prepare(" 52 | SELECT 53 | COUNT(id) AS value_occurrence 54 | FROM hm_fwban WHERE timestamp BETWEEN '{$yesterday} 00:00:00' AND '{$yesterday} 23:59:59' AND (flag=3 OR flag IS NULL) 55 | "); 56 | $sql->execute(); 57 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 58 | if ($row['value_occurrence'] == 1){$singular='';}else{$singular='s';} 59 | echo "".number_format($row['value_occurrence'])." Hit".$singular." Yesterday
"; 60 | } 61 | 62 | $sql = $pdo->prepare(" 63 | SELECT 64 | COUNT(id) AS value_occurrence 65 | FROM hm_fwban 66 | WHERE timestamp BETWEEN '{$twodaysago} 00:00:00' AND '{$twodaysago} 23:59:59' AND (flag=3 OR flag IS NULL) 67 | "); 68 | $sql->execute(); 69 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 70 | if ($row['value_occurrence'] == 1){$singular='';}else{$singular='s';} 71 | echo "".number_format($row['value_occurrence'])." Hit".$singular." on ".date("l", strtotime($twodaysago))."
"; 72 | } 73 | 74 | $sql = $pdo->prepare(" 75 | SELECT 76 | COUNT(id) AS value_occurrence 77 | FROM hm_fwban 78 | WHERE timestamp BETWEEN '{$threedaysago} 00:00:00' AND '{$threedaysago} 23:59:59' AND (flag=3 OR flag IS NULL) 79 | "); 80 | $sql->execute(); 81 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 82 | if ($row['value_occurrence'] == 1){$singular='';}else{$singular='s';} 83 | echo "".number_format($row['value_occurrence'])." Hit".$singular." on ".date("l", strtotime($threedaysago))."
"; 84 | } 85 | 86 | $sql = $pdo->prepare(" 87 | SELECT 88 | COUNT(id) AS value_occurrence 89 | FROM hm_fwban 90 | WHERE timestamp BETWEEN '{$fourdaysago} 00:00:00' AND '{$fourdaysago} 23:59:59' AND (flag=3 OR flag IS NULL) 91 | "); 92 | $sql->execute(); 93 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 94 | if ($row['value_occurrence'] == 1){$singular='';}else{$singular='s';} 95 | echo "".number_format($row['value_occurrence'])." Hit".$singular." on ".date("l", strtotime($fourdaysago))."
"; 96 | } 97 | ?> 98 |
99 |
100 |
101 | 102 |
103 |
104 |

Release a Ban Reason:

105 | Unreleased IPs for the following ban reasons. Click to review.

106 | prepare(" 111 | SELECT 112 | ban_reason, 113 | COUNT(ban_reason) AS value_occurrence 114 | FROM hm_fwban 115 | WHERE flag=3 OR flag IS NULL 116 | GROUP BY ban_reason 117 | ORDER BY value_occurrence DESC 118 | "); 119 | $sql->execute(); 120 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 121 | if ($row['value_occurrence'] == 1){$singular='';}else{$singular='s';} 122 | echo number_format($row['value_occurrence'])." hit".$singular." for ".$row['ban_reason']."
"; 123 | } 124 | ?> 125 |
126 | 127 |
128 |

Release a Country:

129 | Will search for matching unreleased IPs.

130 |
131 | 132 | 133 |
134 |
135 |
136 |
137 | 138 |
139 |
140 |

Release an IP range:

141 | Will release any matching presently banned IPs within the range and remove firewall rule.

142 |
143 | 144 | 145 |
146 |
IP Ranges MUST be in:
147 | 255.255.255.255 OR
148 | 255.255.255.255/24 format.

149 | Single IPs will be automatically converted to /32 CIDR for search purposes. Netmask /22 - /32 only. Click to review options before committing to firewall rule removal. 150 |
151 | 152 |
153 |

Release something else:

154 | Whatever shall we release? Work in progress placeholder. Suggestions welcome. 155 |
156 |
157 |
158 | 159 | -------------------------------------------------------------------------------- /www/charthitsperweekcombined.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | hMailServer Firewall Ban 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 89 | 90 | 168 | 169 | 170 | 171 |
172 | 173 |
174 |
175 |

Hits per day from inception:

176 |
177 |
178 |
179 |

Hits per week from inception:

180 |
181 |
182 |
183 | 184 |
185 |
186 | 187 | 188 |
189 |
190 |

Hits per week from inception:

191 |
192 |
193 |
194 |
195 |
196 | 197 |
198 | 199 | -------------------------------------------------------------------------------- /www/reban.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 15 | 16 |
17 |
18 |

Re-Ban a date range:

19 | Enter start & end dates and click to review.

20 |
21 | 22 | 23 | 24 | 25 | 26 |
Starting Date:
Ending Date:
27 |
28 |
Note: Range can be a single day, but start and end dates must both be filled in.
29 |
30 | 31 |
32 |

Re-Ban a recent day:

33 | Released IPs over the past five days. Click below to review.

34 | 35 | prepare(" 40 | SELECT 41 | COUNT(id) AS value_occurrence 42 | FROM hm_fwban 43 | WHERE timestamp BETWEEN '{$today} 00:00:00' AND '{$today} 23:59:59' AND (flag=1 OR flag=2) 44 | "); 45 | $sql->execute(); 46 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 47 | if ($row['value_occurrence'] == 1){$singular="";}else{$singular="s";} 48 | echo "".number_format($row['value_occurrence'])." Hit".$singular." Today
"; 49 | } 50 | 51 | $sql = $pdo->prepare(" 52 | SELECT 53 | COUNT(id) AS value_occurrence 54 | FROM hm_fwban 55 | WHERE timestamp BETWEEN '{$yesterday} 00:00:00' AND '{$yesterday} 23:59:59' AND (flag=1 OR flag=2) 56 | "); 57 | $sql->execute(); 58 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 59 | if ($row['value_occurrence'] == 1){$singular="";}else{$singular="s";} 60 | echo "".number_format($row['value_occurrence'])." Hit".$singular." Yesterday
"; 61 | } 62 | 63 | $sql = $pdo->prepare(" 64 | SELECT 65 | COUNT(id) AS value_occurrence 66 | FROM hm_fwban 67 | WHERE timestamp BETWEEN '{$twodaysago} 00:00:00' AND '{$twodaysago} 23:59:59' AND (flag=1 OR flag=2) 68 | "); 69 | $sql->execute(); 70 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 71 | if ($row['value_occurrence'] == 1){$singular="";}else{$singular="s";} 72 | echo "".number_format($row['value_occurrence'])." Hit".$singular." on ".date("l", strtotime($twodaysago))."
"; 73 | } 74 | 75 | $sql = $pdo->prepare(" 76 | SELECT 77 | COUNT(id) AS value_occurrence 78 | FROM hm_fwban 79 | WHERE timestamp BETWEEN '{$threedaysago} 00:00:00' AND '{$threedaysago} 23:59:59' AND (flag=1 OR flag=2) 80 | "); 81 | $sql->execute(); 82 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 83 | if ($row['value_occurrence'] == 1){$singular="";}else{$singular="s";} 84 | echo "".number_format($row['value_occurrence'])." Hit".$singular." on ".date("l", strtotime($threedaysago))."
"; 85 | } 86 | 87 | $sql = $pdo->prepare(" 88 | SELECT 89 | COUNT(id) AS value_occurrence 90 | FROM hm_fwban 91 | WHERE timestamp BETWEEN '{$fourdaysago} 00:00:00' AND '{$fourdaysago} 23:59:59' AND (flag=1 OR flag=2) 92 | "); 93 | $sql->execute(); 94 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 95 | if ($row['value_occurrence'] == 1){$singular="";}else{$singular="s";} 96 | echo "".number_format($row['value_occurrence'])." Hit".$singular." on ".date("l", strtotime($fourdaysago))."
"; 97 | } 98 | 99 | ?> 100 |
101 |
102 |
103 | 104 |
105 |
106 |

Re-Ban a Ban Reason:

107 | Released IPs for the following ban reasons. Click to review.

108 | prepare(" 112 | SELECT 113 | COUNT(id) AS value_occurrence 114 | FROM hm_fwban 115 | WHERE flag=1 OR flag=2 116 | "); 117 | $sqlcount->execute(); 118 | $total_rows = $sqlcount->fetchColumn(); 119 | if ($total_rows > 0) { 120 | $sql = $pdo->prepare(" 121 | SELECT 122 | ban_reason, 123 | COUNT(ban_reason) AS value_occurrence 124 | FROM hm_fwban 125 | WHERE flag=1 OR flag=2 126 | GROUP BY ban_reason 127 | ORDER BY value_occurrence DESC 128 | "); 129 | $sql->execute(); 130 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 131 | if ($row['value_occurrence'] == 1){$singular="";}else{$singular="s";} 132 | echo number_format($row['value_occurrence'])." hit".$singular." for ".$row['ban_reason']."
"; 133 | } 134 | } else { 135 | echo "No released records for any ban reason."; 136 | } 137 | 138 | ?> 139 |
140 | 141 |
142 |

Re-Ban a Country:

143 | Will search for matching released IPs.

144 |
145 | 146 | 147 |
148 |
Note: Only applies to previously released IPs for the selected country. 149 |
150 |
151 |
152 | 153 |
154 |
155 |

Manually ban an IP range:

156 | Enter an IP or IP range. Will search for matches and if found will reban. If no matches found will add IP to firewall ban list with reason "Manual". Not dependent on previous bans/releases.

157 |
158 | 159 | 160 |
161 |
IP Ranges MUST be in:
162 | 255.255.255.255 OR
163 | 255.255.255.255/24 format.

164 | Single IPs will be automatically converted to /32 CIDR for insertion as firewall rule. Netmask /22 - /32 only. Click to review options before committing to a network ban. 165 |
166 | 167 |
168 |

Ban something else:

169 | Whatever shall we ban? Work in progress placeholder. Suggestions welcome. 170 |
171 |
172 |
173 | 174 | -------------------------------------------------------------------------------- /www/search.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | To search for a date range click here. 5 |
6 | 7 | "; 26 | echo "
"; 27 | echo " "; 28 | echo " "; 35 | echo " "; 36 | echo "
"; 37 | echo "
"; 38 | 39 | echo "
"; 40 | 41 | $no_of_records_per_page = 20; 42 | $offset = ($page-1) * $no_of_records_per_page; 43 | 44 | if ($RS=="NO"){$RS_SQL = " AND (flag IS NULL OR flag=3 OR flag=7)";} 45 | elseif ($RS=="YES"){$RS_SQL = " AND (flag=1 OR flag=2)";} 46 | elseif ($RS=="NEW"){$RS_SQL = " AND flag=4";} 47 | elseif ($RS=="SAF"){$RS_SQL = " AND (flag=5 OR flag=6)";} 48 | elseif ($RS==2){$RS_SQL = " AND flag=2";} 49 | elseif ($RS==3){$RS_SQL = " AND flag=3";} 50 | elseif ($RS==5){$RS_SQL = " AND flag=5";} 51 | elseif ($RS==7){$RS_SQL = " AND flag=7";} 52 | else {$RS_SQL = "";} 53 | 54 | if ($ban_reason==""){ 55 | $ban_reason_sql=""; 56 | } else { 57 | $search=""; 58 | $ban_reason_sql=" AND ban_reason LIKE '{$ban_reason}'"; 59 | } 60 | 61 | $total_pages_sql = $pdo->prepare(" 62 | SELECT Count( * ) AS count 63 | FROM hm_fwban 64 | WHERE (".(IsMSSQL() ? DBCastDateTimeFieldAsDate('timestamp') : 'timestamp')." LIKE '%{$search}%' OR ipaddress LIKE '%{$search}%' OR ban_reason LIKE '%{$search}%' OR country LIKE '%{$search}%' OR helo LIKE '%{$search}%' OR ptr LIKE '%{$search}%')".$ban_reason_sql.$RS_SQL 65 | ); 66 | $total_pages_sql->execute(); 67 | $total_rows = $total_pages_sql->fetchColumn(); 68 | $total_pages = ceil($total_rows / $no_of_records_per_page); 69 | 70 | $sql = $pdo->prepare(" 71 | SELECT 72 | a.tsf, 73 | a.ipaddress, 74 | a.ban_reason, 75 | a.country, 76 | a.flag, 77 | a.helo, 78 | a.ptr, 79 | b.returnhits 80 | FROM 81 | ( 82 | SELECT 83 | ".DBFormatDate('timestamp', '%y/%m/%d %T')." AS tsf, 84 | timestamp, 85 | ipaddress, 86 | ban_reason, 87 | country, 88 | flag, 89 | helo, 90 | ptr 91 | FROM hm_fwban 92 | WHERE (".(IsMSSQL() ? DBCastDateTimeFieldAsDate('timestamp') : 'timestamp')." LIKE '%{$search}%' OR ipaddress LIKE '%{$search}%' OR ban_reason LIKE '%{$search}%' OR country LIKE '%{$search}%' OR helo LIKE '%{$search}%' OR ptr LIKE '%{$search}%')".$ban_reason_sql."".$RS_SQL." 93 | ) a 94 | LEFT JOIN 95 | ( 96 | SELECT 97 | hits AS returnhits, 98 | ipaddress 99 | FROM hm_fwban_blocks_ip 100 | ) b 101 | ON a.ipaddress = b.ipaddress 102 | ".DBLimitRowsWithOffset('a.tsf','DESC',0,0,$offset,$no_of_records_per_page) 103 | ); 104 | $sql->execute(); 105 | 106 | if ($RS=="YES"){$RSres=" with release status \"YES\"";} 107 | elseif ($RS=="NO"){$RSres=" with release status \"NO\"";} 108 | elseif ($RS=="NEW"){$RSres=" with release status \"NEW\"";} 109 | elseif ($RS=="SAF"){$RSres=" with release status \"SAFE\"";} 110 | else {$RSres = "";} 111 | 112 | if ($search==""){$search_res="";} 113 | else {$search_res=" for search term \"".$search."\"";} 114 | 115 | if ($ban_reason==""){$ban_reason_res="";} 116 | else {$ban_reason_res=" for Ban Reason \"".$ban_reason."\"";} 117 | 118 | if ($total_rows == 1){$singular = '';} else {$singular= 's';} 119 | if ($total_rows == 0){ 120 | if ($search == "" && $ban_reason == ""){ 121 | echo "Please enter a search term"; 122 | } else { 123 | echo "No results ".$search_res."".$ban_reason_res.""; 124 | } 125 | } else { 126 | echo "Results ".$search_res."".$ban_reason_res.": ".number_format($total_rows)." Hit".$singular." (Page: ".number_format($page)." of ".number_format($total_pages).")
"; 127 | echo " 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | "; 137 | while($row = $sql->fetch(PDO::FETCH_ASSOC)){ 138 | echo ""; 139 | echo ""; 140 | echo ""; 141 | echo ""; 142 | echo ""; 143 | if (empty($row['helo'])){$helo_row=$row['ptr'];} else {$helo_row=$row['helo'];} 144 | echo "";} 146 | else {echo "";} 147 | if($row['flag'] === NULL || $row['flag'] == 3 || $row['flag'] == 7) echo ""; 148 | elseif($row['flag'] == 1 || $row['flag'] == 2) echo ""; 149 | elseif($row['flag'] == 4) echo ""; 150 | elseif($row['flag'] == 6 || $row['flag'] == 5) echo ""; 151 | else echo ""; 152 | echo ""; 153 | } 154 | echo "
TimestampIP AddressReasonCountryHELOFBRS
".$row['tsf']."".$row['ipaddress']."".$row['ban_reason']."".$row['country']."".$helo_row.""; 145 | if ($row['returnhits']===NULL){echo "0".number_format($row['returnhits'])."NoYESNEWSAFERR
"; 155 | 156 | if ($ban_reason==""){$ban_reason_page="";} else {$ban_reason_page="&ban_reason=".$ban_reason."";} 157 | 158 | if ($total_pages == 1){echo "";} 159 | else { 160 | echo "
    "; 161 | if($page <= 1){echo "
  • First
  • ";} else {echo "
  • First
  • ";} 162 | if($page <= 1){echo "
  • Prev
  • ";} else {echo "
  • Prev
  • ";} 163 | if($page >= $total_pages){echo "
  • Next
  • ";} else {echo "
  • Next
  • ";} 164 | if($page >= $total_pages){echo "
  • Last
  • ";} else {echo "
  • Last
  • ";} 165 | echo "
"; 166 | } 167 | if ($total_pages > 0){ 168 | echo "
169 | FB = Firewall Blocks
170 | RS = Release Status

"; 171 | } 172 | } 173 | ?> 174 | 175 |
176 |
177 | 178 | -------------------------------------------------------------------------------- /www/functions.php: -------------------------------------------------------------------------------- 1 | 'yyyy', 130 | '%c' => 'MM', 131 | '%e' => 'dd', 132 | 'Y-m-d' => 'yyyy-MM-dd', 133 | '%y/%m/%d' => 'yy/MM/dd', 134 | 'Y-m' => 'yyyy-MM', 135 | '%Y-%m' => 'yyyy-MM', 136 | '%y/%m/%d %T' => 'yy-MM-dd HH:mm:ss', 137 | '%Y/%m/%d %H:%i:%s' => 'yyyy-MM-dd HH:mm:ss', 138 | '%Y/%m/01' => 'yyyy-MM-01', 139 | '%y/%c/%e' => 'yy/MM/dd', 140 | '%H' => 'HH', 141 | '%M %D, %Y' => 'MMMM d, yyyy', 142 | '%T' => 'HH:mm:ss', 143 | '%H:%i %p' => 'hh:mm tt', 144 | ); 145 | 146 | if (IsMySQL()) { 147 | $Return = "DATE_FORMAT(".$fieldName.", '".$formatSpecifier."')"; 148 | } elseif (IsMSSQL()) { 149 | switch ($formatSpecifier) 150 | { 151 | case '%Y': 152 | $Return = DBCastDateTimeFieldAsYear($fieldName); 153 | break; 154 | case '%c': 155 | $Return = DBCastDateTimeFieldAsMonth($fieldName); 156 | break; 157 | case '%e': 158 | $Return = DBCastDateTimeFieldAsDay($fieldName); 159 | break; 160 | case '%H': 161 | $Return = DBCastDateTimeFieldAsHour($fieldName); 162 | break; 163 | default: 164 | $Return = "FORMAT(".$fieldName.", '".$dateFormatSpecifiers[$formatSpecifier]."', 'en-US')"; 165 | break; 166 | } } 167 | return $Return; 168 | } 169 | 170 | Function DBIpStringToIntField($fieldName){ 171 | global $Database; 172 | $Return = ""; 173 | 174 | if (IsMySQL()) { 175 | $Return = "INET_ATON(".$fieldName.")"; 176 | } elseif (IsMSSQL()) { 177 | $Return = "dbo.ipStringToInt(".$fieldName.")"; 178 | } 179 | return $Return; 180 | } 181 | 182 | Function DBIpStringToIntValue($ipString){ 183 | global $Database; 184 | $Return = ""; 185 | 186 | if (IsMySQL()) { 187 | $Return = "INET_ATON('".$ipString."')"; 188 | } elseif (IsMSSQL()) { 189 | $Return = "dbo.ipStringToInt('".$ipString."')"; 190 | } 191 | return $Return; 192 | } 193 | 194 | Function IsMySQL(){ 195 | global $Database; 196 | return ($Database['dbtype'] == 'mysql'); 197 | } 198 | 199 | Function IsMSSQL(){ 200 | global $Database; 201 | return ($Database['dbtype'] == 'mssql'); 202 | } 203 | 204 | function ip_country($ip) { 205 | global $GeoIPDatabase; 206 | global $geo_pdo; 207 | 208 | if ($GeoIPDatabase['use_geoip'] == 'true'){ 209 | 210 | $getcountry_sql = $geo_pdo->prepare(" 211 | SELECT 212 | countryname 213 | FROM ( 214 | SELECT * 215 | FROM geo_ip 216 | WHERE ".DBIpStringToIntValue($ip)." <= maxipaton 217 | ".DBLimitRowsWithOffset(0,0,0,0,0,1)." 218 | ) AS A 219 | WHERE minipaton <= ".DBIpStringToIntValue($ip) 220 | ); 221 | $getcountry_sql->execute(); 222 | $country = $getcountry_sql->fetchColumn(); 223 | if (empty($country)) { 224 | $output = "NOT FOUND"; 225 | }else { 226 | $output = $country; 227 | } 228 | 229 | } else { 230 | 231 | $ipdat = @json_decode(file_get_contents("http://ip-api.com/json/" . $ip)); 232 | if ($ipdat->status == "success"){ 233 | $output = @$ipdat->country; 234 | } else { 235 | $output = "NOT FOUND"; 236 | } 237 | } 238 | return $output; 239 | } 240 | 241 | 242 | ?> 243 | --------------------------------------------------------------------------------