From e80da3c57d0501d7a5962fcacd6416d47385e86a Mon Sep 17 00:00:00 2001 From: BBcan177 Date: Sat, 23 May 2015 16:28:12 -0400 Subject: pfBlockerNG v1.09 --- config/pfblockerng/pfblockerng.inc | 807 +++++++++++++++++++--------- config/pfblockerng/pfblockerng.php | 296 +++++----- config/pfblockerng/pfblockerng.priv.inc | 6 +- config/pfblockerng/pfblockerng.sh | 11 +- config/pfblockerng/pfblockerng.widget.php | 453 +++++++++++----- config/pfblockerng/pfblockerng.xml | 193 ++++--- config/pfblockerng/pfblockerng_alerts.php | 373 ++++++++----- config/pfblockerng/pfblockerng_diag_dns.php | 23 +- config/pfblockerng/pfblockerng_sync.xml | 13 +- config/pfblockerng/pfblockerng_top20.xml | 129 ++++- config/pfblockerng/pfblockerng_update.php | 162 ++++-- config/pfblockerng/pfblockerng_v4lists.xml | 231 +++++--- config/pfblockerng/pfblockerng_v6lists.xml | 225 +++++--- 13 files changed, 1938 insertions(+), 984 deletions(-) (limited to 'config/pfblockerng') diff --git a/config/pfblockerng/pfblockerng.inc b/config/pfblockerng/pfblockerng.inc index 26eeb5e5..d40ea61a 100644 --- a/config/pfblockerng/pfblockerng.inc +++ b/config/pfblockerng/pfblockerng.inc @@ -58,9 +58,6 @@ function pfb_global() { $prefix = "/usr/local"; } - # Collect pfSense Version - $pfb['pfsenseversion'] = substr(trim(file_get_contents("/etc/version")),0,3); - # Folders $pfb['dbdir'] = "{$g['vardb_path']}/pfblockerng"; $pfb['aliasdir'] = "{$g['vardb_path']}/aliastables"; @@ -71,7 +68,7 @@ function pfb_global() { $pfb['matchdir'] = "{$pfb['dbdir']}/match"; $pfb['permitdir'] = "{$pfb['dbdir']}/permit"; $pfb['origdir'] = "{$pfb['dbdir']}/original"; - $pfb['ccdir'] = $prefix . "/share/GeoIP"; + $pfb['ccdir'] = "{$prefix}/share/GeoIP"; # Create Folders if not Exist. $folder_array = array ("{$pfb['dbdir']}","{$pfb['logdir']}","{$pfb['ccdir']}","{$pfb['origdir']}","{$pfb['nativedir']}","{$pfb['denydir']}","{$pfb['matchdir']}","{$pfb['permitdir']}","{$pfb['aliasdir']}"); @@ -80,28 +77,38 @@ function pfb_global() { } # Files - $pfb['master'] = "{$pfb['dbdir']}/masterfile"; - $pfb['errlog'] = "{$pfb['logdir']}/error.log"; - $pfb['geolog'] = "{$pfb['logdir']}/geoip.log"; - $pfb['log'] = "{$pfb['logdir']}/pfblockerng.log"; - $pfb['supptxt'] = "{$pfb['dbdir']}/pfbsuppression.txt"; - $pfb['script'] = 'sh /usr/local/pkg/pfblockerng/pfblockerng.sh'; - $pfb['aliasarchive'] = $prefix . "/etc/aliastables.tar.bz2"; + $pfb['master'] = "{$pfb['dbdir']}/masterfile"; + $pfb['errlog'] = "{$pfb['logdir']}/error.log"; + $pfb['geolog'] = "{$pfb['logdir']}/geoip.log"; + $pfb['log'] = "{$pfb['logdir']}/pfblockerng.log"; + $pfb['supptxt'] = "{$pfb['dbdir']}/pfbsuppression.txt"; + $pfb['script'] = 'sh /usr/local/pkg/pfblockerng/pfblockerng.sh'; + $pfb['aliasarchive'] = "{$prefix}/etc/aliastables.tar.bz2"; # General Variables - $pfb['config'] = $config['installedpackages']['pfblockerng']['config'][0]; + $pfb['config'] = $config['installedpackages']['pfblockerng']['config'][0]; # Enable/Disable of pfBlockerNG - $pfb['enable'] = $pfb['config']['enable_cb']; + $pfb['enable'] = $pfb['config']['enable_cb']; # Keep Blocklists on pfBlockerNG Disable - $pfb['keep'] = $pfb['config']['pfb_keep']; + $pfb['keep'] = $pfb['config']['pfb_keep']; # Enable Suppression - $pfb['supp'] = $pfb['config']['suppression']; + $pfb['supp'] = $pfb['config']['suppression']; # Max Lines in pfblockerng.log file - $pfb['logmax'] = $pfb['config']['log_maxlines']; - $pfb['iplocal'] = $config['interfaces']['lan']['ipaddr']; + $pfb['logmax'] = $pfb['config']['log_maxlines']; + # Lan IP Address + $pfb['iplocal'] = $config['interfaces']['lan']['ipaddr']; # Disable Country Database CRON Updates - $pfb['cc'] = $pfb['config']['database_cc']; + $pfb['cc'] = $pfb['config']['database_cc']; + + # User Defined CRON Start Minute + $pfb['min'] = $pfb['config']['pfb_min']; + # Start hour of the Scheduler + $pfb['hour'] = $pfb['config']['pfb_hour']; + # Hour cycle for Scheduler + $pfb['interval'] = $pfb['config']['pfb_interval']; + # Start hour of the 'Once a day' Schedule + $pfb['24hour'] = $pfb['config']['pfb_dailystart']; # Set pfBlockerNG to Disabled on 'Re-Install' if (isset($pfb['install']) && $pfb['install']) { @@ -114,13 +121,24 @@ pfb_global(); # Set Max PHP Memory Setting $uname = posix_uname(); -if ($uname['machine'] == 'amd64') +if ($uname['machine'] == 'amd64') { ini_set('memory_limit', '256M'); +} -# Function to decode to Alias Custom Entry Box. +# Function to decode to Alias Custom entry box. function pfbng_text_area_decode($text) { - return preg_replace('/\r\n/', "\n",base64_decode($text)); + $customlist = explode("\r\n", base64_decode($text)); + foreach ($customlist as $line) { + if (substr(trim($line), 0, 1) != '#' && !empty($line)) { + if (strpos($line, '#')) { + $custom .= trim(strstr($line, '#', TRUE)) . "\n"; + } else { + $custom .= $line . "\n"; + } + } + } + return $custom; } @@ -132,7 +150,9 @@ function pfb_log_mgmt() { if ($pfb['logmax'] == "nolimit") { # Skip Log Mgmt } else { - exec("/usr/bin/tail -n {$pfb['logmax']} {$pfb['log']} > /tmp/pfblog; /bin/mv -f /tmp/pfblog {$pfb['log']}"); + if (file_exists($pfb['log'])) { + exec("/usr/bin/tail -n {$pfb['logmax']} {$pfb['log']} > /tmp/pfblog; /bin/mv -f /tmp/pfblog {$pfb['log']}"); + } } } @@ -164,9 +184,9 @@ function pfb_logger($log, $type) { } -# Determine Folder Location for 'List' -function pfb_determine_list_detail($list) { - global $g,$pfb,$pfbarr; +// Determine 'List' Details +function pfb_determine_list_detail($list="", $header_url="", $confconfig="", $key="") { + global $pfb,$pfbarr,$config; $pfbarr = array(); if (in_array($list,array('Match_Both','Match_Inbound','Match_Outbound','Alias_Match'))) { @@ -191,9 +211,175 @@ function pfb_determine_list_detail($list) { $pfbarr['descr'] = " Auto "; } + //Determine length of Header to format log Output + if (strlen($header_url) > 19) { + $pfbarr['logtab'] = ""; + } + elseif (strlen($header_url) > 11) { + $pfbarr['logtab'] = "\t"; + } + elseif (strlen($header_url) < 4) { + $pfbarr['logtab'] = "\t\t\t"; + } + else { + $pfbarr['logtab'] = "\t\t"; + } + + if ($confconfig != "") { + // Configure Autoports/Protocol and Auto Destination if required. + $autotype = array( 'autoports' => 'aliasports', 'autodest' => 'aliasdest'); + $aports = ""; $adest = ""; + $pfbarr['aproto'] = $config['installedpackages'][$confconfig]['config'][$key]['autoproto']; + foreach ($autotype as $akey => $atype) { + if ($config['installedpackages'][$confconfig]['config'][$key][$akey] == "on" && is_array($config['aliases']['alias'])) { + foreach ($config['aliases']['alias'] as $palias) { + if ($palias['name'] == $config['installedpackages'][$confconfig]['config'][$key][$atype]) { + if (!empty($palias['address'])) { + switch($akey) { + case "autoports": + $pfbarr['aports'] = $config['installedpackages'][$confconfig]['config'][$key][$atype]; + break; + case "autodest": + $pfbarr['adest'] = $config['installedpackages'][$confconfig]['config'][$key][$atype]; + break; + } + } + } + } + } + } + } return $pfbarr; } + +// Determine if Cron Task requires updating +function pfblockerng_cron_exists($crontask, $pfb_min, $pfb_hour) { + global $config; + + if (is_array($config['cron']['item'])) { + foreach ($config['cron']['item'] as $item) { + if (strpos($item['command'], $crontask) !== FALSE) { + if ($item['minute'] != $pfb_min) { + return FALSE; + } + if ($item['hour'] != $pfb_hour) { + return FALSE; + } + return TRUE; + } + } + } + return FALSE; +} + + +// Calculate the cron task base hour setting +function pfb_cron_base_hour() { + global $pfb; + + if ($pfb['interval'] == 1) { + return; + } + + if ($pfb['interval'] == 2) { + # 2 Hour Schedule Converter + $shour = intval(substr($pfb['hour'], 0, 2)); + $sch2 = strval($shour); + for ($i=0; $i<11; $i++) { + $shour += 2; + if ($shour >= 24) + $shour -= 24; + $sch2 .= "," . strval($shour); + } + $sch2 = explode(",", $sch2); + sort($sch2); + return $sch2; + } + + if ($pfb['interval'] == 3) { + # 3 Hour Schedule Converter + $shour = intval(substr($pfb['hour'], 0, 2)); + $sch3 = strval($shour); + for ($i=0; $i<7; $i++) { + $shour += 3; + if ($shour >= 24) + $shour -= 24; + $sch3 .= "," . strval($shour); + } + $sch3 = explode(",", $sch3); + sort($sch3); + return $sch3; + } + + if ($pfb['interval'] == 4) { + # 4 Hour Schedule Converter + $shour = intval(substr($pfb['hour'], 0, 2)); + $sch4 = strval($shour); + for ($i=0; $i<5; $i++) { + $shour += 4; + if ($shour >= 24) + $shour -= 24; + $sch4 .= "," . strval($shour); + } + $sch4 = explode(",", $sch4); + sort($sch4); + return $sch4; + } + + if ($pfb['interval'] == 6) { + # 6 Hour Schedule Converter + $shour = intval(substr($pfb['hour'], 0, 2)); + $sch6 = strval($shour); + for ($i=0; $i<3; $i++) { + $shour += 6; + if ($shour >= 24) + $shour -= 24; + $sch6 .= "," . strval($shour); + } + $sch6 = explode(",", $sch6); + sort($sch6); + return $sch6; + } + + if ($pfb['interval'] == 8) { + # 8 Hour Schedule Converter + $shour = intval(substr($pfb['hour'], 0, 2)); + $sch8 = strval($shour); + for ($i=0; $i<2; $i++) { + $shour += 8; + if ($shour >= 24) + $shour -= 24; + $sch8 .= "," . strval($shour); + } + $sch8 = explode(",", $sch8); + sort($sch8); + return $sch8; + } + + if ($pfb['interval'] == 12) { + # 12 Hour Schedule Converter + $shour = intval(substr($pfb['hour'], 0, 2)); + $sch12 = strval($shour) . ","; + $shour += 12; + if ($shour >= 24) + $shour -= 24; + $sch12 .= strval($shour); + $sch12 = explode(",", $sch12); + sort($sch12); + return $sch12; + } + + if ($pfb['interval'] == 24) { + return array($pfb['24hour']); + } + + // Default to hourly schedule + $pfb['interval'] = 1; + return; +} + + # Create Suppression Alias function pfb_create_suppression_alias() { global $config; @@ -212,7 +398,7 @@ function pfb_create_suppression_alias() { "detail" => "" ); $config['aliases']['alias'] = $new_aliases; - write_config(); + $pfb['cron_mod'] = TRUE; } @@ -235,7 +421,7 @@ function pfb_create_suppression_file() { if ($pfb['found']) { $pfb_suppress = str_replace(" ", "\n", $config['aliases']['alias'][$pfb_id]['address']); if (!empty($pfb_suppress)) { - @file_put_contents("{$pfb['supptxt']}",$pfb_suppress, LOCK_EX); + @file_put_contents("{$pfb['supptxt']}", $pfb_suppress, LOCK_EX); } else { unlink_if_exists("{$pfb['supptxt']}"); } @@ -246,8 +432,9 @@ function pfb_create_suppression_file() { } // Call Function to Create Suppression Alias. - if (!$pfb['found']) + if (!$pfb['found']) { pfb_create_suppression_alias(); + } } @@ -306,7 +493,7 @@ function ip_range_to_subnet_array_temp2($ip1, $ip2) { // already checked for the edge case where end = start+1 and start ends in 0x1, above, so it's safe } - // this is the only edge case arising from increment/decrement. + // this is the only edge case arising from increment/decrement. // it happens if the range at start of loop is exactly 2 adjacent ips, that spanned the 1->0 gap. (we will have enumerated both by now) if (strcmp($ip2bin, $ip1bin) < 0) @@ -393,8 +580,10 @@ function pfb_aliastables($mode) { } } - if ($msg != "") + if ($msg != "") { pfb_logger("{$msg}","1"); + $pfb['cron_mod'] = TRUE; + } } @@ -403,6 +592,7 @@ function sync_package_pfblockerng($cron = "") { global $g,$config,$pfb,$pfbarr; pfb_global(); + $pfb['cron_mod'] = FALSE; // Flag to check for mods to the config.xml file. # Detect Boot Process or Update via CRON if (isset($_POST) && $cron == "") { @@ -433,10 +623,12 @@ function sync_package_pfblockerng($cron = "") { pfb_aliastables("conf"); # Collect pfSense Max Table Size Entry - $pfb['table_limit'] = ($config['system']['maximumtableentries'] != "" ? $config['system']['maximumtableentries'] : "2000000"); - - # If Table limit not defined, set Default to 2M - $config['system']['maximumtableentries'] = "{$pfb['table_limit']}"; + if (empty($config['system']['maximumtableentries'])) { + # If Table limit not defined, set Default to 2M + $config['system']['maximumtableentries'] = "2000000"; + $pfb['cron_mod'] = TRUE; + } + $pfb['table_limit'] = $config['system']['maximumtableentries']; # Collect local web gui configuration $pfb['weblocal'] = ($config['system']['webgui']['protocol'] != "" ? $config['system']['webgui']['protocol'] : "http"); @@ -454,10 +646,6 @@ function sync_package_pfblockerng($cron = "") { $pfb['deny_action_inbound'] = ($pfb['config']['inbound_deny_action'] != "" ? $pfb['config']['inbound_deny_action'] : "block"); $pfb['deny_action_outbound'] = ($pfb['config']['outbound_deny_action'] != "" ? $pfb['config']['outbound_deny_action'] : "reject"); - # Validation check to see if the Original pfBlocker package is Enabled - $pfb['validate']= $pfb['config']['pfblocker_cb']; - # User Defined CRON Start Minute - $pfb['min'] = $pfb['config']['pfb_min']; # Reloads Existing Blocklists without Downloading New Lists $pfb['reuse'] = $pfb['config']['pfb_reuse']; # Enable OpenVPN AutoRules @@ -506,17 +694,6 @@ function sync_package_pfblockerng($cron = "") { ## $pfb['save'] is used to determine if User pressed "Save" Button to avoid Collision with CRON. ## This is defined in each pfBlockerNG XML Files - # Validation Check to ensure pfBlocker and pfBlockerNG are not running at the same time. - if ($pfb['validate'] == "") { - # Collect pfBlocker Enabled Status from config file - $pfb['validate_chk'] = $config['installedpackages']['pfblocker']['config'][0]['enable_cb']; - if ($pfb['validate_chk'] == "on") { - $log = "\n The Package 'pfBlocker' is currently Enabled. Either Disable pfBlocker, or 'Disable Validation Check' in pfBlockerNG \n"; - pfb_logger("{$log}","1"); - return; - } - } - ################################# # Configure ARRAYS # @@ -690,9 +867,11 @@ function sync_package_pfblockerng($cron = "") { # Sort pfBlockerNG Interface order to pfSense Interface Order $sort_interfaces = array_intersect($ifaces, $selected_interfaces); // If OpenVPN Interfaces are not in dropdown menu - if ($pfb['openvpn'] == "on" && $config['openvpn']['openvpn-server'] || $pfb['openvpn'] == "on" && $config['openvpn']['openvpn-client']) - if (!in_array("openvpn",$sort_interfaces)) + if ($pfb['openvpn'] == "on" && $config['openvpn']['openvpn-server'] || $pfb['openvpn'] == "on" && $config['openvpn']['openvpn-client']) { + if (!in_array("openvpn",$sort_interfaces)) { array_push($sort_interfaces, "openvpn"); + } + } $implode_interfaces = ltrim(implode(",",$sort_interfaces), ","); # CSV String for Outbound Interfaces for 'pfB_' Match Rules $pfb['outbound_floating'] = $implode_interfaces; @@ -706,9 +885,11 @@ function sync_package_pfblockerng($cron = "") { $base_rule = $base_rule_reg; $pfb['outbound_interfaces'] = explode(",",$pfb['config']['outbound_interface']); // If OpenVPN Interfaces are not in dropdown menu - if ($pfb['openvpn'] == "on" && $config['openvpn']['openvpn-server'] || $pfb['openvpn'] == "on" && $config['openvpn']['openvpn-client']) - if (!in_array("openvpn",$sort_interfaces)) + if ($pfb['openvpn'] == "on" && $config['openvpn']['openvpn-server'] || $pfb['openvpn'] == "on" && $config['openvpn']['openvpn-client']) { + if (!in_array("openvpn",$sort_interfaces)) { array_push($pfb['outbound_interfaces'], "openvpn"); + } + } } } else { # Define Empty Variable/Array @@ -725,8 +906,9 @@ function sync_package_pfblockerng($cron = "") { $pfb['sync_master'] = TRUE; # Don't execute this function when pfBlockerNG is Disabled and 'Keep Blocklists' is enabled. - if ($pfb['enable'] == "" && $pfb['keep'] == "on") + if ($pfb['enable'] == "" && $pfb['keep'] == "on") { $pfb['sync_master'] = FALSE; + } if ($pfb['sync_master']) { $pfb['existing']['match']['type'] = "match"; @@ -816,6 +998,7 @@ function sync_package_pfblockerng($cron = "") { if ($row['format'] == "et") { unlink_if_exists("{$pfb['denydir']}/{$aliasname}.txt"); $config['installedpackages']['pfblockerngreputation']['config'][0]['et_update'] = "disabled"; + $pfb['cron_mod'] = TRUE; break; } } @@ -848,6 +1031,7 @@ function sync_package_pfblockerng($cron = "") { unlink_if_exists("{$pfbfolder}/{$pfb_alias}.txt"); # Uncheck 'Enabled' in List 'Custom_update' Setting $config['installedpackages'][$ip_type]['config'][$count]['custom_update'] = "disabled"; + $pfb['cron_mod'] = TRUE; } } } @@ -901,10 +1085,10 @@ function sync_package_pfblockerng($cron = "") { # This variable ($f_result) used in next section below. $f_result = implode($results); if (!empty($results)) { - foreach ($results as $pfb_results) { - $log = "[ Removing List(s) : {$pfb_results} ]\n"; + foreach ($results as $pfb_result) { + $log = "[ Removing List : {$pfb_result} ]\n"; pfb_logger("{$log}","1"); - unlink_if_exists("{$pfbfolder}/{$pfb_results}.txt"); + unlink_if_exists("{$pfbfolder}/{$pfb_result}.txt"); } $pfb['summary'] = TRUE; $pfb['remove'] = TRUE; @@ -912,12 +1096,12 @@ function sync_package_pfblockerng($cron = "") { break; } - # Allow Rebuilding of Changed Aliase to purge 'SKIP' Lists (when pfBlockerNG is Enabled) + # Allow rebuilding of changed Alias to purge 'SKIP' Lists (when pfBlockerNG is enabled) $list_type = array ("pfblockernglistsv4" => "_v4", "pfblockernglistsv6" => "_v6"); foreach ($list_type as $ip_type => $vtype) { if ($f_result != "" && $pfb['enable'] == "on") { foreach ($results as $removed_header) { - if ($config['installedpackages'][$ip_type]['config'] != "" && $pfb['enable'] == "on") { + if ($config['installedpackages'][$ip_type]['config'] != "") { foreach ($config['installedpackages'][$ip_type]['config'] as $list) { $alias = "pfB_" . preg_replace("/\W/","",$list['aliasname']); if (is_array($list['row'])) { @@ -964,12 +1148,13 @@ function sync_package_pfblockerng($cron = "") { } - ######################################### - # Create Suppression Txt File # - ######################################### + ################################################# + # Create IP Suppression Txt File # + ################################################# - if ($pfb['enable'] == "on" && $pfb['supp'] == "on") + if ($pfb['enable'] == "on" && $pfb['supp'] == "on") { pfb_create_suppression_file(); + } ################################# @@ -979,18 +1164,23 @@ function sync_package_pfblockerng($cron = "") { foreach ($continents as $continent => $pfb_alias) { if (is_array($config['installedpackages']['pfblockerng' . strtolower(preg_replace('/ /','',$continent))]['config'])) { $continent_config = $config['installedpackages']['pfblockerng' . strtolower(preg_replace('/ /','',$continent))]['config'][0]; + $cc_name = 'pfblockerng' . strtolower(preg_replace('/ /','',$continent)); if ($continent_config['action'] != "Disabled" && $pfb['enable'] == "on") { - # Determine Folder Location for Alias (return array $pfbarr) - pfb_determine_list_detail($continent_config['action']); - $pfb['skip'] = $pfbarr['skip']; - $pfb_descr = $pfbarr['descr']; - $pfbfolder = $pfbarr['folder']; - // Determine if Continent Lists require Action (IPv4 and IPv6) $cont_type = array ("countries4" => "_v4", "countries6" => "_v6"); foreach ($cont_type as $c_type => $vtype) { + # Determine 'List' details (return array $pfbarr) + pfb_determine_list_detail($continent_config['action'], "{$pfb_alias}{$vtype}", $cc_name, "0"); + $pfb['skip'] = $pfbarr['skip']; + $pfb_descr = $pfbarr['descr']; + $pfbfolder = $pfbarr['folder']; + $log_tab = $pfbarr['logtab']; + $aports = $pfbarr['aports']; + $adest = $pfbarr['adest']; + $aproto = $pfbarr['aproto']; + $continent = ""; if ($continent_config[$c_type] != "") { @@ -1001,9 +1191,9 @@ function sync_package_pfblockerng($cron = "") { } } - if (file_exists($pfb['origdir'] . '/' . $pfb_alias . $vtype . '.orig')) + if (file_exists($pfb['origdir'] . '/' . $pfb_alias . $vtype . '.orig')) { $continent_existing = preg_replace('/\s/', '', file ($pfb['origdir'] . '/' . $pfb_alias . $vtype . '.orig')); - + } // Collect New Continent Data for comparison. Cleanup Array for Comparison $continent_new = preg_split ('/$\R?^/m', $continent); $line = count ( $continent_new ) - 1; @@ -1024,22 +1214,14 @@ function sync_package_pfblockerng($cron = "") { // Compare Existing (Original File) and New Continent Data if ($continent_new === $continent_existing && !empty($pfctlck) && file_exists($pfbfolder . '/' . $pfb_alias . $vtype . '.txt') && $pfb['reuse'] == "") { - # Format Log into clean Tab Spaces - $string_final = "{$pfb_alias}{$vtype}"; - if (strlen($string_final) > 10) { - $log_tab = "\t"; - } else { - $log_tab = "\t\t"; - } - if (!$pfb['save']) { - $log = "\n[ {$pfb_alias}{$vtype} ] {$log_tab} exists, Reloading File [ NOW ]\n"; + $log = "\n[ {$pfb_alias}{$vtype} ]{$log_tab} exists, Reloading File [ NOW ]"; pfb_logger("{$log}","1"); } } else { // Do not proceed with Changes on User 'Save' if (!$pfb['save']) { - $log = "\n[ {$pfb_alias}{$vtype} ] {$log_tab} Changes Found... Updating \n"; + $log = "\n[ {$pfb_alias}{$vtype} ]{$log_tab} Changes Found... Updating \n"; pfb_logger("{$log}","1"); # Test to Skip d-dup and p-dup functions when changes are found. @@ -1061,11 +1243,12 @@ function sync_package_pfblockerng($cron = "") { @file_put_contents($pfb['aliasdir'] . '/' . $pfb_alias . $vtype . '.txt',$continent, LOCK_EX); } - # Check if File Exists and is >0 in Size and Save alias file + # Check if File Exists and is > 0 in Size and Save alias file $file_chk = "0"; $cont_chk = "{$pfbfolder}/{$pfb_alias}{$vtype}.txt"; - if (file_exists($cont_chk) && @filesize($cont_chk) >0) + if (file_exists($cont_chk) && @filesize($cont_chk) > 0) { $file_chk = exec ("/usr/bin/grep -cv '^#\|^$' {$cont_chk}"); + } if ($file_chk == "0" || $file_chk == "1") { $new_file = "1.1.1.1\n"; @@ -1077,7 +1260,6 @@ function sync_package_pfblockerng($cron = "") { } } - if (file_exists($pfbfolder . '/' . $pfb_alias . $vtype . '.txt')) { #Create alias config $new_aliases_list[] = "{$pfb_alias}{$vtype}"; @@ -1105,7 +1287,7 @@ function sync_package_pfblockerng($cron = "") { $rule['direction'] = "any"; $rule['descr']= "{$pfb_alias}{$vtype}{$pfb['suffix']}"; $rule['source'] = array("any" => ""); - $rule['destination'] = array ("address" => "{$pfb_alias}{$vtype}"); + $rule['destination'] = array("address" => "{$pfb_alias}{$vtype}"); if ($pfb['config']['enable_log'] == "on" || $pfb_contlog == "enabled") $rule['log'] = ""; $deny_outbound[] = $rule; @@ -1120,7 +1302,19 @@ function sync_package_pfblockerng($cron = "") { $rule['direction'] = "any"; $rule['descr'] = "{$pfb_alias}{$vtype}{$pfb['suffix']}"; $rule['source'] = array("address" => "{$pfb_alias}{$vtype}"); - $rule['destination'] = array ("any" => ""); + if (!empty($adest) && !empty($aports)) { + $rule['destination'] = array("address" => "{$adest}", "port" => "{$aports}"); + } elseif (!empty($adest) && empty($aports)) { + $rule['destination'] = array("address" => "{$adest}"); + } elseif (empty($adest) && !empty($aports)) { + $rule['destination'] = array("any" => "", "port" => "{$aports}"); + } else { + $rule['destination'] = array("any" => ""); + } + if (!empty($adest) && $continent_config['autonot'] == "on") + $rule['destination']['not'] = ""; + if (!empty($aproto)) + $rule['protocol'] = "{$aproto}"; if ($pfb['config']['enable_log'] == "on" || $pfb_contlog == "enabled") $rule['log'] = ""; $deny_inbound[] = $rule; @@ -1150,7 +1344,19 @@ function sync_package_pfblockerng($cron = "") { $rule['direction'] = "any"; $rule['descr'] = "{$pfb_alias}{$vtype}{$pfb['suffix']}"; $rule['source'] = array("address"=> "{$pfb_alias}{$vtype}"); - $rule['destination'] = array ("any" => ""); + if (!empty($adest) && !empty($aports)) { + $rule['destination'] = array("address" => "{$adest}", "port" => "{$aports}"); + } elseif (!empty($adest) && empty($aports)) { + $rule['destination'] = array("address" => "{$adest}"); + } elseif (empty($adest) && !empty($aports)) { + $rule['destination'] = array("any" => "", "port" => "{$aports}"); + } else { + $rule['destination'] = array("any" => ""); + } + if (!empty($adest) && $continent_config['autonot'] == "on") + $rule['destination']['not'] = ""; + if (!empty($aproto)) + $rule['protocol'] = "{$aproto}"; if ($pfb['config']['enable_log'] == "on" || $pfb_contlog == "enabled") $rule['log'] = ""; $permit_inbound[] = $rule; @@ -1163,8 +1369,8 @@ function sync_package_pfblockerng($cron = "") { $rule['ipprotocol'] = "inet6"; $rule['direction'] = "any"; $rule['descr'] = "{$pfb_alias}{$vtype}{$pfb['suffix']}"; - $rule['source'] = array ("any" => ""); - $rule['destination'] = array ("address" => "{$pfb_alias}{$vtype}"); + $rule['source'] = array("any" => ""); + $rule['destination'] = array("address" => "{$pfb_alias}{$vtype}"); if ($pfb['config']['enable_log'] == "on" || $pfb_contlog == "enabled") $rule['log'] = ""; $match_outbound[] = $rule; @@ -1178,7 +1384,19 @@ function sync_package_pfblockerng($cron = "") { $rule['direction'] = "any"; $rule['descr'] = "{$pfb_alias}{$vtype}{$pfb['suffix']}"; $rule['source'] = array ("address" => "{$pfb_alias}{$vtype}"); - $rule['destination'] = array ( "any" => ""); + if (!empty($adest) && !empty($aports)) { + $rule['destination'] = array("address" => "{$adest}", "port" => "{$aports}"); + } elseif (!empty($adest) && empty($aports)) { + $rule['destination'] = array("address" => "{$adest}"); + } elseif (empty($adest) && !empty($aports)) { + $rule['destination'] = array("any" => "", "port" => "{$aports}"); + } else { + $rule['destination'] = array("any" => ""); + } + if (!empty($adest) && $continent_config['autonot'] == "on") + $rule['destination']['not'] = ""; + if (!empty($aproto)) + $rule['protocol'] = "{$aproto}"; if ($pfb['config']['enable_log'] == "on" || $pfb_contlog == "enabled") $rule['log'] = ""; $match_inbound[] = $rule; @@ -1207,7 +1425,7 @@ function sync_package_pfblockerng($cron = "") { # IPv4 REGEX Definitions $pfb['range'] = '/((?:(?: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]?))-((?:(?: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]?))/'; $pfb['block'] = '/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[ 0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.([0]{1})\s+/'; - $pfb['cidr'] = '/(?:(?: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]?)?\/[0-9]{2}/'; + $pfb['cidr'] = '/(?:(?: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]?)?\/([0-9]{2}|[0-9]{1})/'; $pfb['single'] = '/(?:(?: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]?)\s+/'; $pfb['s_html'] = '/(?:(?: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]?)/'; @@ -1215,8 +1433,8 @@ function sync_package_pfblockerng($cron = "") { $pfb_ipreg = array(); $pfb_ipreg[0] = '/\b0+(?=\d)/'; # Remove any Leading Zeros in each Octet $pfb_ipreg[1] = '/\s/'; # Remove any Whitespaces - $pfb_ipreg[2] = '/127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/'; # Remove any Loopback Addresses 127/8 - $pfb_ipreg[3] = '/0\.0\.0\.0\/32/'; # Remove 0.0.0.0/32 + $pfb_ipreg[2] = '/\/32/'; # Remove any /32 CIDR + $pfb_ipreg[3] = '/127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/'; # Remove any Loopback Addresses 127/8 $pfb_ipreg[4] = '/0\.0\.0\.0/'; # Remove 0.0.0.0 # IPv6 REGEX Definitions -- ** Still Needs some Adjustment on Regex Definition for IPv6 ** @@ -1244,23 +1462,17 @@ function sync_package_pfblockerng($cron = "") { foreach ($list['row'] as $row) { if ($row['url'] != "" && $row['state'] != "Disabled") { - # Determine Folder Location for Alias (return array $pfbarr) - pfb_determine_list_detail($list['action']); - $pfb['skip'] = $pfbarr['skip']; - $pfbfolder = $pfbarr['folder']; - if ($vtype == "_v4") { $header_url = "{$row['header']}"; } else { $header_url = "{$row['header']}_v6"; } - # Format Log into clean Tab Spaces - if (strlen($header_url) > 10) { - $log_tab = "\t"; - } else { - $log_tab = "\t\t"; - } + # Determine 'List' details (return array $pfbarr) + pfb_determine_list_detail($list['action'], $header_url, "", ""); + $pfb['skip'] = $pfbarr['skip']; + $pfbfolder = $pfbarr['folder']; + $log_tab = $pfbarr['logtab']; // Empty Header Field Validation Check if (empty($header_url) || preg_match("/\W/",$header_url)) { @@ -1274,28 +1486,30 @@ function sync_package_pfblockerng($cron = "") { if (file_exists($pfbfolder . '/' . $header_url . '.txt') && $pfb['reuse'] == "") { if ($row['state'] == "Hold") { - $log = "\n[ {$header_url} ] {$log_tab} Static Hold [ NOW ]\n"; + $log = "\n[ {$header_url} ]{$log_tab} Static Hold [ NOW ]"; } else { - $log = "\n[ {$header_url} ] {$log_tab} exists, Reloading File [ NOW ]\n"; + $log = "\n[ {$header_url} ]{$log_tab} exists, Reloading File [ NOW ]"; } pfb_logger("{$log}","1"); } else { if ($pfb['reuse'] == "on" && file_exists($pfb['origdir'] . '/' . $header_url . '.orig')) { - $log = "\n[ {$header_url} ] {$log_tab} Using Previously Downloaded File [ NOW ]\n"; + $log = "\n[ {$header_url} ]{$log_tab} Using Previously Downloaded File [ NOW ]"; } else { - $log = "\n[ {$header_url} ] {$log_tab} Downloading New File [ NOW ]\n"; - } + $log = "\n[ {$header_url} ]{$log_tab} Downloading New File [ NOW ]"; + } pfb_logger("{$log}","1"); - # Perform Remote URL Date/Time Stamp checks - $host = @parse_url($row['url']); $list_url = "{$row['url']}"; - if ($row['format'] != "rsync" || $row['format'] != "html") { - if ($host['host'] == "127.0.0.1" || $host['host'] == $pfb['iplocal'] || empty($host['host'])) { - $remote_tds = "local"; - } else { - $remote_tds = @implode(preg_grep("/Last-Modified/", get_headers($list_url))); - $remote_tds = preg_replace("/^Last-Modified: /","", $remote_tds); + if (!$pfb['reuse'] == "on") { + # Perform Remote URL Date/Time Stamp checks + $host = @parse_url($row['url']); + if ($row['format'] != "rsync" || $row['format'] != "html") { + if ($host['host'] == "127.0.0.1" || $host['host'] == $pfb['iplocal'] || empty($host['host'])) { + $remote_tds = "local"; + } else { + $remote_tds = @implode(preg_grep("/Last-Modified/", get_headers($list_url))); + $remote_tds = preg_replace("/^Last-Modified: /","", $remote_tds); + } } } @@ -1344,7 +1558,7 @@ function sync_package_pfblockerng($cron = "") { $url_zip = "{$row['url']}"; if (!$file_zip = @file_get_contents($url_zip)) { $error = error_get_last(); - $log = "\n [ {$header_url} ] {$error['message']} \n"; + $log = "\n [ {$header_url} ] {$error['message']}\n"; pfb_logger("{$log}","2"); } else { @file_put_contents($file_dwn, $file_zip, LOCK_EX); @@ -1421,7 +1635,7 @@ function sync_package_pfblockerng($cron = "") { $return = 0; } else { $url_html = "{$row['url']}"; - exec ("/usr/bin/fetch -v -o {$file_dwn} -T 20 {$url_html}",$output,$return); + exec ("/usr/bin/fetch -v -o {$file_dwn} -T 20 '{$url_html}'",$output,$return); } if ($return == 0) $url_list = @file($file_dwn); @@ -1497,8 +1711,17 @@ function sync_package_pfblockerng($cron = "") { else { foreach ($url_list as $line) { if (!preg_match("/^#/", $line)) { + # Network range 192.168.0.0-192.168.0.254 + if (preg_match($pfb['range'],$line,$matches)) { + $a_cidr = ip_range_to_subnet_array_temp2($matches[1],$matches[2]); + if (!empty($a_cidr)) { + foreach ($a_cidr as $cidr) { + $new_file .= preg_replace($pfb_ipreg,'',$cidr) . "\n"; + } + } + } # CIDR format 192.168.0.0/16 - if (preg_match($pfb['cidr'],$line,$matches)) { + elseif (preg_match($pfb['cidr'],$line,$matches)) { $new_file .= preg_replace($pfb_ipreg, '',$matches[0]) . "\n"; } # Single ip addresses @@ -1517,10 +1740,11 @@ function sync_package_pfblockerng($cron = "") { $url_chk = "{$pfb['origdir']}/{$header_url}.orig"; } - # Check if File Exists and is >0 in Size + # Check if File Exists and is > 0 in Size $file_chk = ""; - if (file_exists($url_chk) && @filesize($url_chk) >0) + if (file_exists($url_chk) && @filesize($url_chk) > 0) { $file_chk = exec ("/usr/bin/grep -cv '^#\|^$' {$url_chk}"); + } if ($file_chk == "0") { $new_file = "1.1.1.1\n"; @@ -1552,12 +1776,13 @@ function sync_package_pfblockerng($cron = "") { # PFCTL - Update Only Aliases that have been updated only. $pfb_alias_lists[] = "{$alias}"; # Launch d-dup and p-dup functions when changes are found. - if ($pfb['skip'] && $vtype == "_v4") + if ($pfb['skip'] && $vtype == "_v4") { $pfb['dupcheck'] = TRUE; + } # Enable Suppression Process due to Updates - if ($pfb['supp'] == "on" && $vtype == "_v4") + if ($pfb['supp'] == "on" && $vtype == "_v4") { $pfb['supp_update'] = TRUE; - + } } else { # Log FAILED Downloads and Check if Firewall or Snort/Suricata is Blocking Host $log = "\n [ {$alias} {$header_url} ] Download FAIL [ NOW ]\n"; @@ -1632,27 +1857,21 @@ function sync_package_pfblockerng($cron = "") { $aliascustom = "{$list['aliasname']}_custom_v6"; } - # Format Log into clean Tab Spaces - if (strlen($aliascustom) > 10) { - $log_tab = "\t"; - } else { - $log_tab = "\t\t"; - } - # Collect Active Alias List (Used for pfctl Update when 'Reputation' is enabled. $pfb_alias_lists_all[] = "{$alias}"; - # Determine Folder Location for Alias (return array $pfbarr) - pfb_determine_list_detail($list['action']); - $pfb['skip'] = $pfbarr['skip']; - $pfbfolder = $pfbarr['folder']; + # Determine 'List' details (return array $pfbarr) + pfb_determine_list_detail($list['action'], $aliascustom, "", ""); + $pfb['skip'] = $pfbarr['skip']; + $pfbfolder = $pfbarr['folder']; + $log_tab = $pfbarr['logtab']; if (file_exists($pfbfolder . '/' . $aliascustom . '.txt') && $pfb['reuse'] == "") { - $log = "\n[ {$aliascustom} ] {$log_tab} exists, Reloading File [ NOW ]\n"; + $log = "\n[ {$aliascustom} ]{$log_tab} exists, Reloading File [ NOW ]"; pfb_logger("{$log}","1"); } else { $url_list = array(); - $log = "\n[ {$aliascustom} ] {$log_tab} Loading Custom File [ NOW ]\n"; + $log = "\n[ {$aliascustom} ]{$log_tab} Loading Custom File [ NOW ]\n"; pfb_logger("{$log}","1"); $custom_list = pfbng_text_area_decode($list['custom']) . "\n"; @@ -1663,16 +1882,8 @@ function sync_package_pfblockerng($cron = "") { if (!empty($url_list)) { foreach ($url_list as $line) { if ($vtype == "_v4") { - # CIDR format 192.168.0.0/16 - if (preg_match($pfb['cidr'],$line,$matches)) { - $new_file .= preg_replace($pfb_ipreg, '',$matches[0]) . "\n"; - } - # Single ip addresses - elseif (preg_match($pfb['s_html'],$line,$matches)) { - $new_file .= preg_replace($pfb_ipreg, '',$matches[0]) . "\n"; - } # Network range 192.168.0.0-192.168.0.254 - elseif (preg_match($pfb['range'],$line,$matches)) { + if (preg_match($pfb['range'],$line,$matches)) { $a_cidr = ip_range_to_subnet_array_temp2($matches[1],$matches[2]); if (!empty($a_cidr)) { foreach ($a_cidr as $cidr) { @@ -1680,6 +1891,14 @@ function sync_package_pfblockerng($cron = "") { } } } + # CIDR format 192.168.0.0/16 + elseif (preg_match($pfb['cidr'],$line,$matches)) { + $new_file .= preg_replace($pfb_ipreg, '',$matches[0]) . "\n"; + } + # Single ip addresses + elseif (preg_match($pfb['s_html'],$line,$matches)) { + $new_file .= preg_replace($pfb_ipreg, '',$matches[0]) . "\n"; + } } else { # IPv6 Regex if (preg_match($pfb['ipv6'],$line,$matches)) { @@ -1695,8 +1914,9 @@ function sync_package_pfblockerng($cron = "") { # Collect Updated lists for Suppression Process @file_put_contents($pfbfolder . '/'. $aliascustom . '.txt',$new_file, LOCK_EX); # Enable Suppression Process due to Updates - if ($pfb['supp'] == "on" && $vtype == "_v4") + if ($pfb['supp'] == "on" && $vtype == "_v4") { $pfb['supp_update'] = TRUE; + } if ($pfb['rep'] == "on" && $pfb['skip'] && $vtype == "_v4") { # Script to Call p24 Process exec ("{$pfb['script']} p24 {$aliascustom} {$pfb['max']} {$pfb['dedup']} {$pfb['ccexclude']} {$pfb['ccwhite']} {$pfb['ccblack']} >> {$pfb['log']} 2>&1"); @@ -1739,24 +1959,29 @@ function sync_package_pfblockerng($cron = "") { foreach ($list_type as $ip_type => $vtype) { if ($config['installedpackages'][$ip_type]['config'] != "" && $pfb['enable'] == "on") { $runonce = 0; - foreach ($config['installedpackages'][$ip_type]['config'] as $list) { + foreach ($config['installedpackages'][$ip_type]['config'] as $key => $list) { $alias = "pfB_" . preg_replace("/\W/","",$list['aliasname']); - # Determine Folder Location for Alias (return array $pfbarr) - pfb_determine_list_detail($list['action']); + # Determine 'List' details (return array $pfbarr) + pfb_determine_list_detail($list['action'], "", $ip_type, $key); $pfb['skip'] = $pfbarr['skip']; $pfb_descr = $pfbarr['descr']; $pfbfolder = $pfbarr['folder']; + $aports = $pfbarr['aports']; + $adest = $pfbarr['adest']; + $aproto = $pfbarr['aproto']; // Re-Save Only Aliases that have been updated only. // When 'Reputation' is used, all Aliases need to be Updated. $final_alias = array(); if ($pfb['dedup'] == "on" || $pfb['pdup'] == "on") { - if (!empty($pfb_alias_lists_all)) + if (!empty($pfb_alias_lists_all)) { $final_alias = array_unique($pfb_alias_lists_all); + } } else { - if (!empty($pfb_alias_lists)) + if (!empty($pfb_alias_lists)) { $final_alias = array_unique($pfb_alias_lists); + } } if ($list['action'] != "Disabled") { @@ -1862,7 +2087,19 @@ function sync_package_pfblockerng($cron = "") { $rule['direction'] = "any"; $rule['descr'] = "{$alias}{$pfb['suffix']}"; $rule['source'] = array("address" => "{$alias}"); - $rule['destination'] = array ("any" => ""); + if (!empty($adest) && !empty($aports)) { + $rule['destination'] = array ("address" => "{$adest}", "port" => "{$aports}"); + } elseif (!empty($adest) && empty($aports)) { + $rule['destination'] = array ("address" => "{$adest}"); + } elseif (empty($adest) && !empty($aports)) { + $rule['destination'] = array ("any" => "", "port" => "{$aports}"); + } else { + $rule['destination'] = array ("any" => ""); + } + if (!empty($adest) && $list['autonot'] == "on") + $rule['destination']['not'] = ""; + if (!empty($aproto)) + $rule['protocol'] = "{$aproto}"; if ($pfb['config']['enable_log'] == "on" || $alias_log == "enabled") $rule['log'] = ""; $deny_inbound[] = $rule; @@ -1892,7 +2129,19 @@ function sync_package_pfblockerng($cron = "") { $rule['direction'] = "any"; $rule['descr'] = "{$alias}{$pfb['suffix']}"; $rule['source'] = array ("address" => "{$alias}"); - $rule['destination'] = array ("any" => ""); + if (!empty($adest) && !empty($aports)) { + $rule['destination'] = array ("address" => "{$adest}", "port" => "{$aports}"); + } elseif (!empty($adest) && empty($aports)) { + $rule['destination'] = array ("address" => "{$adest}"); + } elseif (empty($adest) && !empty($aports)) { + $rule['destination'] = array ("any" => "", "port" => "{$aports}"); + } else { + $rule['destination'] = array ("any" => ""); + } + if (!empty($adest) && $list['autonot'] == "on") + $rule['destination']['not'] = ""; + if (!empty($aproto)) + $rule['protocol'] = "{$aproto}"; if ($pfb['config']['enable_log'] == "on" || $alias_log == "enabled") $rule['log'] = ""; $permit_inbound[] = $rule; @@ -1920,7 +2169,19 @@ function sync_package_pfblockerng($cron = "") { $rule['direction'] = "any"; $rule['descr'] = "{$alias}{$pfb['suffix']}"; $rule['source'] = array ("address" => "{$alias}"); - $rule['destination'] = array ("any" => ""); + if (!empty($adest) && !empty($aports)) { + $rule['destination'] = array ("address" => "{$adest}", "port" => "{$aports}"); + } elseif (!empty($adest) && empty($aports)) { + $rule['destination'] = array ("address" => "{$adest}"); + } elseif (empty($adest) && !empty($aports)) { + $rule['destination'] = array ("any" => "", "port" => "{$aports}"); + } else { + $rule['destination'] = array ("any" => ""); + } + if (!empty($adest) && $list['autonot'] == "on") + $rule['destination']['not'] = ""; + if (!empty($aproto)) + $rule['protocol'] = "{$aproto}"; if ($pfb['config']['enable_log'] == "on" || $alias_log == "enabled") $rule['log'] = ""; $match_inbound[] = $rule; @@ -1949,7 +2210,7 @@ function sync_package_pfblockerng($cron = "") { #update pfsense alias table if (is_array($config['aliases']['alias'])) { foreach ($config['aliases']['alias'] as $cbalias) { - if (preg_match("/pfB_/",$cbalias['name'])) { + if (substr($cbalias['name'], 0, 4) == 'pfB_') { #mark pfctl aliastable for cleaning if (!in_array($cbalias['name'], $aliases_list)) { $aliases_list[] = $cbalias['name']; #mark aliastable for cleaning @@ -1976,6 +2237,7 @@ function sync_package_pfblockerng($cron = "") { #apply new alias table to xml if ($message == "") { $config['aliases']['alias'] = $new_aliases; + $pfb['cron_mod'] = TRUE; } # UNSET Variables unset($new_aliases, $cbalias); @@ -2241,26 +2503,25 @@ function sync_package_pfblockerng($cron = "") { # Save New Rule Order to Config $config['filter']['rule'] = $new_rules; } - $log = "\n {$message} \n"; - pfb_logger("{$log}","1"); + if (!empty($message)) { + $log = "\n {$message}\n"; + pfb_logger("{$log}","1"); + } # UNSET arrays unset ($cb_rules,$permit_inbound,$permit_outbound,$deny_inbound,$deny_outbound,$match_inbound,$match_outbound); unset ($other_rules,$fother_rules,$permit_rules,$fpermit_rules,$match_rules,$fmatch_rules); } + // Set flag to Update config file. + if ($pfb['autorules'] && $rules != $new_rules) { + $pfb['cron_mod'] = TRUE; + } ################################# - # Closing Processes # + # pfSense Integration # ################################# - #uncheck Reusing Existing Downloads Check box - if (!$pfb['save'] && $pfb['enable'] == "on") - $config['installedpackages']['pfblockerng']['config'][0]['pfb_reuse'] = ""; - - # Save all Changes to pfSense config file - write_config(); - # If 'Rule Changes' are found, utilize the 'filter_configure()' function, if not, utilize 'pfctl replace' command if ($pfb['autorules'] && $rules != $new_rules || $pfb['enable'] == "" || $pfb['remove']) { require_once("filter.inc"); @@ -2269,7 +2530,7 @@ function sync_package_pfblockerng($cron = "") { $log = "\n===[ Aliastables / Rules ]================================\n\n"; pfb_logger("{$log}","1"); - $log = "Firewall Rule Changes Found, Applying Filter Reload \n"; + $log = "Firewall Rule Changes Found, Applying Filter Reload\n"; pfb_logger("{$log}","1"); } @@ -2289,37 +2550,45 @@ function sync_package_pfblockerng($cron = "") { # Don't Execute on User 'Save' if (!$pfb['save']) { - $log = "\n===[ Aliastables / Rules ]================================\n\n"; + $log = "\n\n===[ Aliastables / Rules ]================================\n\n"; pfb_logger("{$log}","1"); - $log = "No Changes to Firewall Rules, Skipping Filter Reload \n"; + $log = "No Changes to Firewall Rules, Skipping Filter Reload\n"; pfb_logger("{$log}","1"); // Re-Save Only Aliases that have been updated only. // When 'Reputation' is used, all Aliases Need to be Updated. $final_alias = array(); if ($pfb['dedup'] == "on" || $pfb['pdup'] == "on") { - if (!empty($pfb_alias_lists_all)) + if (!empty($pfb_alias_lists_all)) { $final_alias = array_unique($pfb_alias_lists_all); + } } else { - if (!empty($pfb_alias_lists)) + if (!empty($pfb_alias_lists)) { $final_alias = array_unique($pfb_alias_lists); + } } if (!empty($final_alias)) { foreach ($final_alias as $final) { - $log = "\n Updating: {$final} \n"; + $log = "\n Updating: {$final}\n"; pfb_logger("{$log}","1"); $result_pfctl = ""; - exec ("/sbin/pfctl -t " . escapeshellarg($final) . " -T replace -f " . $pfb['aliasdir'] . "/" . escapeshellarg($final) . ".txt 2>&1", $result_pfctl); - $log = implode($result_pfctl); + if (file_exists("{$pfb['aliasdir']}/{$final}.txt")) { + exec ("/sbin/pfctl -t " . escapeshellarg($final) . " -T replace -f " . $pfb['aliasdir'] . "/" . escapeshellarg($final) . ".txt 2>&1", $result_pfctl); + $log = implode($result_pfctl); + } + else { + $log = "Aliastable file not found\n"; + } pfb_logger("{$log}","1"); } + pfb_logger("\n","1"); // Call function for NanoBSD/Ramdisk processes. pfb_aliastables("update"); } else { - $log = "\nNo Changes to Aliases, Skipping pfctl Update \n"; + $log = "No Changes to Aliases, Skipping pfctl Update\n"; pfb_logger("{$log}","1"); } } @@ -2330,6 +2599,7 @@ function sync_package_pfblockerng($cron = "") { #sync config pfblockerng_sync_on_changes(); + ################################# # FINAL REPORTING # ################################# @@ -2340,8 +2610,8 @@ function sync_package_pfblockerng($cron = "") { exec ("{$pfb['script']} closing {$pfb['dup']} >> {$pfb['log']} 2>&1"); } - if ($pfb['enable'] == "on" && !$pfb['save']) { - $log = "\n\n UPDATE PROCESS ENDED [ NOW ]\n"; + if ($pfb['enable'] == "on" && !$pfb['save'] || $pfb['summary']) { + $log = "\n UPDATE PROCESS ENDED [ NOW ]\n"; pfb_logger("{$log}","1"); } @@ -2350,32 +2620,40 @@ function sync_package_pfblockerng($cron = "") { # Define/Apply CRON Jobs # ######################################### - # Clear any existing pfBlockerNG Cron Jobs - install_cron_job("pfblockerng.php cron", false); - - # Replace Cron job with any User Changes to $pfb_min + // Replace Cron job with any User Changes to $pfb_min if ($pfb['enable'] == "on") { - # Define pfBlockerNG CRON Job + // Define pfBlockerNG CRON Job $pfb_cmd = "/usr/local/bin/php /usr/local/www/pfblockerng/pfblockerng.php cron >> {$pfb['log']} 2>&1"; - # $pfb['min'] ( User Defined Variable. Variable defined at start of Script ) - $pfb_hour = "*"; + // $pfb['min'] ( User Defined Variable. Variable defined at start of Script ) + + // Define Cron hour (Cron Interval & Start Hour) + if ($pfb['interval'] == 1) { + $pfb_hour = "*"; + } elseif ($pfb['interval'] == 24) { + $pfb_hour = $pfb['24hour']; + } else { + $pfb_hour = implode(",", pfb_cron_base_hour()); + } + $pfb_mday = "*"; $pfb_month = "*"; $pfb_wday = "*"; $pfb_who = "root"; - install_cron_job($pfb_cmd, true, $pfb['min'], $pfb_hour, $pfb_mday, $pfb_month, $pfb_wday, $pfb_who); + // Determine if Cron Task requires updating + if (!pfblockerng_cron_exists($pfb_cmd, $pfb['min'], $pfb_hour)) { + install_cron_job($pfb_cmd, true, $pfb['min'], $pfb_hour, $pfb_mday, $pfb_month, $pfb_wday, $pfb_who); + } + } + else { + // Clear any existing pfBlockerNG Cron Jobs + install_cron_job("pfblockerng.php cron", false); } - - # Clear any existing pfBlockerNG MaxMind CRON Job - install_cron_job("pfblockerng.php dc", false); if ($pfb['enable'] == "on") { - # Define pfBlockerNG MaxMind CRON Job + // Define pfBlockerNG MaxMind CRON Job $pfb_gcmd = "/usr/local/bin/php /usr/local/www/pfblockerng/pfblockerng.php dc >> {$pfb['geolog']} 2>&1"; - - # MaxMind GeoIP Cron Hour is randomized between 0-23 Hour to minimize effect on MaxMind Website - + // MaxMind GeoIP Cron Hour is randomized between 0-23 Hour to minimize effect on MaxMind Website $pfb_gmin = "0"; $pfb_ghour = rand(0,23); $pfb_gmday = "1,2,3,4,5,6,7"; @@ -2383,32 +2661,61 @@ function sync_package_pfblockerng($cron = "") { $pfb_gwday = "2"; $pfb_gwho = "root"; - install_cron_job($pfb_gcmd, true, $pfb_gmin, $pfb_ghour, $pfb_gmday, $pfb_gmonth, $pfb_gwday, $pfb_gwho); + // Determine if Cron Task requires updating + if (!pfblockerng_cron_exists($pfb_gcmd, $pfb_gmin, $pfb_ghour)) { + install_cron_job($pfb_gcmd, true, $pfb_gmin, $pfb_ghour, $pfb_gmday, $pfb_gmonth, $pfb_gwday, $pfb_gwho); + } + } + else { + // Clear any existing pfBlockerNG Cron Jobs + install_cron_job("pfblockerng.php dc", false); + } + + + ################################# + # Closing Processes # + ################################# + + // uncheck Reusing Existing Downloads Check box + if (!$pfb['save'] && $pfb['enable'] == "on" && $pfb['reuse'] == "on") { + $config['installedpackages']['pfblockerng']['config'][0]['pfb_reuse'] = ""; + $pfb['cron_mod'] = TRUE; + } + + // Only save config.xml changes if changes are found. + // Temporay to ensure all conditions are defined before fully enabling this feature + if ($pfb['cron_mod'] || !$pfb['cron_mod']) { + write_config("pfBlockerNG: Save settings"); } } function pfblockerng_validate_input($post, &$input_errors) { global $config; + foreach ($post as $key => $value) { - if (empty($value)) - continue; - if ($key == "message_size_limit" && !is_numeric($value)) - $input_errors[] = "Message size limit must be numeric."; - if ($key == "process_limit" && !is_numeric($value)) - $input_errors[] = "Process limit must be numeric."; - if ($key == "freq" && (!preg_match("/^\d+(h|m|d)$/",$value) || $value == 0)) - $input_errors[] = "A valid number with a time reference is required for the field 'Frequency'"; - if (substr($key, 0, 2) == "dc" && !is_hostname($value)) - $input_errors[] = "{$value} is not a valid host name."; - if (substr($key, 0, 6) == "domain" && is_numeric(substr($key, 6))) { - if (!is_domain($value)) - $input_errors[] = "{$value} is not a valid domain name."; - } else if (substr($key, 0, 12) == "mailserverip" && is_numeric(substr($key, 12))) { - if (empty($post['domain' . substr($key, 12)])) - $input_errors[] = "Domain for {$value} cannot be blank."; - if (!is_ipaddr($value) && !is_hostname($value)) - $input_errors[] = "{$value} is not a valid IP address or host name."; + + if (substr($key, 0, 3) == "url" && is_numeric( substr($key, 3, (strlen($key) - 3))) ) { + if (empty($value)) { + $input_url_empty = TRUE; + continue; + } + if (substr($value, 0, 1) == ' ') { + $input_errors[] = "Leading whitespace not allowed in URL field"; + } + } + + if (substr($key, 0, 6) == "header" && is_numeric( substr($key, 6, (strlen($key) - 6))) ) { + if ($input_url_empty && empty($value)) { + $input_url_empty = FALSE; + continue; + } + if ($input_url_empty && !empty($value)) { + $input_errors[] = "No URL Defined."; + } + if (substr($value, 0, 1) == ' ' || empty($value)) { + $input_errors[] = "Header field must be defined."; + } } } } @@ -2423,7 +2730,8 @@ function pfblockerng_php_install_command() { @rmdir_recursive("{$pfb['dbdir']}/cc"); # Uncompress Country Code File - exec("/usr/bin/tar -jx -C {$pfb['ccdir']} -f {$pfb['dbdir']}/countrycodes.tar.bz2"); + @copy("{$pfb['dbdir']}/countrycodes.tar.bz2", "{$pfb['ccdir']}/countrycodes.tar.bz2"); + exec("/usr/bin/tar -jx -C {$pfb['ccdif']} -f {$pfb['ccdir']}/countrycodes.tar.bz2"); # Download MaxMind Files and Create Country Code files and Build Continent XML Files update_output_window(gettext("Downloading MaxMind Country Databases. This may take a minute...")); exec("/bin/sh /usr/local/pkg/pfblockerng/geoipupdate.sh all >> {$pfb['geolog']} 2>&1"); @@ -2525,7 +2833,6 @@ function pfblockerng_php_deinstall_command() { foreach ($widgetlist as $key => $widget) { if (strstr($widget, "pfblockerng-container")) { unset($widgetlist[$key]); - break; } } $config['widgets']['sequence'] = implode(",", $widgetlist); @@ -2540,9 +2847,9 @@ function pfblockerng_sync_on_changes() { // Create Array of Sync Settings and exit if Sync is Disabled. if (is_array($config['installedpackages']['pfblockerngsync']['config'][0])) { $pfb_sync = $config['installedpackages']['pfblockerngsync']['config'][0]; - if ($pfb_sync['varsynconchanges'] == "disabled" || $pfb_sync['varsynconchanges'] == "") + if ($pfb_sync['varsynconchanges'] == "disabled" || $pfb_sync['varsynconchanges'] == "") { return; - + } $synctimeout = $pfb_sync['varsynctimeout']; } else { return; @@ -2553,15 +2860,15 @@ function pfblockerng_sync_on_changes() { if (is_array($config['installedpackages']['pfblockerngsync']['config'])) { switch ($pfb_sync['varsynconchanges']) { case "manual": - if (is_array($pfb_sync[row])) { - $rs = $pfb_sync[row]; + if (is_array($pfb_sync['row'])) { + $rs = $pfb_sync['row']; } else { - log_error("[pfBlockerNG] XMLRPC sync is enabled but there are no replication targets configured."); + log_error("[pfBlockerNG] Manual XMLRPC sync is enabled but there are no replication targets configured."); return; } break; case "auto": - if (is_array($config['installedpackages']['carpsettings']) && is_array($config['installedpackages']['carpsettings']['config'])){ + if (is_array($config['installedpackages']['carpsettings']) && is_array($config['installedpackages']['carpsettings']['config'])) { $system_carp = $config['installedpackages']['carpsettings']['config'][0]; $rs[0]['varsyncipaddress'] = $system_carp['synchronizetoip']; $rs[0]['varsyncusername'] = $system_carp['username']; @@ -2575,11 +2882,11 @@ function pfblockerng_sync_on_changes() { } if ($system_carp['synchronizetoip'] == "") { - log_error("[pfBlockerNG] XMLRPC sync is enabled but there are no replication targets configured."); + log_error("[pfBlockerNG] XMLRPC sync is enabled but there is no sync IP address configured."); return; } } else { - log_error("[pfBlockerNG] XMLRPC sync is enabled but there are no replication targets configured."); + log_error("[pfBlockerNG] Auto XMLRPC sync is enabled but there are no replication targets configured."); return; } break; @@ -2605,8 +2912,9 @@ function pfblockerng_sync_on_changes() { pfblockerng_do_xmlrpc_sync($sync_to_ip, $port, $protocol, $username, $password, $synctimeout); } } - if ($success) + if ($success) { log_error("[pfBlockerNG] XMLRPC sync completed successfully."); + } } } } @@ -2639,9 +2947,9 @@ function pfblockerng_do_xmlrpc_sync($sync_to_ip, $port, $protocol, $username, $p } /* Test key variables and set defaults if empty */ - if (empty($synctimeout)) + if (empty($synctimeout)) { $synctimeout = 150; - + } $url = "{$protocol}://{$sync_to_ip}"; if ($port == "") { $port = $config['system']['webgui']['port']; }; @@ -2656,26 +2964,37 @@ function pfblockerng_do_xmlrpc_sync($sync_to_ip, $port, $protocol, $username, $p /* xml will hold the sections to sync */ $xml = array(); // If User Disabled, remove 'General Tab Customizations' from Sync - if ($config['installedpackages']['pfblockerngsync']['config'][0]['syncinterfaces'] == "") - $xml['pfblockerng'] = $config['installedpackages']['pfblockerng']; - $xml['pfblockerngreputation'] = $config['installedpackages']['pfblockerngreputation']; - $xml['pfblockernglistsv4'] = $config['installedpackages']['pfblockernglistsv4']; - $xml['pfblockernglistsv6'] = $config['installedpackages']['pfblockernglistsv6']; - $xml['pfblockerngtopspammers'] = $config['installedpackages']['pfblockerngtopspammers']; - $xml['pfblockerngafrica'] = $config['installedpackages']['pfblockerngafrica']; - $xml['pfblockerngantartica'] = $config['installedpackages']['pfblockerngantartica']; - $xml['pfblockerngasia'] = $config['installedpackages']['pfblockerngasia']; - $xml['pfblockerngeurope'] = $config['installedpackages']['pfblockerngeurope']; - $xml['pfblockerngnorthamerica'] = $config['installedpackages']['pfblockerngnorthamerica']; - $xml['pfblockerngoceania'] = $config['installedpackages']['pfblockerngoceania']; - $xml['pfblockerngsouthamerica'] = $config['installedpackages']['pfblockerngsouthamerica']; - $xml['pfblockerngproxyandsatellite'] = $config['installedpackages']['pfblockerngproxyandsatellite']; + if ($config['installedpackages']['pfblockerngsync']['config'][0]['syncinterfaces'] == "") { + if (is_array($config['installedpackages']['pfblockerng'])) + $xml['pfblockerng'] = $config['installedpackages']['pfblockerng']; + } + if (is_array($config['installedpackages']['pfblockerngreputation'])) + $xml['pfblockerngreputation'] = $config['installedpackages']['pfblockerngreputation']; + if (is_array($config['installedpackages']['pfblockernglistsv4'])) + $xml['pfblockernglistsv4'] = $config['installedpackages']['pfblockernglistsv4']; + if (is_array($config['installedpackages']['pfblockernglistsv6'])) + $xml['pfblockernglistsv6'] = $config['installedpackages']['pfblockernglistsv6']; + if (is_array($config['installedpackages']['pfblockerngtopspammers'])) + $xml['pfblockerngtopspammers'] = $config['installedpackages']['pfblockerngtopspammers']; + if (is_array($config['installedpackages']['pfblockerngafrica'])) + $xml['pfblockerngafrica'] = $config['installedpackages']['pfblockerngafrica']; + if (is_array($config['installedpackages']['pfblockerngantartica'])) + $xml['pfblockerngantartica'] = $config['installedpackages']['pfblockerngantartica']; + if (is_array($config['installedpackages']['pfblockerngasia'])) + $xml['pfblockerngasia'] = $config['installedpackages']['pfblockerngasia']; + if (is_array($config['installedpackages']['pfblockerngeurope'])) + $xml['pfblockerngeurope'] = $config['installedpackages']['pfblockerngeurope']; + if (is_array($config['installedpackages']['pfblockerngnorthamerica'])) + $xml['pfblockerngnorthamerica'] = $config['installedpackages']['pfblockerngnorthamerica']; + if (is_array($config['installedpackages']['pfblockerngoceania'])) + $xml['pfblockerngoceania'] = $config['installedpackages']['pfblockerngoceania']; + if (is_array($config['installedpackages']['pfblockerngsouthamerica'])) + $xml['pfblockerngsouthamerica'] = $config['installedpackages']['pfblockerngsouthamerica']; + if (is_array($config['installedpackages']['pfblockerngproxyandsatellite'])) + $xml['pfblockerngproxyandsatellite'] = $config['installedpackages']['pfblockerngproxyandsatellite']; /* assemble xmlrpc payload */ - $params = array( - XML_RPC_encode($password), - XML_RPC_encode($xml) - ); + $params = array(XML_RPC_encode($password), XML_RPC_encode($xml)); /* set a few variables needed for sync code borrowed from filter.inc */ log_error("[pfBlockerNG] XMLRPC syncing to {$url}:{$port}."); @@ -2707,4 +3026,4 @@ function pfblockerng_do_xmlrpc_sync($sync_to_ip, $port, $protocol, $username, $p } return $success; } -?> +?> \ No newline at end of file diff --git a/config/pfblockerng/pfblockerng.php b/config/pfblockerng/pfblockerng.php index 8c0c478d..194f4071 100644 --- a/config/pfblockerng/pfblockerng.php +++ b/config/pfblockerng/pfblockerng.php @@ -148,8 +148,9 @@ function ip_range_to_subnet_array_temp($ip1, $ip2) { # Set php Memory Limit $uname = posix_uname(); -if ($uname['machine'] == "amd64") +if ($uname['machine'] == "amd64") { ini_set('memory_limit', '256M'); +} function pfb_update_check($header_url, $list_url, $url_format, $pfbfolder) { global $pfb; @@ -220,7 +221,6 @@ function pfb_update_check($header_url, $list_url, $url_format, $pfbfolder) { } } - if ($argv[1] == 'update') { sync_package_pfblockerng("cron"); } @@ -251,85 +251,13 @@ if ($argv[1] == 'gc') { } if ($argv[1] == 'cron') { + + // Call Base Hour converter + $pfb_sch = pfb_cron_base_hour(); + $hour = date('G'); $dow = date('N'); $pfb['update_cron'] = FALSE; - - # Start hour of the 'Once a day' Schedule - $pfb['dailystart'] = $config['installedpackages']['pfblockerng']['config'][0]['pfb_dailystart']; - # Start hour of the Scheduler - if ($config['installedpackages']['pfblockerng']['config'][0]['pfb_hour'] != "") { - $pfb['hour'] = $config['installedpackages']['pfblockerng']['config'][0]['pfb_hour']; - } else { - $pfb['hour'] = "1"; - } - $updates = 0; - - # 2 Hour Schedule Converter - $shour = intval(substr($pfb['hour'], 0, 2)); - $sch2 = strval($shour); - for ($i=0; $i<11; $i++) { - $shour += 2; - if ($shour >= 24) - $shour -= 24; - $sch2 .= "," . strval($shour); - } - - # 3 Hour Schedule Converter - $shour = intval(substr($pfb['hour'], 0, 2)); - $sch3 = strval($shour); - for ($i=0; $i<7; $i++) { - $shour += 3; - if ($shour >= 24) - $shour -= 24; - $sch3 .= "," . strval($shour); - } - - # 4 Hour Schedule Converter - $shour = intval(substr($pfb['hour'], 0, 2)); - $sch4 = strval($shour); - for ($i=0; $i<5; $i++) { - $shour += 4; - if ($shour >= 24) - $shour -= 24; - $sch4 .= "," . strval($shour); - } - - # 6 Hour Schedule Converter - $shour = intval(substr($pfb['hour'], 0, 2)); - $sch6 = strval($shour); - for ($i=0; $i<3; $i++) { - $shour += 6; - if ($shour >= 24) - $shour -= 24; - $sch6 .= "," . strval($shour); - } - - # 8 Hour Schedule Converter - $shour = intval(substr($pfb['hour'], 0, 2)); - $sch8 = strval($shour); - for ($i=0; $i<2; $i++) { - $shour += 8; - if ($shour >= 24) - $shour -= 24; - $sch8 .= "," . strval($shour); - } - - # 12 Hour Schedule Converter - $shour = intval(substr($pfb['hour'], 0, 2)); - $sch12 = strval($shour) . ","; - $shour += 12; - if ($shour >= 24) - $shour -= 24; - $sch12 .= strval($shour); - - $e_sch2 = explode(",", $sch2); - $e_sch3 = explode(",", $sch3); - $e_sch4 = explode(",", $sch4); - $e_sch6 = explode(",", $sch6); - $e_sch8 = explode(",", $sch8); - $e_sch12 = explode(",", $sch12); - $log = " CRON PROCESS START [ NOW ]\n"; pfb_logger("{$log}","1"); @@ -348,7 +276,7 @@ if ($argv[1] == 'cron') { } # Determine Folder Location for Alias (return array $pfbarr) - pfb_determine_list_detail($list['action']); + pfb_determine_list_detail($list['action'], "", "", ""); $pfbfolder = $pfbarr['folder']; $list_cron = $list['cron']; @@ -370,42 +298,20 @@ if ($argv[1] == 'cron') { } switch ($list_cron) { - case "01hour": - pfb_update_check($header_url, $list_url, $url_format, $pfbfolder); - break; - case "02hours": - if (in_array($hour, $e_sch2)) - pfb_update_check($header_url, $list_url, $url_format, $pfbfolder); - break; - case "03hours": - if (in_array($hour, $e_sch3)) - pfb_update_check($header_url, $list_url, $url_format, $pfbfolder); - break; - case "04hours": - if (in_array($hour, $e_sch4)) - pfb_update_check($header_url, $list_url, $url_format, $pfbfolder); - break; - case "06hours": - if (in_array($hour, $e_sch6)) - pfb_update_check($header_url, $list_url, $url_format, $pfbfolder); - break; - case "08hours": - if (in_array($hour, $e_sch8)) - pfb_update_check($header_url, $list_url, $url_format, $pfbfolder); - break; - case "12hours": - if (in_array($hour, $e_sch12)) - pfb_update_check($header_url, $list_url, $url_format, $pfbfolder); - break; case "EveryDay": - if ($hour == $pfb['dailystart']) + if ($hour == $pfb['24hour']) { pfb_update_check($header_url, $list_url, $url_format, $pfbfolder); + } break; case "Weekly": - if ($hour == $pfb['dailystart'] && $dow == $header_dow) + if ($hour == $pfb['24hour'] && $dow == $header_dow) { pfb_update_check($header_url, $list_url, $url_format, $pfbfolder); + } break; default: + if ($pfb['interval'] == "1" || in_array($hour, $pfb_sch)) { + pfb_update_check($header_url, $list_url, $url_format, $pfbfolder); + } break; } } @@ -415,6 +321,30 @@ if ($argv[1] == 'cron') { } } + // If Continents are Defined, continue with Update Process to determine if further changes are required. + $continents = array ( "Africa" => "pfB_Africa", + "Antartica" => "pfB_Antartica", + "Asia" => "pfB_Asia", + "Europe" => "pfB_Europe", + "North America" => "pfB_NAmerica", + "Oceania" => "pfB_Oceania", + "South America" => "pfB_SAmerica", + "Top Spammers" => "pfB_Top", + "Proxy and Satellite" => "pfB_PS" + ); + + if (!$pfb['update_cron']) { + foreach ($continents as $continent => $pfb_alias) { + if (is_array($config['installedpackages']['pfblockerng' . strtolower(preg_replace('/ /','',$continent))]['config'])) { + $continent_config = $config['installedpackages']['pfblockerng' . strtolower(preg_replace('/ /','',$continent))]['config'][0]; + if ($continent_config['action'] != "Disabled" && $pfb['enable'] == "on") { + $pfb['update_cron'] = TRUE; + break; + } + } + } + } + if ($pfb['update_cron']) { sync_package_pfblockerng("cron"); } else { @@ -824,44 +754,57 @@ $xml = << LINKS - - Firewall Alias     Firewall Rules     Firewall Logs]]> + Firewall Alias     + Firewall Rules     Firewall Logs]]> info - - IPv4
Countries]]>
+ countries4 - - - Use CTRL + CLICK to unselect countries]]> - +
Countries

