aboutsummaryrefslogtreecommitdiffstats
path: root/config/pfblockerng/pfblockerng.inc
diff options
context:
space:
mode:
Diffstat (limited to 'config/pfblockerng/pfblockerng.inc')
-rw-r--r--config/pfblockerng/pfblockerng.inc1237
1 files changed, 780 insertions, 457 deletions
diff --git a/config/pfblockerng/pfblockerng.inc b/config/pfblockerng/pfblockerng.inc
index 26eeb5e5..379ce223 100644
--- a/config/pfblockerng/pfblockerng.inc
+++ b/config/pfblockerng/pfblockerng.inc
@@ -46,7 +46,7 @@ require_once("pfsense-utils.inc");
require_once("globals.inc");
require_once("services.inc");
-# [ $pfb ] pfBlockerNG Global Array for Paths and Variables. This needs to be called to get the Updated Settings.
+// [ $pfb ] pfBlockerNG Global Array for Paths and Variables. This needs to be called to get the Updated Settings.
function pfb_global() {
global $g,$config,$pfb;
@@ -58,10 +58,7 @@ function pfb_global() {
$prefix = "/usr/local";
}
- # Collect pfSense Version
- $pfb['pfsenseversion'] = substr(trim(file_get_contents("/etc/version")),0,3);
-
- # Folders
+ // Folders
$pfb['dbdir'] = "{$g['vardb_path']}/pfblockerng";
$pfb['aliasdir'] = "{$g['vardb_path']}/aliastables";
$pfb['logdir'] = "{$g['varlog_path']}/pfblockerng";
@@ -71,39 +68,49 @@ 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.
+ // 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']}");
foreach ($folder_array as $folder) {
safe_mkdir ("{$folder}",0755);
}
- # 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";
-
- # General Variables
- $pfb['config'] = $config['installedpackages']['pfblockerng']['config'][0];
-
- # Enable/Disable of pfBlockerNG
- $pfb['enable'] = $pfb['config']['enable_cb'];
- # Keep Blocklists on pfBlockerNG Disable
- $pfb['keep'] = $pfb['config']['pfb_keep'];
- # Enable Suppression
- $pfb['supp'] = $pfb['config']['suppression'];
- # Max Lines in pfblockerng.log file
- $pfb['logmax'] = $pfb['config']['log_maxlines'];
- $pfb['iplocal'] = $config['interfaces']['lan']['ipaddr'];
- # Disable Country Database CRON Updates
- $pfb['cc'] = $pfb['config']['database_cc'];
-
- # Set pfBlockerNG to Disabled on 'Re-Install'
+ // 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";
+
+ // General Variables
+ $pfb['config'] = $config['installedpackages']['pfblockerng']['config'][0];
+
+ // Enable/Disable of pfBlockerNG
+ $pfb['enable'] = $pfb['config']['enable_cb'];
+ // Keep Blocklists on pfBlockerNG Disable
+ $pfb['keep'] = $pfb['config']['pfb_keep'];
+ // Enable Suppression
+ $pfb['supp'] = $pfb['config']['suppression'];
+ // Max Lines in pfblockerng.log file
+ $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'];
+
+ // 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']) {
$pfb['enable'] = "";
$pfb['install'] = FALSE;
@@ -112,38 +119,51 @@ function pfb_global() {
pfb_global();
-# Set Max PHP Memory Setting
+// 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;
}
-# Manage Log File Line Limit
+// Manage Log File Line Limit
function pfb_log_mgmt() {
global $pfb;
pfb_global();
if ($pfb['logmax'] == "nolimit") {
- # Skip Log Mgmt
+ // 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']}");
+ }
}
}
-# Record Log Messsages to pfBlockerNG Log File and/or Error Log File.
+// Record Log Messsages to pfBlockerNG Log File and/or Error Log File.
function pfb_logger($log, $type) {
global $g,$pfb,$pfbarr;
$now = date("m/d/y G:i:s", time());
- # Only log timestamp if new
+ // Only log timestamp if new
if (preg_match("/NOW/", $log)) {
if ($now == $pfb['pnow']) {
$log = str_replace("[ NOW ]", "", "{$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'))) {
@@ -179,7 +199,7 @@ function pfb_determine_list_detail($list) {
$pfbarr['skip'] = FALSE;
$pfbarr['folder'] = "{$pfb['nativedir']}";
} else {
- # Deny
+ // Deny
$pfbarr['skip'] = TRUE;
$pfbarr['folder'] = "{$pfb['denydir']}";
}
@@ -191,10 +211,180 @@ 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;
}
-# Create Suppression Alias
+
+// 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 ($pfb_hour == 'maxmind' && !empty($item['hour'])) {
+ // Maxmind hour is randomized. Skip comparison.
+ return TRUE;
+ }
+ 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,11 +402,11 @@ function pfb_create_suppression_alias() {
"detail" => ""
);
$config['aliases']['alias'] = $new_aliases;
- write_config();
+ $pfb['cron_mod'] = TRUE;
}
-# Create Suppression file from Alias
+// Create Suppression file from Alias
function pfb_create_suppression_file() {
global $config,$pfb;
@@ -235,19 +425,20 @@ 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']}");
}
} else {
- # Delete Suppression File if Alias is Empty.
+ // Delete Suppression File if Alias is Empty.
unlink_if_exists("{$pfb['supptxt']}");
}
}
// Call Function to Create Suppression Alias.
- if (!$pfb['found'])
+ if (!$pfb['found']) {
pfb_create_suppression_alias();
+ }
}
@@ -306,7 +497,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,18 +584,21 @@ function pfb_aliastables($mode) {
}
}
- if ($msg != "")
+ if ($msg != "") {
pfb_logger("{$msg}","1");
+ $pfb['cron_mod'] = TRUE;
+ }
}
-# Main pfBlockerNG Function
+// Main pfBlockerNG Function
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
+ // Detect Boot Process or Update via CRON
if (isset($_POST) && $cron == "") {
if (!preg_match("/\w+/",$_POST['__csrf_magic'])) {
log_error("[pfBlockerNG] Sync terminated during boot process.");
@@ -418,7 +612,7 @@ function sync_package_pfblockerng($cron = "") {
$pfb['save'] = TRUE;
}
- # Start of pfBlockerNG Logging to 'pfblockerng.log'
+ // Start of pfBlockerNG Logging to 'pfblockerng.log'
if ($pfb['enable'] == "on" && !$pfb['save']) {
$log = " UPDATE PROCESS START [ NOW ]\n";
pfb_logger("{$log}","1");
@@ -432,13 +626,15 @@ function sync_package_pfblockerng($cron = "") {
// Call function for NanoBSD/Ramdisk processes.
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']}";
+ // Collect pfSense Max Table Size Entry
+ 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
+ // Collect local web gui configuration
$pfb['weblocal'] = ($config['system']['webgui']['protocol'] != "" ? $config['system']['webgui']['protocol'] : "http");
$pfb['port'] = $config['system']['webgui']['port'];
if ($pfb['port'] == "") {
@@ -450,72 +646,57 @@ function sync_package_pfblockerng($cron = "") {
}
$pfb['weblocal'] .= "://127.0.0.1:{$pfb['port']}/pfblockerng/pfblockerng.php";
- # Define Inbound/Outbound Action is not user selected.
+ // Define Inbound/Outbound Action is not user selected.
$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
+ // Reloads Existing Blocklists without Downloading New Lists
$pfb['reuse'] = $pfb['config']['pfb_reuse'];
- # Enable OpenVPN AutoRules
+ // Enable OpenVPN AutoRules
$pfb['openvpn'] = $pfb['config']['openvpn_action'];
- # Enable/Disable Floating Auto-Rules
+ // Enable/Disable Floating Auto-Rules
$pfb['float'] = $pfb['config']['enable_float'];
- # Enable Remove of Duplicate IPs utilizing Grepcidr
+ // Enable Remove of Duplicate IPs utilizing Grepcidr
$pfb['dup'] = $pfb['config']['enable_dup'];
- # Order of the Auto-Rules
+ // Order of the Auto-Rules
$pfb['order'] = $pfb['config']['pass_order'];
- # Suffix used for Auto-Rules
+ // Suffix used for Auto-Rules
$pfb['suffix'] = $pfb['config']['autorule_suffix'];
- # Reputation Variables
+ // Reputation Variables
$pfb['config_rep'] = $config['installedpackages']['pfblockerngreputation']['config'][0];
- # Enable/Disable Reputation
+ // Enable/Disable Reputation
$pfb['rep'] = $pfb['config_rep']['enable_rep'];
- # Enable/Disable 'pDup'
+ // Enable/Disable 'pDup'
$pfb['pdup'] = $pfb['config_rep']['enable_pdup'];
- # Enable/Disable 'dDup'
+ // Enable/Disable 'dDup'
$pfb['dedup'] = ($pfb['config_rep']['enable_dedup'] != "" ? $pfb['config_rep']['enable_dedup'] : "x");
- # 'Max' variable setting for Reputation
+ // 'Max' variable setting for Reputation
$pfb['max'] = ($pfb['config_rep']['p24_max_var'] != "" ? $pfb['config_rep']['p24_max_var'] : "x");
- # 'dMax' variable setting for Reputation
+ // 'dMax' variable setting for Reputation
$pfb['dmax'] = ($pfb['config_rep']['p24_dmax_var'] != "" ? $pfb['config_rep']['p24_dmax_var'] : "x");
- # 'pMax' variable setting for Reputation
+ // 'pMax' variable setting for Reputation
$pfb['pmax'] = ($pfb['config_rep']['p24_pmax_var'] != "" ? $pfb['config_rep']['p24_pmax_var'] : "x");
- # Action for Whitelist Country Category
+ // Action for Whitelist Country Category
$pfb['ccwhite'] = $pfb['config_rep']['ccwhite'];
- # Action for Blacklist Country Category
+ // Action for Blacklist Country Category
$pfb['ccblack'] = $pfb['config_rep']['ccblack'];
- # List of Countries in the Whitelist Category
+ // List of Countries in the Whitelist Category
$pfb['ccexclude']= ($pfb['config_rep']['ccexclude'] != "" ? $pfb['config_rep']['ccexclude'] : "x");
- # Emerging Threats IQRisk Block Categories
+ // Emerging Threats IQRisk Block Categories
$pfb['etblock'] = ($pfb['config_rep']['etblock'] != "" ? $pfb['config_rep']['etblock'] : "x");
- # Emerging Threats IQRisk Match Categories
+ // Emerging Threats IQRisk Match Categories
$pfb['etmatch'] = ($pfb['config_rep']['etmatch'] != "" ? $pfb['config_rep']['etmatch'] : "x");
- # Perform a Force Update on ET Categories
+ // Perform a Force Update on ET Categories
$pfb['etupdate']= $pfb['config_rep']['et_update'];
- # Variables
+ // Variables
- # Starting Variable to Skip rep, pdup and dedeup functions if no changes are required
+ // Starting Variable to Skip rep, pdup and dedeup functions if no changes are required
$pfb['dupcheck'] = FALSE;
- ## $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;
- }
- }
+ // $pfb['save'] is used to determine if User pressed "Save" Button to avoid Collision with CRON.
+ // This is defined in each pfBlockerNG XML Files
#################################
@@ -533,8 +714,8 @@ function sync_package_pfblockerng($cron = "") {
"Proxy and Satellite" => "pfB_PS"
);
- #create rules vars and arrays
- # Array used to Collect Changes to Aliases to be saved to Config
+ // create rules vars and arrays
+ // Array used to Collect Changes to Aliases to be saved to Config
$new_aliases = array();
$new_aliases_list = array();
$continent_existing = array();
@@ -543,14 +724,14 @@ function sync_package_pfblockerng($cron = "") {
$permit_outbound = array();
$deny_inbound = array();
$deny_outbound = array();
- # An Array of all Aliases (Active and non-Active)
+ // An Array of all Aliases (Active and non-Active)
$aliases_list = array();
- # This is an Array of Aliases that Have Updated Lists via CRON/Force Update when 'Reputation' disabled.
+ // This is an Array of Aliases that Have Updated Lists via CRON/Force Update when 'Reputation' disabled.
$pfb_alias_lists = array();
- # This is an Array of All Active Aliases used when 'Reputation' enabled
+ // This is an Array of All Active Aliases used when 'Reputation' enabled
$pfb_alias_lists_all = array();
- # Base Rule Array
+ // Base Rule Array
$base_rule_reg = array( "id" => "",
"tag" => "",
"tagged" => "",
@@ -563,7 +744,7 @@ function sync_package_pfblockerng($cron = "") {
"os" => ""
);
- # Floating Rules, Base Rule Array
+ // Floating Rules, Base Rule Array
$base_rule_float = array("id" => "",
"tag" => "",
"tagged" => "",
@@ -583,8 +764,8 @@ function sync_package_pfblockerng($cron = "") {
# Configure Rule Suffix #
#########################################
- # Discover if any Rules are AutoRules (If no AutoRules found, $pfb['autorules'] is FALSE, Skip Rules Re-Order )
- # To configure Auto Rule Suffix. pfBlockerNG must be disabled to change Suffix and to avoid Duplicate Rules
+ // Discover if any Rules are AutoRules (If no AutoRules found, $pfb['autorules'] is FALSE, Skip Rules Re-Order )
+ // To configure Auto Rule Suffix. pfBlockerNG must be disabled to change Suffix and to avoid Duplicate Rules
$pfb['autorules'] = FALSE;
$pfb['found'] = FALSE;
foreach ($continents as $continent => $pfb_alias) {
@@ -610,16 +791,16 @@ function sync_package_pfblockerng($cron = "") {
}
}
- #Configure Auto Rule Suffix. pfBlockerNG must be disabled to change Suffix and to avoid Duplicate Rules
- # Count Number of Rules with 'pfB_'
+ // Configure Auto Rule Suffix. pfBlockerNG must be disabled to change Suffix and to avoid Duplicate Rules
+ // Count Number of Rules with 'pfB_'
$count = 0;
if (is_array($config['filter']['rule'])) {
foreach ($config['filter']['rule'] as $rule) {
- # Collect any pre-existing Suffix
+ // Collect any pre-existing Suffix
if (preg_match("/pfB_\w+(\s.*)/",$rule['descr'], $pfb_suffix_real) && $count == 0) {
$pfb_suffix_match = $pfb_suffix_real[1];
}
- # Query for Existing pfB Rules
+ // Query for Existing pfB Rules
if (preg_match("/pfB_/",$rule['descr'])) {
$count++;
break;
@@ -627,7 +808,7 @@ function sync_package_pfblockerng($cron = "") {
}
}
- # Change Suffix only if No pfB Rules Found and Auto Rules are Enabled.
+ // Change Suffix only if No pfB Rules Found and Auto Rules are Enabled.
if ($pfb['autorules'] && $count == 0) {
switch ($pfb['suffix']) {
case "autorule":
@@ -642,10 +823,10 @@ function sync_package_pfblockerng($cron = "") {
}
} else {
if ($pfb['autorules']) {
- # Use existing Suffix Match
+ // Use existing Suffix Match
$pfb['suffix'] = $pfb_suffix_match;
} else {
- # Leave Rule Suffix 'Blank'
+ // Leave Rule Suffix 'Blank'
$pfb['suffix'] = "";
}
}
@@ -655,50 +836,52 @@ function sync_package_pfblockerng($cron = "") {
# Configure INBOUND/OUTBOUND INTERFACES #
#########################################################
- # Collect pfSense Interface Order
+ // Collect pfSense Interface Order
$ifaces = get_configured_interface_list();
if (!empty($pfb['config']['inbound_interface'])) {
- # Sort Interface Array to match pfSense Interface order to allow Floating Rules to populate.
+ // Sort Interface Array to match pfSense Interface order to allow Floating Rules to populate.
$selected_interfaces = explode(",",$pfb['config']['inbound_interface']);
- # Sort pfBlockerNG Interface order to pfSense Interface Order
+ // Sort pfBlockerNG Interface order to pfSense Interface Order
$sort_interfaces = array_intersect($ifaces, $selected_interfaces);
$implode_interfaces = ltrim(implode(",",$sort_interfaces), ",");
- # CSV String for Inbound Interfaces for 'pfB_' Match Rules
+ // CSV String for Inbound Interfaces for 'pfB_' Match Rules
$pfb['inbound_floating'] = $implode_interfaces;
$pfb['inbound_interfaces_float'] = explode(" ",$implode_interfaces);
- # Assign Inbound Base Rule/Interfaces
+ // Assign Inbound Base Rule/Interfaces
if ($pfb['float'] == "on") {
- # Define Base Firewall Floating Rules Settings
+ // Define Base Firewall Floating Rules Settings
$base_rule = $base_rule_float;
$pfb['inbound_interfaces'] = $pfb['inbound_interfaces_float'];
} else {
- # Define Base Firewall Rules Settings
+ // Define Base Firewall Rules Settings
$base_rule = $base_rule_reg;
$pfb['inbound_interfaces'] = explode(",",$pfb['config']['inbound_interface']);
}
} else {
- # Define Empty Variable/Array
+ // Define Empty Variable/Array
$pfb['inbound_interfaces_float'] = "";
$pfb['inbound_interfaces'] = array();
}
if (!empty($pfb['config']['outbound_interface'])) {
- # Sort Interface Array to match pfSense Interface order to allow Floating Rules to populate.
+ // Sort Interface Array to match pfSense Interface order to allow Floating Rules to populate.
$selected_interfaces = explode(",",$pfb['config']['outbound_interface']);
- # Sort pfBlockerNG Interface order to pfSense Interface Order
+ // 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
+ // CSV String for Outbound Interfaces for 'pfB_' Match Rules
$pfb['outbound_floating'] = $implode_interfaces;
$pfb['outbound_interfaces_float'] = explode(" ",$implode_interfaces);
- # Assign Outbound Base Rule/Interfaces
+ // Assign Outbound Base Rule/Interfaces
if ($pfb['float'] == "on") {
$base_rule = $base_rule_float;
$pfb['outbound_interfaces'] = $pfb['outbound_interfaces_float'];
@@ -706,12 +889,14 @@ 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
+ // Define Empty Variable/Array
$pfb['outbound_interfaces_float'] = "";
$pfb['outbound_interfaces'] = array();
}
@@ -721,12 +906,13 @@ function sync_package_pfblockerng($cron = "") {
# Clear Removed Lists from Masterfiles #
#################################################
- # Process to keep Masterfiles in Sync with Valid Lists from config.conf file.
+ // Process to keep Masterfiles in Sync with Valid Lists from config.conf file.
$pfb['sync_master'] = TRUE;
- # Don't execute this function when pfBlockerNG is Disabled and 'Keep Blocklists' is enabled.
- if ($pfb['enable'] == "" && $pfb['keep'] == "on")
+ // Don't execute this function when pfBlockerNG is Disabled and 'Keep Blocklists' is enabled.
+ if ($pfb['enable'] == "" && $pfb['keep'] == "on") {
$pfb['sync_master'] = FALSE;
+ }
if ($pfb['sync_master']) {
$pfb['existing']['match']['type'] = "match";
@@ -754,7 +940,7 @@ function sync_package_pfblockerng($cron = "") {
$cont_type = array ("countries4" => "_v4", "countries6" => "_v6");
foreach ($cont_type as $c_type => $vtype) {
if ($continent_config[$c_type] != "") {
- # Set Parameters for 'Match', 'Permit', 'Native' and 'Deny'
+ // Set Parameters for 'Match', 'Permit', 'Native' and 'Deny'
if (in_array($continent_config['action'],array('Match_Both','Match_Inbound','Match_Outbound','Alias_Match'))) {
$pfb['existing']['match'][] = "{$pfb_alias}{$vtype}";
} elseif (in_array($continent_config['action'],array('Permit_Both','Permit_Inbound','Permit_Outbound','Alias_Permit'))){
@@ -770,7 +956,7 @@ function sync_package_pfblockerng($cron = "") {
}
}
- # Find all Enabled IPv4/IPv6 Lists
+ // Find all Enabled IPv4/IPv6 Lists
$list_type = array ("pfblockernglistsv4" => "_v4", "pfblockernglistsv6" => "_v6");
foreach ($list_type as $ip_type => $vtype) {
if ($config['installedpackages'][$ip_type]['config'] != "" && $pfb['enable'] == "on") {
@@ -782,9 +968,9 @@ function sync_package_pfblockerng($cron = "") {
} else {
$pfb_alias = "{$row['header']}_v6";
}
- # Collect Enabled Lists
+ // Collect Enabled Lists
if ($row['url'] != "" && $row['state'] != "Disabled") {
- # Set Parameters for 'Match', 'Permit', 'Native' and 'Deny'
+ // Set Parameters for 'Match', 'Permit', 'Native' and 'Deny'
if (in_array($list['action'],array('Match_Both','Match_Inbound','Match_Outbound','Alias_Match'))) {
$pfb['existing']['match'][] = "{$pfb_alias}";
} elseif (in_array($list['action'],array('Permit_Both','Permit_Inbound','Permit_Outbound','Alias_Permit'))) {
@@ -801,7 +987,7 @@ function sync_package_pfblockerng($cron = "") {
}
}
- # Find all Enabled IPv4 'Custom List' Header Names and Check if 'Emerging Threats Update' and 'Custom List Update' Needs Force Updating
+ // Find all Enabled IPv4 'Custom List' Header Names and Check if 'Emerging Threats Update' and 'Custom List Update' Needs Force Updating
$list_type = array ("pfblockernglistsv4" => "_v4", "pfblockernglistsv6" => "_v6");
foreach ($list_type as $ip_type => $vtype) {
if ($config['installedpackages'][$ip_type]['config'] != "" && $pfb['enable'] == "on") {
@@ -809,27 +995,28 @@ function sync_package_pfblockerng($cron = "") {
foreach ($config['installedpackages'][$ip_type]['config'] as $list) {
if (is_array($list['row']) && $list['action'] != "Disabled") {
$count++;
- # Check if 'Emerging Threats Update' Needs Updating before next CRON Event.
+ // Check if 'Emerging Threats Update' Needs Updating before next CRON Event.
if (is_array($list['row']) && $row['state'] != "Disabled" && $pfb['etupdate'] == "enabled" && $vtype == "_v4") {
foreach ($list['row'] as $row) {
$aliasname = $row['header'];
if ($row['format'] == "et") {
unlink_if_exists("{$pfb['denydir']}/{$aliasname}.txt");
$config['installedpackages']['pfblockerngreputation']['config'][0]['et_update'] = "disabled";
+ $pfb['cron_mod'] = TRUE;
break;
}
}
}
}
- # Collect Enabled Custom List Box Aliases
+ // Collect Enabled Custom List Box Aliases
if (pfbng_text_area_decode($list['custom']) != "") {
if ($vtype == "_v4") {
$pfb_alias = "{$list['aliasname']}_custom";
} else {
$pfb_alias = "{$list['aliasname']}_custom_v6";
}
- # Determine Folder Location for 'List'
+ // Determine Folder Location for 'List'
if (in_array($list['action'],array('Match_Both','Match_Inbound','Match_Outbound','Alias_Match'))) {
$pfb['existing']['match'][] = "{$pfb_alias}";
$pfbfolder = "{$pfb['matchdir']}";
@@ -843,18 +1030,19 @@ function sync_package_pfblockerng($cron = "") {
$pfb['existing']['deny'][] = "{$pfb_alias},"; // Add Trailing ','
$pfbfolder = "{$pfb['denydir']}";
}
- # Determine if 'Custom List' Needs Force Updating before next CRON Event.
+ // Determine if 'Custom List' Needs Force Updating before next CRON Event.
if ($list['custom_update'] == "enabled") {
unlink_if_exists("{$pfbfolder}/{$pfb_alias}.txt");
- # Uncheck 'Enabled' in List 'Custom_update' Setting
+ // Uncheck 'Enabled' in List 'Custom_update' Setting
$config['installedpackages'][$ip_type]['config'][$count]['custom_update'] = "disabled";
+ $pfb['cron_mod'] = TRUE;
}
}
}
}
}
- # Collect all .txt file Names for each List Type
+ // Collect all .txt file Names for each List Type
$list_types = array('match' => $pfb['matchdir'], 'permit' => $pfb['permitdir'], 'deny' => $pfb['denydir'], 'native' => $pfb['nativedir']);
foreach ($list_types as $type => $pfbfolder) {
$pfb_files = glob("$pfbfolder/*.txt");
@@ -868,12 +1056,12 @@ function sync_package_pfblockerng($cron = "") {
}
}
- # Flag to execute pfctl and Rules Ordering
+ // Flag to execute pfctl and Rules Ordering
$pfb['remove'] = FALSE;
- # Execute Final Summary as a List was Removed
+ // Execute Final Summary as a List was Removed
$pfb['summary'] = FALSE;
- # Process to Remove Lists from Masterfile/DB Folder if they do not Exist
+ // Process to Remove Lists from Masterfile/DB Folder if they do not Exist
if (isset($pfb['existing'])) {
foreach ($pfb['existing'] as $pfb_exist) {
$existing_type = $pfb_exist['type'];
@@ -888,7 +1076,7 @@ function sync_package_pfblockerng($cron = "") {
if ($f_result != "") {
$log = "[ Removing List(s) : {$f_result} ]\n";
pfb_logger("{$log}","1");
- # Script to Remove un-associated Lists
+ // Script to Remove un-associated Lists
exec ("{$pfb['script']} remove x x x {$f_result} >> {$pfb['log']} 2>&1");
$pfb['summary'] = TRUE;
$pfb['remove'] = TRUE;
@@ -898,13 +1086,13 @@ function sync_package_pfblockerng($cron = "") {
case "permit":
case "native":
$results = array_diff($pfb_act, $pfb_exist);
- # This variable ($f_result) used in next section below.
+ // 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 +1100,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'])) {
@@ -926,7 +1114,7 @@ function sync_package_pfblockerng($cron = "") {
if ($row['header'] == $removed) {
$pfb['summary'] = TRUE;
$pfb['remove'] = TRUE;
- # Add Alias to Update Array
+ // Add Alias to Update Array
$pfb_alias_lists[] = "{$alias}";
$pfb_alias_lists_all[] = "{$alias}";
}
@@ -947,7 +1135,7 @@ function sync_package_pfblockerng($cron = "") {
# Clear Match/Pass/ET/Original Files/Folders #
#########################################################
- # When pfBlockerNG is Disabled and 'Keep Blocklists' is Disabled.
+ // When pfBlockerNG is Disabled and 'Keep Blocklists' is Disabled.
if ($pfb['enable'] == "" && $pfb['keep'] == "" && !$pfb['install']) {
$log = "\n Removing DB Files/Folders \n";
pfb_logger("{$log}","1");
@@ -964,12 +1152,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 +1168,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,48 +1195,40 @@ 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;
$match = $continent_new[$line];
$continent_new[$line] = rtrim($match, "\n");
- # Check if pfBlockerNG pfctl Continent Tables are Empty (pfBlockerNG was Disabled w/ "keep", then Re-enabled)
+ // Check if pfBlockerNG pfctl Continent Tables are Empty (pfBlockerNG was Disabled w/ "keep", then Re-enabled)
$pfctlck = exec ("/sbin/pfctl -vvsTables | grep -A1 {$pfb_alias}{$vtype} | awk '/Addresses/ {s+=$2}; END {print s}'");
if (empty($pfctlck) && file_exists($pfbfolder . '/' . $pfb_alias . $vtype . '.txt')) {
$file_cont = file_get_contents($pfbfolder . '/' . $pfb_alias . $vtype . '.txt');
@file_put_contents($pfb['aliasdir'] . '/' . $pfb_alias . $vtype . '.txt',$file_cont, LOCK_EX);
- # PFCTL - Update Only Aliases that have been updated. ('Reputation' Disabled)
+ // PFCTL - Update Only Aliases that have been updated. ('Reputation' Disabled)
$pfb_alias_lists[] = "{$pfb_alias}{$vtype}";
}
- # Collect Active Alias Lists (Used for pfctl Update when 'Reputation' is enabled).
+ // Collect Active Alias Lists (Used for pfctl Update when 'Reputation' is enabled).
$pfb_alias_lists_all[] = "{$pfb_alias}{$vtype}";
// 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.
+ // Test to Skip d-dup and p-dup functions when changes are found.
$pfb['dupcheck'] = TRUE;
$pfb_alias_lists[] = "{$pfb_alias}{$vtype}";
@@ -1061,11 +1247,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,9 +1264,8 @@ function sync_package_pfblockerng($cron = "") {
}
}
-
if (file_exists($pfbfolder . '/' . $pfb_alias . $vtype . '.txt')) {
- #Create alias config
+ // Create alias config
$new_aliases_list[] = "{$pfb_alias}{$vtype}";
$pfb_contlog = $continent_config['aliaslog'];
@@ -1093,7 +1279,7 @@ function sync_package_pfblockerng($cron = "") {
"detail" => "DO NOT EDIT THIS ALIAS"
);
- #Create rule if action permits
+ // Create rule if action permits
switch ($continent_config['action']) {
case "Deny_Both":
case "Deny_Outbound":
@@ -1105,7 +1291,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 +1306,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 +1348,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 +1373,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,49 +1388,61 @@ 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;
break;
}
} else {
- #unlink continent list if any
+ // unlink continent list if any
unlink_if_exists($pfb['aliasdir'] . '/' . $pfb_alias . $vtype . '.txt');
}
}
}
}
- #mark pfctl aliastable for cleanup
+ // mark pfctl aliastable for cleanup
if (!in_array($pfb_alias, $aliases_list)) {
$aliases_list[] = "{$pfb_alias}{$vtype}";
}
}
}
- # UNSET variables
+ // UNSET variables
unset ($continent, $continent_existing, $continent_new);
#################################################
# Download and Collect IPv4/IPv6 lists #
#################################################
- # IPv4 REGEX Definitions
+ // 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]?)/';
- # IPv4 preg_replace Regex Filter array
+ // IPv4 preg_replace Regex Filter array
$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[4] = '/0\.0\.0\.0/'; # Remove 0.0.0.0
-
- # IPv6 REGEX Definitions -- ** Still Needs some Adjustment on Regex Definition for IPv6 **
- # https://mebsd.com/coding-snipits/php-regex-ipv6-with-preg_match.html
+ $pfb_ipreg[0] = '/\b0+(?=\d)/'; // Remove any Leading Zeros in each Octet
+ $pfb_ipreg[1] = '/\s/'; // Remove any Whitespaces
+ $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 **
+ // https://mebsd.com/coding-snipits/php-regex-ipv6-with-preg_match.html
$pattern1 = '([A-Fa-f0-9]{1,4}:){7}[A-Fa-f0-9]{1,4}';
$pattern2 = '[A-Fa-f0-9]{1,4}::([A-Fa-f0-9]{1,4}:){0,5}[A-Fa-f0-9]{1,4}';
$pattern3 = '([A-Fa-f0-9]{1,4}:){2}:([A-Fa-f0-9]{1,4}:){0,4}[A-Fa-f0-9]{1,4}';
@@ -1239,28 +1461,22 @@ function sync_package_pfblockerng($cron = "") {
if ($config['installedpackages'][$ip_type]['config'] != "") {
foreach ($config['installedpackages'][$ip_type]['config'] as $list) {
if ($list['action'] != "Disabled" && $pfb['enable'] == "on" && !$pfb['save'] && is_array($list['row'])) {
- # Capture Alias Name
+ // capture Alias Name
$alias = "pfB_" . preg_replace("/\W/","",$list['aliasname']);
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)) {
@@ -1269,33 +1485,35 @@ function sync_package_pfblockerng($cron = "") {
continue;
}
- # Collect Active Alias List (Used for pfctl Update when 'Reputation' is enabled.
+ // Collect Active Alias List (Used for pfctl Update when 'Reputation' is enabled.
$pfb_alias_lists_all[] = "{$alias}";
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);
+ }
}
}
@@ -1303,7 +1521,7 @@ function sync_package_pfblockerng($cron = "") {
if ($row['format'] == "gz" || $row['format'] == "gz_2") {
$file_dwn = "{$pfb['origdir']}/{$header_url}.gz";
if ($pfb['reuse'] == "on" && file_exists($file_dwn)) {
- # File Exists/Reuse
+ // File Exists/Reuse
} else {
$url_gz = "{$row['url']}";
$file_gz = @file_get_contents($url_gz);
@@ -1317,11 +1535,11 @@ function sync_package_pfblockerng($cron = "") {
$url_list = @gzfile($file_dwn);
}
- # IBlock Large Files mixed with IPs and Domains. PHP mem of 256M can't handle very large Files.
+ // IBlock Large Files mixed with IPs and Domains. PHP mem of 256M can't handle very large Files.
if ($row['format'] == "gz_lg") {
$file_dwn = "{$pfb['origdir']}/{$header_url}.gz";
if ($pfb['reuse'] == "on" && file_exists($file_dwn)) {
- # File Exists/Reuse
+ // File Exists/Reuse
} else {
$url_gz = "{$row['url']}";
$file_gz = @file_get_contents($url_gz);
@@ -1339,12 +1557,12 @@ function sync_package_pfblockerng($cron = "") {
elseif ($row['format'] == "zip") {
$file_dwn = "{$pfb['origdir']}/{$header_url}.zip";
if ($pfb['reuse'] == "on" && file_exists($file_dwn)) {
- # File Exists/Reuse
+ // File Exists/Reuse
} else {
$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);
@@ -1362,9 +1580,9 @@ function sync_package_pfblockerng($cron = "") {
elseif ($row['format'] == "et") {
$file_dwn = "{$pfb['origdir']}/{$header_url}.gz";
- # Script to Call ET IQRISK Process
+ // Script to Call ET IQRISK Process
if ($pfb['reuse'] == "on" && file_exists($file_dwn)) {
- # File Exists/Reuse
+ // File Exists/Reuse
} else {
$url_et = "{$row['url']}";
$file_et = @file_get_contents($url_et);
@@ -1381,9 +1599,9 @@ function sync_package_pfblockerng($cron = "") {
elseif ($row['format'] == "xlsx") {
$file_dwn = "{$pfb['origdir']}/{$header_url}.zip";
- # Script to Call XLSX Process
+ // Script to Call XLSX Process
if ($pfb['reuse'] == "on" && file_exists($file_dwn)) {
- # File Exists/Reuse
+ // File Exists/Reuse
} else {
$url_xlsx = "{$row['url']}";
$file_xlsx = @file_get_contents($url_xlsx);
@@ -1417,11 +1635,11 @@ function sync_package_pfblockerng($cron = "") {
elseif ($row['format'] == "html" || $row['format'] == "block") {
$file_dwn = "{$pfb['origdir']}/{$header_url}.raw";
if ($pfb['reuse'] == "on" && file_exists($file_dwn)) {
- # File Exists/Reuse
+ // File Exists/Reuse
$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);
@@ -1430,7 +1648,7 @@ function sync_package_pfblockerng($cron = "") {
elseif ($row['format'] == "rsync") {
$file_dwn = "{$pfb['origdir']}/{$header_url}.orig";
if ($pfb['reuse'] == "on" && file_exists($file_dwn)) {
- # File Exists/Reuse
+ // File Exists/Reuse
} else {
$url_rsync = "{$row['url']}";
exec ("/usr/local/bin/rsync --timeout=5 {$url_rsync} {$file_dwn}");
@@ -1438,13 +1656,13 @@ function sync_package_pfblockerng($cron = "") {
$url_list = @file($file_dwn);
}
- #extract range lists
+ // extract range lists
$new_file = "";
if (!empty($url_list)) {
if ($row['format'] == "gz" && $vtype == "_v4") {
foreach ($url_list as $line) {
if (!preg_match("/^#/", $line)) {
- # Network range 192.168.0.0-192.168.0.254
+ // 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)) {
@@ -1460,7 +1678,7 @@ function sync_package_pfblockerng($cron = "") {
elseif ($row['format'] == "block" && $vtype == "_v4") {
foreach ($url_list as $line) {
if (!preg_match("/^#/", $line)) {
- # Block Type '218.77.79.0 218.77.79.255 24'
+ // Block Type '218.77.79.0 218.77.79.255 24'
if (preg_match($pfb['block'],$line,$matches)) {
$new_file .= preg_replace($pfb_ipreg, '',$matches[0]) . "/24\n";
}
@@ -1471,11 +1689,11 @@ function sync_package_pfblockerng($cron = "") {
elseif ($row['format'] == "html" && $vtype == "_v4") {
foreach ($url_list as $line) {
if (!preg_match("/^#/", $line)) {
- # CIDR format 192.168.0.0/16
+ // 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
+ // Single ip addresses
elseif (preg_match($pfb['s_html'],$line,$matches)) {
$new_file .= preg_replace($pfb_ipreg, '',$matches[0]) . "\n";
}
@@ -1486,7 +1704,7 @@ function sync_package_pfblockerng($cron = "") {
elseif ($vtype == "_v6") {
foreach ($url_list as $line) {
if (!preg_match("/^#/", $line)) {
- # IPv6 Regex Match
+ // IPv6 Regex Match
if (preg_match($pfb['ipv6'],$line,$matches)) {
$new_file .= preg_replace($pfb_ipreg, '',$matches[0]) . "\n";
}
@@ -1497,11 +1715,20 @@ function sync_package_pfblockerng($cron = "") {
else {
foreach ($url_list as $line) {
if (!preg_match("/^#/", $line)) {
- # CIDR format 192.168.0.0/16
- if (preg_match($pfb['cidr'],$line,$matches)) {
+ // 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
+ elseif (preg_match($pfb['cidr'],$line,$matches)) {
$new_file .= preg_replace($pfb_ipreg, '',$matches[0]) . "\n";
}
- # Single ip addresses
+ // Single ip addresses
elseif (preg_match($pfb['single'],$line,$matches)) {
$new_file .= preg_replace($pfb_ipreg, '',$matches[0]) . "\n";
}
@@ -1510,17 +1737,18 @@ function sync_package_pfblockerng($cron = "") {
}
}
- # Check to see if Blocklist actually Failed Download or has no IPs listed.
+ // Check to see if Blocklist actually Failed Download or has no IPs listed.
if ($row['format'] == "html" || $row['format'] == "block") {
$url_chk = $file_dwn;
} else {
$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";
@@ -1531,41 +1759,42 @@ function sync_package_pfblockerng($cron = "") {
if ($new_file != "") {
if ($row['format'] == "gz" || $row['format'] == "gz_2" || $row['format'] == "html" || $row['format'] == "block") {
- # Re-Save these formats as original file
+ // Re-Save these formats as original file
$url_other = $new_file;
@file_put_contents($pfb['origdir'] . '/' . $header_url . '.orig',$url_other, LOCK_EX);
}
- # Save List to '.txt' format in appropriate Folder
+ // Save List to '.txt' format in appropriate Folder
@file_put_contents($pfbfolder . '/' .$header_url . '.txt',$new_file, LOCK_EX);
if ($pfb['rep'] == "on" && $pfb['skip'] && $vtype == "_v4") {
- # Script to Call p24 Process
+ // Script to Call p24 Process
exec ("{$pfb['script']} p24 {$header_url} {$pfb['max']} {$pfb['dedup']} {$pfb['ccexclude']} {$pfb['ccwhite']} {$pfb['ccblack']} >> {$pfb['log']} 2>&1");
}
if ($pfb['dup'] == "on" && $pfb['skip'] && $vtype == "_v4") {
- # Script to call Duplication Check Process
+ // Script to call Duplication Check Process
exec ("{$pfb['script']} duplicate {$header_url} >> {$pfb['log']} 2>&1");
}
- # PFCTL - Update Only Aliases that have been updated only.
+ // 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")
+ // Launch d-dup and p-dup functions when changes are found.
+ if ($pfb['skip'] && $vtype == "_v4") {
$pfb['dupcheck'] = TRUE;
- # Enable Suppression Process due to Updates
- if ($pfb['supp'] == "on" && $vtype == "_v4")
+ }
+ // Enable Suppression Process due to Updates
+ 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 FAILED Downloads and Check if Firewall or Snort/Suricata is Blocking Host
$log = "\n [ {$alias} {$header_url} ] Download FAIL [ NOW ]\n";
pfb_logger("{$log}","2");
- # Rebuild Previous List File from contents of Masterfile
+ // Rebuild Previous List File from contents of Masterfile
if ($pfb['skip'] && $vtype == "_v4") {
- # Search with trailing Whitespace to match exact Header in Masterfile
+ // Search with trailing Whitespace to match exact Header in Masterfile
$header_url2 = $header_url . "[[:space:]]";
$file_chk = exec ("/usr/bin/grep {$header_url2} {$pfb['master']} | grep -c ^");
@@ -1575,17 +1804,17 @@ function sync_package_pfblockerng($cron = "") {
exec ("/usr/bin/grep {$header_url2} {$pfb['master']} | cut -d' ' -f2 > {$pfbfolder}/{$header_url}.txt");
}
}
- # A "Space" string Variable
+ // A "Space" string Variable
$sp = " ";
$ip = @gethostbyname($host['host']);
$ip2 = preg_replace("/(\d{1,3})\.(\d{1,3}).(\d{1,3}).(\d{1,3})/", "\"^$1\.$2\.$3\.\"", $ip);
- # Only Perform these Checks if they are not "localfiles"
+ // Only Perform these Checks if they are not "localfiles"
if ($host['host'] == "127.0.0.1" || $host['host'] == $pfb['iplocal'] || empty($host['host'])) {
$log = " [ {$alias} {$header_url} ] Local File Failure \n";
pfb_logger("{$log}","2");
} else {
- # only perform these steps if an 'IP' is found.
+ // only perform these steps if an 'IP' is found.
if (!empty($ip)) {
// Query for Exact IP Match
$result_b1 = array();
@@ -1596,7 +1825,7 @@ function sync_package_pfblockerng($cron = "") {
// Query Snort/Suricata snort2c IP Block Table
$snort_pfb = exec("/sbin/pfctl -t snort2c -T show | grep {$ip}");
- # If an exact IP Match is not found report any First Three IP Octets.
+ // If an exact IP Match is not found report any First Three IP Octets.
if (!empty($result_b1)) {
$final_b1 = implode("\n ", $result_b1);
$log = " [ {$alias} {$header_url}, {$ip} ] Firewall IP Block Found in : \n{$sp}{$final_b1}\n";
@@ -1618,12 +1847,12 @@ function sync_package_pfblockerng($cron = "") {
}
}
}
- # UNSET variables
+ // UNSET variables
unset ($file_gz,$file_zip,$file_et,$file_xlsx,$url_other,$url_list);
}
}
}
- #check custom network list
+ // check custom network list
if (pfbng_text_area_decode($list['custom']) != "") {
if ($vtype == "_v4") {
@@ -1632,27 +1861,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.
+ // 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 +1886,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)) {
+ // 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) {
@@ -1680,8 +1895,16 @@ 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
+ // IPv6 Regex
if (preg_match($pfb['ipv6'],$line,$matches)) {
$new_file .= preg_replace($pfb_ipreg, '',$matches[0]) . "\n";
}
@@ -1690,19 +1913,20 @@ function sync_package_pfblockerng($cron = "") {
}
if ($new_file != "") {
- # PFCTL - Collect Only Aliases that have been updated only.
+ // PFCTL - Collect Only Aliases that have been updated only.
$pfb_alias_lists[] = "{$alias}";
- # Collect Updated lists for Suppression Process
+ // 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")
+ // Enable Suppression Process due to Updates
+ if ($pfb['supp'] == "on" && $vtype == "_v4") {
$pfb['supp_update'] = TRUE;
+ }
if ($pfb['rep'] == "on" && $pfb['skip'] && $vtype == "_v4") {
- # Script to Call p24 Process
+ // Script to Call p24 Process
exec ("{$pfb['script']} p24 {$aliascustom} {$pfb['max']} {$pfb['dedup']} {$pfb['ccexclude']} {$pfb['ccwhite']} {$pfb['ccblack']} >> {$pfb['log']} 2>&1");
}
if ($pfb['dup'] == "on" && $pfb['skip'] && $vtype == "_v4") {
- # Script to call Duplication Check Process
+ // Script to call Duplication Check Process
exec ("{$pfb['script']} duplicate {$aliascustom} >> {$pfb['log']} 2>&1");
}
} else {
@@ -1721,13 +1945,13 @@ function sync_package_pfblockerng($cron = "") {
# REPUTATION PROCESSES #
#################################
- # IP Reputation processes (pdup and ddup)
+ // IP Reputation processes (pdup and ddup)
if ($pfb['pdup'] == "on" && $pfb['dupcheck'] && !$pfb['save'] && $pfb['enable'] == "on") {
- # Script to run pdup process
+ // Script to run pdup process
exec ("{$pfb['script']} pdup x {$pfb['pmax']} >> {$pfb['log']} 2>&1");
}
if ($pfb['dedup'] == "on" && $pfb['dupcheck'] && !$pfb['save'] && $pfb['enable'] == "on") {
- # Script to run dedup process
+ // Script to run dedup process
exec ("{$pfb['script']} dedup x {$pfb['dmax']} {$pfb['dedup']} {$pfb['ccexclude']} {$pfb['ccwhite']} {$pfb['ccblack']} >> {$pfb['log']} 2>&1");
}
@@ -1739,28 +1963,33 @@ 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") {
- #remove empty lists files if any
+ // remove empty lists files if any
if (is_array($list['row'])) {
$update = 0;
${$alias} = "";
@@ -1773,20 +2002,20 @@ function sync_package_pfblockerng($cron = "") {
}
$pfctlck = exec ("/sbin/pfctl -vvsTables | grep -A1 {$alias} | awk '/Addresses/ {s+=$2}; END {print s}'");
- # Update Alias if List File Exists and its been updated or if the Alias URL Table is Empty.
+ // Update Alias if List File Exists and its been updated or if the Alias URL Table is Empty.
if (file_exists($pfbfolder . "/" . $header_url . ".txt") && in_array($alias, $final_alias) || file_exists($pfbfolder . "/" . $header_url . ".txt") && empty($pfctlck)) {
- # Script to run Suppression process (Print Header Only)
+ // Script to run Suppression process (Print Header Only)
if ($pfb['supp'] == "on" && $vtype == "_v4" && $runonce == 0 && $pfb['supp_update']) {
exec ("{$pfb['script']} suppress x x x suppressheader >> {$pfb['log']} 2>&1");
$runonce++;
}
- # Script to run Suppression Process (Body)
+ // Script to run Suppression Process (Body)
if ($pfb['supp'] == "on" && $vtype == "_v4" && $pfb['supp_update']) {
if ($pfb['dup'] == "on" || !$pfb['skip']) {
- # Execute if Duplication Process is Enabled or List is Permit or Match
+ // Execute if Duplication Process is Enabled or List is Permit or Match
exec ("{$pfb['script']} suppress x x x {$header_url}\|{$pfbfolder}/ >> {$pfb['log']} 2>&1");
} else {
- # Execute if Duplication Process is Disabled
+ // Execute if Duplication Process is Disabled
exec ("{$pfb['script']} suppress x x off {$header_url}\|{$pfbfolder}/ >> {$pfb['log']} 2>&1");
}
}
@@ -1797,14 +2026,14 @@ function sync_package_pfblockerng($cron = "") {
}
}
- #check custom network list
+ // check custom network list
if ($vtype == "_v4") {
$aliasname = "{$list['aliasname']}_custom";
} else {
$aliasname = "{$list['aliasname']}_custom_v6";
}
- # Update Alias if List File Exists and its been updated or if the Alias URL Table is Empty.
+ // Update Alias if List File Exists and its been updated or if the Alias URL Table is Empty.
$pfctlck = exec ("/sbin/pfctl -vvsTables | grep -A1 {$alias} | awk '/Addresses/ {s+=$2}; END {print s}'");
if (pfbng_text_area_decode($list['custom']) != "") {
@@ -1813,7 +2042,7 @@ function sync_package_pfblockerng($cron = "") {
$update++;
}
}
- # Determine Validity of Alias URL Tables/Rules. ie: Don't create Empty URL Tables or Aliases
+ // Determine Validity of Alias URL Tables/Rules. ie: Don't create Empty URL Tables or Aliases
if (${$alias} == "" && empty($pfctlck)) {
unlink_if_exists($pfb['aliasdir'] . '/' . $alias. '.txt');
} else {
@@ -1823,7 +2052,7 @@ function sync_package_pfblockerng($cron = "") {
}
$alias_log = $list['aliaslog'];
- #create alias
+ // create alias
$new_aliases_list[] = "{$alias}";
$new_aliases[] = array( "name" => "{$alias}",
@@ -1835,7 +2064,7 @@ function sync_package_pfblockerng($cron = "") {
"detail" => "DO NOT EDIT THIS ALIAS"
);
- #Create rule if action permits
+ // Create rule if action permits
switch ($list['action']) {
case "Deny_Both":
case "Deny_Outbound":
@@ -1862,7 +2091,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 +2133,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,25 +2173,37 @@ 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;
break;
}
}
- #mark pfctl aliastable for cleanup
+ // mark pfctl aliastable for cleanup
if (!in_array($alias, $aliases_list)) {
$aliases_list[] = "{$alias}";
}
} else {
- #unlink previous pfblockerNG alias list if any
+ // unlink previous pfblockerNG alias list if any
unlink_if_exists($pfb['aliasdir'] . '/' . $alias . '.txt');
}
}
}
}
- # Clear Variables
+ // Clear Variables
${$alias} = "";
@@ -1946,38 +2211,39 @@ function sync_package_pfblockerng($cron = "") {
# UPDATE pfSense ALIAS TABLES #
#########################################
- #update pfsense alias table
+ // update pfsense alias table
if (is_array($config['aliases']['alias'])) {
foreach ($config['aliases']['alias'] as $cbalias) {
- if (preg_match("/pfB_/",$cbalias['name'])) {
- #mark pfctl aliastable for cleaning
+ 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
+ $aliases_list[] = $cbalias['name']; // mark aliastable for cleaning
}
- #remove previous aliastable file if alias is not defined any more
+ // remove previous aliastable file if alias is not defined any more
if (!in_array($cbalias['name'], $new_aliases_list)) {
unlink_if_exists($pfb['aliasdir'] . '/' . $cbalias['name'] . ".txt");
}
} else {
$new_aliases[] = $cbalias;
- # Check Table Size
+ // Check Table Size
if (file_exists($pfb['aliasdir'] . '/' . $alias . '.txt') && $message == "") {
preg_match("/(\d+)/",exec("/usr/bin/grep -c ^ " . $pfb['aliasdir'] . '/' . $alias . '.txt'),$matches);
}
if (($matches[1] * 2.1) >= $pfb['table_limit']) {
- #alias table too large
+ // alias table too large
$message = "{$alias} alias table is too large. Reduce networks in list or increase 'Firewall Maximum Table Entries' value to at least " . (int)($matches[1] * 2.1) . ' in "system - advanced - Firewall/NAT" . ';
}
}
}
}
- #apply new alias table to xml
+ // apply new alias table to xml
if ($message == "") {
$config['aliases']['alias'] = $new_aliases;
+ $pfb['cron_mod'] = TRUE;
}
- # UNSET Variables
+ // UNSET Variables
unset($new_aliases, $cbalias);
@@ -1985,7 +2251,7 @@ function sync_package_pfblockerng($cron = "") {
# Assign Rules #
#########################
- # Only Execute if AutoRules are defined or if an Alias has been removed.
+ // Only Execute if AutoRules are defined or if an Alias has been removed.
if ($pfb['autorules'] || $pfb['enable'] == "" || $pfb['remove']) {
if (count($deny_inbound) > 0 || count($permit_inbound) > 0 || count($match_inbound) > 0) {
if ($pfb['inbound_interfaces'] == "") {
@@ -2007,9 +2273,9 @@ function sync_package_pfblockerng($cron = "") {
$fmatch_rules = array();
$fother_rules = array();
- # Collect All Existing Rules
+ // Collect All Existing Rules
$rules = $config['filter']['rule'];
- # Collect Existing pfSense Rules 'Pass', 'Match' and 'Other' pfSense rules into new Arrays.
+ // Collect Existing pfSense Rules 'Pass', 'Match' and 'Other' pfSense rules into new Arrays.
if (!empty($rules)) {
foreach ($rules as $rule) {
if (!preg_match("/pfB_.*" . $pfb['suffix'] . "/",$rule['descr'])) {
@@ -2083,7 +2349,7 @@ function sync_package_pfblockerng($cron = "") {
}
}
- # Define Inbound Interface Rules
+ // Define Inbound Interface Rules
if (!empty($pfb['inbound_interfaces'])) {
$counter = 0;
foreach ($pfb['inbound_interfaces'] as $inbound_interface) {
@@ -2099,7 +2365,7 @@ function sync_package_pfblockerng($cron = "") {
$new_rules[] = $cb_rules;
}
}
- # Match Inbound Rules defined as Floating Only.
+ // Match Inbound Rules defined as Floating Only.
if (!empty($match_inbound) && $counter == 0) {
foreach ($match_inbound as $cb_rules) {
$cb_rules['interface'] = $pfb['inbound_floating'];
@@ -2144,7 +2410,7 @@ function sync_package_pfblockerng($cron = "") {
}
}
- # Define Outbound Interface Rules
+ // Define Outbound Interface Rules
if (!empty($pfb['outbound_interfaces'])) {
$counter = 0;
foreach ($pfb['outbound_interfaces'] as $outbound_interface) {
@@ -2160,7 +2426,7 @@ function sync_package_pfblockerng($cron = "") {
$new_rules[] = $cb_rules;
}
}
- # Match Outbound Rules defined as Floating Only.
+ // Match Outbound Rules defined as Floating Only.
if (!empty($match_outbound) && $counter == 0) {
foreach ($match_outbound as $cb_rules) {
$cb_rules['interface'] = $pfb['outbound_floating'];
@@ -2238,30 +2504,29 @@ function sync_package_pfblockerng($cron = "") {
}
}
- # Save New Rule Order to Config
+ // 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 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 '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,79 +2534,88 @@ 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");
}
- # Remove all pfBlockerNG Alias tables
+ // Remove all pfBlockerNG Alias tables
if (!empty($aliases_list)) {
foreach ($aliases_list as $table) {
exec ("/sbin/pfctl -t " . escapeshellarg($table) . " -T kill 2>&1", $pfb_null);
}
}
- #load filter file which will create the pfctl tables
+ // load filter file which will create the pfctl tables
filter_configure();
// Call function for NanoBSD/Ramdisk processes.
pfb_aliastables("update");
} else {
- # Don't Execute on User 'Save'
+ // 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");
}
}
}
- # UNSET Variables
+ // UNSET Variables
unset($rules, $new_rules);
- #sync config
+ // sync config
pfblockerng_sync_on_changes();
+
#################################
# FINAL REPORTING #
#################################
- # Only run with CRON or Force Invoked Process
+ // Only run with CRON or Force Invoked Process
if ((!$pfb['save'] && $pfb['dupcheck'] && $pfb['enable'] == "on") || $pfb['summary']) {
- # Script to run Final Script Processes.
+ // Script to run Final Script Processes.
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 +2624,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 +2665,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, 'maxmind')) {
+ 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.";
+ }
}
}
}
@@ -2422,9 +2733,10 @@ function pfblockerng_php_install_command() {
// Remove previously used CC folder location if exists
@rmdir_recursive("{$pfb['dbdir']}/cc");
- # Uncompress Country Code File
- exec("/usr/bin/tar -jx -C {$pfb['ccdir']} -f {$pfb['dbdir']}/countrycodes.tar.bz2");
- # Download MaxMind Files and Create Country Code files and Build Continent XML Files
+ // Uncompress Country Code File
+ @copy("{$pfb['dbdir']}/countrycodes.tar.bz2", "{$pfb['ccdir']}/countrycodes.tar.bz2");
+ exec("/usr/bin/tar -jx -C {$pfb['ccdir']} -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");
@@ -2441,7 +2753,7 @@ function pfblockerng_php_install_command() {
@unlink_if_exists("{$pfb['dbdir']}/GeoIPv6.csv");
@unlink_if_exists("{$pfb['dbdir']}/country_continent.csv");
- # Add Widget to Dashboard
+ // Add Widget to Dashboard
update_output_window(gettext("Adding pfBlockerNG Widget to Dashboard."));
if ($pfb['keep'] == "on" && !empty($pfb['widgets'])) {
// Restore previous Widget setting if "Keep" is enabled.
@@ -2463,16 +2775,16 @@ function pfblockerng_php_deinstall_command() {
require_once("config.inc");
global $config,$pfb;
- # Set these two variables to Disable pfBlockerNG on De-Install
+ // Set these two variables to Disable pfBlockerNG on De-Install
$pfb['save'] = TRUE;
$pfb['install'] = TRUE;
sync_package_pfblockerng();
rmdir_recursive("/usr/local/pkg/pfblockerng");
rmdir_recursive("/usr/local/www/pfblockerng");
- # Maintain pfBlockerNG Settings and Database Files if $pfb['keep'] is ON.
+ // Maintain pfBlockerNG Settings and Database Files if $pfb['keep'] is ON.
if ($pfb['keep'] != "on") {
- # Remove pfBlockerNG Log and DB Folder
+ // Remove pfBlockerNG Log and DB Folder
rmdir_recursive("{$pfb['dbdir']}");
rmdir_recursive("{$pfb['logdir']}");
@@ -2485,7 +2797,7 @@ function pfblockerng_php_deinstall_command() {
}
}
- # Remove Settings from Config
+ // Remove Settings from Config
if (is_array($config['installedpackages']['pfblockerng']))
unset($config['installedpackages']['pfblockerng']);
if (is_array($config['installedpackages']['pfblockerngglobal']))
@@ -2518,14 +2830,13 @@ function pfblockerng_php_deinstall_command() {
unset($config['installedpackages']['pfblockerngproxyandsatellite']);
}
- # Remove Widget (code from Snort deinstall)
+ // Remove Widget (code from Snort deinstall)
$pfb['widgets'] = $config['widgets']['sequence'];
if (!empty($pfb['widgets'])) {
$widgetlist = explode(",", $pfb['widgets']);
foreach ($widgetlist as $key => $widget) {
if (strstr($widget, "pfblockerng-container")) {
unset($widgetlist[$key]);
- break;
}
}
$config['widgets']['sequence'] = implode(",", $widgetlist);
@@ -2540,9 +2851,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 +2864,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 +2886,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 +2916,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 +2951,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 +2968,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 +3030,4 @@ function pfblockerng_do_xmlrpc_sync($sync_to_ip, $port, $protocol, $username, $p
}
return $success;
}
-?>
+?> \ No newline at end of file