+
Use CTRL + CLICK to unselect countries
]]> +
select ${'options4'} ${'ftotal4'} + +EOF; + +// Adjust combinefields variable if IPv6 is empty. +if (!empty (${'options6'})) { + $xml .= <<
IPv4 Countries]]> + + begin
EOF; +} else { + $xml .= <<IPv4 Countries]]> +
+ +EOF; +} // Skip IPv6 when Null data found if (!empty (${'options6'})) { $xml .= << - IPv6
Countries]]>
countries6 - - - Use CTRL + CLICK to unselect countries]]> - +
IPv6 Countries
]]>
select ${'options6'} ${'ftotal6'} + + + end EOF; @@ -870,7 +813,7 @@ EOF; $xml .= << List Action - Default : Disabled

+ Default: Disabled

Select the Action for Firewall Rules on lists you have selected.

'Disabled' Rules: Disables selection and does nothing to selected Alias.

@@ -901,7 +844,7 @@ $xml .= <<'Alias Permit' and 'Alias Match' will be saved in the Same folder as the other Permit/Match Auto-Rules
  • 'Alias Native' lists are kept in their Native format without any modifications.
  • When using 'Alias' rules, change (pfB_) to ( pfb_ ) in the beginning of rule description and use the 'Exact' spelling of - the Alias (no trailing Whitespace)  Custom 'Alias' rules with 'pfB_ xxx' description will be removed by package if + the Alias (no trailing Whitespace) Custom 'Alias' rules with 'pfB_ xxx' description will be removed by package if using Auto Rule Creation.

    Tip: You can create the Auto Rules and remove "auto rule" from the Rule Descriptions, then disable Auto Rules. This method will 'KEEP' these rules from being 'Deleted' which will allow editing for a Custom Alias Configuration
    ]]> @@ -928,9 +871,10 @@ $xml .= << Enable Logging aliaslog - Enable
    + Enable
    Select - Logging to Status: System Logs: FIREWALL ( Log )
    - This can be overriden by the 'Global Logging' Option in the General Tab.]]>
    + This can be overriden by the 'Global Logging' Option in the General Tab.]]> +
    select @@ -938,9 +882,87 @@ $xml .= << - Click to SAVE Settings and/or Rule Edits.      Changes are Applied via CRON or - 'Force Update']]> - + Advanced Inbound Firewall Rule Settings + listtopic + + + info + Note: In general Auto-Rules are created as follows:
    +
      Inbound   - 'any' port, 'any' protocol and 'any' destination
      + Outbound - 'any' port, 'any' protocol and 'any' destination address in the lists
    + Configuring the Adv. Inbound Rule settings, will allow for more customization of the Inbound Auto-Rules.
    + Select the pfSense 'Port' and/or 'Destination' Alias below:]]> +
    +
    + + autoports + Enable Custom Port + checkbox + aliasports + + begin + + + Define Alias + aliasports + Click Here to add/edit Aliases + Do not manually enter port numbers.
    Do not use 'pfB_' in the Port Alias name.]]> +
    + 21 + aliases + port + + + end +
    + + autodest + Enable Custom Destination + checkbox + aliasdest,autonot + + begin + + + aliasdest + Click Here to add/edit Aliases + Do not manually enter Addresses(es).
    Do not use 'pfB_' in the 'IP Network Type' Alias name.]]> +
    + 21 + aliases + network + + + +
    + + Invert + autonot + Invert - Option to invert the sense of the match.
    + ie - Not (!) Destination Address(es)]]> +
    + checkbox + + + end +
    + + Custom Protocol + autoproto + Default: any
    Select the Protocol used for Inbound Firewall Rule(s).]]>
    + select + + + + + + + 4 + +
    + + Click to SAVE Settings and/or Rule Edits.       Changes are Applied via CRON or + 'Force Update']]> listtopic @@ -1122,14 +1144,13 @@ $xmlrep = << LINKS - - Firewall Alias     Firewall Rules     Firewall Logs]]> + Firewall Alias     + Firewall Rules     Firewall Logs]]> info Why Reputation Matters:]]> - info Reputation', each Blocklist will be analyzed for Repeat Offenders in each IP Range.
      Example:    x.x.x.1, x.x.x.2, x.x.x.3, x.x.x.4, x.x.x.5
      @@ -1150,7 +1171,6 @@ $xmlrep = <<listtopic - Individual List Reputation

      ]]>
      info @@ -1177,13 +1197,11 @@ $xmlrep = <<
      - Collective List Reputation

      ]]>
      info
      - info [ pMax ] and [ dMax ]
      Can be used to Further analyze for Repeat Offenders.
      @@ -1244,7 +1262,6 @@ $xmlrep = <<listtopic
      - INFO info ignore Repeat Offenders in select Countries. The Original Blocklisted IPs remain intact. All other Repeat Offending Country Ranges will be processed.

      @@ -1286,7 +1303,7 @@ $xmlrep = << IPv4
      Country Exclusion
      -
      Geolite Data by:
      MaxMind Inc.  (ISO 3166)]]>
      +
      Geolite Data by:
      MaxMind Inc.  (ISO 3166)]]> ccexclude Exclude from the Reputation Process.
      @@ -1305,7 +1322,6 @@ $xmlrep = << Subscription Pro. Blocklist - ETINFO info Emerging Threats IQRisk is a Subscription Professional Reputation List.

      ET IQRisk Blocklist must be entered in the Lists Tab using the following example: @@ -1429,7 +1445,7 @@ $xmlrep = << Update ET Categories et_update - Disable
      + Disable
      Select - Enable ET Update if Category Changes are Made.
      You can perform a 'Force Update' to enable these changes.
      Cron will also resync this list at the next Scheduled Update.]]> @@ -1441,8 +1457,8 @@ $xmlrep = <<
      - Click to SAVE Settings and/or Rule Edits.       Changes are Applied via CRON or - 'Force Update'
    ]]> + Click to SAVE Settings and/or Rule Edits.       Changes are Applied via CRON or + 'Force Update']]> listtopic
    diff --git a/config/pfblockerng/pfblockerng.priv.inc b/config/pfblockerng/pfblockerng.priv.inc index 970ab25f..97cf6288 100644 --- a/config/pfblockerng/pfblockerng.priv.inc +++ b/config/pfblockerng/pfblockerng.priv.inc @@ -8,8 +8,6 @@ $priv_list['page-firewall-pfblockerng']['descr'] = "Allow access to pfBlockerNG $priv_list['page-firewall-pfblockerng']['match'] = array(); $priv_list['page-firewall-pfblockerng']['match'][] = "pkg_edit.php?xml=pfblockerng.xml*"; $priv_list['page-firewall-pfblockerng']['match'][] = "pkg_edit.php?xml=pfblockerng/pfblockerng_reputation.xml*"; -$priv_list['page-firewall-pfblockerng']['match'][] = "pkg_edit.php?xml=pfblockerng/pfblockerng_v4lists.xml*"; -$priv_list['page-firewall-pfblockerng']['match'][] = "pkg_edit.php?xml=pfblockerng/pfblockerng_v6lists.xml*"; $priv_list['page-firewall-pfblockerng']['match'][] = "pkg_edit.php?xml=pfblockerng/pfblockerng_top20.xml*"; $priv_list['page-firewall-pfblockerng']['match'][] = "pkg_edit.php?xml=pfblockerng/pfblockerng_Africa.xml*"; $priv_list['page-firewall-pfblockerng']['match'][] = "pkg_edit.php?xml=pfblockerng/pfblockerng_Asia.xml*"; @@ -19,6 +17,10 @@ $priv_list['page-firewall-pfblockerng']['match'][] = "pkg_edit.php?xml=pfblocker $priv_list['page-firewall-pfblockerng']['match'][] = "pkg_edit.php?xml=pfblockerng/pfblockerng_SouthAmerica.xml*"; $priv_list['page-firewall-pfblockerng']['match'][] = "pkg_edit.php?xml=pfblockerng/pfblockerng_ProxyandSatellite.xml*"; $priv_list['page-firewall-pfblockerng']['match'][] = "pkg_edit.php?xml=pfblockerng/pfblockerng_sync.xml*"; + +$priv_list['page-firewall-pfblockerng']['match'][] = "pkg.php?xml=pfblockerng/pfblockerng_v4lists.xml*"; +$priv_list['page-firewall-pfblockerng']['match'][] = "pkg.php?xml=pfblockerng/pfblockerng_v6lists.xml*"; + $priv_list['page-firewall-pfblockerng']['match'][] = "pfblockerng/pfblockerng_update.php*"; $priv_list['page-firewall-pfblockerng']['match'][] = "pfblockerng/pfblockerng_alerts.php*"; $priv_list['page-firewall-pfblockerng']['match'][] = "pfblockerng/pfblockerng_log.php*"; diff --git a/config/pfblockerng/pfblockerng.sh b/config/pfblockerng/pfblockerng.sh index ba0c908b..9754d73c 100644 --- a/config/pfblockerng/pfblockerng.sh +++ b/config/pfblockerng/pfblockerng.sh @@ -24,7 +24,7 @@ fi now=$(/bin/date +%m/%d/%y' '%T) -# Application Paths +# Application Locations pathgrepcidr="${prefix}/bin/grepcidr" pathgeoip="${prefix}/bin/geoiplookup" @@ -165,7 +165,7 @@ fi if [ -s "$matchfile" -a ! "$dedup" == "on" -a "$ccwhite" == "match" ]; then mon=$(sed -e 's/^/^/' -e 's/\./\\\./g' $matchfile) for ip in $mon; do - grep $ip $tempfile >> $tempfile2 + grep $ip $tempfile >> $tempfile2 done mcount=$(grep -c ^ $tempfile2) if [ "$ccwhite" == "match" ]; then @@ -372,7 +372,7 @@ if [ -e "$pfbsuppression" ] && [ -s "$pfbsuppression" ]; then fi else if [ "$cc" == "suppressheader" ]; then - echo "===[ Suppression Stats ]========================================"; echo + echo; echo "===[ Suppression Stats ]========================================"; echo printf "%-20s %-10s %-10s %-10s %-10s\n" "List" "Pre" "RFC1918" "Suppress" "Masterfile" echo "----------------------------------------------------------------" exitnow @@ -675,7 +675,6 @@ if [ -s $pfborig$alias".gz" ]; then $pathgunzip -c $pfborig$alias".gz" > $pfborig$alias".raw" # ET CSV Format (IP, Category, Score) - echo; echo "Processing [ $alias ]" while IFS="," read a b c; do # Some ET Categories are not in use (For Future Use) case "$b" in @@ -795,7 +794,7 @@ if [ "$alias" == "on" ]; then sort -o $masterfile $masterfile sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n $mastercat > $tempfile; mv -f $tempfile $mastercat - echo; echo; echo "===[ FINAL Processing ]====================================="; echo + echo; echo "===[ FINAL Processing ]====================================="; echo echo " [ Original count ] [ $fcount ]" count=$(grep -c ^ $masterfile) echo; echo " [ Processed Count ] [ $count ]"; echo @@ -976,4 +975,4 @@ case $1 in exitnow ;; esac -exitnow +exitnow \ No newline at end of file diff --git a/config/pfblockerng/pfblockerng.widget.php b/config/pfblockerng/pfblockerng.widget.php index 229e084b..c9522cd7 100644 --- a/config/pfblockerng/pfblockerng.widget.php +++ b/config/pfblockerng/pfblockerng.widget.php @@ -15,7 +15,7 @@ snort_alerts.widget.php Copyright (C) 2009 Jim Pingle mod 24-07-2012 - mod 28-02-2014 by Bill Meeks + mod 28-02-2015 by Bill Meeks Javascript and Integration modifications by J. Nieuwenhuizen @@ -42,58 +42,268 @@ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - +$nocsrf = true; @require_once("/usr/local/www/widgets/include/widget-pfblockerng.inc"); @require_once("/usr/local/pkg/pfblockerng/pfblockerng.inc"); @require_once("guiconfig.inc"); -@require_once("globals.inc"); -@require_once("pfsense-utils.inc"); -@require_once("functions.inc"); pfb_global(); -// Ackwnowlege Failed Downloads +// Image source definition +$pfb['down'] = ""; +$pfb['up'] = ""; +$pfb['err'] = ""; + +// Alternating line shading +$pfb['RowOddClass'] = "style='background-color: #FFFFFF;'"; +$pfb['RowEvenClass'] = "style='background-color: #F0F0F0;'"; +$pfb['RowEvenClass2'] = "style='background-color: #D0D0D0;'"; +$pfb['ColClass'] = "listMRr"; + +$pfb['global'] = &$config['installedpackages']['pfblockerngglobal']; + +// Define default widget customizations +if (!isset($pfb['global']['widget-maxfails'])) { + $pfb['global']['widget-maxfails'] = '3'; +} +if (!isset($pfb['global']['widget-maxpivot'])) { + $pfb['global']['widget-maxpivot'] = '200'; +} +if (!isset($pfb['global']['widget-sortcolumn'])) { + $pfb['global']['widget-sortcolumn'] = 'none'; +} +if (!isset($pfb['global']['widget-sortdir'])) { + $pfb['global']['widget-sortdir'] = 'asc'; +} +if (!isset($pfb['global']['widget-popup'])) { + $pfb['global']['widget-popup'] = 'on'; +} + +// Collect variables +if (is_array($pfb['global'])) { + $pfb['maxfails'] = $pfb['global']['widget-maxfails']; + $pfb['maxpivot'] = $pfb['global']['widget-maxpivot']; + $pfb['sortcolumn'] = $pfb['global']['widget-sortcolumn']; + $pfb['sortdir'] = $pfb['global']['widget-sortdir']; + $pfb['popup'] = $pfb['global']['widget-popup']; +} + +// Save widget customizations +if ($_POST) { + if (is_numeric($_POST['pfb_maxfails'])) { + $pfb['global']['widget-maxfails'] = $_POST['pfb_maxfails']; + } + if (is_numeric($_POST['pfb_maxpivot'])) { + $pfb['global']['widget-maxpivot'] = $_POST['pfb_maxpivot']; + } + if (!empty($_POST['pfb_popup'])) { + $pfb['global']['widget-popup'] = $_POST['pfb_popup']; + } + if (!empty($_POST['pfb_sortcolumn'])) { + $pfb['global']['widget-sortcolumn'] = $_POST['pfb_sortcolumn']; + } + if (!empty($_POST['pfb_sortdir'])) { + $pfb['global']['widget-sortdir'] = $_POST['pfb_sortdir']; + } + write_config("pfBlockerNG: Saved Widget customizations via Dashboard"); + header("Location: ../../index.php"); +} + +// Ackwnowlege failed downloads if (isset($_POST['pfblockerngack'])) { - $clear = exec("/usr/bin/sed -i '' 's/FAIL/Fail/g' {$pfb['errlog']}"); + exec("/usr/bin/sed -i '' 's/FAIL/Fail/g' {$pfb['errlog']}"); header("Location: ../../index.php"); } -// This function will create the counts -function pfBlockerNG_get_counts() { - global $config, $g, $pfb; +// Called by Ajax to update table contents +if (isset($_GET['getNewCounts'])) { + pfBlockerNG_get_table("js"); + return; +} - // Collect Alias Count and Update Date/Time +// Sort widget table according to user configuration +function pfbsort(&$array, $subkey="id", $sort_ascending=FALSE) { + if (empty($array)) { + return; + } + if (count($array)) { + $temp_array[key($array)] = array_shift($array); + } + + foreach ($array as $key => $val) { + $offset = 0; + $found = FALSE; + foreach ($temp_array as $tmp_key => $tmp_val) { + if (!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey])) { + $temp_array = array_merge((array)array_slice($temp_array,0,$offset), array($key => $val), array_slice($temp_array,$offset)); + $found = TRUE; + } + $offset++; + } + if (!$found) { + $temp_array = array_merge($temp_array, array($key => $val)); + } + } + + if ($sort_ascending) { + $array = array_reverse($temp_array); + } else { + $array = $temp_array; + } + return; +} + +// Collect all pfBlockerNG statistics +function pfBlockerNG_get_counts() { + global $config, $pfb; $pfb_table = array(); - $out = "\"\""; - $in = "\"\""; - if (is_array($config['aliases']['alias'])) { - foreach ($config['aliases']['alias'] as $cbalias) { - if (preg_match("/pfB_/", $cbalias['name'])) { - if (file_exists("{$pfb['aliasdir']}/{$cbalias['name']}.txt")) { - preg_match("/(\d+)/", exec("/usr/bin/grep -cv \"^1\.1\.1\.1\" {$pfb['aliasdir']}/{$cbalias['name']}.txt"), $matches); - $pfb_table[$cbalias['name']] = array("count" => $matches[1], "img" => $out); - $updates = exec("ls -ld {$pfb['aliasdir']}/{$cbalias['name']}.txt | awk '{ print $6,$7,$8 }'", $update); - $pfb_table[$cbalias['name']]['up'] = $updates; + + /* Alias Table Definitions - 'update' - Last Updated Timestamp + 'rule' - Total number of Firewall rules per alias + 'count' - Total Line Count per alias + 'packets' - Total number of pf packets per alias */ + + exec("/sbin/pfctl -vvsTables | grep -A4 'pfB_'", $pfb_pfctl); + if (!empty($pfb_pfctl)) { + foreach($pfb_pfctl as $line) { + $line = trim(str_replace(array( '[', ']' ), '', $line)); + if (substr($line, 0, 1) == '-') { + $pfb_alias = trim(strstr($line, 'pfB', FALSE)); + if (empty($pfb_alias)) { + unset($pfb_alias); + continue; + } + exec("/usr/bin/grep -cv '^1\.1\.1\.1' {$pfb['aliasdir']}/{$pfb_alias}.txt", $match); + $pfb_table[$pfb_alias] = array('count' => $match[1], 'img' => $pfb['down']); + exec("ls -ld {$pfb['aliasdir']}/{$pfb_alias}.txt | awk '{ print $6,$7,$8 }'", $update); + $pfb_table[$pfb_alias]['update'] = $update[0]; + $pfb_table[$pfb_alias]['rule'] = 0; + unset($match, $update); + continue; + } + + if (isset($pfb_alias)) { + if (substr($line, 0, 9) == 'Addresses') { + $addr = trim(substr(strrchr($line, ':'), 1)); + $pfb_table[$pfb_alias]['count'] = $addr; + continue; + } + if (substr($line, 0, 11) == 'Evaluations') { + $packets = trim(substr(strrchr($line, ':'), 1)); + $pfb_table[$pfb_alias]['packets'] = $packets; + unset($pfb_alias); } } } } + else { + // Error. No pf labels found. + $pfb['pfctl'] = TRUE; + } - // Collect if Rules are defined using pfBlockerNG Aliases. + // Determine if firewall rules are defined if (is_array($config['filter']['rule'])) { foreach ($config['filter']['rule'] as $rule) { - if (preg_match("/pfB_/",$rule['source']['address']) || preg_match("/pfb_/",$rule['source']['address'])) { - $pfb_table[$rule['source']['address']]['img'] = $in; + // Skip disabled rules + if (isset($rule['disabled'])) { + continue; + } + if (stripos($rule['source']['address'], "pfb_") !== FALSE) { + $pfb_table[$rule['source']['address']]['img'] = $pfb['up']; + $pfb_table[$rule['source']['address']]['rule'] += 1; } - if (preg_match("/pfB_/",$rule['destination']['address']) || preg_match("/pfb_/",$rule['destination']['address'])) { - $pfb_table[$rule['destination']['address']]['img'] = $in; + if (stripos($rule['destination']['address'], "pfb_") !== FALSE) { + $pfb_table[$rule['destination']['address']]['img'] = $pfb['up']; + $pfb_table[$rule['destination']['address']]['rule'] += 1; } } - return $pfb_table; } + + // Collect packet fence rule numbers + exec("/sbin/pfctl -vv -sr | grep 'pfB_'", $pfrules); + if (!empty($pfrules)) { + foreach ($pfrules as $result) { + // Sample : @112(0) block return in log quick on em1 from any to label "USER_RULE: pfB_PRI1" + if (preg_match("/@(\d+)\(\d+\).*\<(pfB_\w+):\d+\>/", $result, $rule)) { + $pfb_table[$rule[2]]['rules'] .= $rule[1] . '|'; + } + } + } + + // Sort tables per sort customization + if ($pfb['sortcolumn'] != "none") { + if ($pfb['sortdir'] == "asc") { + pfbsort($pfb_table, $pfb['sortcolumn'], TRUE); + } else { + pfbsort($pfb_table, $pfb['sortcolumn'], FALSE); + } + } + return $pfb_table; } -// Status Indicator if pfBlockerNG is Enabled/Disabled +// Called on initial load and Ajax to update table contents +function pfBlockerNG_get_table($mode="") { + global $pfb; + $counter = 0; $dcounter = 1; $response = ''; + + $pfb_table = pfBlockerNG_get_counts(); + if (!empty($pfb_table)) { + foreach ($pfb_table as $pfb_alias => $values) { + // Add firewall rules count associated with alias + $values['img'] = $values['img'] . "({$values['rule']})"; + + // If packet fence errors found, display error. + if ($pfb['pfctl']) { + $values['img'] = $pfb['err']; + } + + // Alias table popup + if ($values['count'] > 0 && $pfb['popup'] == "on") { + $alias_popup = rule_popup($pfb_alias, '', '', ''); + $alias_span = $alias_popup['src']; + $alias_span_end = $alias_popup['src_end']; + } + else { + $alias_span = ''; + $alias_span_end = ''; + } + + // Packet column pivot to Alerts Tab + if ($values['packets'] > 0) { + $rules = rtrim($values['rules'], '|'); + if ($values['packets'] > $pfb['maxpivot']) { + $aentries = $pfb['maxpivot']; + } else { + $aentries = $values['packets']; + } + + $packets = " + " . $alias_span . $pfb_alias . $alias_span_end . " + {$values['count']} + {$packets} + {$values['update']} + {$values['img']} + "); + } + } + } +} + +// Status indicator if pfBlockerNG is enabled/disabled if ("{$pfb['enable']}" == "on") { $pfb_status = "/themes/{$g['theme']}/images/icons/icon_pass.gif"; $pfb_msg = "pfBlockerNG is Active."; @@ -102,70 +312,78 @@ if ("{$pfb['enable']}" == "on") { $pfb_msg = "pfBlockerNG is Disabled."; } -// Collect Total IP/Cidr Counts +// Collect total IP/Cidr counts $dcount = exec("cat {$pfb['denydir']}/*.txt | grep -cv '^#\|^$\|^1\.1\.1\.1'"); $pcount = exec("cat {$pfb['permitdir']}/*.txt | grep -cv '^#\|^$\|^1\.1\.1\.1'"); $mcount = exec("cat {$pfb['matchdir']}/*.txt | grep -cv '^#\|^$\|^1\.1\.1\.1'"); $ncount = exec("cat {$pfb['nativedir']}/*.txt | grep -cv '^#\|^$\|^1\.1\.1\.1'"); -// Collect Number of Suppressed Hosts +// Collect number of suppressed hosts if (file_exists("{$pfb['supptxt']}")) { $pfbsupp_cnt = exec ("/usr/bin/grep -c ^ {$pfb['supptxt']}"); } else { $pfbsupp_cnt = 0; } -#check rule count -#(label, evaluations,packets total, bytes total, packets in, bytes in,packets out, bytes out) -$packets = exec("/sbin/pfctl -s labels", $debug); -if (!empty($debug)) { - foreach ($debug as $line) { - // Auto-Rules start with 'pfB_', Alias Rules should start with 'pfb_' and exact spelling of Alias Name. - $line = str_replace("pfb_","pfB_",$line); - if ("{$pfb['pfsenseversion']}" >= '2.2') { - #USER_RULE: pfB_Top auto rule 8494 17 900 17 900 0 0 0 - if (preg_match("/USER_RULE: (\w+).*\s+\d+\s+(\d+)\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+/", $line, $matches)) { - if (isset($matches)) { - ${$matches[1]}+=$matches[2]; - } else { - ${$matches[1]} = 'Err'; - } - } - } else { - #USER_RULE: pfB_Top auto rule 1656 0 0 0 0 0 0 - if (preg_match("/USER_RULE: (\w+).*\s+\d+\s+(\d+)\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+/", $line, $matches)) { - if (isset($matches)) { - ${$matches[1]}+=$matches[2]; - } else { - ${$matches[1]} = 'Err'; - } - } - } - } -} +// Collect any failed downloads +exec("grep $(date +%m/%d/%y) {$pfb['errlog']} | grep 'FAIL'", $results); +$results = array_reverse($results); -// Called by Ajax to update alerts table contents -if (isset($_GET['getNewCounts'])) { - $response = ""; - $pfb_table = pfBlockerNG_get_counts(); - if (!empty($pfb_table)) { - foreach ($pfb_table as $alias => $values){ - if (!isset(${$alias})) { ${$alias} = "-";} - $response .= $alias . "||" . $values['count'] . "||" . ${$alias} . "||" . $values['up'] . "||" . $values['img'] . "\n"; - } - echo $response; - return; - } -} +?> + + + -// Print widget Status Bar Items -?> +
    - +
    @@ -187,12 +405,14 @@ $fails = exec("grep $(date +%m/%d/%y) {$pfb['errlog']} | grep 'FAIL'", $results) " . $pfbsupp_cnt . ""); ?> - @@ -205,76 +425,53 @@ $fails = exec("grep $(date +%m/%d/%y) {$pfb['errlog']} | grep 'FAIL'", $results) '2.0') { - $alertRowEvenClass = "listMReven"; - $alertRowOddClass = "listMRodd"; - $alertColClass = "listMRr"; -} else { - $alertRowEvenClass = "listr"; - $alertRowOddClass = "listr"; - $alertColClass = "listr"; -} - -# Last errors first -$results = array_reverse($results); - +// Report any failed downloads $counter = 0; -# Max errors to display -$maxfailcount = 3; if (!empty($results)) { foreach ($results as $result) { - $alertRowClass = $counter % 2 ? $alertRowEvenClass : $alertRowOddClass; - if (!isset(${$alias})) { ${$alias} = "-";} - echo(" "); + $RowClass = $counter % 2 ? $pfb['RowEvenClass'] : $pfb['RowOddClass']; + echo(" "); $counter++; - if ($counter > $maxfailcount) { - # To many errors stop displaying - echo(" "); + if ($counter > $pfb['maxfails']) { + // To many errors stop displaying + echo(" "); break; } } } -// Print Main Table Header ?> +
        " alt="" />  + " alt="" /> 
    - "/> + "/>
    " . $result . "
    " . $result . "
    " . (count($results) - $maxfailcount) . " more error(s)...
    " . (count($results) - $pfb['maxfails']) . " more error(s)...
    - +
    - - - - - - + + + + + + - $values) { - $evenRowClass = $counter % 2 ? " listMReven" : " listMRodd"; - if (!isset(${$alias})) { ${$alias} = "-";} - echo(" - - - - - - "); - $counter++; - } -} -?> + + +
    {$alias}{$values['count']}{${$alias}}{$values['up']}{$values['img']}
    \ No newline at end of file diff --git a/config/pfblockerng/pfblockerng.xml b/config/pfblockerng/pfblockerng.xml index 67deab8d..c8e07b21 100644 --- a/config/pfblockerng/pfblockerng.xml +++ b/config/pfblockerng/pfblockerng.xml @@ -49,7 +49,7 @@ Describe your package requirements here Currently there are no FAQ items provided. pfblockerng - 1.08 + 1.09 pfBlockerNG: General Settings /usr/local/pkg/pfblockerng/pfblockerng.inc
    @@ -219,45 +219,83 @@ LINKS - Firewall Alias     Firewall Rules     Firewall Logs]]> + Firewall Alias     + Firewall Rules     Firewall Logs]]> + info - Enable pfBlockerNG]]> + Enable pfBlockerNG enable_cb checkbox - - If "Keep Settings" is not "enabled" on pkg Install/De-Install, all Settings will be Wiped!]]> + Enable/Disable
    ]]>
    + + begin - Keep Settings/Lists After Disable/Re-Install/De-Install]]> pfb_keep checkbox - Keep Settings and Lists intact when pfBlockerNG is Disabled or After pfBlockerNG Re-Install/De-Install + Note: - with 'Keep settings' enabled, pfBlockerNG will maintain run state + on Installation/Upgrade
    If 'Keep Settings' is not 'enabled' on pkg Install/De-Install, all Settings will be Wiped!

    + Note: To clear all downloaded lists, uncheck these two checkboxes and 'Save'. + re-check both boxes and run a 'Force Update']]> +
    on + + + end +
    + + CRON Settings + begin + + + Hour Interval + pfb_interval + Every hour
    + Select the cron Hour Interval. The interval selected will be used with the Start min/hour below.
    + Ensure that all List 'Update Settings' are within the selected Interval/Start Hour Settings.]]> +
    + select + + + + + + + + + + + 1 +
    - CRON MIN Start Time + Start Min pfb_min - : 00
    - Select Cron Update Minute ]]>
    + :00
    + Select Cron Update Minute]]> +
    select - - - - + + + + + 0 +
    - CRON Base Hour Start Time + Start Hour pfb_hour - 1
    - Select Cron Base Start Hour ]]>
    + 0
    + Select the Start Hour]]> +
    select - - + + @@ -281,17 +319,17 @@ + 0 +
    - 'Daily/Weekly' Start Hour + Start Hour]]> pfb_dailystart - 1
    - Select 'Daily' Schedule Start Hour
    - This is used for the 'Daily/Weekly' Scheduler Only.]]>
    + 0
    This is used for the 'Daily/Weekly' Scheduler Only.]]>
    select - - + + @@ -315,6 +353,8 @@ + 0 + end
    Enable De-Duplication @@ -327,17 +367,20 @@ suppression checkbox - Country Blocking Lists cannot be Suppressed.
    - This will also remove any RFC1918 addresses from all Lists.

    + Country Blocking Lists cannot be Suppressed.
    This will also remove any RFC1918 addresses from all Lists.

    Alerts can be Suppressed using the '+' icon in the Alerts Tab and IPs added to the 'pfBlockerNGSuppress' Alias
    - A Blocked IP in a CIDR other than /24 will need to be Suppressed by an 'Permit Outbound' Firewall Rule]]> + A Blocked IP in a CIDR other than /32 or /24 will need a 'Whitelist Alias' w/ List Action: 'Permit Outbound' Firewall Rule +
    Do not use the pfBlockerNGSuppress Alias in a Firewall Rule. + This alias is used during the cron download process only.]]>
    Global Enable Logging enable_log checkbox - Enable Global Logging to Status: System Logs: FIREWALL ( Log ). This overrides any Log Settings in the Alias Tabs. + + This overrides any Log Settings in the Alias Tabs.]]> + Disable MaxMind Country Database CRON Updates @@ -350,8 +393,9 @@ Logfile Size log_maxlines - 20000
    - Select number of Lines to Keep in Log File]]>
    + 20000
    + Select number of Lines to keep in the pfblockerng.log and dnsbl.log files]]> +
    select @@ -361,72 +405,89 @@ + 20000
    - + listtopic - Inbound Interface(s) + Inbound Firewall Rules + begin + + inbound_interface + Interface(s) Select the Inbound interface(s) you want to Apply Auto Rules to interfaces_selection loopback + - - Rule Action + Rule Action inbound_deny_action - Block
    - Select 'Rule Action' for Inbound Rules]]>
    + Block
    Select 'Rule Action' for Inbound Rules]]>
    select + block + + end
    - Outbound Interface(s) + Outbound Firewall Rules + begin + + + Interface(s) outbound_interface Select the Outbound interface(s) you want to Apply Auto Rules to interfaces_selection loopback + - - Rule Action + Rule Action outbound_deny_action - Reject
    - Select 'Rule Action' for Outbound rules]]>
    + Reject
    Select 'Rule Action' for Outbound rules]]>
    select + reject + + end
    - OpenVPN Interface]]> + OpenVPN Interface openvpn_action checkbox Select to add Auto-Rules for OpenVPN. These will be added to 'Floating Rules' or OpenVPN Rules Tab. - Floating Rules]]> + Floating Rules enable_float checkbox - Enabled:  Auto-Rules will be generated in the 'Floating Rules' Tab

    + Enabled: Auto-Rules will be generated in the 'Floating Rules' Tab

    Disabled: Auto-Rules will be generated in the Selected Inbound/Outbound Interfaces

    - Rules will be ordered by the selection below.]]>
    + Rules will be ordered by the selection below.]]> +
    - Rule Order]]> + Rule Order pass_order - Default Order: | pfB_Block/Reject | All other Rules | (original format)

    + Default Order: | pfB_Block/Reject | All other Rules | (original format)

    Select The 'Order' of the Rules
      Selecting 'original format', sets pfBlockerNG rules at the top of the Firewall TAB.
    -   Selecting any other 'Order' will re-order all the Rules to the format indicated!]]>
    +   Selecting any other 'Order' will re-order all the Rules to the format indicated!]]> +
    select @@ -434,48 +495,48 @@ + order_0
    - Auto Rule Suffix]]> + Auto Rule Suffix autorule_suffix - auto rule
    - Select 'Auto Rule' Description Suffix for Auto Defined rules. pfBlockerNG Must be Disabled to Modify Suffix]]>
    + auto rule
    + Select 'Auto Rule' Description Suffix for Auto Defined rules. pfBlockerNG Must be Disabled to Modify Suffix]]> +
    select + autorule
    - + listtopic Credits credits info - - pfBlockerNG Created in 2015 by BBcan177. -

    Based upon pfBlocker by Marcello Coutinho and Tom Schaefer.
    + pfBlockerNG + Created in 2015 by BBcan177.

    + Based upon pfBlocker by Marcello Coutinho and Tom Schaefer.
    Country Database GeoLite distributed under the Creative Commons Attribution-ShareAlike 3.0 Unported License by: MaxMind Inc. @ MaxMind.com. - The Database is Automatically Updated the First Tuesday of Each Month]]>
    -
    - - pfBlocker Validation Check - pfblocker_cb - checkbox - Disable pfBlockerNG if the pfBlocker package is Enabled. Click to Disable this validation check. + The Database is Automatically Updated the First Tuesday of Each Month]]> +
    - Gold Membership + Support info - Gold Membership
    or support the developer @ BBCan177@gmail.com]]>
    + + If you like this package, please support the developer @ BBCan177@gmail.com.]]> +
    - Click to SAVE Settings and/or Rule Edits.       Changes are Applied via CRON or - 'Force Update']]> + Click to SAVE Settings and/or Rule Edits.       Changes are Applied via CRON or + 'Force Update']]> listtopic @@ -493,4 +554,4 @@ $pfb['save'] = TRUE; sync_package_pfblockerng(); - + \ No newline at end of file diff --git a/config/pfblockerng/pfblockerng_alerts.php b/config/pfblockerng/pfblockerng_alerts.php index 0b251295..25971ab5 100644 --- a/config/pfblockerng/pfblockerng_alerts.php +++ b/config/pfblockerng/pfblockerng_alerts.php @@ -57,7 +57,7 @@ if (isset($_REQUEST['getpfhostname'])) { require_once("util.inc"); require_once("guiconfig.inc"); require_once("/usr/local/pkg/pfblockerng/pfblockerng.inc"); -global $rule_list; +global $rule_list, $pfb_localsub; pfb_global(); $pfs_version = substr(trim(file_get_contents("/etc/version")),0,3); @@ -69,26 +69,25 @@ if ($pfs_version == "2.2") { } // Application Paths -$pathgeoip = $prefix . "/bin/geoiplookup"; -$pathgeoip6 = $prefix . "/bin/geoiplookup6"; +$pathgeoip = "{$prefix}/bin/geoiplookup"; +$pathgeoip6 = "{$prefix}/bin/geoiplookup6"; // Define File Locations $filter_logfile = "{$g['varlog_path']}/filter.log"; -$pathgeoipdat = $prefix . "/share/GeoIP/GeoIP.dat"; -$pathgeoipdat6 = $prefix . "/share/GeoIP/GeoIPv6.dat"; - -// Define Alerts Log filter Rollup window variable. (Alert Filtering Code adapted from B.Meeks - Snort Package) -$pfb['filterlogentries'] = FALSE; +$pathgeoipdat = "{$prefix}/share/GeoIP/GeoIP.dat"; +$pathgeoipdat6 = "{$prefix}/share/GeoIP/GeoIPv6.dat"; // Emerging Threats IQRisk Header Name Reference $pfb['et_header'] = TRUE; $et_header = $config['installedpackages']['pfblockerngreputation']['config'][0]['et_header']; -if (empty($et_header)) +if (empty($et_header)) { $pfb['et_header'] = FALSE; +} // Collect pfBlockerNGSuppress Alias and Create pfbsuppression.txt -if ($pfb['supp'] == "on") +if ($pfb['supp'] == "on") { pfb_create_suppression_file(); +} // Collect Number of Suppressed Hosts if (file_exists("{$pfb['supptxt']}")) { @@ -97,62 +96,88 @@ if (file_exists("{$pfb['supptxt']}")) { $pfbsupp_cnt = 0; } -// Collect pfBlockerNG Rule Names and Number -$rule_list = array(); -$results = array(); -$data = exec ("/sbin/pfctl -vv -sr | grep 'pfB_'", $results); - -if (!isset($config['installedpackages']['pfblockerngglobal']['pfbdenycnt'])) - $config['installedpackages']['pfblockerngglobal']['pfbdenycnt'] = '25'; -if (!isset($config['installedpackages']['pfblockerngglobal']['pfbpermitcnt'])) - $config['installedpackages']['pfblockerngglobal']['pfbpermitcnt'] = '5'; -if (!isset($config['installedpackages']['pfblockerngglobal']['pfbmatchcnt'])) - $config['installedpackages']['pfblockerngglobal']['pfbmatchcnt'] = '5'; -if (empty($config['installedpackages']['pfblockerngglobal']['alertrefresh'])) - $config['installedpackages']['pfblockerngglobal']['alertrefresh'] = 'off'; -if (empty($config['installedpackages']['pfblockerngglobal']['hostlookup'])) - $config['installedpackages']['pfblockerngglobal']['hostlookup'] = 'off'; +$pfb['global'] = &$config['installedpackages']['pfblockerngglobal']; -if (isset($_POST['save'])) { - if (!is_array($config['installedpackages']['pfblockerngglobal'])) - $config['installedpackages']['pfblockerngglobal'] = array(); - $config['installedpackages']['pfblockerngglobal']['alertrefresh'] = $_POST['alertrefresh'] ? 'on' : 'off'; - $config['installedpackages']['pfblockerngglobal']['hostlookup'] = $_POST['hostlookup'] ? 'on' : 'off'; - if (is_numeric($_POST['pfbdenycnt'])) - $config['installedpackages']['pfblockerngglobal']['pfbdenycnt'] = $_POST['pfbdenycnt']; - if (is_numeric($_POST['pfbpermitcnt'])) - $config['installedpackages']['pfblockerngglobal']['pfbpermitcnt'] = $_POST['pfbpermitcnt']; - if (is_numeric($_POST['pfbmatchcnt'])) - $config['installedpackages']['pfblockerngglobal']['pfbmatchcnt'] = $_POST['pfbmatchcnt']; +if (!isset($pfb['global']['pfbdenycnt'])) { + $pfb['global']['pfbdenycnt'] = '25'; +} +if (!isset($pfb['global']['pfbpermitcnt'])) { + $pfb['global']['pfbpermitcnt'] = '5'; +} +if (!isset($pfb['global']['pfbmatchcnt'])) { + $pfb['global']['pfbmatchcnt'] = '5'; +} +if (!isset($pfb['global']['pfbdnscnt'])) { + $pfb['global']['pfbdnscnt'] = '5'; +} +if (empty($pfb['global']['alertrefresh'])) { + $pfb['global']['alertrefresh'] = 'off'; +} +if (empty($pfb['global']['hostlookup'])) { + $pfb['global']['hostlookup'] = 'off'; +} +if (isset($_POST['save'])) { + if (!is_array($pfb['global'])) { + $pfb['global'] = array(); + } + $pfb['global']['alertrefresh'] = $_POST['alertrefresh'] ? 'on' : 'off'; + $pfb['global']['hostlookup'] = $_POST['hostlookup'] ? 'on' : 'off'; + if (is_numeric($_POST['pfbdenycnt'])) { + $pfb['global']['pfbdenycnt'] = $_POST['pfbdenycnt']; + } + if (is_numeric($_POST['pfbpermitcnt'])) { + $pfb['global']['pfbpermitcnt'] = $_POST['pfbpermitcnt']; + } + if (is_numeric($_POST['pfbmatchcnt'])) { + $pfb['global']['pfbmatchcnt'] = $_POST['pfbmatchcnt']; + } + if (is_numeric($_POST['pfbdnscnt'])) { + $pfb['global']['pfbdnscnt'] = $_POST['pfbdnscnt']; + } write_config("pfBlockerNG pkg: updated ALERTS tab settings."); header("Location: " . $_SERVER['PHP_SELF']); exit; } -if (is_array($config['installedpackages']['pfblockerngglobal'])) { - $alertrefresh = $config['installedpackages']['pfblockerngglobal']['alertrefresh']; - $hostlookup = $config['installedpackages']['pfblockerngglobal']['hostlookup']; - $pfbdenycnt = $config['installedpackages']['pfblockerngglobal']['pfbdenycnt']; - $pfbpermitcnt = $config['installedpackages']['pfblockerngglobal']['pfbpermitcnt']; - $pfbmatchcnt = $config['installedpackages']['pfblockerngglobal']['pfbmatchcnt']; +if (is_array($pfb['global'])) { + $alertrefresh = $pfb['global']['alertrefresh']; + $hostlookup = $pfb['global']['hostlookup']; + $pfbdenycnt = $pfb['global']['pfbdenycnt']; + $pfbpermitcnt = $pfb['global']['pfbpermitcnt']; + $pfbmatchcnt = $pfb['global']['pfbmatchcnt']; + $pfbdnscnt = $pfb['global']['pfbdnscnt']; +} + + +// Define Alerts Log filter Rollup window variable and collect Widget Alert Pivot details +if (isset($_REQUEST['rule'])) { + $filterfieldsarray[0] = $_REQUEST['rule']; + $pfbdenycnt = $pfbpermitcnt = $pfbmatchcnt = $_REQUEST['entries']; + $pfb['filterlogentries'] = TRUE; +} +else { + $pfb['filterlogentries'] = FALSE; } function pfb_match_filter_field($flent, $fields) { foreach ($fields as $key => $field) { - if ($field == null) + if ($field == null) { continue; + } if ((strpos($field, '!') === 0)) { $field = substr($field, 1); $field_regex = str_replace('/', '\/', str_replace('\/', '/', $field)); - if (@preg_match("/{$field_regex}/i", $flent[$key])) + if (@preg_match("/{$field_regex}/i", $flent[$key])) { return false; + } } else { $field_regex = str_replace('/', '\/', str_replace('\/', '/', $field)); - if (!@preg_match("/{$field_regex}/i", $flent[$key])) + if (!@preg_match("/{$field_regex}/i", $flent[$key])) { return false; + } } } return true; @@ -185,21 +210,20 @@ if ($_POST['filterlogentries_clear']) { } -// Collect pfBlockerNG Firewall Rules +// Collect pfBlockerNG Rule Names and Number +$rule_list = array(); +exec("/sbin/pfctl -vv -sr | grep 'pfB_'", $results); if (!empty($results)) { foreach ($results as $result) { # Find Rule Descriptions $descr = ""; - if (preg_match("/USER_RULE: (\w+)/",$result,$desc)) + if (preg_match("/USER_RULE: (\w+)/",$result,$desc)) { $descr = $desc[1]; - - if ($pfb['pfsenseversion'] >= '2.2') { - preg_match ("/@(\d+)\(/",$result, $rule); - } else { - preg_match ("/@(\d+)\s/",$result, $rule); } + preg_match ("/@(\d+)\(/",$result, $rule); + $id = $rule[1]; # Create array of Rule Description and pfctl Rule Number $rule_list['id'][] = $id; @@ -291,8 +315,9 @@ if (isset($_POST['addsuppress'])) { } // Call Function to Create Suppression Alias if not found. - if (!$pfb['found']) + if (!$pfb['found']) { pfb_create_suppression_alias(); + } // Save New Suppress IP to pfBlockerNGSuppress Alias if (in_array($ip . '/' . $cidr, $pfb_sup_list)) { @@ -332,12 +357,13 @@ if (isset($_POST['addsuppress'])) { if ($pfb['found'] || $pfb['update']) { // Save all Changes to pfsense config file - write_config(); + write_config("pfBlockerNG: Added {$ip} to IP Suppress List"); } } } } + // Host Resolve Function lookup function getpfbhostname($type = 'src', $hostip, $countme = 0) { $hostnames['src'] = ''; @@ -347,10 +373,18 @@ function getpfbhostname($type = 'src', $hostip, $countme = 0) { } -// Determine if Alert Host 'Dest' is within the Local Lan IP Range. -function check_lan_dest($lan_ip,$lan_mask,$dest_ip,$dest_mask="32") { - $result = check_subnets_overlap($lan_ip, $lan_mask, $dest_ip, $dest_mask); - return $result; +// For subnet addresses - Determine if Alert Host 'Dest' is within a Local IP Range. +function ip_in_pfb_localsub($subnet) { + global $pfb_localsub; + + if (!empty($pfb_localsub)) { + foreach ($pfb_localsub as $line) { + if (ip_in_subnet($subnet, $line)) { + return true; + } + } + } + return false; } @@ -373,16 +407,18 @@ function conv_log_filter_lite($logfile, $nentries, $tail, $pfbdenycnt, $pfbpermi $pfbalert = array(); $log_split = ""; - if (!preg_match("/(.*)\s(.*)\sfilterlog:\s(.*)$/", $logent, $log_split)) + if (!preg_match("/(.*)\s(.*)\sfilterlog:\s(.*)$/", $logent, $log_split)) { continue; + } list($all, $pfbalert[99], $host, $rule) = $log_split; $rule_data = explode(",", $rule); $pfbalert[0] = $rule_data[0]; // Rulenum // Skip Alert if Rule is not a pfBNG Alert - if (!in_array($pfbalert[0], $rule_list['id'])) + if (!in_array($pfbalert[0], $rule_list['id'])) { continue; + } $pfbalert[1] = $rule_data[4]; // Realint $pfbalert[3] = $rule_data[6]; // Act @@ -415,8 +451,9 @@ function conv_log_filter_lite($logfile, $nentries, $tail, $pfbdenycnt, $pfbpermi } // Skip Repeated Alerts - if (($pfbalert[3] . $pfbalert[8] . $pfbalert[10]) == $previous_dstip || ($pfbalert[3] . $pfbalert[7] . $pfbalert[9]) == $previous_srcip) + if (($pfbalert[3] . $pfbalert[8] . $pfbalert[10]) == $previous_dstip || ($pfbalert[3] . $pfbalert[7] . $pfbalert[9]) == $previous_srcip) { continue; + } $pfbalert[2] = convert_real_interface_to_friendly_descr($rule_data[4]); // Friendly Interface Name $pfbalert[6] = str_replace("TCP", "TCP-", strtoupper($pfbalert[6]), $pfbalert[6]) . $pfbalert[11]; // Protocol Flags @@ -474,12 +511,14 @@ include_once("head.inc"); include_once("fbegin.inc"); /* refresh every 60 secs */ -if ($alertrefresh == 'on') +if ($alertrefresh == 'on') { echo "\n"; +} if ($savemsg) { print_info_box($savemsg); } +$skipcount = 0; $counter = 0; ?> @@ -518,17 +557,22 @@ if ($savemsg) { "> @@ -552,48 +597,67 @@ if ($savemsg) { - + + - + -
    - + ', ''); ?> - + ', ''); ?> - + ', ''); ?> -     />  -     />   
    @@ -542,7 +586,8 @@ if ($savemsg) {
    - " onclick="enable_showFilter();" /> + " + onclick="enable_showFilter();" />   
    -
    +
    -
    -
    +
    +
    -
    -
    +
    +
    -
    -
    +
    +
    -
    -
    -
    -
    -
    +
    +
    -
    +
    -
    +
    +
    +
    +
    +
    +  
    -
    ', '');?>   +
    +
    ', '');?>   +

    +
    -
    " title="" /> -    " title="" /> -    " onclick="enable_hideFilter();" title="" />
    +
    +
    " title="" /> +    " title="" /> +    " onclick="enable_hideFilter();" + title="" />
    @@ -601,7 +665,7 @@ if ($savemsg) { - $pfb['denydir'] . " " . $pfb['nativedir'], "Permit" => $pfb['permitdir'], "Match" => $pfb['matchdir']) as $type => $pfbfolder ): + $pfb['denydir'] . " " . $pfb['nativedir'], "Permit" => $pfb['permitdir'], "Match" => $pfb['matchdir']) as $type => $pfbfolder ): switch($type) { case "Deny": $rtype = "block"; @@ -612,15 +676,16 @@ if ($savemsg) { $pfbentries = "{$pfbpermitcnt}"; break; case "Match": - if ($pfb['pfsenseversion'] >= '2.2') { - $rtype = "unkn(%u)"; - } else { - $rtype = "unkn(11)"; - } + $rtype = "unkn(%u)"; $pfbentries = "{$pfbmatchcnt}"; break; } + // Skip Table output if $pfbentries is zero. + if ($pfbentries == 0 && $skipcount != 2) { + $skipcount++; + continue; + } ?> @@ -660,30 +725,27 @@ if ($savemsg) { = '2.2') { - $pfblines = exec("/usr/local/sbin/clog {$filter_logfile} | /usr/bin/grep -c ^"); - } else { - $pfblines = (exec("/usr/local/sbin/clog {$filter_logfile} | /usr/bin/grep -c ^") /2 ); - } - + $pfblines = exec("/usr/local/sbin/clog {$filter_logfile} | /usr/bin/grep -c ^"); $fields_array = conv_log_filter_lite($filter_logfile, $pfblines, $pfblines, $pfbdenycnt, $pfbpermitcnt, $pfbmatchcnt); $continents = array('pfB_Africa','pfB_Antartica','pfB_Asia','pfB_Europe','pfB_NAmerica','pfB_Oceania','pfB_SAmerica','pfB_Top'); - $supp_ip_txt .= "Clicking this Suppression Icon, will immediately remove the Block.\n\nSuppressing a /32 CIDR is better than Suppressing the full /24"; + $supp_ip_txt = "Clicking this Suppression Icon, will immediately remove the Block.\n\nSuppressing a /32 CIDR is better than Suppressing the full /24"; $supp_ip_txt .= " CIDR.\nThe Host will be added to the pfBlockerNG Suppress Alias Table.\n\nOnly 32 or 24 CIDR IPs can be Suppressed with the '+' Icon."; $supp_ip_txt .= "\nTo manually add Host(s), edit the 'pfBlockerNGSuppress' Alias in the Alias Tab.\nManual entries will not remove existing Blocked Hosts"; // Array of all Local IPs for Alert Analysis $pfb_local = array(); + $pfb_localsub = array(); // Collect Gateway IP Addresses for Inbound/Outbound List matching $int_gateway = get_interfaces_with_gateway(); @@ -697,12 +759,16 @@ if ($pfb['runonce']) { // Collect Virtual IP Aliases for Inbound/Outbound List Matching if (is_array($config['virtualip']['vip'])) { foreach ($config['virtualip']['vip'] as $list) { - if ($list['type'] == "single" && $list['subnet_bits'] == "32") - $pfb_local[] = $list['subnet']; - elseif ($list['type'] == "single" || $list['type'] == "network") - $pfb_local = array_merge (subnet_expand ("{$list['subnet']}/{$list['subnet_bits']}"), $pfb_local); + if ($list['subnet'] != "" && $list['subnet_bits'] != "") { + if ($list['subnet_bits'] >= 24) { + $pfb_local = array_merge(subnetv4_expand("{$list['subnet']}/{$list['subnet_bits']}"), $pfb_local); + } else { + $pfb_localsub[] = "{$list['subnet']}/{$list['subnet_bits']}"; + } + } } } + // Collect NAT IP Addresses for Inbound/Outbound List Matching if (is_array($config['nat']['rule'])) { foreach ($config['nat']['rule'] as $natent) { @@ -711,7 +777,7 @@ if ($pfb['runonce']) { } // Collect 1:1 NAT IP Addresses for Inbound/Outbound List Matching - if(is_array($config['nat']['onetoone'])) { + if (is_array($config['nat']['onetoone'])) { foreach ($config['nat']['onetoone'] as $onetoone) { $pfb_local[] = $onetoone['source']['address']; } @@ -729,17 +795,27 @@ if ($pfb['runonce']) { } } } - // Remove any Duplicate IPs - $pfb_local = array_unique($pfb_local); - // Determine Lan IP Address and Mask - if (is_array($config['interfaces']['lan'])) { - $lan_ip = $config['interfaces']['lan']['ipaddr']; - $lan_mask = $config['interfaces']['lan']['subnet']; + // Collect all Interface Addresses for Inbound/Outbound List Matching + if (is_array($config['interfaces'])) { + foreach ($config['interfaces'] as $int) { + if ($int['ipaddr'] != "dhcp") { + if ($int['ipaddr'] != "" && $int['subnet'] != "") { + if ($int['subnet'] >= 24) { + $pfb_local = array_merge(subnetv4_expand("{$int['ipaddr']}/{$int['subnet']}"), $pfb_local); + } else { + $pfb_localsub[] = "{$int['ipaddr']}/{$int['subnet']}"; + } + } + } + } } + + // Remove any Duplicate IPs + $pfb_local = array_unique($pfb_local); + $pfb_localsub = array_unique($pfb_localsub); } -$counter = 0; // Process Fields_array and generate Output if (!empty($fields_array[$type]) && !empty($rule_list)) { $key = 0; @@ -774,19 +850,19 @@ if (!empty($fields_array[$type]) && !empty($rule_list)) { } // Add DNS Resolve and Suppression Icons to External IPs only. GeoIP Code to External IPs only. - if (in_array($fields[8], $pfb_local) || check_lan_dest($lan_ip,$lan_mask,$fields[8],"32")) { + if (in_array($fields[8], $pfb_local) || ip_in_pfb_localsub($fields[8])) { // Destination is Gateway/NAT/VIP $rule = $rule_list[$rulenum]['name'] . "
    (" . $rulenum .")"; $host = $fields[7]; - $alert_ip .= " "; + $alert_ip = " "; if ($pfb_query != "Country" && $rtype == "block" && $pfb['supp'] == "on") { - $supp_ip .= ""; + $supp_ip .= gettext($supp_ip_txt) . "\" border='0' width='11' height='11' />"; } if ($pfb_query != "Country" && $rtype == "block" && $hostlookup == "on") { @@ -802,14 +878,14 @@ if (!empty($fields_array[$type]) && !empty($rule_list)) { $rule = $rule_list[$rulenum]['name'] . "
    (" . $rulenum .")"; $host = $fields[8]; - $alert_ip .= " "; + $alert_ip = " "; if ($pfb_query != "Country" && $rtype == "block" && $pfb['supp'] == "on") { - $supp_ip .= ""; + $supp_ip .= gettext($supp_ip_txt) . "\" border='0' width='11' height='11' />"; } if ($pfb_query != "Country" && $rtype == "block" && $hostlookup == "on") { @@ -857,8 +933,9 @@ if (!empty($fields_array[$type]) && !empty($rule_list)) { $host3 = $host2 - $cnt . '\''; $pfb_query = exec("/usr/bin/grep -rH {$host1}{$host3} {$pfbfolder} | sed -e 's/^.*[a-zA-Z]\///' -e 's/\.txt:/ /' | {$pfb_ex2}"); // Break out of loop if found. - if (!empty($pfb_query)) + if (!empty($pfb_query)) { $cnt = 6; + } } } // Search for First Three Octets @@ -886,8 +963,9 @@ if (!empty($fields_array[$type]) && !empty($rule_list)) { } // Default to "No Match" if not found. - if (empty($pfb_query)) + if (empty($pfb_query)) { $pfb_query = "No Match"; + } # Split List Column into Two lines. unset ($pfb_match); @@ -921,43 +999,44 @@ if (!empty($fields_array[$type]) && !empty($rule_list)) { } // Print Alternating Line Shading - if ($pfb['pfsenseversion'] > '2.0') { - $alertRowEvenClass = "listMReven"; - $alertRowOddClass = "listMRodd"; - } else { - $alertRowEvenClass = "listr"; - $alertRowOddClass = "listr"; - } + $alertRowEvenClass = "style='background-color: #D8D8D8;'"; + $alertRowOddClass = "style='background-color: #E8E8E8;'"; $alertRowClass = $counter % 2 ? $alertRowEvenClass : $alertRowOddClass; - echo " + echo " - - + + "; $counter++; - if ($counter > 0 && $rtype == "block") { - $mycounter = $counter; - } else { - $mycounter = 0; + if ($rtype == "block") { + $resolvecounter = $counter; } } } } ?> + + + Found {$counter} Alert Entries {$msg}"); + $counter = 0; $msg = ''; + ?> +
    {$fields[99]} {$fields[2]} {$rule} {$fields[6]}{$src_icons}{$fields[97]}{$srcport}
    {$hostname['src']}
    {$dst_icons}{$fields[98]}{$dstport}
    {$hostname['dst']}
    {$src_icons}{$fields[97]}{$srcport}
    {$hostname['src']}
    {$dst_icons}{$fields[98]}{$dstport}
    {$hostname['dst']}
    {$country} {$pfb_match[1]}
    {$pfb_match[2]}
    - -