summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--etc/inc/filter.inc1858
-rw-r--r--etc/inc/filter_log.inc187
-rw-r--r--etc/inc/functions.inc189
-rw-r--r--etc/inc/globals.inc120
-rw-r--r--etc/inc/gmirror.inc59
-rw-r--r--etc/inc/growl.class162
-rw-r--r--etc/inc/gwlb.inc417
7 files changed, 1742 insertions, 1250 deletions
diff --git a/etc/inc/filter.inc b/etc/inc/filter.inc
index 6efb5da..3e3fb25 100644
--- a/etc/inc/filter.inc
+++ b/etc/inc/filter.inc
@@ -5,7 +5,7 @@
Copyright (C) 2004-2006 Scott Ullrich
Copyright (C) 2005 Bill Marquette
Copyright (C) 2006 Peter Allgeyer
- Copyright (C) 2008-2010 Ermal Luci
+ Copyright (C) 2008-2010 Ermal Luci
All rights reserved.
originally part of m0n0wall (http://m0n0.ch/wall)
@@ -52,7 +52,7 @@ $FilterIflist = array();
$GatewaysList = array();
/* Used for the hostname dns resolver */
-$filterdns = array();
+$filterdns = array();
/* Used for aliases and interface macros */
$aliases = "";
@@ -130,10 +130,11 @@ function filter_rule_tracker($tracker) {
function fix_rule_label($descr) {
$descr = str_replace('"', '', $descr);
- if (strlen($descr) > 63)
+ if (strlen($descr) > 63) {
return substr($descr, 0, 60) . "...";
- else
+ } else {
return $descr;
+ }
}
function is_bogonsv6_used() {
@@ -142,7 +143,7 @@ function is_bogonsv6_used() {
$usebogonsv6 = false;
if (isset($config['system']['ipv6allow'])) {
foreach ($config['interfaces'] as $ifacedata) {
- if(isset($ifacedata['enable']) && isset($ifacedata['blockbogons'])) {
+ if (isset($ifacedata['enable']) && isset($ifacedata['blockbogons'])) {
$usebogonsv6 = true;
break;
}
@@ -153,22 +154,24 @@ function is_bogonsv6_used() {
function filter_pflog_start($kill_first = false) {
global $config, $g;
- if ($g['platform'] == 'jail')
+ if ($g['platform'] == 'jail') {
return;
- if(isset($config['system']['developerspew'])) {
+ }
+ if (isset($config['system']['developerspew'])) {
$mt = microtime();
echo "filter_pflog_start() being called $mt\n";
}
- if (!file_exists("{$g['varrun_path']}/filterlog.pid") ||
- !isvalidpid("{$g['varrun_path']}/filterlog.pid"))
+ if ((!file_exists("{$g['varrun_path']}/filterlog.pid")) ||
+ (!isvalidpid("{$g['varrun_path']}/filterlog.pid"))) {
mwexec("/usr/local/sbin/filterlog -i pflog0 -p {$g['varrun_path']}/filterlog.pid");
+ }
}
/* reload filter async */
function filter_configure() {
global $g;
- if(isset($config['system']['developerspew'])) {
+ if (isset($config['system']['developerspew'])) {
$mt = microtime();
echo "filter_configure() being called $mt\n";
}
@@ -177,28 +180,34 @@ function filter_configure() {
* NOTE: Check here for bootup status since this should not be triggered during bootup.
* The reason is that rc.bootup calls filter_configure_sync directly which does this too.
*/
- if (!platform_booting())
+ if (!platform_booting()) {
send_event("filter reload");
+ }
}
function filter_delete_states_for_down_gateways() {
global $config, $GatewaysList;
- if (isset($config['system']['kill_states']))
+ if (isset($config['system']['kill_states'])) {
return;
+ }
$any_gateway_down = false;
$a_gateways = return_gateways_status();
if (is_array($GatewaysList)) {
foreach ($GatewaysList as $gwname => $gateway) {
- if (empty($gateway['monitor']))
+ if (empty($gateway['monitor'])) {
continue;
- if (!is_ipaddr($gateway['monitor']))
+ }
+ if (!is_ipaddr($gateway['monitor'])) {
continue;
- if (strstr($gateway['monitor'], "127.0.0."))
+ }
+ if (strstr($gateway['monitor'], "127.0.0.")) {
continue;
- if (empty($a_gateways[$gateway['monitor']]))
+ }
+ if (empty($a_gateways[$gateway['monitor']])) {
continue;
+ }
$gwstatus =& $a_gateways[$gateway['monitor']];
if (strstr($gwstatus['status'], "down")) {
$any_gateway_down = true;
@@ -206,8 +215,9 @@ function filter_delete_states_for_down_gateways() {
}
}
}
- if ($any_gateway_down == true)
+ if ($any_gateway_down == true) {
mwexec("/sbin/pfctl -Fs");
+ }
}
/* reload filter sync */
@@ -218,81 +228,90 @@ function filter_configure_sync($delete_states_if_needed = true) {
/* Use filter lock to not allow concurrent filter reloads during this run. */
$filterlck = lock('filter', LOCK_EX);
-
filter_pflog_start();
update_filter_reload_status(gettext("Initializing"));
/* invalidate interface cache */
get_interface_arr(true);
- if(isset($config['system']['developerspew'])) {
+ if (isset($config['system']['developerspew'])) {
$mt = microtime();
echo "filter_configure_sync() being called $mt\n";
}
/* Get interface list to work with. */
filter_generate_optcfg_array();
- if(platform_booting() == true)
+ if (platform_booting() == true) {
echo gettext("Configuring firewall");
+ }
/* generate aliases */
- if(platform_booting() == true)
+ if (platform_booting() == true) {
echo ".";
+ }
update_filter_reload_status(gettext("Creating aliases"));
$aliases = filter_generate_aliases();
$gateways = filter_generate_gateways();
- if(platform_booting() == true)
+ if (platform_booting() == true) {
echo ".";
+ }
update_filter_reload_status(gettext("Generating Limiter rules"));
$dummynet_rules = filter_generate_dummynet_rules();
$dummynet_name_list = get_unique_dnqueue_list();
update_filter_reload_status(gettext("Generating NAT rules"));
/* generate nat rules */
$natrules = filter_nat_rules_generate();
- if(platform_booting() == true)
+ if (platform_booting() == true) {
echo ".";
+ }
update_filter_reload_status(gettext("Generating filter rules"));
/* generate pfctl rules */
$pfrules = filter_rules_generate();
/* generate altq, limiter */
- if(platform_booting() == true)
+ if (platform_booting() == true) {
echo ".";
+ }
update_filter_reload_status(gettext("Generating ALTQ queues"));
$altq_queues = filter_generate_altq_queues();
update_filter_reload_status(gettext("Generating Layer7 rules"));
generate_layer7_files();
- if(platform_booting() == true)
+ if (platform_booting() == true) {
echo ".";
+ }
update_filter_reload_status(gettext("Loading filter rules"));
/* enable pf if we need to, otherwise disable */
- if(!isset ($config['system']['disablefilter'])) {
+ if (!isset ($config['system']['disablefilter'])) {
mwexec("/sbin/pfctl -e", true);
} else {
mwexec("/sbin/pfctl -d", true);
unlink_if_exists("{$g['tmp_path']}/filter_loading");
update_filter_reload_status(gettext("Filter is disabled. Not loading rules."));
- if(platform_booting() == true)
+ if (platform_booting() == true) {
echo gettext("done.") . "\n";
+ }
unlock($filterlck);
return;
}
$limitrules = "";
/* User defined maximum table entries in Advanced menu. */
- if ($config['system']['maximumtableentries'] <> "" && is_numeric($config['system']['maximumtableentries']))
+ if ($config['system']['maximumtableentries'] <> "" && is_numeric($config['system']['maximumtableentries'])) {
$limitrules .= "set limit table-entries {$config['system']['maximumtableentries']}\n";
+ }
if ($config['system']['optimization'] <> "") {
$limitrules .= "set optimization {$config['system']['optimization']}\n";
- if($config['system']['optimization'] == "conservative") {
+ if ($config['system']['optimization'] == "conservative") {
$limitrules .= "set timeout { udp.first 300, udp.single 150, udp.multiple 900 }\n";
}
- } else
+ } else {
$limitrules .= "set optimization normal\n";
+ }
- if (!empty($config['system']['adaptivestart']) && !empty($config['system']['adaptiveend']))
+ if (!empty($config['system']['adaptivestart']) && !empty($config['system']['adaptiveend'])) {
$limitrules .= "set timeout { adaptive.start {$config['system']['adaptivestart']}, adaptive.end {$config['system']['adaptiveend']} }\n";
- else
+ } else {
$limitrules .= "set timeout { adaptive.start 0, adaptive.end 0 }\n";
+ }
if ($config['system']['maximumstates'] <> "" && is_numeric($config['system']['maximumstates'])) {
/* User defined maximum states in Advanced menu. */
@@ -304,8 +323,9 @@ function filter_configure_sync($delete_states_if_needed = true) {
$limitrules .= "set limit src-nodes {$max_states}\n";
}
- if (isset($config['system']['lb_use_sticky']) && is_numeric($config['system']['srctrack']) && ($config['system']['srctrack'] > 0))
+ if (isset($config['system']['lb_use_sticky']) && is_numeric($config['system']['srctrack']) && ($config['system']['srctrack'] > 0)) {
$limitrules .= "set timeout src.track {$config['system']['srctrack']}\n";
+ }
$rules = "";
$rules = "{$limitrules}\n";
@@ -327,8 +347,9 @@ function filter_configure_sync($delete_states_if_needed = true) {
unset($aliases, $gateways, $altq_queues, $natrules, $pfrules);
// Copy rules.debug to rules.debug.old
- if(file_exists("{$g['tmp_path']}/rules.debug"))
+ if (file_exists("{$g['tmp_path']}/rules.debug")) {
@copy("{$g['tmp_path']}/rules.debug", "{$g['tmp_path']}/rules.debug.old");
+ }
if (!@file_put_contents("{$g['tmp_path']}/rules.debug", $rules, LOCK_EX)) {
log_error("WARNING: Could not write new rules!");
@@ -340,13 +361,13 @@ function filter_configure_sync($delete_states_if_needed = true) {
mwexec("/sbin/pfctl -Of {$g['tmp_path']}/rules.limits");
unset($rules, $limitrules);
- if(isset($config['system']['developerspew'])) {
+ if (isset($config['system']['developerspew'])) {
$mt = microtime();
echo "pfctl being called at $mt\n";
}
unset($rules_loading, $rules_error);
$_grbg = exec("/sbin/pfctl -o basic -f {$g['tmp_path']}/rules.debug 2>&1", $rules_error, $rules_loading);
- if(isset($config['system']['developerspew'])) {
+ if (isset($config['system']['developerspew'])) {
$mt = microtime();
echo "pfctl done at $mt\n";
}
@@ -354,13 +375,14 @@ function filter_configure_sync($delete_states_if_needed = true) {
* check for a error while loading the rules file. if an error has occurred
* then output the contents of the error to the caller
*/
- if($rules_loading <> 0) {
+ if ($rules_loading <> 0) {
$saved_line_error = $rules_error[0];
$line_error = explode(":", $rules_error[0]);
$line_number = $line_error[1];
$line_split = file("{$g['tmp_path']}/rules.debug");
- if(is_array($line_split))
+ if (is_array($line_split)) {
$line_error = sprintf(gettext('The line in question reads [%1$d]: %2$s'), $line_number, $line_split[$line_number-1]);
+ }
unset($line_split);
/* Brutal ugly hack but required -- PF is stuck, unwedge */
@@ -382,26 +404,28 @@ function filter_configure_sync($delete_states_if_needed = true) {
}
# If we are not using bogonsv6 then we can remove any bogonsv6 table from the running pf (if the table is not there, the kill is still fine).
- if (!is_bogonsv6_used())
+ if (!is_bogonsv6_used()) {
$_grbg = exec("/sbin/pfctl -t bogonsv6 -T kill 2>/dev/null");
+ }
update_filter_reload_status(gettext("Starting up layer7 daemon"));
layer7_start_l7daemon();
- if(!empty($filterdns)) {
+ if (!empty($filterdns)) {
@file_put_contents("{$g['varetc_path']}/filterdns.conf", implode("", $filterdns));
unset($filterdns);
- if (isvalidpid("{$g['varrun_path']}/filterdns.pid"))
+ if (isvalidpid("{$g['varrun_path']}/filterdns.pid")) {
sigkillbypid("{$g['varrun_path']}/filterdns.pid", "HUP");
- else {
+ } else {
/*
* FilterDNS has three debugging levels. The default chosen is 1.
* Available are level 2 and greater then 2.
*/
- if (isset($config['system']['aliasesresolveinterval']) && is_numeric($config['system']['aliasesresolveinterval']))
+ if (isset($config['system']['aliasesresolveinterval']) && is_numeric($config['system']['aliasesresolveinterval'])) {
$resolve_interval = $config['system']['aliasesresolveinterval'];
- else
+ } else {
$resolve_interval = 300;
+ }
mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns.pid -i {$resolve_interval} -c {$g['varetc_path']}/filterdns.conf -d 1");
}
} else {
@@ -411,10 +435,11 @@ function filter_configure_sync($delete_states_if_needed = true) {
/* run items scheduled for after filter configure run */
$fda = fopen("{$g['tmp_path']}/commands.txt", "w");
- if($fda) {
- if($after_filter_configure_run) {
- foreach($after_filter_configure_run as $afcr)
+ if ($fda) {
+ if ($after_filter_configure_run) {
+ foreach ($after_filter_configure_run as $afcr) {
fwrite($fda, $afcr . "\n");
+ }
unset($after_filter_configure_run);
}
@@ -423,34 +448,37 @@ function filter_configure_sync($delete_states_if_needed = true) {
* filter_configure() call. run this xml command after
* each change.
*/
- if($config['system']['afterfilterchangeshellcmd'] <> "")
+ if ($config['system']['afterfilterchangeshellcmd'] <> "") {
fwrite($fda, $config['system']['afterfilterchangeshellcmd'] . "\n");
+ }
fclose($fda);
}
- if(file_exists("{$g['tmp_path']}/commands.txt")) {
+ if (file_exists("{$g['tmp_path']}/commands.txt")) {
mwexec("sh {$g['tmp_path']}/commands.txt &");
unlink("{$g['tmp_path']}/commands.txt");
}
/* if time based rules are enabled then swap in the set */
- if($time_based_rules == true)
+ if ($time_based_rules == true) {
filter_tdr_install_cron(true);
- else
+ } else {
filter_tdr_install_cron(false);
+ }
- if(platform_booting() == true)
+ if (platform_booting() == true) {
echo ".";
+ }
- if($delete_states_if_needed) {
+ if ($delete_states_if_needed) {
update_filter_reload_status(gettext("Processing down interface states"));
filter_delete_states_for_down_gateways();
}
update_filter_reload_status(gettext("Running plugins"));
- if(is_dir("/usr/local/pkg/pf/")) {
+ if (is_dir("/usr/local/pkg/pf/")) {
/* process packager manager custom rules */
update_filter_reload_status(gettext("Running plugins (pf)"));
run_plugins("/usr/local/pkg/pf/");
@@ -458,8 +486,9 @@ function filter_configure_sync($delete_states_if_needed = true) {
}
update_filter_reload_status(gettext("Done"));
- if(platform_booting() == true)
+ if (platform_booting() == true) {
echo gettext("done.") . "\n";
+ }
unlock($filterlck);
return 0;
@@ -471,35 +500,44 @@ function filter_generate_scrubing() {
if (isset($config['system']['maxmss_enable'])) {
$maxmss = 1400;
- if (!empty($config['system']['maxmss']))
+ if (!empty($config['system']['maxmss'])) {
$maxmss = $config['system']['maxmss'];
+ }
$scrubrules .= "scrub from any to <vpn_networks> max-mss {$maxmss}\n";
$scrubrules .= "scrub from <vpn_networks> to any max-mss {$maxmss}\n";
}
/* disable scrub option */
foreach ($FilterIflist as $scrubif => $scrubcfg) {
- if(isset($scrubcfg['virtual']) || empty($scrubcfg['descr']))
+ if (isset($scrubcfg['virtual']) || empty($scrubcfg['descr'])) {
continue;
+ }
/* set up MSS clamping */
- if($scrubcfg['mss'] <> "" && is_numeric($scrubcfg['mss']) && $scrubcfg['if'] != "pppoe" && $scrubcfg['if'] != "pptp" &&
- $scrubif['if'] != "l2tp")
+ if (($scrubcfg['mss'] <> "") &&
+ (is_numeric($scrubcfg['mss'])) &&
+ ($scrubcfg['if'] != "pppoe") &&
+ ($scrubcfg['if'] != "pptp") &&
+ ($scrubif['if'] != "l2tp")) {
$mssclamp = "max-mss " . (intval($scrubcfg['mss'] - 40));
- else
+ } else {
$mssclamp = "";
+ }
/* configure no-df for linux nfs and others */
- if($config['system']['scrubnodf'])
+ if ($config['system']['scrubnodf']) {
$scrubnodf = "no-df";
- else
+ } else {
$scrubnodf = "";
- if($config['system']['scrubrnid'])
+ }
+ if ($config['system']['scrubrnid']) {
$scrubrnid = "random-id";
- else
+ } else {
$scrubrnid = "";
- if(!isset($config['system']['disablescrub']))
+ }
+ if (!isset($config['system']['disablescrub'])) {
$scrubrules .= "scrub on \${$scrubcfg['descr']} all {$scrubnodf} {$scrubrnid} {$mssclamp} fragment reassemble\n"; // reassemble all directions
- else if(!empty($mssclamp))
+ } else if (!empty($mssclamp)) {
$scrubrules .= "scrub on \${$scrubcfg['descr']} {$mssclamp}\n";
+ }
}
return $scrubrules;
}
@@ -514,17 +552,18 @@ function filter_generate_nested_alias($name, $alias, &$aliasnesting, &$aliasaddr
$urltable_nesting = "";
$aliasnesting[$name] = $name;
foreach ($addresses as $address) {
- if (empty($address))
+ if (empty($address)) {
continue;
+ }
$linelength = strlen($builtlist);
$tmpline = "";
- if(is_alias($address)) {
+ if (is_alias($address)) {
if (alias_get_type($address) == 'urltable') {
// Feature#1603. For this type of alias we do not need to recursively call filter_generate_nested_alias. Just load IPs from the file.
$urltable_netsting = alias_expand_urltable($address);
if (!empty($urltable_nesting)) {
$urlfile_as_arr = file($urltable_nesting);
- foreach($urlfile_as_arr as $line) {
+ foreach ($urlfile_as_arr as $line) {
$address= rtrim($line);
if ((strlen($tmpline) + $linelength) > 4036) {
$finallist .= "{$tmpline} \\\n";
@@ -535,9 +574,10 @@ function filter_generate_nested_alias($name, $alias, &$aliasnesting, &$aliasaddr
}
}
/* We already expanded this alias so there is no necessity to do it again. */
- else if(!isset($aliasnesting[$address]))
+ else if (!isset($aliasnesting[$address])) {
$tmpline = filter_generate_nested_alias($name, $aliastable[$address], $aliasnesting, $aliasaddrnesting);
- } else if(!isset($aliasaddrnesting[$address])) {
+ }
+ } else if (!isset($aliasaddrnesting[$address])) {
if (!is_ipaddr($address) && !is_subnet($address) && !is_port($address) && !is_portrange($address) && is_hostname($address)) {
if (!isset($filterdns["{$address}{$name}"])) {
$use_filterdns = true;
@@ -552,17 +592,20 @@ function filter_generate_nested_alias($name, $alias, &$aliasnesting, &$aliasaddr
$finallist .= "{$builtlist} \\\n";
$builtlist = "";
}
- if (!empty($tmpline))
+ if (!empty($tmpline)) {
$builtlist .= " {$tmpline}";
+ }
}
$finallist .= $builtlist;
if ($use_filterdns === true && !empty($finallist)) {
foreach (explode(" ", $finallist) as $address) {
- if (empty($address))
+ if (empty($address)) {
continue;
- if ((is_ipaddr($address) || is_subnet($address)) && !isset($filterdns["{$address}{$name}"]))
+ }
+ if ((is_ipaddr($address) || is_subnet($address)) && !isset($filterdns["{$address}{$name}"])) {
$filterdns["{$address}{$name}"] = "pf {$address} {$name}\n";
+ }
}
$finallist = '';
}
@@ -574,9 +617,9 @@ function filter_expand_alias($alias_name)
{
global $config;
- if(isset($config['aliases']['alias'])) {
+ if (isset($config['aliases']['alias'])) {
foreach ($config['aliases']['alias'] as $aliased) {
- if($aliased['name'] == $alias_name) {
+ if ($aliased['name'] == $alias_name) {
$aliasnesting = array();
$aliasaddrnesting = array();
return filter_generate_nested_alias($aliased['name'], $aliased['address'], $aliasnesting, $aliasaddrnesting);
@@ -593,7 +636,7 @@ function filter_expand_alias_array($alias_name) {
function filter_generate_aliases() {
global $config, $FilterIflist, $after_filter_configure_run;
- if(isset($config['system']['developerspew'])) {
+ if (isset($config['system']['developerspew'])) {
$mt = microtime();
echo "filter_generate_aliases() being called $mt\n";
}
@@ -608,11 +651,11 @@ function filter_generate_aliases() {
$aliases .= " }\"\n";
}
} elseif (!empty($ifcfg['descr']) && !empty($ifcfg['if'])) {
- if ($ifcfg['type6'] == '6rd')
+ if ($ifcfg['type6'] == '6rd') {
$aliases .= "{$ifcfg['descr']} = \"{ {$ifcfg['if']} {$if}_stf";
- else if ($ifcfg['type6'] == '6to4')
+ } else if ($ifcfg['type6'] == '6to4') {
$aliases .= "{$ifcfg['descr']} = \"{ {$ifcfg['if']} {$if}_stf";
- else {
+ } else {
$aliases .= "{$ifcfg['descr']} = \"{ {$ifcfg['if']}";
if ($ifcfg['type'] == 'pptp') {
@@ -634,27 +677,32 @@ function filter_generate_aliases() {
$aliases .= "#Snort tables\n";
$aliases .= "table <snort2c>\n";
$aliases .= "table <virusprot>\n";
- if (!file_exists("/etc/bogons"))
+ if (!file_exists("/etc/bogons")) {
@file_put_contents("/etc/bogons", "");
- if (!file_exists("/etc/bogonsv6"))
+ }
+ if (!file_exists("/etc/bogonsv6")) {
@file_put_contents("/etc/bogonsv6", "");
+ }
$aliases .= "table <bogons> persist file \"/etc/bogons\"\n";
- if (is_bogonsv6_used())
+ if (is_bogonsv6_used()) {
$aliases .= "table <bogonsv6> persist file \"/etc/bogonsv6\"\n";
+ }
$vpns_list = filter_get_vpns_list();
- if($vpns_list)
+ if ($vpns_list) {
$aliases .= "table <vpn_networks> { $vpns_list }\n";
+ }
/* add a Negate_networks table */
$aliases .= "table <negate_networks> ";
- if($vpns_list)
+ if ($vpns_list) {
$aliases .= "{ $vpns_list }";
+ }
$aliases .= "\n";
$aliases .= "\n# User Aliases \n";
/* Setup pf groups */
- if(isset($config['aliases']['alias'])) {
+ if (isset($config['aliases']['alias'])) {
foreach ($config['aliases']['alias'] as $aliased) {
$extralias = "";
$aliasnesting = array();
@@ -665,27 +713,30 @@ function filter_generate_aliases() {
case "network":
case "url":
$tableaddrs = "{$addrlist}{$extralias}";
- if(empty($tableaddrs)) {
+ if (empty($tableaddrs)) {
$aliases .= "table <{$aliased['name']}> persist\n";
- if (empty($aliased['address']))
+ if (empty($aliased['address'])) {
$after_filter_configure_run[] = "/sbin/pfctl -T flush -t " . escapeshellarg($aliased['name']);
- } else
+ }
+ } else {
$aliases .= "table <{$aliased['name']}> { {$addrlist}{$extralias} } \n";
+ }
$aliases .= "{$aliased['name']} = \"<{$aliased['name']}>\"\n";
break;
case "openvpn":
$openvpncfg = array();
- if($config['openvpn']['user']) {
+ if ($config['openvpn']['user']) {
/* XXX: Check if we have a correct ip? */
- foreach ($config['openvpn']['user'] as $openvpn)
+ foreach ($config['openvpn']['user'] as $openvpn) {
$openvpncfg[$openvpn['name']] = $openvpn['ip'];
+ }
}
$vpn_lines = explode("\n", $addrlist);
foreach ($vpn_lines as $vpn_line) {
$vpn_address_split = explode(" ", $vpn_line);
- foreach($vpn_address_split as $vpnsplit) {
- if(isset($openvpncfg[$vpnsplit])) {
+ foreach ($vpn_address_split as $vpnsplit) {
+ if (isset($openvpncfg[$vpnsplit])) {
$newaddress .= " ";
$newaddress .= $openvpn[$vpnsplit];
break;
@@ -705,8 +756,9 @@ function filter_generate_aliases() {
case "urltable_ports":
// TODO: Change it when pf supports tables with ports
$urlfn = alias_expand_urltable($aliased['name']);
- if ($urlfn)
+ if ($urlfn) {
$aliases .= "{$aliased['name']} = \"{ " . preg_replace("/\n/", " ", file_get_contents($urlfn)) . " }\"\n";
+ }
break;
case "port":
case "url_ports":
@@ -740,14 +792,17 @@ function filter_generate_gateways() {
$int = $gateway['interface'];
$gwip = $gateway['gateway'];
$route = "";
- if (!is_ipaddr($gwip))
+ if (!is_ipaddr($gwip)) {
$gwip = get_interface_gateway($gateway['friendlyiface']);
- if (is_ipaddr($gwip) && !empty($int))
+ }
+ if (is_ipaddr($gwip) && !empty($int)) {
$route = "route-to ( {$int} {$gwip} )";
- if (($route === "") && isset($config['system']['skip_rules_gw_down']))
+ }
+ if (($route === "") && isset($config['system']['skip_rules_gw_down'])) {
unset($GatewaysList[$gwname]);
- else
+ } else {
$rules .= "GW{$gwname} = \" {$route} \"\n";
+ }
}
}
@@ -759,34 +814,39 @@ function filter_generate_gateways() {
if (count($members) > 0) {
$foundlb = 0;
$routeto = "";
- foreach($members as $idx => $member) {
+ foreach ($members as $idx => $member) {
$int = $member['int'];
$gatewayip = $member['gwip'];
if (($int <> "") && is_ipaddr($gatewayip)) {
- if ($g['debug'])
+ if ($g['debug']) {
log_error(sprintf(gettext('Setting up route with %1$s on %2$s'), $gatewayip, $int));
+ }
if ($member['weight'] > 1) {
$routeto .= str_repeat("( {$int} {$gatewayip} ) ", $member['weight']);
- } else
+ } else {
$routeto .= "( {$int} {$gatewayip} ) ";
+ }
$foundlb++;
- } else
+ } else {
log_error(sprintf(gettext("An error occurred while trying to find the interface got %s . The rule has not been added."), $gatewayip));
+ }
}
$route = "";
if ($foundlb > 0) {
$route = " route-to { {$routeto} } ";
- if($foundlb > 1) {
+ if ($foundlb > 1) {
$route .= " round-robin ";
- if (isset($config['system']['lb_use_sticky']))
+ if (isset($config['system']['lb_use_sticky'])) {
$route .= " sticky-address ";
+ }
}
}
}
- if (($route === "") && isset($config['system']['skip_rules_gw_down']))
+ if (($route === "") && isset($config['system']['skip_rules_gw_down'])) {
unset($GatewayGroupsList[$gateway]);
- else
+ } else {
$rules .= "GW{$gateway} = \" {$route} \"\n";
+ }
}
}
@@ -810,14 +870,17 @@ function filter_get_vpns_list() {
if (is_array($config['ipsec']['phase2'])) {
foreach ($config['ipsec']['phase2'] as $ph2ent) {
if ((!$ph2ent['mobile']) && ($ph2ent['mode'] != 'transport')) {
- if (!function_exists('ipsec_idinfo_to_cidr'))
+ if (!function_exists('ipsec_idinfo_to_cidr')) {
require_once("ipsec.inc");
- if (!is_array($ph2ent['remoteid']))
+ }
+ if (!is_array($ph2ent['remoteid'])) {
continue;
+ }
$ph2ent['remoteid']['mode'] = $ph2ent['mode'];
$vpns_subnet = ipsec_idinfo_to_cidr($ph2ent['remoteid']);
- if (!is_subnet($vpns_subnet) || $vpns_subnet == "0.0.0.0/0")
+ if (!is_subnet($vpns_subnet) || $vpns_subnet == "0.0.0.0/0") {
continue;
+ }
$vpns_arr[] = $vpns_subnet;
}
}
@@ -826,17 +889,19 @@ function filter_get_vpns_list() {
/* openvpn */
foreach (array('client', 'server') as $type) {
- if(is_array($config['openvpn']["openvpn-$type"])) {
+ if (is_array($config['openvpn']["openvpn-$type"])) {
foreach ($config['openvpn']["openvpn-$type"] as $settings) {
- if(is_array($settings)) {
+ if (is_array($settings)) {
if (!isset($settings['disable'])) {
$remote_networks = explode(',', $settings['remote_network']);
foreach ($remote_networks as $remote_network) {
- if (is_subnet($remote_network) && ($remote_network <> "0.0.0.0/0"))
+ if (is_subnet($remote_network) && ($remote_network <> "0.0.0.0/0")) {
$vpns_arr[] = $remote_network;
+ }
}
- if (is_subnet($settings['tunnel_network']) && $settings['tunnel_network'] <> "0.0.0.0/0")
+ if (is_subnet($settings['tunnel_network']) && $settings['tunnel_network'] <> "0.0.0.0/0") {
$vpns_arr[] = $settings['tunnel_network'];
+ }
}
}
}
@@ -844,19 +909,21 @@ function filter_get_vpns_list() {
}
/* pppoe */
if (is_array($config['pppoes']['pppoe'])) {
- foreach($config['pppoes']['pppoe'] as $pppoe) {
+ foreach ($config['pppoes']['pppoe'] as $pppoe) {
if ($pppoe['mode'] == "server") {
- if(is_ipaddr($pppoe['remoteip'])) {
+ if (is_ipaddr($pppoe['remoteip'])) {
$pppoesub = gen_subnet($pppoe['remoteip'], $pppoe['pppoe_subnet']);
- if (is_subnet($pppoesub))
+ if (is_subnet($pppoesub)) {
$vpns_arr[] = $pppoesub;
+ }
}
}
}
}
- if (!empty($vpns_arr))
+ if (!empty($vpns_arr)) {
$vpns = implode(" ", $vpns_arr);
+ }
return $vpns;
}
@@ -869,13 +936,13 @@ function filter_get_direct_networks_list($returnsubnetsonly = true) {
/* build list of directly connected interfaces and networks */
$networks = "";
$networks_arr = array();
- if(empty($FilterIflist)) {
+ if (empty($FilterIflist)) {
filter_generate_optcfg_array();
}
foreach ($FilterIflist as $ifent => $ifcfg) {
$subnet = "{$ifcfg['sa']}/{$ifcfg['sn']}";
- if(is_subnet($subnet)) {
- if($returnsubnetsonly) {
+ if (is_subnet($subnet)) {
+ if ($returnsubnetsonly) {
$networks_arr[] = $subnet;
} else {
$networks_arr[] = array(
@@ -885,14 +952,15 @@ function filter_get_direct_networks_list($returnsubnetsonly = true) {
}
}
}
- foreach(get_configured_ip_aliases_list(true) as $vip) {
+ foreach (get_configured_ip_aliases_list(true) as $vip) {
$subnet = "{$vip['subnet']}/{$vip['subnet_bits']}";
- if(is_subnet($subnet) && !(is_subnetv4($subnet) && $vip['subnet_bits'] == 32) && !(is_subnetv6($subnet) && $vip['subnet_bits'] == 128)) {
- if(is_subnetv4($subnet))
+ if (is_subnet($subnet) && !(is_subnetv4($subnet) && $vip['subnet_bits'] == 32) && !(is_subnetv6($subnet) && $vip['subnet_bits'] == 128)) {
+ if (is_subnetv4($subnet)) {
$subnet = gen_subnet($vip['subnet'], $vip['subnet_bits']) . "/{$vip['subnet_bits']}";
- else if(is_subnetv6($subnet))
+ } else if (is_subnetv6($subnet)) {
$subnet = gen_subnetv6($vip['subnet'], $vip['subnet_bits']) . "/{$vip['subnet_bits']}";
- if($returnsubnetsonly) {
+ }
+ if ($returnsubnetsonly) {
$networks_arr[] = $subnet;
} else {
$networks_arr[] = array(
@@ -902,11 +970,11 @@ function filter_get_direct_networks_list($returnsubnetsonly = true) {
}
}
}
- foreach(get_staticroutes() as $netent) {
- if(is_subnet($netent['network'])) {
- if($returnsubnetsonly) {
+ foreach (get_staticroutes() as $netent) {
+ if (is_subnet($netent['network'])) {
+ if ($returnsubnetsonly) {
$networks_arr[] = $netent['network'];
- } else if(isset($GatewaysList[$netent['gateway']])) {
+ } else if (isset($GatewaysList[$netent['gateway']])) {
$networks_arr[] = array(
'subnet' => $netent['network'],
'if' => $GatewaysList[$netent['gateway']]['friendlyiface'],
@@ -914,8 +982,8 @@ function filter_get_direct_networks_list($returnsubnetsonly = true) {
}
}
}
- if($returnsubnetsonly) {
- if(!empty($networks_arr)) {
+ if ($returnsubnetsonly) {
+ if (!empty($networks_arr)) {
$networks = implode(" ", $networks_arr);
}
return $networks;
@@ -926,7 +994,7 @@ function filter_get_direct_networks_list($returnsubnetsonly = true) {
function filter_generate_optcfg_array() {
global $config, $FilterIflist;
- if(isset($config['system']['developerspew'])) {
+ if (isset($config['system']['developerspew'])) {
$mt = microtime();
echo "filter_generate_optcfg_array() being called $mt\n";
}
@@ -938,17 +1006,21 @@ function filter_generate_optcfg_array() {
$oc = $config['interfaces'][$if];
$oic = array();
$oic['if'] = get_real_interface($if);
- if (!does_interface_exist($oic['if']))
+ if (!does_interface_exist($oic['if'])) {
continue;
+ }
$oic['ifv6'] = get_real_interface($if, "inet6");
$oic['ip'] = get_interface_ip($if);
$oic['ipv6'] = get_interface_ipv6($if);
- if(!is_ipaddrv4($oc['ipaddr']) && !empty($oc['ipaddr']))
+ if (!is_ipaddrv4($oc['ipaddr']) && !empty($oc['ipaddr'])) {
$oic['type'] = $oc['ipaddr'];
- if(!is_ipaddrv6($oc['ipaddrv6']) && !empty($oc['ipaddrv6']))
+ }
+ if (!is_ipaddrv6($oc['ipaddrv6']) && !empty($oc['ipaddrv6'])) {
$oic['type6'] = $oc['ipaddrv6'];
- if (!empty($oc['track6-interface']))
+ }
+ if (!empty($oc['track6-interface'])) {
$oic['track6-interface'] = $oc['track6-interface'];
+ }
$oic['sn'] = get_interface_subnet($if);
$oic['snv6'] = get_interface_subnetv6($if);
$oic['mtu'] = empty($oc['mtu']) ? 1500 : $oc['mtu'];
@@ -967,21 +1039,25 @@ function filter_generate_optcfg_array() {
if (!empty($vips)) {
foreach ($vips as $vipidx => $vip) {
if (is_ipaddrv4($vip['subnet'])) {
- if (!is_array($oic['vips']))
+ if (!is_array($oic['vips'])) {
$oic['vips'] = array();
+ }
$oic['vips'][$vipidx]['ip'] = $vip['subnet'];
- if (empty($vip['subnet_bits']))
+ if (empty($vip['subnet_bits'])) {
$oic['vips'][$vipidx]['sn'] = 32;
- else
+ } else {
$oic['vips'][$vipidx]['sn'] = $vip['subnet_bits'];
+ }
} else if (is_ipaddrv6($vip['subnet'])) {
- if (!is_array($oic['vips6']))
+ if (!is_array($oic['vips6'])) {
$oic['vips6'] = array();
+ }
$oic['vips6'][$vipidx]['ip'] = $vip['subnet'];
- if (empty($vip['subnet_bits']))
+ if (empty($vip['subnet_bits'])) {
$oic['vips6'][$vipidx]['sn'] = 128;
- else
+ } else {
$oic['vips6'][$vipidx]['sn'] = $vip['subnet_bits'];
+ }
}
}
}
@@ -989,7 +1065,7 @@ function filter_generate_optcfg_array() {
$FilterIflist[$if] = $oic;
}
- if($config['pptpd']['mode'] == "server" || $config['pptpd']['mode'] == "redir") {
+ if ($config['pptpd']['mode'] == "server" || $config['pptpd']['mode'] == "redir") {
$oic = array();
$oic['if'] = 'pptp';
$oic['descr'] = 'pptp';
@@ -997,29 +1073,31 @@ function filter_generate_optcfg_array() {
$oic['sa'] = $config['pptpd']['remoteip'];
$oic['mode'] = $config['pptpd']['mode'];
$oic['virtual'] = true;
- if($config['pptpd']['pptp_subnet'] <> "")
+ if ($config['pptpd']['pptp_subnet'] <> "") {
$oic['sn'] = $config['pptpd']['pptp_subnet'];
- else
+ } else {
$oic['sn'] = "32";
+ }
$FilterIflist['pptp'] = $oic;
}
- if($config['l2tp']['mode'] == "server") {
+ if ($config['l2tp']['mode'] == "server") {
$oic = array();
$oic['if'] = 'l2tp';
$oic['descr'] = 'L2TP';
$oic['ip'] = $config['l2tp']['localip'];
$oic['sa'] = $config['l2tp']['remoteip'];
- if($config['l2tp']['l2tp_subnet'] <> "")
+ if ($config['l2tp']['l2tp_subnet'] <> "") {
$oic['sn'] = $config['l2tp']['l2tp_subnet'];
- else
+ } else {
$oic['sn'] = "32";
+ }
$oic['mode'] = $config['l2tp']['mode'];
$oic['virtual'] = true;
$FilterIflist['l2tp'] = $oic;
}
if (is_array($config['pppoes']['pppoe']) && (count($config['pppoes']['pppoe']) > 0)) {
$pppoeifs = array();
- foreach($config['pppoes']['pppoe'] as $pppoe) {
+ foreach ($config['pppoes']['pppoe'] as $pppoe) {
if ($pppoe['mode'] == "server") {
$oic = array();
$oic['if'] = 'pppoe';
@@ -1028,18 +1106,20 @@ function filter_generate_optcfg_array() {
$oic['sa'] = $pppoe['remoteip'];
$oic['mode'] = $pppoe['mode'];
$oic['virtual'] = true;
- if($pppoe['pppoe_subnet'] <> "")
+ if ($pppoe['pppoe_subnet'] <> "") {
$oic['sn'] = $pppoe['pppoe_subnet'];
- else
+ } else {
$oic['sn'] = "32";
+ }
$pppoeifs[] = $oic;
}
}
- if (count($pppoeifs))
+ if (count($pppoeifs)) {
$FilterIflist['pppoe'] = $pppoeifs;
+ }
}
/* add ipsec interfaces */
- if(isset($config['ipsec']['enable']) || isset($config['ipsec']['client']['enable'])) {
+ if (isset($config['ipsec']['enable']) || isset($config['ipsec']['client']['enable'])) {
$oic = array();
$oic['if'] = 'enc0';
$oic['descr'] = 'IPsec';
@@ -1048,7 +1128,7 @@ function filter_generate_optcfg_array() {
$FilterIflist['enc0'] = $oic;
}
/* add openvpn interfaces */
- if($config['openvpn']['openvpn-server'] || $config['openvpn']['openvpn-client']) {
+ if ($config['openvpn']['openvpn-server'] || $config['openvpn']['openvpn-client']) {
$oic = array();
$oic['if'] = "openvpn";
$oic['descr'] = 'OpenVPN';
@@ -1057,8 +1137,8 @@ function filter_generate_optcfg_array() {
$FilterIflist['openvpn'] = $oic;
}
/* add interface groups */
- if(is_array($config['ifgroups']['ifgroupentry'])) {
- foreach($config['ifgroups']['ifgroupentry'] as $ifgen) {
+ if (is_array($config['ifgroups']['ifgroupentry'])) {
+ foreach ($config['ifgroups']['ifgroupentry'] as $ifgen) {
$oc = array();
$oc['if'] = $ifgen['ifname'];
$oc['descr'] = $ifgen['ifname'];
@@ -1070,7 +1150,7 @@ function filter_generate_optcfg_array() {
function filter_flush_nat_table() {
global $config, $g;
- if(isset($config['system']['developerspew'])) {
+ if (isset($config['system']['developerspew'])) {
$mt = microtime();
echo "filter_flush_nat_table() being called $mt\n";
}
@@ -1087,12 +1167,14 @@ function filter_get_reflection_interfaces($natif = "") {
$nat_if_list = array();
foreach ($FilterIflist as $ifent => $ifname) {
- if($ifname['if'] == $natif)
+ if ($ifname['if'] == $natif) {
continue;
+ }
/* Do not add reflection redirects for interfaces with gateways */
- if(interface_has_gateway($ifent))
+ if (interface_has_gateway($ifent)) {
continue;
+ }
$nat_if_list[] = $ifname['if'];
}
@@ -1103,8 +1185,9 @@ function filter_get_reflection_interfaces($natif = "") {
function filter_generate_reflection_nat($rule, &$route_table, $nat_ifs, $protocol, $target, $target_ip, $target_subnet = "") {
global $config, $FilterIflist;
- if(!isset($config['system']['enablenatreflectionhelper']))
+ if (!isset($config['system']['enablenatreflectionhelper'])) {
return "";
+ }
// Initialize natrules holder string
$natrules = "";
@@ -1112,37 +1195,40 @@ function filter_generate_reflection_nat($rule, &$route_table, $nat_ifs, $protoco
update_filter_reload_status(sprintf(gettext("Creating reflection NAT rule for %s..."), $rule['descr']));
/* TODO: Add this option to port forwards page. */
- if(isset($rule['staticnatport'])) {
+ if (isset($rule['staticnatport'])) {
$static_port = " static-port";
} else {
$static_port = " port 1024:65535";
}
- if(!empty($protocol)) {
+ if (!empty($protocol)) {
$protocol_text = " proto {$protocol}";
} else {
$protocol_text = "";
}
- if(empty($target_subnet) || !is_numeric($target_subnet))
+ if (empty($target_subnet) || !is_numeric($target_subnet)) {
$target_subnet = 32;
+ }
- if(!is_array($route_table)) {
+ if (!is_array($route_table)) {
/* get a simulated IPv4-only route table based on the config */
$route_table = filter_get_direct_networks_list(false);
- foreach($route_table as $rt_key => $rt_ent) {
- if(!is_subnetv4($rt_ent['subnet']))
+ foreach ($route_table as $rt_key => $rt_ent) {
+ if (!is_subnetv4($rt_ent['subnet'])) {
unset($route_table[$rt_key]);
- if(isset($route_table[$rt_key]) && isset($FilterIflist[$rt_ent['if']]['if']))
+ }
+ if (isset($route_table[$rt_key]) && isset($FilterIflist[$rt_ent['if']]['if'])) {
$route_table[$rt_key]['if'] = $FilterIflist[$rt_ent['if']]['if'];
+ }
}
}
/* Check if the target is accessed through a static route */
- foreach($route_table as $route) {
- if(isset($route['gateway']) && is_ipaddr($route['gateway'])) {
+ foreach ($route_table as $route) {
+ if (isset($route['gateway']) && is_ipaddr($route['gateway'])) {
$subnet_split = explode("/", $route['subnet']);
- if(in_array($route['if'], $nat_ifs) && check_subnets_overlap($target_ip, $target_subnet, $subnet_split[0], $subnet_split[1])) {
+ if (in_array($route['if'], $nat_ifs) && check_subnets_overlap($target_ip, $target_subnet, $subnet_split[0], $subnet_split[1])) {
$target_ip = $route['gateway'];
$target_subnet = 32;
break;
@@ -1151,36 +1237,39 @@ function filter_generate_reflection_nat($rule, &$route_table, $nat_ifs, $protoco
}
/* Search for matching subnets in the routing table */
- foreach($route_table as $route) {
+ foreach ($route_table as $route) {
$subnet = $route['subnet'];
$subnet_split = explode("/", $subnet);
$subnet_if = $route['if'];
- if(in_array($subnet_if, $nat_ifs) && check_subnets_overlap($target_ip, $target_subnet, $subnet_split[0], $subnet_split[1])) {
+ if (in_array($subnet_if, $nat_ifs) && check_subnets_overlap($target_ip, $target_subnet, $subnet_split[0], $subnet_split[1])) {
$ifsubnet_ip = "";
/* Find interface IP to use for NAT */
foreach ($route_table as $ifnetwork) {
- if(isset($ifnetwork['ip']) && is_ipaddr($ifnetwork['ip']) && $ifnetwork['if'] == $subnet_if && ip_in_subnet($ifnetwork['ip'], $subnet)) {
+ if (isset($ifnetwork['ip']) && is_ipaddr($ifnetwork['ip']) && $ifnetwork['if'] == $subnet_if && ip_in_subnet($ifnetwork['ip'], $subnet)) {
$ifsubnet_ip = $ifnetwork['ip'];
break;
}
}
- if(!empty($ifsubnet_ip)) {
+ if (!empty($ifsubnet_ip)) {
$subnets = array($subnet);
/* Find static routes that also need to be referenced in the NAT rule */
- foreach($route_table as $rtentry) {
- if(isset($rtentry['gateway']) && is_ipaddr($rtentry['gateway']) && $rtentry['if'] == $subnet_if && ip_in_subnet($rtentry['gateway'], $subnet))
+ foreach ($route_table as $rtentry) {
+ if (isset($rtentry['gateway']) && is_ipaddr($rtentry['gateway']) && $rtentry['if'] == $subnet_if && ip_in_subnet($rtentry['gateway'], $subnet)) {
$subnets[] = $rtentry['subnet'];
+ }
}
- if(count($subnets) > 1)
+ if (count($subnets) > 1) {
$subnet = "{ " . implode(" ", $subnets) . " }";
+ }
$natrules .= "no nat on {$subnet_if}{$protocol_text} from {$subnet_if} to {$target}\n";
$natrules .= "nat on {$subnet_if}{$protocol_text} from {$subnet} to {$target} -> {$ifsubnet_ip}{$static_port}\n";
}
}
}
- if(!empty($natrules))
+ if (!empty($natrules)) {
$natrules .= "\n";
+ }
return $natrules;
}
@@ -1192,22 +1281,24 @@ function filter_generate_reflection_proxy($rule, $nordr, $rdr_ifs, $srcaddr, $ds
$natrules = "";
$reflection_txt = array();
- if(!empty($rdr_ifs)) {
- if($config['system']['reflectiontimeout'])
+ if (!empty($rdr_ifs)) {
+ if ($config['system']['reflectiontimeout']) {
$reflectiontimeout = $config['system']['reflectiontimeout'];
- else
+ } else {
$reflectiontimeout = "2000";
+ }
update_filter_reload_status(sprintf(gettext("Creating reflection rule for %s..."), $rule['descr']));
$rdr_if_list = implode(" ", $rdr_ifs);
- if(count($rdr_ifs) > 1)
+ if (count($rdr_ifs) > 1) {
$rdr_if_list = "{ {$rdr_if_list} }";
+ }
$natrules .= "\n# Reflection redirects\n";
$localport = $rule['local-port'];
- if(!empty($localport) && is_alias($localport)) {
+ if (!empty($localport) && is_alias($localport)) {
$localport = filter_expand_alias($localport);
$localport = explode(" ", trim($localport));
// The translation port for rdr, when specified, does not support more than one port or range.
@@ -1215,138 +1306,152 @@ function filter_generate_reflection_proxy($rule, $nordr, $rdr_ifs, $srcaddr, $ds
$localport = $localport[0];
}
- if(is_alias($rule['destination']['port'])) {
- if(empty($localport) || $rule['destination']['port'] == $rule['local-port']) {
+ if (is_alias($rule['destination']['port'])) {
+ if (empty($localport) || $rule['destination']['port'] == $rule['local-port']) {
$dstport = filter_expand_alias($rule['destination']['port']);
$dstport = array_filter(explode(" ", trim($dstport)));
$localport = "";
- } else if(!empty($localport)) {
+ } else if (!empty($localport)) {
$dstport = array($localport);
}
} else {
$dstport = array(str_replace("-", ":", $rule['destination']['port']));
$dstport_split = explode(":", $dstport[0]);
- if(!empty($localport) && $dstport_split[0] != $rule['local-port']) {
- if(!is_alias($rule['local-port']) && $dstport_split[1] && $dstport_split[0] != $dstport_split[1]) {
+ if (!empty($localport) && $dstport_split[0] != $rule['local-port']) {
+ if (!is_alias($rule['local-port']) && $dstport_split[1] && $dstport_split[0] != $dstport_split[1]) {
$localendport = $localport + ($dstport_split[1] - $dstport_split[0]);
$localport .= ":$localendport";
}
$dstport = array($localport);
- } else
+ } else {
$localport = "";
+ }
}
$dstaddr = explode(" ", $dstaddr_port);
- if($dstaddr[2]) {
+ if ($dstaddr[2]) {
$rflctintrange = array_pop($dstaddr);
array_pop($dstaddr);
- } else
+ } else {
return "";
+ }
$dstaddr = implode(" ", $dstaddr);
- if(empty($dstaddr) || trim($dstaddr) == "0.0.0.0" || strtolower(trim($dstaddr)) == "port")
+ if (empty($dstaddr) || trim($dstaddr) == "0.0.0.0" || strtolower(trim($dstaddr)) == "port") {
return "";
+ }
- if(isset($rule['destination']['any'])) {
- if(!$rule['interface'])
+ if (isset($rule['destination']['any'])) {
+ if (!$rule['interface']) {
$natif = "wan";
- else
+ } else {
$natif = $rule['interface'];
+ }
- if(!isset($FilterIflist[$natif]))
+ if (!isset($FilterIflist[$natif])) {
return "";
- if(is_ipaddr($FilterIflist[$natif]['ip']))
+ }
+ if (is_ipaddr($FilterIflist[$natif]['ip'])) {
$dstaddr = $FilterIflist[$natif]['ip'];
- else
+ } else {
return "";
+ }
- if(!empty($FilterIflist[$natif]['sn']))
+ if (!empty($FilterIflist[$natif]['sn'])) {
$dstaddr = gen_subnet($dstaddr, $FilterIflist[$natif]['sn']) . '/' . $FilterIflist[$natif]['sn'];
+ }
}
- switch($rule['protocol']) {
- case "tcp/udp":
- $protocol = "{ tcp udp }";
- $reflect_protos = array('tcp', 'udp');
- break;
- case "tcp":
- case "udp":
- $protocol = $rule['protocol'];
- $reflect_protos = array($rule['protocol']);
- break;
- default:
- return "";
- break;
+ switch ($rule['protocol']) {
+ case "tcp/udp":
+ $protocol = "{ tcp udp }";
+ $reflect_protos = array('tcp', 'udp');
+ break;
+ case "tcp":
+ case "udp":
+ $protocol = $rule['protocol'];
+ $reflect_protos = array($rule['protocol']);
+ break;
+ default:
+ return "";
+ break;
}
- if(!empty($nordr)) {
+ if (!empty($nordr)) {
$natrules .= "no rdr on {$rdr_if_list} proto {$protocol} from {$srcaddr} to {$dstaddr} port {$rflctintrange}\n";
return $natrules;
}
- if (is_alias($rule['target']))
+ if (is_alias($rule['target'])) {
$target = filter_expand_alias($rule['target']);
- else if(is_ipaddr($rule['target']))
+ } else if (is_ipaddr($rule['target'])) {
$target = $rule['target'];
- else if (is_ipaddr($FilterIflist[$rule['target']]['ip']))
+ } else if (is_ipaddr($FilterIflist[$rule['target']]['ip'])) {
$target = $FilterIflist[$rule['target']]['ip'];
- else
+ } else {
return "";
+ }
$starting_localhost_port_tmp = $starting_localhost_port;
$toomanyports = false;
/* only install reflection rules for < 19991 items */
- foreach($dstport as $loc_pt) {
- if($starting_localhost_port < 19991) {
+ foreach ($dstport as $loc_pt) {
+ if ($starting_localhost_port < 19991) {
$toadd_array = array();
$inetdport = $starting_localhost_port;
$rflctrange = $starting_localhost_port;
$loc_pt = explode(":", $loc_pt);
- if($loc_pt[1] && $loc_pt[1] > $loc_pt[0])
+ if ($loc_pt[1] && $loc_pt[1] > $loc_pt[0]) {
$delta = $loc_pt[1] - $loc_pt[0];
- else
+ } else {
$delta = 0;
+ }
- if(($inetdport + $delta + 1) - $starting_localhost_port_tmp > 500) {
+ if (($inetdport + $delta + 1) - $starting_localhost_port_tmp > 500) {
log_error("Not installing NAT reflection rules for a port range > 500");
$inetdport = $starting_localhost_port;
$toadd_array = array();
$toomanyports = true;
break;
- } else if(($inetdport + $delta) > 19990) {
+ } else if (($inetdport + $delta) > 19990) {
log_error("Installing partial NAT reflection rules. Maximum 1,000 reached.");
$delta = 19990 - $inetdport;
$loc_pt[1] = $loc_pt[0] + $delta;
- if($delta == 0)
+ if ($delta == 0) {
unset($loc_pt[1]);
+ }
$toomanyports = true;
- if(!empty($localport)) {
- if(is_alias($rule['destination']['port'])) {
+ if (!empty($localport)) {
+ if (is_alias($rule['destination']['port'])) {
$rflctintrange = alias_expand($rule['destination']['port']);
} else {
- if($dstport_split[1])
+ if ($dstport_split[1]) {
$dstport_split[1] = $dstport_split[0] + $inetdport + $delta - $starting_localhost_port;
+ }
$rflctintrange = implode(":", $dstport_split);
}
}
}
- if(empty($localport))
+ if (empty($localport)) {
$rflctintrange = implode(":", $loc_pt);
- if($inetdport + $delta > $starting_localhost_port)
+ }
+ if ($inetdport + $delta > $starting_localhost_port) {
$rflctrange .= ":" . ($inetdport + $delta);
+ }
$starting_localhost_port = $inetdport + $delta + 1;
$toadd_array = array_merge($toadd_array, range($loc_pt[0], $loc_pt[0] + $delta));
- if(!empty($toadd_array)) {
+ if (!empty($toadd_array)) {
$rtarget = explode(" ", trim($target));
- foreach($toadd_array as $tda) {
- if (empty($tda))
+ foreach ($toadd_array as $tda) {
+ if (empty($tda)) {
continue;
- foreach($reflect_protos as $reflect_proto) {
- if($reflect_proto == "udp") {
+ }
+ foreach ($reflect_protos as $reflect_proto) {
+ if ($reflect_proto == "udp") {
$socktype = "dgram";
$dash_u = "-u ";
$wait = "wait\t";
@@ -1356,8 +1461,9 @@ function filter_generate_reflection_proxy($rule, $nordr, $rdr_ifs, $srcaddr, $ds
$wait = "nowait/0";
}
foreach ($rtarget as $targip) {
- if (empty($targip))
+ if (empty($targip)) {
continue;
+ }
$reflection_txt[] = "{$inetdport}\t{$socktype}\t{$reflect_proto}\t{$wait}\tnobody\t/usr/bin/nc\tnc {$dash_u}-w {$reflectiontimeout} {$targip} {$tda}\n";
}
}
@@ -1367,8 +1473,9 @@ function filter_generate_reflection_proxy($rule, $nordr, $rdr_ifs, $srcaddr, $ds
}
}
- if($toomanyports)
+ if ($toomanyports) {
break;
+ }
}
$reflection_txt = array_unique($reflection_txt);
@@ -1387,7 +1494,7 @@ function filter_nat_rules_automatic_tonathosts($with_descr = false) {
$netip = explode("/", $route['network']);
if (isset($GatewaysList[$route['gateway']])) {
$gateway =& $GatewaysList[$route['gateway']];
- if(!interface_has_gateway($gateway['interface']) && is_private_ip($netip[0])) {
+ if (!interface_has_gateway($gateway['interface']) && is_private_ip($netip[0])) {
$tonathosts[] = $route['network'];
$descriptions[] = gettext("static route");
}
@@ -1395,25 +1502,29 @@ function filter_nat_rules_automatic_tonathosts($with_descr = false) {
}
/* create outbound nat entries for all local networks */
- foreach($FilterIflist as $ocname => $oc) {
- if(interface_has_gateway($ocname))
+ foreach ($FilterIflist as $ocname => $oc) {
+ if (interface_has_gateway($ocname)) {
continue;
- if(is_ipaddr($oc['alias-address'])) {
+ }
+ if (is_ipaddr($oc['alias-address'])) {
$tonathosts[] = "{$oc['alias-address']}/{$oc['alias-subnet']}";
$descriptions[] = $oc['descr'] . " " . gettext("DHCP alias address");
}
- if($oc['sa']) {
+ if ($oc['sa']) {
$tonathosts[] = "{$oc['sa']}/{$oc['sn']}";
$descriptions[] = $oc['descr'];
if (isset($oc['vips']) && is_array($oc['vips'])) {
$if_subnets = array("{$oc['sa']}/{$oc['sn']}");
foreach ($oc['vips'] as $vip) {
- if (!is_ipaddrv4($vip['ip']))
+ if (!is_ipaddrv4($vip['ip'])) {
continue;
+ }
- foreach ($if_subnets as $subnet)
- if (ip_in_subnet($vip['ip'], $subnet))
+ foreach ($if_subnets as $subnet) {
+ if (ip_in_subnet($vip['ip'], $subnet)) {
continue 2;
+ }
+ }
$network = gen_subnet($vip['ip'], $vip['sn']);
array_unshift($tonathosts, $network . '/' . $vip['sn']);
@@ -1427,13 +1538,14 @@ function filter_nat_rules_automatic_tonathosts($with_descr = false) {
}
/* PPTP subnet */
- if(($config['pptpd']['mode'] == "server" ) && is_private_ip($config['pptpd']['remoteip'])) {
- if (isset($config['pptpd']['n_pptp_units']) && is_numeric($config['pptpd']['n_pptp_units']))
+ if (($config['pptpd']['mode'] == "server" ) && is_private_ip($config['pptpd']['remoteip'])) {
+ if (isset($config['pptpd']['n_pptp_units']) && is_numeric($config['pptpd']['n_pptp_units'])) {
$pptp_subnets = ip_range_to_subnet_array($config['pptpd']['remoteip'],
long2ip32(ip2long($config['pptpd']['remoteip'])+($config['pptpd']['n_pptp_units']-1)));
- else
+ } else {
$pptp_subnets = ip_range_to_subnet_array($config['pptpd']['remoteip'],
long2ip32(ip2long($config['pptpd']['remoteip'])));
+ }
foreach ($pptp_subnets as $subnet) {
$tonathosts[] = $subnet;
@@ -1442,42 +1554,48 @@ function filter_nat_rules_automatic_tonathosts($with_descr = false) {
}
/* PPPoE subnet */
- if (is_array($FilterIflist['pppoe']))
- foreach ($FilterIflist['pppoe'] as $pppoe)
- if(is_private_ip($pppoe['ip'])) {
+ if (is_array($FilterIflist['pppoe'])) {
+ foreach ($FilterIflist['pppoe'] as $pppoe) {
+ if (is_private_ip($pppoe['ip'])) {
$tonathosts[] = "{$pppoe['sa']}/{$pppoe['sn']}";
$descriptions[] = gettext("PPPoE server");
}
+ }
+ }
/* L2TP subnet */
- if(isset($FilterIflist['l2tp']) && $FilterIflist['l2tp']['mode'] == "server") {
+ if (isset($FilterIflist['l2tp']) && $FilterIflist['l2tp']['mode'] == "server") {
$l2tp_sa = $FilterIflist['l2tp']['sa'];
$l2tp_sn = $FilterIflist['l2tp']['sn'];
- if(is_private_ip($l2tp_sa) && !empty($l2tp_sn)) {
+ if (is_private_ip($l2tp_sa) && !empty($l2tp_sn)) {
$tonathosts[] = "{$l2tp_sa}/{$l2tp_sn}";
$descriptions[] = gettext("L2TP server");
}
}
/* add openvpn interfaces */
- if(is_array($config['openvpn']['openvpn-server']))
- foreach ($config['openvpn']['openvpn-server'] as $ovpnsrv)
+ if (is_array($config['openvpn']['openvpn-server'])) {
+ foreach ($config['openvpn']['openvpn-server'] as $ovpnsrv) {
if (!isset($ovpnsrv['disable']) && !empty($ovpnsrv['tunnel_network'])) {
$tonathosts[] = $ovpnsrv['tunnel_network'];
$descriptions[] = gettext("OpenVPN server");
}
+ }
+ }
- if(is_array($config['openvpn']['openvpn-client']))
- foreach ($config['openvpn']['openvpn-client'] as $ovpncli)
+ if (is_array($config['openvpn']['openvpn-client'])) {
+ foreach ($config['openvpn']['openvpn-client'] as $ovpncli) {
if (!isset($ovpncli['disable']) && !empty($ovpncli['tunnel_network'])) {
$tonathosts[] = $ovpncli['tunnel_network'];
$descriptions[] = gettext("OpenVPN client");
}
+ }
+ }
/* IPsec mode_cfg subnet */
- if (isset($config['ipsec']['client']['enable']) &&
- !empty($config['ipsec']['client']['pool_address']) &&
- !empty($config['ipsec']['client']['pool_netbits'])) {
+ if ((isset($config['ipsec']['client']['enable'])) &&
+ (!empty($config['ipsec']['client']['pool_address'])) &&
+ (!empty($config['ipsec']['client']['pool_netbits']))) {
$tonathosts[] = "{$config['ipsec']['client']['pool_address']}/{$config['ipsec']['client']['pool_netbits']}";
$descriptions[] = gettext("IPsec client");
}
@@ -1491,8 +1609,9 @@ function filter_nat_rules_automatic_tonathosts($with_descr = false) {
}
return $combined;
- } else
+ } else {
return $tonathosts;
+ }
}
function filter_nat_rules_outbound_automatic($src) {
@@ -1500,10 +1619,12 @@ function filter_nat_rules_outbound_automatic($src) {
$rules = array();
foreach ($FilterIflist as $if => $ifcfg) {
- if (substr($ifcfg['if'], 0, 4) == "ovpn")
+ if (substr($ifcfg['if'], 0, 4) == "ovpn") {
continue;
- if (!interface_has_gateway($if))
+ }
+ if (!interface_has_gateway($if)) {
continue;
+ }
$natent = array();
$natent['interface'] = $if;
@@ -1523,8 +1644,9 @@ function filter_nat_rules_outbound_automatic($src) {
$natent['destination']['any'] = true;
$natent['natport'] = "";
$natent['descr'] = gettext('Auto created rule');
- if (isset($ifcfg['nonat']))
+ if (isset($ifcfg['nonat'])) {
$natent['nonat'] = true;
+ }
$rules[] = $natent;
}
@@ -1532,70 +1654,82 @@ function filter_nat_rules_outbound_automatic($src) {
}
/* Generate a 'nat on' or 'no nat on' rule for given interface */
-function filter_nat_rules_generate_if($if, $src = "any", $srcport = "", $dst = "any", $dstport = "", $natip = "", $natport = "", $nonat = false, $staticnatport = false, $proto = "", $poolopts = "") {
+function filter_nat_rules_generate_if ($if, $src = "any", $srcport = "", $dst = "any", $dstport = "", $natip = "", $natport = "", $nonat = false, $staticnatport = false, $proto = "", $poolopts = "") {
global $config, $FilterIflist;
/* XXX: billm - any idea if this code is needed? */
- if($src == "/32" || $src{0} == "/")
+ if ($src == "/32" || $src{0} == "/") {
return "# src incorrectly specified\n";
- if($natip != "") {
- if (is_subnet($natip))
+ }
+ if ($natip != "") {
+ if (is_subnet($natip)) {
$tgt = $natip;
- elseif (is_alias($natip))
+ } elseif (is_alias($natip)) {
$tgt = "\${$natip}";
- else
+ } else {
$tgt = "{$natip}/32";
+ }
} else {
$natip = get_interface_ip($if);
- if(is_ipaddr($natip))
+ if (is_ipaddr($natip)) {
$tgt = "{$natip}/32";
- else
+ } else {
$tgt = "(" . $FilterIflist[$if]['if'] . ")";
+ }
}
/* Add the protocol, if defined */
if (!empty($proto) && $proto != "any") {
- if ($proto == "tcp/udp")
+ if ($proto == "tcp/udp") {
$protocol = " proto { tcp udp }";
- else
+ } else {
$protocol = " proto {$proto}";
- } else
+ }
+ } else {
$protocol = "";
- /* Set tgt for IPv6 */
+ }
+ /* Set tgt for IPv6 */
if ($proto == "ipv6") {
$natip = get_interface_ipv6($if);
- if(is_ipaddrv6($natip))
+ if (is_ipaddrv6($natip)) {
$tgt = "{$natip}/128";
+ }
}
/* Add the hard set source port (useful for ISAKMP) */
- if($natport != "")
+ if ($natport != "") {
$tgt .= " port {$natport}";
+ }
/* sometimes this gets called with "" instead of a value */
- if($src == "")
+ if ($src == "") {
$src = "any";
+ }
/* Match on this source port */
- if($srcport != "") {
+ if ($srcport != "") {
$srcportexpand = alias_expand($srcport);
- if(!$srcportexpand)
+ if (!$srcportexpand) {
$srcportexpand = $srcport;
+ }
$src .= " port {$srcportexpand}";
}
/* sometimes this gets called with "" instead of a value */
- if($dst == "")
+ if ($dst == "") {
$dst = "any";
+ }
/* Match on this dest port */
- if($dstport != "") {
+ if ($dstport != "") {
$dstportexpand = alias_expand($dstport);
- if(!$dstportexpand)
+ if (!$dstportexpand) {
$dstportexpand = $dstport;
+ }
$dst .= " port {$dstportexpand}";
}
/* outgoing static-port option, hamachi, Grandstream, VOIP, etc */
$staticnatport_txt = "";
- if($staticnatport)
+ if ($staticnatport) {
$staticnatport_txt = "static-port";
- elseif(!$natport)
+ } elseif (!$natport) {
$tgt .= " port 1024:65535"; // set source port range
+ }
/* Allow for negating NAT entries */
- if($nonat) {
+ if ($nonat) {
$nat = "no nat";
$target = "";
$staticnatport_txt = "";
@@ -1606,10 +1740,11 @@ function filter_nat_rules_generate_if($if, $src = "any", $srcport = "", $dst = "
}
$if_friendly = $FilterIflist[$if]['descr'];
/* Put all the pieces together */
- if($if_friendly)
+ if ($if_friendly) {
$natrule = "{$nat} on \${$if_friendly} {$protocol} from {$src} to {$dst} {$target} {$poolopts} {$staticnatport_txt}\n";
- else
+ } else {
$natrule .= "# Could not convert {$if} to friendly name(alias)\n";
+ }
return $natrule;
}
@@ -1627,10 +1762,11 @@ function filter_nat_rules_generate() {
$route_table = "";
/* any 1:1 mappings? */
- if(is_array($config['nat']['onetoone'])) {
+ if (is_array($config['nat']['onetoone'])) {
foreach ($config['nat']['onetoone'] as $rule) {
- if (isset($rule['disabled']))
+ if (isset($rule['disabled'])) {
continue;
+ }
$sn = "";
$sn1 = "";
@@ -1640,17 +1776,20 @@ function filter_nat_rules_generate() {
continue; /* unresolvable alias */
}
- if (!$rule['interface'])
+ if (!$rule['interface']) {
$natif = "wan";
- else
+ } else {
$natif = $rule['interface'];
- if (!isset($FilterIflist[$natif]))
+ }
+ if (!isset($FilterIflist[$natif])) {
continue;
+ }
$srcaddr = filter_generate_address($rule, 'source');
$dstaddr = filter_generate_address($rule, 'destination');
- if(!$dstaddr)
+ if (!$dstaddr) {
$dstaddr = $FilterIflist[$natif]['ip'];
+ }
$srcaddr = trim($srcaddr);
$dstaddr = trim($dstaddr);
@@ -1668,11 +1807,12 @@ function filter_nat_rules_generate() {
* If reflection is enabled, turn on extra redirections
* for this rule by adding other interfaces to an rdr rule.
*/
- if ((isset($config['system']['enablebinatreflection']) || $rule['natreflection'] == "enable")
- && $rule['natreflection'] != "disable")
+ if ((isset($config['system']['enablebinatreflection']) || $rule['natreflection'] == "enable") &&
+ ($rule['natreflection'] != "disable")) {
$nat_if_list = filter_get_reflection_interfaces($natif);
- else
+ } else {
$nat_if_list = array();
+ }
$natrules .= "binat on {$natif} from {$srcaddr} to {$dstaddr} -> {$target}{$sn1}\n";
if (!empty($nat_if_list)) {
@@ -1687,17 +1827,20 @@ function filter_nat_rules_generate() {
}
/* Add binat rules for Network Prefix translation */
- if(is_array($config['nat']['npt'])) {
+ if (is_array($config['nat']['npt'])) {
foreach ($config['nat']['npt'] as $rule) {
- if (isset($rule['disabled']))
+ if (isset($rule['disabled'])) {
continue;
+ }
- if (!$rule['interface'])
+ if (!$rule['interface']) {
$natif = "wan";
- else
+ } else {
$natif = $rule['interface'];
- if (!isset($FilterIflist[$natif]))
+ }
+ if (!isset($FilterIflist[$natif])) {
continue;
+ }
$srcaddr = filter_generate_address($rule, 'source');
$dstaddr = filter_generate_address($rule, 'destination');
@@ -1718,43 +1861,55 @@ function filter_nat_rules_generate() {
if (is_array($config['ipsec']['phase2'])) {
foreach ($config['ipsec']['phase2'] as $ph2ent) {
if ($ph2ent['mode'] != 'transport' && !empty($ph2ent['natlocalid'])) {
- if (!function_exists('ipsec_idinfo_to_cidr'))
+ if (!function_exists('ipsec_idinfo_to_cidr')) {
require_once("ipsec.inc");
- if (!is_array($ph2ent['localid']))
+ }
+ if (!is_array($ph2ent['localid'])) {
$ph2ent['localid'] = array();
+ }
$ph2ent['localid']['mode'] = $ph2ent['mode'];
$local_subnet = ipsec_idinfo_to_cidr($ph2ent['localid']);
- if (empty($local_subnet) || $local_subnet == "0.0.0.0/0")
+ if (empty($local_subnet) || $local_subnet == "0.0.0.0/0") {
continue;
- if (!is_subnet($local_subnet) && !is_ipaddr($local_subnet))
+ }
+ if (!is_subnet($local_subnet) && !is_ipaddr($local_subnet)) {
continue;
- if (!is_array($ph2ent['natlocalid']))
+ }
+ if (!is_array($ph2ent['natlocalid'])) {
$ph2ent['natlocalid'] = array();
+ }
$ph2ent['natlocalid']['mode'] = $ph2ent['mode'];
$natlocal_subnet = ipsec_idinfo_to_cidr($ph2ent['natlocalid']);
- if (empty($natlocal_subnet) || $natlocal_subnet == "0.0.0.0/0")
+ if (empty($natlocal_subnet) || $natlocal_subnet == "0.0.0.0/0") {
continue;
- if (!is_subnet($natlocal_subnet) && !is_ipaddr($natlocal_subnet))
+ }
+ if (!is_subnet($natlocal_subnet) && !is_ipaddr($natlocal_subnet)) {
continue;
- if (!is_array($ph2ent['remoteid']))
+ }
+ if (!is_array($ph2ent['remoteid'])) {
$ph2ent['remoteid'] = array();
+ }
$ph2ent['remoteid']['mode'] = $ph2ent['mode'];
$remote_subnet = ipsec_idinfo_to_cidr($ph2ent['remoteid']);
- if (empty($remote_subnet))
+ if (empty($remote_subnet)) {
continue;
- if (!is_subnet($remote_subnet) && !is_ipaddr($remote_subnet))
+ }
+ if (!is_subnet($remote_subnet) && !is_ipaddr($remote_subnet)) {
continue;
- if ($remote_subnet == "0.0.0.0/0")
+ }
+ if ($remote_subnet == "0.0.0.0/0") {
$remote_subnet = "any";
- if (is_ipaddr($natlocal_subnet) && !is_ipaddr($local_subnet) )
+ }
+ if (is_ipaddr($natlocal_subnet) && !is_ipaddr($local_subnet) ) {
$nattype = "nat";
- else {
+ } else {
list($natnet, $natmask) = explode('/', $natlocal_subnet);
list($locnet, $locmask) = explode('/', $local_subnet);
- if (intval($natmask) != intval($locmask))
+ if (intval($natmask) != intval($locmask)) {
$nattype = "nat";
- else
+ } else {
$nattype = "binat";
+ }
unset($natnet, $natmask, $locnet, $locmask);
}
$natrules .= "{$nattype} on enc0 from {$local_subnet} to {$remote_subnet} -> {$natlocal_subnet}\n";
@@ -1763,28 +1918,34 @@ function filter_nat_rules_generate() {
}
}
- if ($config['nat']['outbound']['mode'] == "disabled")
+ if ($config['nat']['outbound']['mode'] == "disabled") {
$natrules .= "\n# Outbound NAT rules are disabled\n";
+ }
if ($config['nat']['outbound']['mode'] == "advanced" || $config['nat']['outbound']['mode'] == "hybrid") {
$natrules .= "\n# Outbound NAT rules (manual)\n";
/* advanced outbound rules */
- if(is_array($config['nat']['outbound']['rule'])) {
+ if (is_array($config['nat']['outbound']['rule'])) {
foreach ($config['nat']['outbound']['rule'] as $obent) {
- if (isset($obent['disabled']))
+ if (isset($obent['disabled'])) {
continue;
+ }
update_filter_reload_status(sprintf(gettext("Creating advanced outbound rule %s"), $obent['descr']));
$src = alias_expand($obent['source']['network']);
- if(!$src)
+ if (!$src) {
$src = $obent['source']['network'];
+ }
$dst = alias_expand($obent['destination']['address']);
- if(!$dst)
+ if (!$dst) {
$dst = $obent['destination']['address'];
- if(isset($obent['destination']['not']) && !isset($obent['destination']['any']))
+ }
+ if (isset($obent['destination']['not']) && !isset($obent['destination']['any'])) {
$dst = "!" . $dst;
+ }
- if(!$obent['interface'] || !isset($FilterIflist[$obent['interface']]))
+ if (!$obent['interface'] || !isset($FilterIflist[$obent['interface']])) {
continue;
+ }
$obtarget = ($obent['target'] == "other-subnet") ? $obent['targetip'] . '/' . $obent['targetip_subnet']: $obent['target'];
$poolopts = (is_subnet($obtarget) || is_alias($obtarget)) ? $obent['poolopts'] : "";
@@ -1806,9 +1967,9 @@ function filter_nat_rules_generate() {
}
/* outbound rules */
- if (!isset($config['nat']['outbound']['mode']) ||
- $config['nat']['outbound']['mode'] == "automatic" ||
- $config['nat']['outbound']['mode'] == "hybrid") {
+ if ((!isset($config['nat']['outbound']['mode'])) ||
+ ($config['nat']['outbound']['mode'] == "automatic") ||
+ ($config['nat']['outbound']['mode'] == "hybrid")) {
$natrules .= "\n# Outbound NAT rules (automatic)\n";
/* standard outbound rules (one for each interface) */
update_filter_reload_status(gettext("Creating outbound NAT rules"));
@@ -1854,58 +2015,62 @@ function filter_nat_rules_generate() {
if (!empty($config['system']['tftpinterface'])) {
$tftpifs = explode(",", $config['system']['tftpinterface']);
- foreach($tftpifs as $tftpif) {
- if ($FilterIflist[$tftpif])
+ foreach ($tftpifs as $tftpif) {
+ if ($FilterIflist[$tftpif]) {
$natrules .= "rdr pass on {$FilterIflist[$tftpif]['if']} proto udp from any to any port tftp -> 127.0.0.1 port 6969\n";
+ }
}
}
/* DIAG: add ipv6 NAT, if requested */
- if(isset($config['diag']['ipv6nat']['enable']) &&
- is_ipaddr($config['diag']['ipv6nat']['ipaddr']) &&
- is_array($FilterIflist['wan'])) {
+ if ((isset($config['diag']['ipv6nat']['enable'])) &&
+ (is_ipaddr($config['diag']['ipv6nat']['ipaddr'])) &&
+ (is_array($FilterIflist['wan']))) {
/* XXX: FIX ME! IPV6 */
$natrules .= "rdr on \${$FilterIflist['wan']['descr']} proto ipv6 from any to any -> {$config['diag']['ipv6nat']['ipaddr']}\n";
}
- if(file_exists("/var/etc/inetd.conf"))
+ if (file_exists("/var/etc/inetd.conf")) {
@unlink("/var/etc/inetd.conf");
+ }
// Open inetd.conf write handle
$inetd_fd = fopen("/var/etc/inetd.conf","w");
/* add tftp protocol helper */
fwrite($inetd_fd, "tftp-proxy\tdgram\tudp\twait\t\troot\t/usr/libexec/tftp-proxy\ttftp-proxy -v\n");
- if(isset($config['nat']['rule'])) {
+ if (isset($config['nat']['rule'])) {
/* start reflection redirects on port 19000 of localhost */
$starting_localhost_port = 19000;
$natrules .= "# NAT Inbound Redirects\n";
foreach ($config['nat']['rule'] as $rule) {
update_filter_reload_status(sprintf(gettext("Creating NAT rule %s"), $rule['descr']));
- if(isset($rule['disabled']))
+ if (isset($rule['disabled'])) {
continue;
+ }
/* if item is an alias, expand */
$dstport = "";
$dstport[0] = alias_expand($rule['destination']['port']);
- if(!$dstport[0])
+ if (!$dstport[0]) {
$dstport = explode("-", $rule['destination']['port']);
+ }
/* if item is an alias, expand */
$localport = alias_expand($rule['local-port']);
- if(!$localport || $dstport[0] == $localport) {
+ if (!$localport || $dstport[0] == $localport) {
$localport = "";
- } else if(is_alias($rule['local-port'])) {
+ } else if (is_alias($rule['local-port'])) {
$localport = filter_expand_alias($rule['local-port']);
- if($localport) {
+ if ($localport) {
$localport = explode(" ", trim($localport));
$localport = $localport[0];
$localport = " port {$localport}";
}
- } else if(is_alias($rule['destination']['port'])) {
+ } else if (is_alias($rule['destination']['port'])) {
$localport = " port {$localport}";
} else {
- if(($dstport[1]) && ($dstport[0] != $dstport[1])) {
+ if (($dstport[1]) && ($dstport[0] != $dstport[1])) {
$localendport = $localport + ($dstport[1] - $dstport[0]);
$localport .= ":$localendport";
@@ -1914,114 +2079,127 @@ function filter_nat_rules_generate() {
$localport = " port {$localport}";
}
- switch(strtolower($rule['protocol'])) {
- case "tcp/udp":
- $protocol = "{ tcp udp }";
- break;
- case "tcp":
- case "udp":
- $protocol = strtolower($rule['protocol']);
- break;
- default:
- $protocol = strtolower($rule['protocol']);
- $localport = "";
- break;
+ switch (strtolower($rule['protocol'])) {
+ case "tcp/udp":
+ $protocol = "{ tcp udp }";
+ break;
+ case "tcp":
+ case "udp":
+ $protocol = strtolower($rule['protocol']);
+ break;
+ default:
+ $protocol = strtolower($rule['protocol']);
+ $localport = "";
+ break;
}
$target = alias_expand($rule['target']);
- if(!$target && !isset($rule['nordr'])) {
+ if (!$target && !isset($rule['nordr'])) {
$natrules .= "# Unresolvable alias {$rule['target']}\n";
continue; /* unresolvable alias */
}
- if(is_alias($rule['target']))
+ if (is_alias($rule['target'])) {
$target_ip = filter_expand_alias($rule['target']);
- else if(is_ipaddr($rule['target']))
+ } else if (is_ipaddr($rule['target'])) {
$target_ip = $rule['target'];
- else if(is_ipaddr($FilterIflist[$rule['target']]['ip']))
+ } else if (is_ipaddr($FilterIflist[$rule['target']]['ip'])) {
$target_ip = $FilterIflist[$rule['target']]['ip'];
- else
+ } else {
$target_ip = $rule['target'];
+ }
$target_ip = trim($target_ip);
- if($rule['associated-rule-id'] == "pass")
+ if ($rule['associated-rule-id'] == "pass") {
$rdrpass = "pass ";
- else
+ } else {
$rdrpass = "";
+ }
if (isset($rule['nordr'])) {
$nordr = "no ";
$rdrpass = "";
- } else
+ } else {
$nordr = "";
+ }
- if(!$rule['interface'])
+ if (!$rule['interface']) {
$natif = "wan";
- else
+ } else {
$natif = $rule['interface'];
+ }
- if (!isset($FilterIflist[$natif]))
+ if (!isset($FilterIflist[$natif])) {
continue;
+ }
$srcaddr = filter_generate_address($rule, 'source', true);
$dstaddr = filter_generate_address($rule, 'destination', true);
$srcaddr = trim($srcaddr);
$dstaddr = trim($dstaddr);
- if(!$dstaddr)
+ if (!$dstaddr) {
$dstaddr = $FilterIflist[$natif]['ip'];
+ }
$dstaddr_port = explode(" ", $dstaddr);
- if(empty($dstaddr_port[0]) || strtolower(trim($dstaddr_port[0])) == "port")
+ if (empty($dstaddr_port[0]) || strtolower(trim($dstaddr_port[0])) == "port") {
continue; // Skip port forward if no destination address found
+ }
$dstaddr_reflect = $dstaddr;
- if(isset($rule['destination']['any'])) {
+ if (isset($rule['destination']['any'])) {
/* With reflection enabled, destination of 'any' has side effects
* that most people would not expect, so change it on reflection rules. */
$dstaddr_reflect = $FilterIflist[$natif]['ip'];
- if(!empty($FilterIflist[$natif]['sn']))
+ if (!empty($FilterIflist[$natif]['sn'])) {
$dstaddr_reflect = gen_subnet($dstaddr_reflect, $FilterIflist[$natif]['sn']) . '/' . $FilterIflist[$natif]['sn'];
+ }
- if($dstaddr_port[2])
+ if ($dstaddr_port[2]) {
$dstaddr_reflect .= " port " . $dstaddr_port[2];
+ }
}
$natif = $FilterIflist[$natif]['if'];
$reflection_type = "none";
- if($rule['natreflection'] != "disable" && $dstaddr_port[0] != "0.0.0.0") {
- if($rule['natreflection'] == "enable")
+ if ($rule['natreflection'] != "disable" && $dstaddr_port[0] != "0.0.0.0") {
+ if ($rule['natreflection'] == "enable") {
$reflection_type = "proxy";
- else if($rule['natreflection'] == "purenat")
+ } else if ($rule['natreflection'] == "purenat") {
$reflection_type = "purenat";
- else if(!isset($config['system']['disablenatreflection'])) {
- if(isset($config['system']['enablenatreflectionpurenat']))
+ } else if (!isset($config['system']['disablenatreflection'])) {
+ if (isset($config['system']['enablenatreflectionpurenat'])) {
$reflection_type = "purenat";
- else
+ } else {
$reflection_type = "proxy";
+ }
}
}
- if($reflection_type != "none")
+ if ($reflection_type != "none") {
$nat_if_list = filter_get_reflection_interfaces($natif);
- else
+ } else {
$nat_if_list = array();
+ }
- if(empty($nat_if_list))
+ if (empty($nat_if_list)) {
$reflection_type = "none";
+ }
$localport_nat = $localport;
- if(empty($localport_nat) && $dstaddr_port[2])
+ if (empty($localport_nat) && $dstaddr_port[2]) {
$localport_nat = " port " . $dstaddr_port[2];
+ }
- if($srcaddr <> "" && $dstaddr <> "" && $natif) {
+ if ($srcaddr <> "" && $dstaddr <> "" && $natif) {
$natrules .= "{$nordr}rdr {$rdrpass}on {$natif} proto {$protocol} from {$srcaddr} to {$dstaddr}" . ($nordr == "" ? " -> {$target}{$localport}" : "");
/* Does this rule redirect back to a internal host? */
- if(isset($rule['destination']['any']) && !isset($rule['nordr']) && !isset($config['system']['enablenatreflectionhelper']) && !interface_has_gateway($rule['interface'])) {
+ if (isset($rule['destination']['any']) && !isset($rule['nordr']) && !isset($config['system']['enablenatreflectionhelper']) && !interface_has_gateway($rule['interface'])) {
$rule_interface_ip = find_interface_ip($natif);
$rule_interface_subnet = find_interface_subnet($natif);
- if(!empty($rule_interface_ip) && !empty($rule_interface_subnet)) {
+ if (!empty($rule_interface_ip) && !empty($rule_interface_subnet)) {
$rule_subnet = gen_subnet($rule_interface_ip, $rule_interface_subnet);
$natrules .= "\n";
$natrules .= "no nat on {$natif} proto tcp from ({$natif}) to {$rule_subnet}/{$rule_interface_subnet}\n";
@@ -2030,27 +2208,31 @@ function filter_nat_rules_generate() {
}
if ($reflection_type != "none") {
- if($reflection_type == "proxy" && !isset($rule['nordr'])) {
+ if ($reflection_type == "proxy" && !isset($rule['nordr'])) {
$natrules .= filter_generate_reflection_proxy($rule, $nordr, $nat_if_list, $srcaddr, $dstaddr, $starting_localhost_port, $reflection_rules);
$nat_if_list = array($natif);
- foreach ($reflection_rules as $txtline)
+ foreach ($reflection_rules as $txtline) {
fwrite($inetd_fd, $txtline);
- } else if($reflection_type == "purenat" || isset($rule['nordr'])) {
+ }
+ } else if ($reflection_type == "purenat" || isset($rule['nordr'])) {
$rdr_if_list = implode(" ", $nat_if_list);
- if(count($nat_if_list) > 1)
+ if (count($nat_if_list) > 1) {
$rdr_if_list = "{ {$rdr_if_list} }";
+ }
$natrules .= "\n# Reflection redirect\n";
$natrules .= "{$nordr}rdr {$rdrpass}on {$rdr_if_list} proto {$protocol} from {$srcaddr} to {$dstaddr_reflect}" . ($nordr == "" ? " -> {$target}{$localport}" : "");
$nat_if_list = array_merge(array($natif), $nat_if_list);
}
}
- if(empty($nat_if_list))
+ if (empty($nat_if_list)) {
$nat_if_list = array($natif);
+ }
$natrules .= "\n";
- if(!isset($rule['nordr']))
+ if (!isset($rule['nordr'])) {
$natrules .= filter_generate_reflection_nat($rule, $route_table, $nat_if_list, $protocol, "{$target}{$localport_nat}", $target_ip);
+ }
}
}
}
@@ -2070,16 +2252,18 @@ function filter_nat_rules_generate() {
$natrules .= "# UPnPd rdr anchor\n";
$natrules .= "rdr-anchor \"miniupnpd\"\n";
- if(!empty($reflection_txt))
+ if (!empty($reflection_txt)) {
$natrules .= "\n# Reflection redirects and NAT for 1:1 mappings\n" . $reflection_txt;
+ }
// Check if inetd is running, if not start it. If so, restart it gracefully.
$helpers = isvalidproc("inetd");
- if(file_exists("/var/etc/inetd.conf")) {
- if(!$helpers)
+ if (file_exists("/var/etc/inetd.conf")) {
+ if (!$helpers) {
mwexec("/usr/sbin/inetd -wW -R 0 -a 127.0.0.1 /var/etc/inetd.conf");
- else
+ } else {
sigkillbypid("/var/run/inetd.pid", "HUP");
+ }
}
return $natrules;
@@ -2092,10 +2276,11 @@ function filter_generate_user_rule_arr($rule) {
$line = filter_generate_user_rule($rule);
$ret['rule'] = $line;
$ret['interface'] = $rule['interface'];
- if($rule['descr'] != "" and $line != "")
+ if ($rule['descr'] != "" and $line != "") {
$ret['descr'] = "label \"" . fix_rule_label("USER_RULE: {$rule['descr']}") . "\"";
- else
+ } else {
$ret['descr'] = "label \"USER_RULE\"";
+ }
return $ret;
}
@@ -2105,22 +2290,22 @@ function filter_generate_port(& $rule, $target = "source", $isnat = false) {
$src = "";
$rule['protocol'] = strtolower($rule['protocol']);
- if(in_array($rule['protocol'], array("tcp","udp","tcp/udp"))) {
- if($rule[$target]['port']) {
+ if (in_array($rule['protocol'], array("tcp","udp","tcp/udp"))) {
+ if ($rule[$target]['port']) {
$srcport = explode("-", $rule[$target]['port']);
$srcporta = alias_expand($srcport[0]);
- if(!$srcporta)
+ if (!$srcporta) {
log_error(sprintf(gettext("filter_generate_port: %s is not a valid {$target} port."), $srcport[0]));
- else if((!$srcport[1]) || ($srcport[0] == $srcport[1])) {
+ } else if ((!$srcport[1]) || ($srcport[0] == $srcport[1])) {
$src .= " port {$srcporta} ";
- } else if(($srcport[0] == 1) && ($srcport[1] == 65535)) {
+ } else if (($srcport[0] == 1) && ($srcport[1] == 65535)) {
/* no need for a port statement here */
} else if ($isnat) {
$src .= " port {$srcport[0]}:{$srcport[1]}";
} else {
- if(is_port($srcporta) && $srcport[1] == 65535) {
+ if (is_port($srcporta) && $srcport[1] == 65535) {
$src .= " port >= {$srcporta} ";
- } else if($srcport[0] == 1) {
+ } else if ($srcport[0] == 1) {
$src .= " port <= {$srcport[1]} ";
} else {
$srcport[0]--;
@@ -2139,102 +2324,120 @@ function filter_address_add_vips_subnets(&$subnets, $if, $not) {
$if_subnets = array($subnets);
- if ($not == true)
+ if ($not == true) {
$subnets = "!{$subnets}";
+ }
- if (!isset($FilterIflist[$if]['vips']) || !is_array($FilterIflist[$if]['vips']))
+ if (!isset($FilterIflist[$if]['vips']) || !is_array($FilterIflist[$if]['vips'])) {
return;
+ }
foreach ($FilterIflist[$if]['vips'] as $vip) {
- foreach ($if_subnets as $subnet)
- if (ip_in_subnet($vip['ip'], $subnet))
+ foreach ($if_subnets as $subnet) {
+ if (ip_in_subnet($vip['ip'], $subnet)) {
continue 2;
+ }
+ }
if (is_ipaddrv4($vip['ip'])) {
- if (!is_subnetv4($if_subnets[0]))
+ if (!is_subnetv4($if_subnets[0])) {
continue;
+ }
$network = gen_subnet($vip['ip'], $vip['sn']);
} else if (is_ipaddrv6($vip['ip'])) {
- if (!is_subnetv6($if_subnets[0]))
+ if (!is_subnetv6($if_subnets[0])) {
continue;
+ }
$network = gen_subnetv6($vip['ip'], $vip['sn']);
- } else
+ } else {
continue;
+ }
$subnets .= ' ' . ($not == true ? '!' : '') . $network . '/' . $vip['sn'];
$if_subnets[] = $network . '/' . $vip['sn'];
}
unset($if_subnets);
- if (strpos($subnets, ' ') !== false)
+ if (strpos($subnets, ' ') !== false) {
$subnets = "{ {$subnets} }";
+ }
}
function filter_generate_address(& $rule, $target = "source", $isnat = false) {
global $FilterIflist, $config;
$src = "";
- if(isset($rule[$target]['any'])) {
+ if (isset($rule[$target]['any'])) {
$src = "any";
- } else if($rule[$target]['network']) {
- if(strstr($rule[$target]['network'], "opt")) {
+ } else if ($rule[$target]['network']) {
+ if (strstr($rule[$target]['network'], "opt")) {
$optmatch = "";
$matches = "";
- if($rule['ipprotocol'] == "inet6") {
- if(preg_match("/opt([0-9]*)$/", $rule[$target]['network'], $optmatch)) {
+ if ($rule['ipprotocol'] == "inet6") {
+ if (preg_match("/opt([0-9]*)$/", $rule[$target]['network'], $optmatch)) {
$opt_ip = $FilterIflist["opt{$optmatch[1]}"]['ipv6'];
- if(!is_ipaddrv6($opt_ip))
+ if (!is_ipaddrv6($opt_ip)) {
return "";
+ }
$src = $opt_ip . "/" . $FilterIflist["opt{$optmatch[1]}"]['snv6'];
/* check for opt$NUMip here */
- } else if(preg_match("/opt([0-9]*)ip/", $rule[$target]['network'], $matches)) {
+ } else if (preg_match("/opt([0-9]*)ip/", $rule[$target]['network'], $matches)) {
$src = $FilterIflist["opt{$matches[1]}"]['ipv6'];
- if(!is_ipaddrv6($src))
+ if (!is_ipaddrv6($src)) {
return "";
- if(isset($rule[$target]['not']))
+ }
+ if (isset($rule[$target]['not'])) {
$src = " !{$src}";
+ }
}
} else {
- if(preg_match("/opt([0-9]*)$/", $rule[$target]['network'], $optmatch)) {
+ if (preg_match("/opt([0-9]*)$/", $rule[$target]['network'], $optmatch)) {
$opt_ip = $FilterIflist["opt{$optmatch[1]}"]['ip'];
- if(!is_ipaddrv4($opt_ip))
+ if (!is_ipaddrv4($opt_ip)) {
return "";
+ }
$src = $opt_ip . "/" . $FilterIflist["opt{$optmatch[1]}"]['sn'];
/* check for opt$NUMip here */
- } else if(preg_match("/opt([0-9]*)ip/", $rule[$target]['network'], $matches)) {
+ } else if (preg_match("/opt([0-9]*)ip/", $rule[$target]['network'], $matches)) {
$src = $FilterIflist["opt{$matches[1]}"]['ip'];
- if(!is_ipaddrv4($src))
+ if (!is_ipaddrv4($src)) {
return "";
- if(isset($rule[$target]['not']))
+ }
+ if (isset($rule[$target]['not'])) {
$src = " !{$src}";
+ }
}
}
} else {
- if($rule['ipprotocol'] == "inet6") {
+ if ($rule['ipprotocol'] == "inet6") {
switch ($rule[$target]['network']) {
case 'wan':
$wansa = $FilterIflist['wan']['sav6'];
- if (!is_ipaddrv6($wansa))
+ if (!is_ipaddrv6($wansa)) {
return "";
+ }
$wansn = $FilterIflist['wan']['snv6'];
$src = "{$wansa}/{$wansn}";
break;
case 'wanip':
$src = $FilterIflist["wan"]['ipv6'];
- if (!is_ipaddrv6($src))
+ if (!is_ipaddrv6($src)) {
return "";
+ }
break;
case 'lanip':
$src = $FilterIflist["lan"]['ipv6'];
- if (!is_ipaddrv6($src))
+ if (!is_ipaddrv6($src)) {
return "";
+ }
break;
case 'lan':
$lansa = $FilterIflist['lan']['sav6'];
- if (!is_ipaddrv6($lansa))
+ if (!is_ipaddrv6($lansa)) {
return "";
+ }
$lansn = $FilterIflist['lan']['snv6'];
$src = "{$lansa}/{$lansn}";
break;
@@ -2253,14 +2456,16 @@ function filter_generate_address(& $rule, $target = "source", $isnat = false) {
$src = "{$pppoesav6}/{$pppoesnv6}";
}
}
- if(isset($rule[$target]['not']) && !is_subnet($src))
+ if (isset($rule[$target]['not']) && !is_subnet($src)) {
$src = " !{$src}";
+ }
} else {
switch ($rule[$target]['network']) {
case 'wan':
$wansa = $FilterIflist['wan']['sa'];
- if (!is_ipaddrv4($wansa))
+ if (!is_ipaddrv4($wansa)) {
return "";
+ }
$wansn = $FilterIflist['wan']['sn'];
$src = "{$wansa}/{$wansn}";
break;
@@ -2272,8 +2477,9 @@ function filter_generate_address(& $rule, $target = "source", $isnat = false) {
break;
case 'lan':
$lansa = $FilterIflist['lan']['sa'];
- if (!is_ipaddrv4($lansa))
+ if (!is_ipaddrv4($lansa)) {
return "";
+ }
$lansn = $FilterIflist['lan']['sn'];
$src = "{$lansa}/{$lansn}";
break;
@@ -2281,16 +2487,19 @@ function filter_generate_address(& $rule, $target = "source", $isnat = false) {
$src = "(self)";
break;
case 'pptp':
- if (isset($config['pptpd']['n_pptp_units']) && is_numeric($config['pptpd']['n_pptp_units']))
+ if (isset($config['pptpd']['n_pptp_units']) && is_numeric($config['pptpd']['n_pptp_units'])) {
$pptp_subnets = ip_range_to_subnet_array($config['pptpd']['remoteip'], long2ip32(ip2long($config['pptpd']['remoteip'])+($config['pptpd']['n_pptp_units']-1)));
- else
+ } else {
$pptp_subnets = ip_range_to_subnet_array($config['pptpd']['remoteip'], long2ip32(ip2long($config['pptpd']['remoteip'])));
- if (empty($pptp_subnets))
+ }
+ if (empty($pptp_subnets)) {
return "";
- if(isset($rule[$target]['not']))
+ }
+ if (isset($rule[$target]['not'])) {
array_walk($pptp_subnets, function (&$value, $key) {
$value="!{$value}";
});
+ }
$src = "{ " . implode(" ", $pptp_subnets) . " }";
break;
case 'pppoe':
@@ -2302,19 +2511,23 @@ function filter_generate_address(& $rule, $target = "source", $isnat = false) {
}
break;
}
- if(isset($rule[$target]['not']) && !is_subnet($src) &&
- (strpos($src, '{') === false))
+ if ((isset($rule[$target]['not'])) &&
+ (!is_subnet($src)) &&
+ (strpos($src, '{') === false)) {
$src = " !{$src}";
+ }
}
}
- if (is_subnet($src))
+ if (is_subnet($src)) {
filter_address_add_vips_subnets($src, $rule[$target]['network'], isset($rule[$target]['not']));
- } else if($rule[$target]['address']) {
+ }
+ } else if ($rule[$target]['address']) {
$expsrc = alias_expand($rule[$target]['address']);
- if(isset($rule[$target]['not']))
+ if (isset($rule[$target]['not'])) {
$not = "!";
- else
+ } else {
$not = "";
+ }
$src = " {$not} {$expsrc}";
}
@@ -2327,12 +2540,12 @@ function filter_generate_user_rule($rule) {
global $config, $g, $FilterIflist, $GatewaysList;
global $layer7_rules_list, $dummynet_name_list;
- if(isset($config['system']['developerspew'])) {
+ if (isset($config['system']['developerspew'])) {
$mt = microtime();
echo "filter_generate_user_rule() being called $mt\n";
}
/* don't include disabled rules */
- if(isset($rule['disabled'])) {
+ if (isset($rule['disabled'])) {
return "# rule " . $rule['descr'] . " disabled \n";
}
update_filter_reload_status("Creating filter rules {$rule['descr']} ...");
@@ -2341,125 +2554,139 @@ function filter_generate_user_rule($rule) {
$aline = array();
/* Check to see if the interface is in our list */
- if(isset($rule['floating'])) {
- if(isset($rule['interface']) && $rule['interface'] <> "") {
+ if (isset($rule['floating'])) {
+ if (isset($rule['interface']) && $rule['interface'] <> "") {
$interfaces = explode(",", $rule['interface']);
$ifliste = "";
foreach ($interfaces as $iface) {
- if(array_key_exists($iface, $FilterIflist))
+ if (array_key_exists($iface, $FilterIflist)) {
$ifliste .= " " . $FilterIflist[$iface]['if'] . " ";
+ }
}
- if($ifliste <> "")
+ if ($ifliste <> "") {
$aline['interface'] = " on { {$ifliste} } ";
- else
+ } else {
$aline['interface'] = "";
+ }
} else
$aline['interface'] = "";
- } else if(!array_key_exists($rule['interface'], $FilterIflist)) {
- foreach($FilterIflist as $oc)
+ } else if (!array_key_exists($rule['interface'], $FilterIflist)) {
+ foreach ($FilterIflist as $oc) {
$items .= $oc['descr'] . " ";
+ }
return "# array key \"{$rule['interface']}\" does not exist for \"" . $rule['descr'] . "\" in array: {{$items}}";
- } else if((array_key_exists($rule['interface'], $FilterIflist))
- && (is_array($FilterIflist[$rule['interface']]))
- && (is_array($FilterIflist[$rule['interface']][0]))) {
- /* Currently this only case for this is the pppoe server. There should be an existing macro with this name. */
+ } else if ((array_key_exists($rule['interface'], $FilterIflist)) &&
+ (is_array($FilterIflist[$rule['interface']])) &&
+ (is_array($FilterIflist[$rule['interface']][0]))) {
+ /* Currently the only case for this is the pppoe server. There should be an existing macro with this name. */
$aline['interface'] = " on \$" . $rule['interface'] . " ";
- } else
+ } else {
$aline['interface'] = " on \$" . $FilterIflist[$rule['interface']]['descr'] . " ";
+ }
$ifcfg = $FilterIflist[$rule['interface']];
- if($pptpdcfg['mode'] != "server") {
- if(($rule['source']['network'] == "pptp") ||
- ($rule['destination']['network'] == "pptp"))
- return "# source network or destination network == pptp on " . $rule['descr'];
+ if ($pptpdcfg['mode'] != "server") {
+ if (($rule['source']['network'] == "pptp") ||
+ ($rule['destination']['network'] == "pptp")) {
+ return "# source network or destination network == pptp on " . $rule['descr'];
+ }
}
- switch($rule['ipprotocol']) {
- case "inet":
- $aline['ipprotocol'] = "inet";
- break;
- case "inet6":
- $aline['ipprotocol'] = "inet6";
- break;
- default:
- $aline['ipprotocol'] = "";
- break;
+ switch ($rule['ipprotocol']) {
+ case "inet":
+ $aline['ipprotocol'] = "inet";
+ break;
+ case "inet6":
+ $aline['ipprotocol'] = "inet6";
+ break;
+ default:
+ $aline['ipprotocol'] = "";
+ break;
}
/* check for unresolvable aliases */
- if($rule['source']['address'] && !alias_expand($rule['source']['address'])) {
+ if ($rule['source']['address'] && !alias_expand($rule['source']['address'])) {
$error_text = "Unresolvable source alias '{$rule['source']['address']}' for rule '{$rule['descr']}'";
file_notice("Filter_Reload", $error_text);
return "# {$error_text}";
}
- if($rule['destination']['address'] && !alias_expand($rule['destination']['address'])) {
+ if ($rule['destination']['address'] && !alias_expand($rule['destination']['address'])) {
$error_text = "Unresolvable destination alias '{$rule['destination']['address']}' for rule '{$rule['descr']}'";
file_notice("Filter_Reload", $error_text);
return "# {$error_text}";
}
update_filter_reload_status("Setting up pass/block rules");
$type = $rule['type'];
- if($type != "pass" && $type != "block" && $type != "reject" && $type != "match") {
+ if ($type != "pass" && $type != "block" && $type != "reject" && $type != "match") {
/* default (for older rules) is pass */
$type = "pass";
}
- if($type == "reject") {
+ if ($type == "reject") {
$aline['type'] = "block return ";
- } else
+ } else {
$aline['type'] = $type . " ";
- if(isset($rule['floating']) && $rule['floating'] == "yes") {
- if($rule['direction'] != "any")
+ }
+ if (isset($rule['floating']) && $rule['floating'] == "yes") {
+ if ($rule['direction'] != "any") {
$aline['direction'] = " " . $rule['direction'] . " ";
+ }
} else {
/* ensure the direction is in */
$aline['direction'] = " in ";
}
- if(isset($rule['log']))
+ if (isset($rule['log'])) {
$aline['log'] = "log ";
- if(!isset($rule['floating']) || isset($rule['quick']))
+ }
+ if (!isset($rule['floating']) || isset($rule['quick'])) {
$aline['quick'] = " quick ";
+ }
/* set the gateway interface */
update_filter_reload_status(sprintf(gettext("Setting up pass/block rules %s"), $rule['descr']));
/* do not process reply-to for gateway'd rules */
- if($rule['gateway'] == "" && $aline['direction'] <> "" && (interface_has_gateway($rule['interface']) || interface_has_gatewayv6($rule['interface'])) && !isset($config['system']['disablereplyto']) && !isset($rule['disablereplyto']) && $type != "match") {
+ if ($rule['gateway'] == "" && $aline['direction'] <> "" && (interface_has_gateway($rule['interface']) || interface_has_gatewayv6($rule['interface'])) && !isset($config['system']['disablereplyto']) && !isset($rule['disablereplyto']) && $type != "match") {
if ($rule['ipprotocol'] == "inet6") {
$rg = get_interface_gateway_v6($rule['interface']);
- if (is_ipaddrv6($rg))
+ if (is_ipaddrv6($rg)) {
$aline['reply'] = "reply-to ( {$ifcfg['ifv6']} {$rg} ) ";
- else if ($rule['interface'] <> "pptp")
+ } else if ($rule['interface'] <> "pptp") {
log_error(sprintf(gettext("Could not find IPv6 gateway for interface (%s)."), $rule['interface']));
+ }
} else {
$rg = get_interface_gateway($rule['interface']);
- if (is_ipaddrv4($rg))
+ if (is_ipaddrv4($rg)) {
$aline['reply'] = "reply-to ( {$ifcfg['if']} {$rg} ) ";
- else if ($rule['interface'] <> "pptp")
+ } else if ($rule['interface'] <> "pptp") {
log_error(sprintf(gettext("Could not find IPv4 gateway for interface (%s)."), $rule['interface']));
+ }
}
}
/* if user has selected a custom gateway, lets work with it */
- else if($rule['gateway'] <> "" && $type == "pass") {
- if (isset($GatewaysList[$rule['gateway']]))
+ else if ($rule['gateway'] <> "" && $type == "pass") {
+ if (isset($GatewaysList[$rule['gateway']])) {
/* Add the load balanced gateways */
$aline['route'] = " \$GW{$rule['gateway']} ";
- else if (isset($config['system']['skip_rules_gw_down']))
+ } else if (isset($config['system']['skip_rules_gw_down'])) {
return "# rule " . $rule['descr'] . " disabled because gateway " . $rule['gateway'] . " is down ";
- else
+ } else {
log_error("The gateway: {$rule['gateway']} is invalid or unknown, not using it.");
+ }
}
if (isset($rule['protocol']) && !empty($rule['protocol'])) {
- if($rule['protocol'] == "tcp/udp")
+ if ($rule['protocol'] == "tcp/udp") {
$aline['prot'] = " proto { tcp udp } ";
- elseif(($rule['protocol'] == "icmp") && ($rule['ipprotocol'] == "inet6"))
+ } elseif (($rule['protocol'] == "icmp") && ($rule['ipprotocol'] == "inet6")) {
$aline['prot'] = " proto ipv6-icmp ";
- elseif($rule['protocol'] == "icmp")
+ } elseif ($rule['protocol'] == "icmp") {
$aline['prot'] = " proto icmp ";
- else
+ } else {
$aline['prot'] = " proto {$rule['protocol']} ";
+ }
} else {
- if($rule['source']['port'] <> "" || $rule['destination']['port'] <> "")
+ if ($rule['source']['port'] <> "" || $rule['destination']['port'] <> "") {
$aline['prot'] = " proto tcp ";
+ }
}
update_filter_reload_status(sprintf(gettext("Creating rule %s"), $rule['descr']));
@@ -2471,8 +2698,9 @@ function filter_generate_user_rule($rule) {
$aline['src'] = " from $src ";
/* OS signatures */
- if(($rule['protocol'] == "tcp") && ($rule['os'] <> ""))
+ if (($rule['protocol'] == "tcp") && ($rule['os'] <> "")) {
$aline['os'] = " os \"{$rule['os']}\" ";
+ }
/* destination address */
$dst = trim(filter_generate_address($rule, "destination"));
@@ -2484,60 +2712,88 @@ function filter_generate_user_rule($rule) {
//Layer7 support
$l7_present = false;
$l7_structures = array();
- if(isset($rule['l7container']) && $rule['l7container'] != "none") {
+ if (isset($rule['l7container']) && $rule['l7container'] != "none") {
$l7_present = true;
$l7rule =& $layer7_rules_list[$rule['l7container']];
$l7_structures = $l7rule->get_unique_structures();
$aline['divert'] = "divert-to " . $l7rule->GetRPort() . " ";
}
- if (($rule['protocol'] == "icmp") && $rule['icmptype'] && ($rule['ipprotocol'] == "inet"))
+ if (($rule['protocol'] == "icmp") && $rule['icmptype'] && ($rule['ipprotocol'] == "inet")) {
$aline['icmp-type'] = "icmp-type {$rule['icmptype']} ";
- if (($rule['protocol'] == "icmp") && $rule['icmptype'] && ($rule['ipprotocol'] == "inet6"))
+ }
+ if (($rule['protocol'] == "icmp") && $rule['icmptype'] && ($rule['ipprotocol'] == "inet6")) {
$aline['icmp6-type'] = "icmp6-type {$rule['icmptype']} ";
+ }
if (!empty($rule['tag'])) {
- if (ctype_digit($rule['tag']))
+ if (ctype_digit($rule['tag'])) {
$aline['tag'] = " tag \"" .$rule['tag']. "\" ";
- else
+ } else {
$aline['tag'] = " tag " .$rule['tag']. " ";
+ }
}
- if (!empty($rule['tagged']))
+ if (!empty($rule['tagged'])) {
$aline['tagged'] = " tagged " .$rule['tagged'] . " ";
+ }
if (!empty($rule['dscp'])) {
switch (strtolower($rule['dscp'])) {
- case 'va': $aline['dscp'] = " dscp \"44\" "; break;
- case 'VA': $aline['dscp'] = " dscp \"44\" "; break;
- case 'cs1': $aline['dscp'] = " dscp \"8\" "; break;
- case 'cs2': $aline['dscp'] = " dscp \"16\" "; break;
- case 'cs3': $aline['dscp'] = " dscp \"24\" "; break;
- case 'cs4': $aline['dscp'] = " dscp \"32\" "; break;
- case 'cs5': $aline['dscp'] = " dscp \"40\" "; break;
- case 'cs6': $aline['dscp'] = " dscp \"48\" "; break;
- case 'cs7': $aline['dscp'] = " dscp \"56\" "; break;
- default: $aline['dscp'] = " dscp " . $rule['dscp'] . " "; break;
- }
- }
- if (!empty($rule['vlanprio']) && ($rule['vlanprio'] != "none"))
+ case 'va':
+ $aline['dscp'] = " dscp \"44\" ";
+ break;
+ case 'VA':
+ $aline['dscp'] = " dscp \"44\" ";
+ break;
+ case 'cs1':
+ $aline['dscp'] = " dscp \"8\" ";
+ break;
+ case 'cs2':
+ $aline['dscp'] = " dscp \"16\" ";
+ break;
+ case 'cs3':
+ $aline['dscp'] = " dscp \"24\" ";
+ break;
+ case 'cs4':
+ $aline['dscp'] = " dscp \"32\" ";
+ break;
+ case 'cs5':
+ $aline['dscp'] = " dscp \"40\" ";
+ break;
+ case 'cs6':
+ $aline['dscp'] = " dscp \"48\" ";
+ break;
+ case 'cs7':
+ $aline['dscp'] = " dscp \"56\" ";
+ break;
+ default:
+ $aline['dscp'] = " dscp " . $rule['dscp'] . " ";
+ break;
+ }
+ }
+ if (!empty($rule['vlanprio']) && ($rule['vlanprio'] != "none")) {
$aline['vlanprio'] = " ieee8021q-pcp " . $rule['vlanprio'] . " ";
- if (!empty($rule['vlanprioset']) && ($rule['vlanprioset'] != "none"))
+ }
+ if (!empty($rule['vlanprioset']) && ($rule['vlanprioset'] != "none")) {
$aline['vlanprioset'] = " ieee8021q-setpcp " . $rule['vlanprioset'] . " ";
+ }
if ($type == "pass") {
- if (isset($rule['allowopts']))
+ if (isset($rule['allowopts'])) {
$aline['allowopts'] = " allow-opts ";
+ }
}
$aline['flags'] = "";
if ($rule['protocol'] == "tcp") {
- if (isset($rule['tcpflags_any']))
+ if (isset($rule['tcpflags_any'])) {
$aline['flags'] = "flags any ";
- else if (!empty($rule['tcpflags2'])) {
+ } else if (!empty($rule['tcpflags2'])) {
$aline['flags'] = "flags ";
if (!empty($rule['tcpflags1'])) {
$flags1 = explode(",", $rule['tcpflags1']);
foreach ($flags1 as $flag1) {
// CWR flag needs special treatment
- if($flag1[0] == "c")
+ if ($flag1[0] == "c") {
$aline['flags'] .= "W";
- else
+ } else {
$aline['flags'] .= strtoupper($flag1[0]);
+ }
}
}
$aline['flags'] .= "/";
@@ -2545,10 +2801,11 @@ function filter_generate_user_rule($rule) {
$flags2 = explode(",", $rule['tcpflags2']);
foreach ($flags2 as $flag2) {
// CWR flag needs special treatment
- if($flag2[0] == "c")
+ if ($flag2[0] == "c") {
$aline['flags'] .= "W";
- else
+ } else {
$aline['flags'] .= strtoupper($flag2[0]);
+ }
}
}
$aline['flags'] .= " ";
@@ -2572,15 +2829,16 @@ function filter_generate_user_rule($rule) {
*/
$noadvoptions = false;
if (isset($rule['statetype']) && $rule['statetype'] <> "") {
- switch($rule['statetype']) {
+ switch ($rule['statetype']) {
case "none":
$noadvoptions = true;
$aline['flags'] .= " no state ";
break;
case "modulate state":
case "synproxy state":
- if ($rule['protocol'] == "tcp")
+ if ($rule['protocol'] == "tcp") {
$aline['flags'] .= "{$rule['statetype']} ";
+ }
break;
case "sloppy state":
$aline['flags'] .= "keep state ";
@@ -2590,13 +2848,15 @@ function filter_generate_user_rule($rule) {
$aline['flags'] .= "{$rule['statetype']} ";
break;
}
- } else
+ } else {
$aline['flags'] .= "keep state ";
+ }
- if ($noadvoptions == false && isset($rule['nopfsync']))
+ if ($noadvoptions == false && isset($rule['nopfsync'])) {
$rule['nopfsync'] = true;
+ }
- if ($noadvoptions == false || $l7_present)
+ if ($noadvoptions == false || $l7_present) {
if ((isset($rule['source-track']) and $rule['source-track'] <> "") or
(isset($rule['max']) and $rule['max'] <> "") or
(isset($rule['max-src-nodes']) and $rule['max-src-nodes'] <> "") or
@@ -2606,76 +2866,93 @@ function filter_generate_user_rule($rule) {
(isset($rule['max-src-conn']) and $rule['max-src-conn'] <> "") or
(isset($rule['max-src-conn-rate']) and $rule['max-src-conn-rate'] <> "") or
(isset($rule['max-src-conn-rates']) and $rule['max-src-conn-rates'] <> ""))) or
- isset($rule['sloppy']) or isset($rule['nopfsync']) or $l7_present) {
- $aline['flags'] .= "( ";
- if (isset($rule['sloppy']))
- $aline['flags'] .= "sloppy ";
- if (isset($rule['nopfsync']))
- $aline['flags'] .= "no-sync ";
- if (isset($rule['source-track']) and $rule['source-track'] <> "")
- $aline['flags'] .= "source-track rule ";
- if (isset($rule['max']) and $rule['max'] <> "")
- $aline['flags'] .= "max " . $rule['max'] . " ";
- if (isset($rule['max-src-nodes']) and $rule['max-src-nodes'] <> "")
- $aline['flags'] .= "max-src-nodes " . $rule['max-src-nodes'] . " ";
- if ((in_array($rule['protocol'], array("tcp","tcp/udp")))
- and isset($rule['max-src-conn'])
- and $rule['max-src-conn'] <> "")
- $aline['flags'] .= "max-src-conn " . $rule['max-src-conn'] . " ";
- if (isset($rule['max-src-states']) and $rule['max-src-states'] <> "")
- $aline['flags'] .= "max-src-states " . $rule['max-src-states'] . " ";
- if ((in_array($rule['protocol'], array("tcp","tcp/udp")))
- and isset($rule['statetimeout'])
- and $rule['statetimeout'] <> "")
- $aline['flags'] .= "tcp.established " . $rule['statetimeout'] . " ";
- if ((in_array($rule['protocol'], array("tcp","tcp/udp")))
- and isset($rule['max-src-conn-rate'])
- and $rule['max-src-conn-rate'] <> ""
- and isset($rule['max-src-conn-rates'])
- and $rule['max-src-conn-rates'] <> "") {
- $aline['flags'] .= "max-src-conn-rate " . $rule['max-src-conn-rate'] . " ";
- $aline['flags'] .= "/" . $rule['max-src-conn-rates'] . ", overload <virusprot> flush global ";
- }
-
- if(!empty($aline['divert']))
- $aline['flags'] .= "max-packets 8 ";
+ (isset($rule['sloppy'])) or
+ (isset($rule['nopfsync'])) or
+ ($l7_present)) {
+ $aline['flags'] .= "( ";
+ if (isset($rule['sloppy'])) {
+ $aline['flags'] .= "sloppy ";
+ }
+ if (isset($rule['nopfsync'])) {
+ $aline['flags'] .= "no-sync ";
+ }
+ if (isset($rule['source-track']) and $rule['source-track'] <> "") {
+ $aline['flags'] .= "source-track rule ";
+ }
+ if (isset($rule['max']) and $rule['max'] <> "") {
+ $aline['flags'] .= "max " . $rule['max'] . " ";
+ }
+ if (isset($rule['max-src-nodes']) and $rule['max-src-nodes'] <> "") {
+ $aline['flags'] .= "max-src-nodes " . $rule['max-src-nodes'] . " ";
+ }
+ if ((in_array($rule['protocol'], array("tcp","tcp/udp"))) and
+ (isset($rule['max-src-conn'])) and
+ ($rule['max-src-conn'] <> "")) {
+ $aline['flags'] .= "max-src-conn " . $rule['max-src-conn'] . " ";
+ }
+ if (isset($rule['max-src-states']) and $rule['max-src-states'] <> "") {
+ $aline['flags'] .= "max-src-states " . $rule['max-src-states'] . " ";
+ }
+ if ((in_array($rule['protocol'], array("tcp","tcp/udp"))) and
+ (isset($rule['statetimeout'])) and
+ ($rule['statetimeout'] <> "")) {
+ $aline['flags'] .= "tcp.established " . $rule['statetimeout'] . " ";
+ }
+ if ((in_array($rule['protocol'], array("tcp","tcp/udp"))) and
+ (isset($rule['max-src-conn-rate'])) and
+ ($rule['max-src-conn-rate'] <> "") and
+ (isset($rule['max-src-conn-rates'])) and
+ ($rule['max-src-conn-rates'] <> "")) {
+ $aline['flags'] .= "max-src-conn-rate " . $rule['max-src-conn-rate'] . " ";
+ $aline['flags'] .= "/" . $rule['max-src-conn-rates'] . ", overload <virusprot> flush global ";
+ }
- $aline['flags'] .= " ) ";
+ if (!empty($aline['divert'])) {
+ $aline['flags'] .= "max-packets 8 ";
}
+
+ $aline['flags'] .= " ) ";
+ }
+ }
}
- if($rule['defaultqueue'] <> "") {
+ if ($rule['defaultqueue'] <> "") {
$aline['queue'] = " queue (".$rule['defaultqueue'];
- if($rule['ackqueue'] <> "")
+ if ($rule['ackqueue'] <> "") {
$aline['queue'] .= ",".$rule['ackqueue'];
+ }
$aline['queue'] .= ") ";
}
- if($rule['dnpipe'] <> "") {
+ if ($rule['dnpipe'] <> "") {
if (!empty($dummynet_name_list[$rule['dnpipe']])) {
- if($dummynet_name_list[$rule['dnpipe']][0] == "?") {
+ if ($dummynet_name_list[$rule['dnpipe']][0] == "?") {
$aline['dnpipe'] = " dnqueue( ";
$aline['dnpipe'] .= substr($dummynet_name_list[$rule['dnpipe']],1);
- if($rule['pdnpipe'] <> "")
+ if ($rule['pdnpipe'] <> "") {
$aline['dnpipe'] .= ",".substr($dummynet_name_list[$rule['pdnpipe']], 1);
+ }
} else {
$aline['dnpipe'] = " dnpipe ( " . $dummynet_name_list[$rule['dnpipe']];
- if($rule['pdnpipe'] <> "")
+ if ($rule['pdnpipe'] <> "") {
$aline['dnpipe'] .= "," . $dummynet_name_list[$rule['pdnpipe']];
+ }
}
$aline['dnpipe'] .= ") ";
}
}
/* is a time based rule schedule attached? */
- if(!empty($rule['sched']) && !empty($config['schedules'])) {
+ if (!empty($rule['sched']) && !empty($config['schedules'])) {
$aline['schedlabel'] = "";
foreach ($config['schedules']['schedule'] as $sched) {
- if($sched['name'] == $rule['sched']) {
- if(!filter_get_time_based_rule_status($sched)) {
- if(!isset($config['system']['schedule_states']))
+ if ($sched['name'] == $rule['sched']) {
+ if (!filter_get_time_based_rule_status($sched)) {
+ if (!isset($config['system']['schedule_states'])) {
mwexec("/sbin/pfctl -y {$sched['schedlabel']}");
+ }
return "# schedule finished - {$rule['descr']}";
- } else if($g['debug'])
+ } else if ($g['debug']) {
log_error("[TDR DEBUG] status true -- rule type '$type'");
+ }
$aline['schedlabel'] = " schedule \"{$sched['schedlabel']}\" ";
break;
@@ -2683,13 +2960,14 @@ function filter_generate_user_rule($rule) {
}
}
- if (!empty($rule['tracker']))
+ if (!empty($rule['tracker'])) {
$aline['tracker'] = "tracker {$rule['tracker']} ";
+ }
$line = "";
/* exception(s) to a user rules can go here. */
/* rules with a gateway or pool should create another rule for routing to vpns */
- if((($aline['route'] <> "") && (trim($aline['type']) == "pass") && strstr($dst, "any")) && (!isset($config['system']['disablenegate']))) {
+ if ((($aline['route'] <> "") && (trim($aline['type']) == "pass") && strstr($dst, "any")) && (!isset($config['system']['disablenegate']))) {
/* negate VPN/PPTP/PPPoE/Static Route networks for load balancer/gateway rules */
$negate_networks = " to <negate_networks> " . filter_generate_port($rule, "destination");
$line .= $aline['type'] . $aline['direction'] . $aline['log'] . $aline['quick'] .
@@ -2718,7 +2996,7 @@ function filter_rules_generate() {
$increment_tracker = 'filter_rule_tracker';
update_filter_reload_status(gettext("Creating default rules"));
- if(isset($config['system']['developerspew'])) {
+ if (isset($config['system']['developerspew'])) {
$mt = microtime();
echo "filter_rules_generate() being called $mt\n";
}
@@ -2736,15 +3014,17 @@ function filter_rules_generate() {
$ipfrules .= "anchor \"ipsec/*\"\n";
# BEGIN OF firewall rules
/* default block logging? */
- $log = array();
- if(!isset($config['syslog']['nologdefaultblock']))
+ $log = array();
+ if (!isset($config['syslog']['nologdefaultblock'])) {
$log['block'] = "log";
- if(isset($config['syslog']['nologdefaultpass']))
+ }
+ if (isset($config['syslog']['nologdefaultpass'])) {
$log['pass'] = "log";
+ }
$saved_tracker = $tracker;
- if(!isset($config['system']['ipv6allow'])) {
+ if (!isset($config['system']['ipv6allow'])) {
$ipfrules .= "# Allow IPv6 on loopback\n";
$ipfrules .= "pass in {$log['pass']} quick on \$loopback inet6 all tracker {$increment_tracker($tracker)} label \"pass IPv6 loopback\"\n";
$ipfrules .= "pass out {$log['pass']} quick on \$loopback inet6 all tracker {$increment_tracker($tracker)} label \"pass IPv6 loopback\"\n";
@@ -2810,33 +3090,37 @@ EOD;
$tracker = $saved_tracker;
$ipfrules .= "\n# SSH lockout\n";
- if(is_array($config['system']['ssh']) && !empty($config['system']['ssh']['port'])) {
+ if (is_array($config['system']['ssh']) && !empty($config['system']['ssh']['port'])) {
$ipfrules .= "block in {$log['block']} quick proto tcp from <sshlockout> to (self) port ";
$ipfrules .= $config['system']['ssh']['port'];
$ipfrules .= " tracker {$increment_tracker($tracker)} label \"sshlockout\"\n";
} else {
- if($config['system']['ssh']['port'] <> "")
+ if ($config['system']['ssh']['port'] <> "") {
$sshport = $config['system']['ssh']['port'];
- else
+ } else {
$sshport = 22;
- if($sshport)
+ }
+ if ($sshport) {
$ipfrules .= "block in {$log['block']} quick proto tcp from <sshlockout> to (self) port {$sshport} tracker {$increment_tracker($tracker)} label \"sshlockout\"\n";
+ }
}
$saved_tracker += 50;
$tracker = $saved_tracker;
$ipfrules .= "\n# webConfigurator lockout\n";
- if(!$config['system']['webgui']['port']) {
- if($config['system']['webgui']['protocol'] == "http")
+ if (!$config['system']['webgui']['port']) {
+ if ($config['system']['webgui']['protocol'] == "http") {
$webConfiguratorlockoutport = "80";
- else
+ } else {
$webConfiguratorlockoutport = "443";
+ }
} else {
$webConfiguratorlockoutport = $config['system']['webgui']['port'];
}
- if($webConfiguratorlockoutport)
+ if ($webConfiguratorlockoutport) {
$ipfrules .= "block in {$log['block']} quick proto tcp from <webConfiguratorlockout> to (self) port {$webConfiguratorlockoutport} tracker {$increment_tracker($tracker)} label \"webConfiguratorlockout\"\n";
+ }
$saved_tracker += 100;
$tracker = $saved_tracker;
@@ -2853,29 +3137,32 @@ EOD;
/* if captive portal is enabled, ensure that access to this port
* is allowed on a locked down interface
*/
- if(is_array($config['captiveportal'])) {
+ if (is_array($config['captiveportal'])) {
foreach ($config['captiveportal'] as $cpcfg) {
- if(!isset($cpcfg['enable']))
+ if (!isset($cpcfg['enable'])) {
continue;
+ }
$cpinterfaces = explode(",", $cpcfg['interface']);
$cpiflist = array();
$cpiplist = array();
foreach ($cpinterfaces as $cpifgrp) {
- if(!isset($FilterIflist[$cpifgrp]))
+ if (!isset($FilterIflist[$cpifgrp])) {
continue;
+ }
$tmpif = get_real_interface($cpifgrp);
- if(!empty($tmpif)) {
+ if (!empty($tmpif)) {
$cpiflist[] = "{$tmpif}";
$cpipm = get_interface_ip($cpifgrp);
- if(is_ipaddr($cpipm)) {
+ if (is_ipaddr($cpipm)) {
$carpif = link_ip_to_carp_interface($cpipm);
if (!empty($carpif)) {
$cpiflist[] = $carpif;
$carpsif = explode(" ", $carpif);
foreach ($carpsif as $cpcarp) {
$carpip = find_interface_ip($cpcarp);
- if (is_ipaddr($carpip))
+ if (is_ipaddr($carpip)) {
$cpiplist[] = $carpip;
+ }
}
}
$cpiplist[] = $cpipm;
@@ -2900,8 +3187,8 @@ EOD;
$saved_tracker += 10;
$tracker = $saved_tracker;
- if(isset($config['system']['ipv6allow']) && ($oc['type6'] == "slaac" || $oc['type6'] == "dhcp6")) {
- // The DHCPv6 client rules ***MUST BE ABOVE BOGONSV6!*** https://redmine.pfsense.org/issues/3395
+ if (isset($config['system']['ipv6allow']) && ($oc['type6'] == "slaac" || $oc['type6'] == "dhcp6")) {
+ // The DHCPv6 client rules ***MUST BE ABOVE BOGONSV6!*** https://redmine.pfsense.org/issues/3395
$ipfrules .= <<<EOD
# allow our DHCPv6 client out to the {$oc['descr']}
pass in {$log['pass']} quick on \${$oc['descr']} proto udp from fe80::/10 port = 546 to fe80::/10 port = 546 tracker {$increment_tracker($tracker)} label "{$fix_rule_label("allow dhcpv6 client in {$oc['descr']}")}"
@@ -2918,12 +3205,13 @@ EOD;
/* block bogon networks */
/* http://www.cymru.com/Documents/bogon-bn-nonagg.txt */
/* file is automatically in cron every 3000 minutes */
- if(!isset($config['syslog']['nologbogons']))
+ if (!isset($config['syslog']['nologbogons'])) {
$bogonlog = "log";
- else
+ } else {
$bogonlog = "";
+ }
- if(isset($config['interfaces'][$on]['blockbogons'])) {
+ if (isset($config['interfaces'][$on]['blockbogons'])) {
$ipfrules .= <<<EOD
# block bogon networks (IPv4)
# http://www.cymru.com/Documents/bogon-bn-nonagg.txt
@@ -2931,7 +3219,7 @@ block in $bogonlog quick on \${$oc['descr']} from <bogons> to any tracker {$incr
EOD;
- if(isset($config['system']['ipv6allow'])) {
+ if (isset($config['system']['ipv6allow'])) {
$ipfrules .= <<<EOD
# block bogon networks (IPv6)
# http://www.team-cymru.org/Services/Bogons/fullbogons-ipv6.txt
@@ -2945,29 +3233,31 @@ EOD;
$tracker = $saved_tracker;
$isbridged = false;
- if(is_array($config['bridges']['bridged'])) {
+ if (is_array($config['bridges']['bridged'])) {
foreach ($config['bridges']['bridged'] as $oc2) {
- if(stristr($oc2['members'], $on)) {
+ if (stristr($oc2['members'], $on)) {
$isbridged = true;
break;
}
}
}
- if($oc['ip'] && !($isbridged) && isset($oc['spoofcheck']))
+ if ($oc['ip'] && !($isbridged) && isset($oc['spoofcheck'])) {
$ipfrules .= filter_rules_spoofcheck_generate($on, $oc, $log);
+ }
/* block private networks ? */
- if(!isset($config['syslog']['nologprivatenets']))
+ if (!isset($config['syslog']['nologprivatenets'])) {
$privnetlog = "log";
- else
+ } else {
$privnetlog = "";
+ }
$saved_tracker += 10;
$tracker = $saved_tracker;
- if(isset($config['interfaces'][$on]['blockpriv'])) {
- if($isbridged == false) {
+ if (isset($config['interfaces'][$on]['blockpriv'])) {
+ if ($isbridged == false) {
$ipfrules .= <<<EOD
# block anything from private networks on interfaces with the option set
block in $privnetlog quick on \${$oc['descr']} from 10.0.0.0/8 to any tracker {$increment_tracker($tracker)} label "{$fix_rule_label("Block private networks from {$oc['descr']} block 10/8")}"
@@ -2984,16 +3274,16 @@ EOD;
$tracker = $saved_tracker;
switch ($oc['type']) {
- case "pptp":
+ case "pptp":
$ipfrules .= <<<EOD
# allow PPTP client
pass in {$log['pass']} on \${$oc['descr']} proto tcp from any to any port = 1723 flags S/SA modulate state tracker {$increment_tracker($tracker)} label "{$fix_rule_label("allow PPTP client on {$oc['descr']}")}"
pass in {$log['pass']} on \${$oc['descr']} proto gre from any to any keep state tracker {$increment_tracker($tracker)} label "{$fix_rule_label("allow PPTP client on {$oc['descr']}")}"
EOD;
- break;
- case "dhcp":
- $ipfrules .= <<<EOD
+ break;
+ case "dhcp":
+ $ipfrules .= <<<EOD
# allow our DHCP client out to the {$oc['descr']}
pass in {$log['pass']} on \${$oc['descr']} proto udp from any port = 67 to any port = 68 tracker {$increment_tracker($tracker)} label "{$fix_rule_label("allow dhcp client out {$oc['descr']}")}"
pass out {$log['pass']} on \${$oc['descr']} proto udp from any port = 68 to any port = 67 tracker {$increment_tracker($tracker)} label "{$fix_rule_label("allow dhcp client out {$oc['descr']}")}"
@@ -3001,81 +3291,82 @@ pass out {$log['pass']} on \${$oc['descr']} proto udp from any port = 68 to any
EOD;
- break;
- case "pppoe":
- case "none":
+ break;
+ case "pppoe":
+ case "none":
/* XXX: Nothing to do in this case?! */
- break;
- default:
+ break;
+ default:
/* allow access to DHCP server on interfaces */
- if(isset($config['dhcpd'][$on]['enable'])) {
- $ipfrules .= <<<EOD
+ if (isset($config['dhcpd'][$on]['enable'])) {
+ $ipfrules .= <<<EOD
# allow access to DHCP server on {$oc['descr']}
pass in {$log['pass']} quick on \${$oc['descr']} proto udp from any port = 68 to 255.255.255.255 port = 67 tracker {$increment_tracker($tracker)} label "allow access to DHCP server"
EOD;
- if (is_ipaddrv4($oc['ip'])) {
- $ipfrules .= <<<EOD
+ if (is_ipaddrv4($oc['ip'])) {
+ $ipfrules .= <<<EOD
pass in {$log['pass']} quick on \${$oc['descr']} proto udp from any port = 68 to {$oc['ip']} port = 67 tracker {$increment_tracker($tracker)} label "allow access to DHCP server"
pass out {$log['pass']} quick on \${$oc['descr']} proto udp from {$oc['ip']} port = 67 to any port = 68 tracker {$increment_tracker($tracker)} label "allow access to DHCP server"
EOD;
- }
+ }
- if(is_ipaddrv4($oc['ip']) && $config['dhcpd'][$on]['failover_peerip'] <> "") {
- $ipfrules .= <<<EOD
+ if (is_ipaddrv4($oc['ip']) && $config['dhcpd'][$on]['failover_peerip'] <> "") {
+ $ipfrules .= <<<EOD
# allow access to DHCP failover on {$oc['descr']} from {$config['dhcpd'][$on]['failover_peerip']}
pass in {$log['pass']} quick on \${$oc['descr']} proto { tcp udp } from {$config['dhcpd'][$on]['failover_peerip']} to {$oc['ip']} port = 519 tracker {$increment_tracker($tracker)} label "allow access to DHCP failover"
pass in {$log['pass']} quick on \${$oc['descr']} proto { tcp udp } from {$config['dhcpd'][$on]['failover_peerip']} to {$oc['ip']} port = 520 tracker {$increment_tracker($tracker)} label "allow access to DHCP failover"
EOD;
- }
+ }
- }
- break;
+ }
+ break;
}
$saved_tracker += 10;
$tracker = $saved_tracker;
- switch($oc['type6']) {
- case "6rd":
- $ipfrules .= <<<EOD
+ switch ($oc['type6']) {
+ case "6rd":
+ $ipfrules .= <<<EOD
# allow our proto 41 traffic from the 6RD border relay in
pass in {$log['pass']} on \${$oc['descr']} proto 41 from {$config['interfaces'][$on]['gateway-6rd']} to any tracker {$increment_tracker($tracker)} label "{$fix_rule_label("Allow 6in4 traffic in for 6rd on {$oc['descr']}")}"
pass out {$log['pass']} on \${$oc['descr']} proto 41 from any to {$config['interfaces'][$on]['gateway-6rd']} tracker {$increment_tracker($tracker)} label "{$fix_rule_label("Allow 6in4 traffic out for 6rd on {$oc['descr']}")}"
EOD;
- /* XXX: Really need to allow 6rd traffic coming in for v6 this is against default behaviour! */
- if (0 && is_ipaddrv6($oc['ipv6'])) {
- $ipfrules .= <<<EOD
+ /* XXX: Really need to allow 6rd traffic coming in for v6 this is against default behaviour! */
+ if (0 && is_ipaddrv6($oc['ipv6'])) {
+ $ipfrules .= <<<EOD
pass in {$log['pass']} on \${$oc['descr']} inet6 from any to {$oc['ipv6']}/{$oc['snv6']} tracker {$increment_tracker($tracker)} label "{$fix_rule_label("Allow 6rd traffic in for 6rd on {$oc['descr']}")}"
pass out {$log['pass']} on \${$oc['descr']} inet6 from {$oc['ipv6']}/{$oc['snv6']} to any tracker {$increment_tracker($tracker)} label "{$fix_rule_label("Allow 6rd traffic out for 6rd on {$oc['descr']}")}"
EOD;
- }
- break;
- case "6to4":
- if (is_ipaddrv4($oc['ip'])) {
- $ipfrules .= <<<EOD
+ }
+ break;
+ case "6to4":
+ if (is_ipaddrv4($oc['ip'])) {
+ $ipfrules .= <<<EOD
# allow our proto 41 traffic from the 6to4 border relay in
pass in {$log['pass']} on \${$oc['descr']} proto 41 from any to {$oc['ip']} tracker {$increment_tracker($tracker)} label "{$fix_rule_label("Allow 6in4 traffic in for 6to4 on {$oc['descr']}")}"
pass out {$log['pass']} on \${$oc['descr']} proto 41 from {$oc['ip']} to any tracker {$increment_tracker($tracker)} label "{$fix_rule_label("Allow 6in4 traffic out for 6to4 on {$oc['descr']}")}"
EOD;
- }
- /* XXX: Really need to allow 6to4 traffic coming in for v6 this is against default behaviour! */
- if (0 && is_ipaddrv6($oc['ipv6'])) {
- $ipfrules .= <<<EOD
+ }
+ /* XXX: Really need to allow 6to4 traffic coming in for v6 this is against default behaviour! */
+ if (0 && is_ipaddrv6($oc['ipv6'])) {
+ $ipfrules .= <<<EOD
pass in {$log['pass']} on \${$oc['descr']} inet6 from any to {$oc['ipv6']}/{$oc['snv6']} tracker {$increment_tracker($tracker)} label "{$fix_rule_label("Allow 6in4 traffic in for 6to4 on {$oc['descr']}")}"
pass out {$log['pass']} on \${$oc['descr']} inet6 from {$oc['ipv6']}/{$oc['snv6']} to any tracker {$increment_tracker($tracker)} label "{$fix_rule_label("Allow 6in4 traffic out for 6to4 on {$oc['descr']}")}"
EOD;
- }
- break;
- default:
- if ((is_array($config['dhcpdv6'][$on]) && isset($config['dhcpdv6'][$on]['enable'])) || isset($oc['track6-interface'])
- || (is_array($config['dhcrelay6']) && !empty($config['dhcrelay6']['interface']) && in_array($on, explode(',', $config['dhcrelay6']['interface'])))) {
- $ipfrules .= <<<EOD
+ }
+ break;
+ default:
+ if ((is_array($config['dhcpdv6'][$on]) && isset($config['dhcpdv6'][$on]['enable'])) ||
+ (isset($oc['track6-interface'])) ||
+ (is_array($config['dhcrelay6']) && !empty($config['dhcrelay6']['interface']) && in_array($on, explode(',', $config['dhcrelay6']['interface'])))) {
+ $ipfrules .= <<<EOD
# allow access to DHCPv6 server on {$oc['descr']}
# We need inet6 icmp for stateless autoconfig and dhcpv6
pass {$log['pass']} quick on \${$oc['descr']} inet6 proto udp from fe80::/10 to fe80::/10 port = 546 tracker {$increment_tracker($tracker)} label "allow access to DHCPv6 server"
@@ -3084,15 +3375,15 @@ pass {$log['pass']} quick on \${$oc['descr']} inet6 proto udp from fe80::/10 to
pass {$log['pass']} quick on \${$oc['descr']} inet6 proto udp from ff02::/16 to fe80::/10 port = 547 tracker {$increment_tracker($tracker)} label "allow access to DHCPv6 server"
EOD;
- if (is_ipaddrv6($oc['ipv6'])) {
- $ipfrules .= <<<EOD
+ if (is_ipaddrv6($oc['ipv6'])) {
+ $ipfrules .= <<<EOD
pass in {$log['pass']} quick on \${$oc['descr']} inet6 proto udp from fe80::/10 to {$oc['ipv6']} port = 546 tracker {$increment_tracker($tracker)} label "allow access to DHCPv6 server"
pass out {$log['pass']} quick on \${$oc['descr']} inet6 proto udp from {$oc['ipv6']} port = 547 to fe80::/10 tracker {$increment_tracker($tracker)} label "allow access to DHCPv6 server"
EOD;
+ }
}
- }
- break;
+ break;
}
}
@@ -3120,18 +3411,21 @@ EOD;
$saved_tracker += 100;
$tracker = $saved_tracker;
foreach ($FilterIflist as $ifdescr => $ifcfg) {
- if(isset($ifcfg['virtual']))
+ if (isset($ifcfg['virtual'])) {
continue;
+ }
$gw = get_interface_gateway($ifdescr);
if (is_ipaddrv4($gw) && is_ipaddrv4($ifcfg['ip'])) {
$ipfrules .= "pass out {$log['pass']} route-to ( {$ifcfg['if']} {$gw} ) from {$ifcfg['ip']} to !{$ifcfg['sa']}/{$ifcfg['sn']} tracker {$increment_tracker($tracker)} keep state allow-opts label \"let out anything from firewall host itself\"\n";
if (is_array($ifcfg['vips'])) {
- foreach ($ifcfg['vips'] as $vip)
- if (ip_in_subnet($vip['ip'], "{$ifcfg['sa']}/{$ifcfg['sn']}"))
+ foreach ($ifcfg['vips'] as $vip) {
+ if (ip_in_subnet($vip['ip'], "{$ifcfg['sa']}/{$ifcfg['sn']}")) {
$ipfrules .= "pass out {$log['pass']} route-to ( {$ifcfg['if']} {$gw} ) from {$vip['ip']} to !{$ifcfg['sa']}/{$ifcfg['sn']} tracker {$increment_tracker($tracker)} keep state allow-opts label \"let out anything from firewall host itself\"\n";
- else
+ } else {
$ipfrules .= "pass out {$log['pass']} route-to ( {$ifcfg['if']} {$gw} ) from {$vip['ip']} to !" . gen_subnet($vip['ip'], $vip['sn']) . "/{$vip['sn']} tracker {$increment_tracker($tracker)} keep state allow-opts label \"let out anything from firewall host itself\"\n";
+ }
+ }
}
}
@@ -3141,8 +3435,9 @@ EOD;
if (is_ipaddrv6($gwv6) && is_ipaddrv6($ifcfg['ipv6'])) {
$ipfrules .= "pass out {$log['pass']} route-to ( {$stf} {$gwv6} ) inet6 from {$ifcfg['ipv6']} to !{$ifcfg['ipv6']}/{$pdlen} tracker {$increment_tracker($tracker)} keep state allow-opts label \"let out anything from firewall host itself\"\n";
if (is_array($ifcfg['vips6'])) {
- foreach ($ifcfg['vips6'] as $vip)
+ foreach ($ifcfg['vips6'] as $vip) {
$ipfrules .= "pass out {$log['pass']} route-to ( {$stf} {$gwv6} ) inet6 from {$vip['ip']} to !{$vip['ip']}/{$pdlen} tracker {$increment_tracker($tracker)} keep state allow-opts label \"let out anything from firewall host itself\"\n";
+ }
}
}
}
@@ -3151,20 +3446,21 @@ EOD;
$saved_tracker += 300;
$tracker = $saved_tracker;
/* add ipsec interfaces */
- if(isset($config['ipsec']['enable']) || isset($config['ipsec']['client']['enable']))
+ if (isset($config['ipsec']['enable']) || isset($config['ipsec']['client']['enable'])) {
$ipfrules .= "pass out {$log['pass']} on \$IPsec all tracker {$increment_tracker($tracker)} tracker {$increment_tracker($tracker)} keep state label \"IPsec internal host to host\"\n";
+ }
$saved_tracker += 10;
$tracker = $saved_tracker;
- if(is_array($config['system']['webgui']) && !isset($config['system']['webgui']['noantilockout'])) {
+ if (is_array($config['system']['webgui']) && !isset($config['system']['webgui']['noantilockout'])) {
$alports = filter_get_antilockout_ports();
- if(count($config['interfaces']) > 1 && !empty($FilterIflist['lan']['if'])) {
- /* if antilockout is enabled, LAN exists and has
- * an IP and subnet mask assigned
- */
- $lanif = $FilterIflist['lan']['if'];
- $ipfrules .= <<<EOD
+ if (count($config['interfaces']) > 1 && !empty($FilterIflist['lan']['if'])) {
+ /* if antilockout is enabled, LAN exists and has
+ * an IP and subnet mask assigned
+ */
+ $lanif = $FilterIflist['lan']['if'];
+ $ipfrules .= <<<EOD
# make sure the user cannot lock himself out of the webConfigurator or SSH
pass in {$log['pass']} quick on {$lanif} proto tcp from any to ({$lanif}) port { {$alports} } tracker {$increment_tracker($tracker)} keep state label "anti-lockout rule"
@@ -3184,12 +3480,13 @@ EOD;
$saved_tracker += 10;
$tracker = $saved_tracker;
/* PPTPd enabled? */
- if($pptpdcfg['mode'] && ($pptpdcfg['mode'] != "off") && !isset($config['system']['disablevpnrules'])) {
- if($pptpdcfg['mode'] == "server")
+ if ($pptpdcfg['mode'] && ($pptpdcfg['mode'] != "off") && !isset($config['system']['disablevpnrules'])) {
+ if ($pptpdcfg['mode'] == "server") {
$pptpdtarget = get_interface_ip();
- else
+ } else {
$pptpdtarget = $pptpdcfg['redir'];
- if(is_ipaddr($pptpdtarget) and is_array($FilterIflist['wan'])) {
+ }
+ if (is_ipaddr($pptpdtarget) and is_array($FilterIflist['wan'])) {
$ipfrules .= <<<EOD
# PPTPd rules
pass in {$log['pass']} on \${$FilterIflist['wan']['descr']} proto tcp from any to $pptpdtarget port = 1723 tracker {$increment_tracker($tracker)} modulate state label "{$fix_rule_label("allow pptpd {$pptpdtarget}")}"
@@ -3207,10 +3504,10 @@ EOD;
$saved_tracker += 10;
$tracker = $saved_tracker;
- if(isset($config['nat']['rule']) && is_array($config['nat']['rule'])) {
+ if (isset($config['nat']['rule']) && is_array($config['nat']['rule'])) {
foreach ($config['nat']['rule'] as $rule) {
- if((!isset($config['system']['disablenatreflection']) || $rule['natreflection'] == "enable")
- && $rule['natreflection'] != "disable") {
+ if ((!isset($config['system']['disablenatreflection']) || $rule['natreflection'] == "enable") &&
+ ($rule['natreflection'] != "disable")) {
$ipfrules .= "# NAT Reflection rules\n";
$ipfrules .= <<<EOD
pass in {$log['pass']} inet tagged PFREFLECT tracker {$increment_tracker($tracker)} keep state label "NAT REFLECT: Allow traffic to localhost"
@@ -3232,8 +3529,9 @@ EOD;
*/
foreach ($config['filter']['rule'] as $rule) {
update_filter_reload_status("Pre-caching {$rule['descr']}...");
- if (isset ($rule['disabled']))
+ if (isset ($rule['disabled'])) {
continue;
+ }
if (!empty($rule['ipprotocol']) && $rule['ipprotocol'] == "inet46") {
if (isset($rule['floating'])) {
@@ -3254,39 +3552,47 @@ EOD;
}
$rule['ipprotocol'] = "inet46";
} else {
- if (isset($rule['floating']))
+ if (isset($rule['floating'])) {
$rule_arr1[] = filter_generate_user_rule_arr($rule);
- else if (is_interface_group($rule['interface']) || in_array($rule['interface'], $vpn_and_ppp_ifs))
+ } else if (is_interface_group($rule['interface']) || in_array($rule['interface'], $vpn_and_ppp_ifs)) {
$rule_arr2[] = filter_generate_user_rule_arr($rule);
- else
+ } else {
$rule_arr3[] = filter_generate_user_rule_arr($rule);
+ }
}
- if ($rule['sched'])
+ if ($rule['sched']) {
$time_based_rules = true;
+ }
}
$ipfrules .= "\n# User-defined rules follow\n";
$ipfrules .= "\nanchor \"userrules/*\"\n";
/* Generate user rule lines */
- foreach($rule_arr1 as $rule) {
- if (isset($rule['disabled']))
+ foreach ($rule_arr1 as $rule) {
+ if (isset($rule['disabled'])) {
continue;
- if (!$rule['rule'])
+ }
+ if (!$rule['rule']) {
continue;
+ }
$ipfrules .= "{$rule['rule']} {$rule['descr']}\n";
}
- foreach($rule_arr2 as $rule) {
- if (isset($rule['disabled']))
+ foreach ($rule_arr2 as $rule) {
+ if (isset($rule['disabled'])) {
continue;
- if (!$rule['rule'])
+ }
+ if (!$rule['rule']) {
continue;
+ }
$ipfrules .= "{$rule['rule']} {$rule['descr']}\n";
}
- foreach($rule_arr3 as $rule) {
- if (isset($rule['disabled']))
+ foreach ($rule_arr3 as $rule) {
+ if (isset($rule['disabled'])) {
continue;
- if (!$rule['rule'])
+ }
+ if (!$rule['rule']) {
continue;
+ }
$ipfrules .= "{$rule['rule']} {$rule['descr']}\n";
}
unset($rule_arr1, $rule_arr2, $rule_arr3);
@@ -3299,11 +3605,11 @@ EOD;
* interface in question to avoid problems with complicated routing
* topologies
*/
- if(isset($config['filter']['bypassstaticroutes']) && is_array($config['staticroutes']['route']) && count($config['staticroutes']['route'])) {
+ if (isset($config['filter']['bypassstaticroutes']) && is_array($config['staticroutes']['route']) && count($config['staticroutes']['route'])) {
$ipfrules .= "# Add rules to bypass firewall rules for static routes\n";
foreach (get_staticroutes() as $route) {
$friendly = $GatewaysList[$route['gateway']]['friendlyiface'];
- if(is_array($FilterIflist[$friendly])) {
+ if (is_array($FilterIflist[$friendly])) {
$oc = $FilterIflist[$friendly];
$routeent = explode("/", $route['network']);
unset($sa);
@@ -3349,20 +3655,21 @@ EOD;
$tracker = $saved_tracker;
update_filter_reload_status("Creating uPNP rules...");
if (is_array($config['installedpackages']['miniupnpd']) && is_array($config['installedpackages']['miniupnpd']['config'][0])) {
- if (isset($config['installedpackages']['miniupnpd']['config'][0]['enable']))
+ if (isset($config['installedpackages']['miniupnpd']['config'][0]['enable'])) {
$ipfrules .= "anchor \"miniupnpd\"\n";
+ }
if (is_array($config['installedpackages']['miniupnpd'][0]['config'])) {
$upnp_interfaces = explode(",", $config['installedpackages']['miniupnpd'][0]['config']['iface_array']);
- foreach($upnp_interfaces as $upnp_if) {
+ foreach ($upnp_interfaces as $upnp_if) {
if (is_array($FilterIflist[$upnp_if])) {
$oc = $FilterIflist[$upnp_if];
unset($sa);
- if($oc['ip']) {
+ if ($oc['ip']) {
$sa = $oc['sa'];
$sn = $oc['sn'];
}
- if($sa) {
+ if ($sa) {
$ipfrules .= <<<EOD
pass in {$log['pass']} on \${$oc['descr']} proto tcp from {$sa}/{$sn} to 239.255.255.250/32 port 1900 tracker {$increment_tracker($tracker)} keep state label "pass multicast traffic to miniupnpd"
@@ -3373,13 +3680,12 @@ EOD;
}
}
-
return $ipfrules;
}
function filter_rules_spoofcheck_generate($ifname, $ifcfg, $log) {
global $g, $config, $tracker;
- if(isset($config['system']['developerspew'])) {
+ if (isset($config['system']['developerspew'])) {
$mt = microtime();
echo "filter_rules_spoofcheck_generate() being called $mt\n";
}
@@ -3407,17 +3713,20 @@ function tdr_install_cron($should_install) {
function filter_tdr_install_cron($should_install) {
global $config, $g;
- if(platform_booting()==true)
+ if (platform_booting()==true) {
return;
+ }
- if (!is_array($config['cron']))
+ if (!is_array($config['cron'])) {
$config['cron'] = array();
- if (!is_array($config['cron']['item']))
+ }
+ if (!is_array($config['cron']['item'])) {
$config['cron']['item'] = array();
+ }
$x=0;
$is_installed = false;
- foreach($config['cron']['item'] as $item) {
+ foreach ($config['cron']['item'] as $item) {
if (strstr($item['command'], "filter_configure_sync")) {
$is_installed = true;
break;
@@ -3425,7 +3734,7 @@ function filter_tdr_install_cron($should_install) {
$x++;
}
- switch($should_install) {
+ switch ($should_install) {
case true:
if (!$is_installed) {
$cron_item = array();
@@ -3442,7 +3751,7 @@ function filter_tdr_install_cron($should_install) {
}
break;
case false:
- if ($is_installed == true) {
+ if ($is_installed) {
unset($config['cron']['item'][$x]);
write_config(gettext("Removed 15 minute filter reload for Time Based Rules"));
configure_cron();
@@ -3480,32 +3789,38 @@ function filter_tdr_install_cron($should_install) {
function filter_get_time_based_rule_status($schedule) {
/* no schedule? rule should be installed */
- if (empty($schedule))
+ if (empty($schedule)) {
return true;
+ }
/*
* iterate through time blocks and determine
* if the rule should be installed or not.
*/
- foreach($schedule['timerange'] as $timeday) {
- if (empty($timeday['month']))
+ foreach ($schedule['timerange'] as $timeday) {
+ if (empty($timeday['month'])) {
$monthstatus = true;
- else
+ } else {
$monthstatus = filter_tdr_month($timeday['month']);
- if (empty($timeday['day']))
+ }
+ if (empty($timeday['day'])) {
$daystatus = true;
- else
+ } else {
$daystatus = filter_tdr_day($timeday['day']);
- if (empty($timeday['hour']))
+ }
+ if (empty($timeday['hour'])) {
$hourstatus = true;
- else
+ } else {
$hourstatus = filter_tdr_hour($timeday['hour']);
- if (empty($timeday['position']))
+ }
+ if (empty($timeday['position'])) {
$positionstatus = true;
- else
+ } else {
$positionstatus = filter_tdr_position($timeday['position']);
+ }
- if ($monthstatus == true && $daystatus == true && $positionstatus == true && $hourstatus == true)
+ if ($monthstatus == true && $daystatus == true && $positionstatus == true && $hourstatus == true) {
return true;
+ }
}
return false;
@@ -3514,8 +3829,9 @@ function filter_get_time_based_rule_status($schedule) {
function filter_tdr_day($schedule) {
global $g;
- if($g['debug'])
+ if ($g['debug']) {
log_error("[TDR DEBUG] filter_tdr_day($schedule)");
+ }
/*
* Calculate day of month.
@@ -3523,9 +3839,10 @@ function filter_tdr_day($schedule) {
*/
$date = date("d");
$defined_days = explode(",", $schedule);
- foreach($defined_days as $dd) {
- if ($date == $dd)
+ foreach ($defined_days as $dd) {
+ if ($date == $dd) {
return true;
+ }
}
return false;
}
@@ -3537,10 +3854,12 @@ function filter_tdr_hour($schedule) {
$starting_time = strtotime($tmp[0]);
$ending_time = strtotime($tmp[1]);
$now = strtotime("now");
- if($g['debug'])
+ if ($g['debug']) {
log_error("[TDR DEBUG] S: $starting_time E: $ending_time N: $now");
- if($now >= $starting_time and $now < $ending_time)
+ }
+ if ($now >= $starting_time and $now < $ending_time) {
return true;
+ }
return false;
}
@@ -3555,14 +3874,17 @@ function filter_tdr_position($schedule) {
* ...
*/
$weekday = date("w");
- if($g['debug'])
+ if ($g['debug']) {
log_error("[TDR DEBUG] filter_tdr_position($schedule) $weekday");
- if($weekday == 0)
+ }
+ if ($weekday == 0) {
$weekday = 7;
+ }
$schedule_days = explode(",", $schedule);
- foreach($schedule_days as $day) {
- if($day == $weekday)
+ foreach ($schedule_days as $day) {
+ if ($day == $weekday) {
return true;
+ }
}
return false;
}
@@ -3575,11 +3897,13 @@ function filter_tdr_month($schedule) {
*/
$todays_month = date("n");
$months = explode(",", $schedule);
- if($g['debug'])
+ if ($g['debug']) {
log_error("[TDR DEBUG] filter_tdr_month($schedule)");
- foreach($months as $month) {
- if($month == $todays_month)
+ }
+ foreach ($months as $month) {
+ if ($month == $todays_month) {
return true;
+ }
}
return false;
}
@@ -3587,15 +3911,16 @@ function filter_tdr_month($schedule) {
function filter_setup_logging_interfaces() {
global $config, $FilterIflist;
- if(isset($config['system']['developerspew'])) {
+ if (isset($config['system']['developerspew'])) {
$mt = microtime();
echo "filter_setup_logging_interfaces() being called $mt\n";
}
$rules = "";
- if (isset($FilterIflist['lan']))
+ if (isset($FilterIflist['lan'])) {
$rules .= "set loginterface {$FilterIflist['lan']['if']}\n";
- else if (isset($FilterIflist['wan']))
+ } else if (isset($FilterIflist['wan'])) {
$rules .= "set loginterface {$FilterIflist['wan']['if']}\n";
+ }
return $rules;
}
@@ -3603,7 +3928,7 @@ function filter_setup_logging_interfaces() {
function filter_process_carp_rules($log) {
global $g, $config, $tracker;
- if(isset($config['system']['developerspew'])) {
+ if (isset($config['system']['developerspew'])) {
$mt = microtime();
echo "filter_process_carp_rules() being called $mt\n";
}
@@ -3622,63 +3947,72 @@ function filter_process_carp_rules($log) {
function filter_generate_ipsec_rules($log = array()) {
global $config, $g, $FilterIflist, $tracker;
- if(isset($config['system']['developerspew'])) {
+ if (isset($config['system']['developerspew'])) {
$mt = microtime();
echo "filter_generate_ipsec_rules() being called $mt\n";
}
- if (isset($config['system']['disablevpnrules']))
+ if (isset($config['system']['disablevpnrules'])) {
return "\n# VPN Rules not added disabled in System->Advanced.\n";
+ }
$increment_tracker = 'filter_rule_tracker';
$ipfrules = "\n# VPN Rules\n";
- if(isset($config['ipsec']['enable']) &&
- is_array($config['ipsec']['phase1'])) {
+ if ((isset($config['ipsec']['enable'])) &&
+ (is_array($config['ipsec']['phase1']))) {
/* step through all phase1 entries */
foreach ($config['ipsec']['phase1'] as $ph1ent) {
$tracker += 10;
- if(isset ($ph1ent['disabled']))
+ if (isset ($ph1ent['disabled'])) {
continue;
+ }
/* determine local and remote peer addresses */
- if(!isset($ph1ent['mobile'])) {
- if (!function_exists('ipsec_get_phase1_dst'))
+ if (!isset($ph1ent['mobile'])) {
+ if (!function_exists('ipsec_get_phase1_dst')) {
require_once("ipsec.inc");
+ }
$rgip = ipsec_get_phase1_dst($ph1ent);
- if(!$rgip) {
+ if (!$rgip) {
$ipfrules .= "# ERROR! Unable to determine remote IPsec peer address for {$ph1ent['remote-gateway']}\n";
continue;
}
- } else
+ } else {
$rgip = " any ";
+ }
/* Determine best description */
- if($ph1ent['descr'])
+ if ($ph1ent['descr']) {
$descr = $ph1ent['descr'];
- else
+ } else {
$descr = $rgip;
+ }
/*
* Step through all phase2 entries and determine
* which protocols are in use with this peer
*/
$prot_used_esp = false;
$prot_used_ah = false;
- if(is_array($config['ipsec']['phase2'])) {
+ if (is_array($config['ipsec']['phase2'])) {
foreach ($config['ipsec']['phase2'] as $ph2ent) {
/* only evaluate ph2's bound to our ph1 */
- if($ph2ent['ikeid'] != $ph1ent['ikeid'])
+ if ($ph2ent['ikeid'] != $ph1ent['ikeid']) {
continue;
- if($ph2ent['protocol'] == 'esp')
+ }
+ if ($ph2ent['protocol'] == 'esp') {
$prot_used_esp = true;
- if($ph2ent['protocol'] == 'ah')
+ }
+ if ($ph2ent['protocol'] == 'ah') {
$prot_used_ah = true;
+ }
}
}
- if (strpos($ph1ent['interface'], "_vip"))
+ if (strpos($ph1ent['interface'], "_vip")) {
$parentinterface = get_configured_carp_interface_list($ph1ent['interface'], '', 'iface');
- else
+ } else {
$parentinterface = $ph1ent['interface'];
+ }
if (empty($FilterIflist[$parentinterface]['descr'])) {
$ipfrules .= "# Could not locate interface for IPsec: {$descr}\n";
continue;
@@ -3687,42 +4021,42 @@ function filter_generate_ipsec_rules($log = array()) {
unset($gateway);
/* add endpoint routes to correct gateway on interface if the
remote endpoint is not on this interface's subnet */
- if((is_ipaddrv4($rgip)) && (interface_has_gateway($parentinterface))) {
+ if ((is_ipaddrv4($rgip)) && (interface_has_gateway($parentinterface))) {
$parentifsubnet = get_interface_ip($parentinterface) . "/" . get_interface_subnet($parentinterface);
if (!ip_in_subnet($rgip, $parentifsubnet)) {
$gateway = get_interface_gateway($parentinterface);
$interface = $FilterIflist[$parentinterface]['if'];
-
+
$route_to = " route-to ( $interface $gateway ) ";
- $reply_to = " reply-to ( $interface $gateway ) ";
+ $reply_to = " reply-to ( $interface $gateway ) ";
}
}
- if((is_ipaddrv6($rgip)) && (interface_has_gatewayv6($parentinterface))) {
+ if ((is_ipaddrv6($rgip)) && (interface_has_gatewayv6($parentinterface))) {
$parentifsubnet = get_interface_ipv6($parentinterface) . "/" . get_interface_subnetv6($parentinterface);
if (!ip_in_subnet($rgip, $parentifsubnet)) {
$gateway = get_interface_gateway_v6($parentinterface);
$interface = $FilterIflist[$parentinterface]['if'];
-
+
$route_to = " route-to ( $interface $gateway ) ";
$reply_to = " reply-to ( $interface $gateway ) ";
}
}
/* Just in case */
- if((!is_ipaddr($gateway) || empty($interface))) {
+ if ((!is_ipaddr($gateway) || empty($interface))) {
$route_to = " ";
$reply_to = " ";
}
/* Add rules to allow IKE to pass */
$shorttunneldescr = substr($descr, 0, 35);
- $ipfrules .= <<<EOD
+ $ipfrules .= <<<EOD
pass out {$log['pass']} $route_to proto udp from any to {$rgip} port = 500 tracker {$increment_tracker($tracker)} keep state label "IPsec: {$shorttunneldescr} - outbound isakmp"
pass in {$log['pass']} on \${$FilterIflist[$parentinterface]['descr']} $reply_to proto udp from {$rgip} to any port = 500 tracker {$increment_tracker($tracker)} keep state label "IPsec: {$shorttunneldescr} - inbound isakmp"
EOD;
/* If NAT-T is enabled, add additional rules */
- if($ph1ent['nat_traversal'] != "off" ) {
+ if ($ph1ent['nat_traversal'] != "off" ) {
$ipfrules .= <<<EOD
pass out {$log['pass']} $route_to proto udp from any to {$rgip} port = 4500 tracker {$increment_tracker($tracker)} keep state label "IPsec: {$shorttunneldescr} - outbound nat-t"
pass in {$log['pass']} on \${$FilterIflist[$parentinterface]['descr']} $reply_to proto udp from {$rgip} to any port = 4500 tracker {$increment_tracker($tracker)} keep state label "IPsec: {$shorttunneldescr} - inbound nat-t"
@@ -3730,14 +4064,14 @@ pass in {$log['pass']} on \${$FilterIflist[$parentinterface]['descr']} $reply_to
EOD;
}
/* Add rules to allow the protocols in use */
- if($prot_used_esp == true) {
+ if ($prot_used_esp) {
$ipfrules .= <<<EOD
pass out {$log['pass']} $route_to proto esp from any to {$rgip} tracker {$increment_tracker($tracker)} keep state label "IPsec: {$shorttunneldescr} - outbound esp proto"
pass in {$log['pass']} on \${$FilterIflist[$parentinterface]['descr']} $reply_to proto esp from {$rgip} to any tracker {$increment_tracker($tracker)} keep state label "IPsec: {$shorttunneldescr} - inbound esp proto"
EOD;
}
- if($prot_used_ah == true) {
+ if ($prot_used_ah) {
$ipfrules .= <<<EOD
pass out {$log['pass']} $route_to proto ah from any to {$rgip} tracker {$increment_tracker($tracker)} keep state label "IPsec: {$shorttunneldescr} - outbound ah proto"
pass in {$log['pass']} on \${$FilterIflist[$parentinterface]['descr']} $reply_to proto ah from {$rgip} to any tracker {$increment_tracker($tracker)} keep state label "IPsec: {$shorttunneldescr} - inbound ah proto"
@@ -3745,7 +4079,6 @@ pass in {$log['pass']} on \${$FilterIflist[$parentinterface]['descr']} $reply_to
EOD;
}
}
-
}
return($ipfrules);
}
@@ -3754,18 +4087,20 @@ function discover_pkg_rules($ruletype) {
global $config, $g, $aliases;
/* Bail if there is no pkg directory, or if the package files might be out of sync. */
- if(!is_dir("/usr/local/pkg") || file_exists('/conf/needs_package_sync'))
+ if (!is_dir("/usr/local/pkg") || file_exists('/conf/needs_package_sync')) {
return "";
+ }
$rules = "";
$files = glob("/usr/local/pkg/*.inc");
- foreach($files as $pkg_inc) {
+ foreach ($files as $pkg_inc) {
update_filter_reload_status(sprintf(gettext('Checking for %1$s PF hooks in package %2$s'), $ruletype, $pkg_inc));
$pkg = basename($pkg_inc, ".inc");
$pkg_generate_rules = "{$pkg}_generate_rules";
- if (!function_exists($pkg_generate_rules))
+ if (!function_exists($pkg_generate_rules)) {
require_once($pkg_inc);
- if(function_exists($pkg_generate_rules)) {
+ }
+ if (function_exists($pkg_generate_rules)) {
update_filter_reload_status(sprintf(gettext('Processing early %1$s rules for package %2$s'), $ruletype, $pkg_inc));
$tmprules = $pkg_generate_rules("$ruletype");
file_put_contents("{$g['tmp_path']}/rules.test.packages", $aliases . $tmprules);
@@ -3790,17 +4125,20 @@ function filter_get_antilockout_ports($wantarray = false) {
$guiport = empty($config['system']['webgui']['port']) ? $guiport : $config['system']['webgui']['port'];
$lockoutports[] = $guiport;
- if (($config['system']['webgui']['protocol'] == "https") && !isset($config['system']['webgui']['disablehttpredirect']) && ($guiport != "80"))
+ if (($config['system']['webgui']['protocol'] == "https") && !isset($config['system']['webgui']['disablehttpredirect']) && ($guiport != "80")) {
$lockoutports[] = "80";
+ }
- if (isset($config['system']['enablesshd']))
+ if (isset($config['system']['enablesshd'])) {
$lockoutports[] = empty($config['system']['ssh']['port']) ? "22" : $config['system']['ssh']['port'];
+ }
- if ($wantarray)
+ if ($wantarray) {
return $lockoutports;
- else
+ } else {
return implode(" ", $lockoutports);
+ }
}
-?> \ No newline at end of file
+?>
diff --git a/etc/inc/filter_log.inc b/etc/inc/filter_log.inc
index 46c9b13..f4d9841 100644
--- a/etc/inc/filter_log.inc
+++ b/etc/inc/filter_log.inc
@@ -45,33 +45,36 @@ function conv_log_filter($logfile, $nentries, $tail = 50, $filtertext = "", $fil
global $config, $g;
/* Make sure this is a number before using it in a system call */
- if (!(is_numeric($tail)))
+ if (!(is_numeric($tail))) {
return;
+ }
- if ($filtertext)
+ if ($filtertext) {
$tail = 5000;
+ }
/* Always do a reverse tail, to be sure we're grabbing the 'end' of the log. */
$logarr = "";
- if(isset($config['system']['usefifolog']))
+ if (isset($config['system']['usefifolog'])) {
exec("/usr/sbin/fifolog_reader " . escapeshellarg($logfile) . " | /usr/bin/grep 'filterlog:' | /usr/bin/tail -r -n {$tail}", $logarr);
- else
+ } else {
exec("/usr/local/sbin/clog " . escapeshellarg($logfile) . " | grep -v \"CLOG\" | grep -v \"\033\" | /usr/bin/grep 'filterlog:' | /usr/bin/tail -r -n {$tail}", $logarr);
+ }
$filterlog = array();
$counter = 0;
$filterinterface = strtoupper($filterinterface);
foreach ($logarr as $logent) {
- if($counter >= $nentries)
+ if ($counter >= $nentries) {
break;
+ }
$flent = parse_filter_line($logent);
- if (!$filterinterface || ($filterinterface == $flent['interface']))
- {
- if ( ( ($flent != "") && (!is_array($filtertext)) && (match_filter_line ($flent, $filtertext))) ||
- ( ($flent != "") && ( is_array($filtertext)) && (match_filter_field($flent, $filtertext)) ) ) {
+ if (!$filterinterface || ($filterinterface == $flent['interface'])) {
+ if ((($flent != "") && (!is_array($filtertext)) && (match_filter_line ($flent, $filtertext))) ||
+ (($flent != "") && ( is_array($filtertext)) && (match_filter_field($flent, $filtertext)))) {
$counter++;
$filterlog[] = $flent;
}
@@ -88,34 +91,40 @@ function escape_filter_regex($filtertext) {
}
function match_filter_line($flent, $filtertext = "") {
- if (!$filtertext)
+ if (!$filtertext) {
return true;
+ }
$filtertext = escape_filter_regex(str_replace(' ', '\s+', $filtertext));
return @preg_match("/{$filtertext}/i", implode(" ", array_values($flent)));
}
function match_filter_field($flent, $fields) {
foreach ($fields as $key => $field) {
- if ($field == "All")
+ if ($field == "All") {
continue;
+ }
if ((strpos($field, '!') === 0)) {
$field = substr($field, 1);
if (strtolower($key) == 'act') {
- if (in_arrayi($flent[$key], explode(" ", $field)))
+ if (in_arrayi($flent[$key], explode(" ", $field))) {
return false;
+ }
} else {
$field_regex = escape_filter_regex($field);
- if (@preg_match("/{$field_regex}/i", $flent[$key]))
+ if (@preg_match("/{$field_regex}/i", $flent[$key])) {
return false;
+ }
}
} else {
if (strtolower($key) == 'act') {
- if (!in_arrayi($flent[$key], explode(" ", $field)))
+ if (!in_arrayi($flent[$key], explode(" ", $field))) {
return false;
+ }
} else {
$field_regex = escape_filter_regex($field);
- if (!@preg_match("/{$field_regex}/i", $flent[$key]))
+ if (!@preg_match("/{$field_regex}/i", $flent[$key])) {
return false;
+ }
}
}
}
@@ -133,8 +142,9 @@ function parse_filter_line($line) {
$flent = array();
$log_split = "";
- if (!preg_match("/(.*)\s(.*)\sfilterlog:\s(.*)$/", $line, $log_split))
+ if (!preg_match("/(.*)\s(.*)\sfilterlog:\s(.*)$/", $line, $log_split)) {
return "";
+ }
list($all, $flent['time'], $host, $rule) = $log_split;
@@ -197,45 +207,45 @@ function parse_filter_line($line) {
$flent['icmp_type'] = $rule_data[$field++];
switch ($flent['icmp_type']) {
- case "request":
- case "reply":
- $flent['icmp_id'] = $rule_data[$field++];
- $flent['icmp_seq'] = $rule_data[$field++];
- break;
- case "unreachproto":
- $flent['icmp_dstip'] = $rule_data[$field++];
- $flent['icmp_protoid'] = $rule_data[$field++];
- break;
- case "unreachport":
- $flent['icmp_dstip'] = $rule_data[$field++];
- $flent['icmp_protoid'] = $rule_data[$field++];
- $flent['icmp_port'] = $rule_data[$field++];
- break;
- case "unreach":
- case "timexceed":
- case "paramprob":
- case "redirect":
- case "maskreply":
- $flent['icmp_descr'] = $rule_data[$field++];
- break;
- case "needfrag":
- $flent['icmp_dstip'] = $rule_data[$field++];
- $flent['icmp_mtu'] = $rule_data[$field++];
- break;
- case "tstamp":
- $flent['icmp_id'] = $rule_data[$field++];
- $flent['icmp_seq'] = $rule_data[$field++];
- break;
- case "tstampreply":
- $flent['icmp_id'] = $rule_data[$field++];
- $flent['icmp_seq'] = $rule_data[$field++];
- $flent['icmp_otime'] = $rule_data[$field++];
- $flent['icmp_rtime'] = $rule_data[$field++];
- $flent['icmp_ttime'] = $rule_data[$field++];
- break;
- default :
- $flent['icmp_descr'] = $rule_data[$field++];
- break;
+ case "request":
+ case "reply":
+ $flent['icmp_id'] = $rule_data[$field++];
+ $flent['icmp_seq'] = $rule_data[$field++];
+ break;
+ case "unreachproto":
+ $flent['icmp_dstip'] = $rule_data[$field++];
+ $flent['icmp_protoid'] = $rule_data[$field++];
+ break;
+ case "unreachport":
+ $flent['icmp_dstip'] = $rule_data[$field++];
+ $flent['icmp_protoid'] = $rule_data[$field++];
+ $flent['icmp_port'] = $rule_data[$field++];
+ break;
+ case "unreach":
+ case "timexceed":
+ case "paramprob":
+ case "redirect":
+ case "maskreply":
+ $flent['icmp_descr'] = $rule_data[$field++];
+ break;
+ case "needfrag":
+ $flent['icmp_dstip'] = $rule_data[$field++];
+ $flent['icmp_mtu'] = $rule_data[$field++];
+ break;
+ case "tstamp":
+ $flent['icmp_id'] = $rule_data[$field++];
+ $flent['icmp_seq'] = $rule_data[$field++];
+ break;
+ case "tstampreply":
+ $flent['icmp_id'] = $rule_data[$field++];
+ $flent['icmp_seq'] = $rule_data[$field++];
+ $flent['icmp_otime'] = $rule_data[$field++];
+ $flent['icmp_rtime'] = $rule_data[$field++];
+ $flent['icmp_ttime'] = $rule_data[$field++];
+ break;
+ default :
+ $flent['icmp_descr'] = $rule_data[$field++];
+ break;
}
} else if ($flent['protoid'] == '2') { // IGMP
@@ -250,8 +260,9 @@ function parse_filter_line($line) {
$flent['advbase'] = $rule_data[$field++];
}
} else {
- if($g['debug'])
+ if ($g['debug']) {
log_error(sprintf(gettext("There was a error parsing rule number: %s. Please report to mailing list or forum."), $flent['rulenum']));
+ }
return "";
}
@@ -259,7 +270,7 @@ function parse_filter_line($line) {
if (!((trim($flent['src']) == "") || (trim($flent['dst']) == "") || (trim($flent['time']) == ""))) {
return $flent;
} else {
- if($g['debug']) {
+ if ($g['debug']) {
log_error(sprintf(gettext("There was a error parsing rule: %s. Please report to mailing list or forum."), $errline));
}
return "";
@@ -267,8 +278,9 @@ function parse_filter_line($line) {
}
function get_port_with_service($port, $proto) {
- if (!$port)
+ if (!$port) {
return '';
+ }
$service = getservbyport($port, $proto);
$portstr = "";
@@ -284,27 +296,31 @@ function find_rule_by_number($rulenum, $trackernum, $type="block") {
global $g;
/* Passing arbitrary input to grep could be a Very Bad Thing(tm) */
- if (!is_numeric($rulenum) || !is_numeric($trackernum) || !in_array($type, array('pass', 'block', 'match', 'rdr')))
+ if (!is_numeric($rulenum) || !is_numeric($trackernum) || !in_array($type, array('pass', 'block', 'match', 'rdr'))) {
return;
+ }
- if ($trackernum == "0")
+ if ($trackernum == "0") {
$lookup_pattern = "^@{$rulenum}\([0-9]+\)[[:space:]]{$type}[[:space:]].*[[:space:]]log[[:space:]]";
- else
+ } else {
$lookup_pattern = "^@[0-9]+\({$trackernum}\)[[:space:]]{$type}[[:space:]].*[[:space:]]log[[:space:]]";
+ }
/* At the moment, miniupnpd is the only thing I know of that
generates logging rdr rules */
unset($buffer);
- if ($type == "rdr")
+ if ($type == "rdr") {
$_gb = exec("/sbin/pfctl -vvPsn -a \"miniupnpd\" | /usr/bin/egrep " . escapeshellarg("^@{$rulenum}"), $buffer);
- else {
- if (file_exists("{$g['tmp_path']}/rules.debug"))
+ } else {
+ if (file_exists("{$g['tmp_path']}/rules.debug")) {
$_gb = exec("/sbin/pfctl -vvPnf {$g['tmp_path']}/rules.debug 2>/dev/null | /usr/bin/egrep " . escapeshellarg($lookup_pattern), $buffer);
- else
+ } else {
$_gb = exec("/sbin/pfctl -vvPsr | /usr/bin/egrep " . escapeshellarg($lookup_pattern), $buffer);
+ }
}
- if (is_array($buffer))
+ if (is_array($buffer)) {
return $buffer[0];
+ }
return "";
}
@@ -325,10 +341,11 @@ function buffer_rules_load() {
}
}
unset($buffer, $_gb);
- if (file_exists("{$g['tmp_path']}/rules.debug"))
+ if (file_exists("{$g['tmp_path']}/rules.debug")) {
$_gb = exec("/sbin/pfctl -vvPnf {$g['tmp_path']}/rules.debug 2>/dev/null | /usr/bin/egrep '^@[0-9]+\([0-9]+\)[[:space:]].*[[:space:]]log[[:space:]]' | /usr/bin/egrep -v '^@[0-9]+\([0-9]+\)[[:space:]](nat|rdr|binat|no|scrub)'", $buffer);
- else
+ } else {
$_gb = exec("/sbin/pfctl -vvPsr | /usr/bin/egrep '^@[0-9]+\([0-9]+\)[[:space:]].*[[:space:]]log[[:space:]]'", $buffer);
+ }
if (is_array($buffer)) {
foreach ($buffer as $line) {
@@ -336,10 +353,11 @@ function buffer_rules_load() {
# pfctl rule number output with tracker number: @dd(dddddddddd)
$matches = array();
if (preg_match('/\@(?P<rulenum>\d+)\((?<trackernum>\d+)\)/', $key, $matches) == 1) {
- if ($matches['trackernum'] > 0)
+ if ($matches['trackernum'] > 0) {
$key = $matches['trackernum'];
- else
+ } else {
$key = "@{$matches['rulenum']}";
+ }
}
$buffer_rules_normal[$key] = $value;
}
@@ -352,13 +370,14 @@ function buffer_rules_clear() {
unset($GLOBALS['buffer_rules_rdr']);
}
-function find_rule_by_number_buffer($rulenum, $trackernum, $type){
+function find_rule_by_number_buffer($rulenum, $trackernum, $type) {
global $g, $buffer_rules_rdr, $buffer_rules_normal;
- if ($trackernum == "0")
+ if ($trackernum == "0") {
$lookup_key = "@{$rulenum}";
- else
+ } else {
$lookup_key = $trackernum;
+ }
if ($type == "rdr") {
$ruleString = $buffer_rules_rdr[$lookup_key];
@@ -374,23 +393,26 @@ function find_rule_by_number_buffer($rulenum, $trackernum, $type){
function find_action_image($action) {
global $g;
- if ((strstr(strtolower($action), "p")) || (strtolower($action) == "rdr"))
+ if ((strstr(strtolower($action), "p")) || (strtolower($action) == "rdr")) {
return "/themes/{$g['theme']}/images/icons/icon_pass.gif";
- else if(strstr(strtolower($action), "r"))
+ } else if (strstr(strtolower($action), "r")) {
return "/themes/{$g['theme']}/images/icons/icon_reject.gif";
- else
+ } else {
return "/themes/{$g['theme']}/images/icons/icon_block.gif";
+ }
}
/* AJAX specific handlers */
function handle_ajax($nentries, $tail = 50) {
global $config;
- if($_GET['lastsawtime'] or $_POST['lastsawtime']) {
+ if ($_GET['lastsawtime'] or $_POST['lastsawtime']) {
global $filter_logfile,$filterent;
- if($_GET['lastsawtime'])
+ if ($_GET['lastsawtime']) {
$lastsawtime = $_GET['lastsawtime'];
- if($_POST['lastsawtime'])
+ }
+ if ($_POST['lastsawtime']) {
$lastsawtime = $_POST['lastsawtime'];
+ }
/* compare lastsawrule's time stamp to filter logs.
* afterwards return the newer records so that client
* can update AJAX interface screen.
@@ -399,12 +421,13 @@ function handle_ajax($nentries, $tail = 50) {
$filterlog = conv_log_filter($filter_logfile, $nentries, $tail);
/* We need this to always be in forward order for the AJAX update to work properly */
$filterlog = isset($config['syslog']['reverse']) ? array_reverse($filterlog) : $filterlog;
- foreach($filterlog as $log_row) {
+ foreach ($filterlog as $log_row) {
$row_time = strtotime($log_row['time']);
$img = "<img border='0' src='" . find_action_image($log_row['act']) . "' alt={$log_row['act']} title={$log_row['act']} />";
- if($row_time > $lastsawtime) {
- if ($log_row['proto'] == "TCP")
+ if ($row_time > $lastsawtime) {
+ if ($log_row['proto'] == "TCP") {
$log_row['proto'] .= ":{$log_row['tcpflags']}";
+ }
$img = "<a href=\"#\" onClick=\"javascript:getURL('diag_logs_filter.php?getrulenum={$log_row['rulenum']},{$log_row['rulenum']}', outputrule);\">{$img}</a>";
$new_rules .= "{$img}||{$log_row['time']}||{$log_row['interface']}||{$log_row['srcip']}||{$log_row['srcport']}||{$log_row['dstip']}||{$log_row['dstport']}||{$log_row['proto']}||{$log_row['version']}||" . time() . "||\n";
diff --git a/etc/inc/functions.inc b/etc/inc/functions.inc
index a89aeff..ab9b73d 100644
--- a/etc/inc/functions.inc
+++ b/etc/inc/functions.inc
@@ -1,47 +1,47 @@
<?php
/* $Id$ */
/*
- functions.inc
- Copyright (C) 2004-2006 Scott Ullrich
- All rights reserved.
-
- originally part of m0n0wall (http://m0n0.ch/wall)
- Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
+ functions.inc
+ Copyright (C) 2004-2006 Scott Ullrich
+ All rights reserved.
+
+ originally part of m0n0wall (http://m0n0.ch/wall)
+ Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
pfSense_MODULE: utils
*/
/* BEGIN compatibility goo with HEAD */
-if(!function_exists("gettext")) {
+if (!function_exists("gettext")) {
function gettext($text) {
return $text;
}
}
-if(!function_exists("pfSenseHeader")) {
+if (!function_exists("pfSenseHeader")) {
/****f* pfsense-utils/pfSenseHeader
* NAME
* pfSenseHeader
@@ -51,30 +51,33 @@ if(!function_exists("pfSenseHeader")) {
* Javascript header change or browser Location:
******/
function pfSenseHeader($text) {
- global $_SERVER;
- if (isAjax()) {
- if ($_SERVER['HTTPS'] == "on")
- $protocol = "https";
- else
- $protocol = "http";
-
- $port = ":{$_SERVER['SERVER_PORT']}";
- if ($_SERVER['SERVER_PORT'] == "80" && $protocol == "http")
- $port = "";
- if ($_SERVER['SERVER_PORT'] == "443" && $protocol == "https")
- $port = "";
- $complete_url = "{$protocol}://{$_SERVER['SERVER_NAME']}{$port}/{$text}";
- echo "\ndocument.location.href = '{$complete_url}';\n";
- } else {
- header("Location: $text");
- }
+ global $_SERVER;
+ if (isAjax()) {
+ if ($_SERVER['HTTPS'] == "on") {
+ $protocol = "https";
+ } else {
+ $protocol = "http";
+ }
+
+ $port = ":{$_SERVER['SERVER_PORT']}";
+ if ($_SERVER['SERVER_PORT'] == "80" && $protocol == "http") {
+ $port = "";
+ }
+ if ($_SERVER['SERVER_PORT'] == "443" && $protocol == "https") {
+ $port = "";
+ }
+ $complete_url = "{$protocol}://{$_SERVER['SERVER_NAME']}{$port}/{$text}";
+ echo "\ndocument.location.href = '{$complete_url}';\n";
+ } else {
+ header("Location: $text");
+ }
}
}
/* END compatibility goo with HEAD */
/*fetch menu notices function*/
-if(!function_exists("get_menu_messages")) {
- function get_menu_messages(){
+if (!function_exists("get_menu_messages")) {
+ function get_menu_messages() {
global $g,$config;
if (are_notices_pending()) {
$notices = get_notices();
@@ -82,63 +85,67 @@ if(!function_exists("get_menu_messages")) {
## Get Query Arguments from URL ###
foreach ($_REQUEST as $key => $value) {
- if ($key != "PHPSESSID")
+ if ($key != "PHPSESSID") {
$requests[] = $key.'='.$value;
}
- if(is_array($requests))
+ }
+ if (is_array($requests)) {
$request_string = implode("&", $requests);
+ }
- if(is_array($notices)) {
- $notice_msgs = "<table colspan=\'6\' id=\'notice_table\'>";
- $alert_style="style=\'color:#ffffff; filter:Glow(color=#ff0000, strength=12);\' ";
- $notice = "<a href=\'#\' onclick=notice_action(\'acknowledge\',\'all\');domTT_close(this); {$alert_style}>".gettext("Acknowledge All Notices")."</a>";
- $alert_link="title=\'".gettext("Click to Acknowledge")."\' {$alert_style}";
- $domtt_width=500;
- foreach ($notices as $key => $value) {
- $date = date("m-d-y H:i:s", $key);
- $noticemsg = ($value['notice'] != "" ? $value['notice'] : $value['id']);
- $noticemsg = preg_replace("/(\"|\'|\n|<.?\w+>)/i","",$noticemsg);
- if ((strlen($noticemsg)* 8) > $domtt_width)
- $domtt_width=(strlen($noticemsg) *8);
- if ((strlen($noticemsg)* 8) > 900)
- $domtt_width= 900;
- $alert_action ="onclick=notice_action(\'acknowledge\',\'{$key}\');domTT_close(this);jQuery(this).parent().parent().remove();";
- $notice_msgs .= "<tr><td valign=\'top\' width=\'120\'><a href=\'#\' {$alert_link} {$alert_action}>{$date}</a></td><td valign=\'top\'><a href=\'#\' {$alert_link} {$alert_action}>[ ".htmlspecialchars($noticemsg)."]</a></td></tr>";
- }
- $notice_msgs .="</table>";
-
- $domtt= "onclick=\"domTT_activate(this, event, 'caption', '{$notice}','content', '<br />{$notice_msgs}', 'trail', false, 'delay', 0, 'fade', 'both', 'fadeMax', 93, 'styleClass', 'niceTitle','width','{$domtt_width}','y',5,'type', 'sticky');\"";
- $menu_messages="<div id='alerts'>\n";
- if(count($notices)==1)
- $msg= sprintf("%1$02d",count($notices))." ".gettext("unread notice");
- else
- $msg= sprintf("%1$02d",count($notices))." ".gettext("unread notices");
- $menu_messages.="<div id='marquee-text' style='z-index:1001;'><a href='#' {$domtt}><b> .:. {$msg} .:. </b></a></div>\n";
- $menu_messages.="</div>\n";
- }
+ if (is_array($notices)) {
+ $notice_msgs = "<table colspan=\'6\' id=\'notice_table\'>";
+ $alert_style="style=\'color:#ffffff; filter:Glow(color=#ff0000, strength=12);\' ";
+ $notice = "<a href=\'#\' onclick=notice_action(\'acknowledge\',\'all\');domTT_close(this); {$alert_style}>".gettext("Acknowledge All Notices")."</a>";
+ $alert_link="title=\'".gettext("Click to Acknowledge")."\' {$alert_style}";
+ $domtt_width=500;
+ foreach ($notices as $key => $value) {
+ $date = date("m-d-y H:i:s", $key);
+ $noticemsg = ($value['notice'] != "" ? $value['notice'] : $value['id']);
+ $noticemsg = preg_replace("/(\"|\'|\n|<.?\w+>)/i","",$noticemsg);
+ if ((strlen($noticemsg)* 8) > $domtt_width) {
+ $domtt_width=(strlen($noticemsg) *8);
+ }
+ if ((strlen($noticemsg)* 8) > 900) {
+ $domtt_width= 900;
+ }
+ $alert_action ="onclick=notice_action(\'acknowledge\',\'{$key}\');domTT_close(this);jQuery(this).parent().parent().remove();";
+ $notice_msgs .= "<tr><td valign=\'top\' width=\'120\'><a href=\'#\' {$alert_link} {$alert_action}>{$date}</a></td><td valign=\'top\'><a href=\'#\' {$alert_link} {$alert_action}>[ ".htmlspecialchars($noticemsg)."]</a></td></tr>";
+ }
+ $notice_msgs .="</table>";
+
+ $domtt= "onclick=\"domTT_activate(this, event, 'caption', '{$notice}','content', '<br />{$notice_msgs}', 'trail', false, 'delay', 0, 'fade', 'both', 'fadeMax', 93, 'styleClass', 'niceTitle','width','{$domtt_width}','y',5,'type', 'sticky');\"";
+ $menu_messages="<div id='alerts'>\n";
+ if (count($notices)==1) {
+ $msg= sprintf("%1$02d",count($notices))." ".gettext("unread notice");
+ } else {
+ $msg= sprintf("%1$02d",count($notices))." ".gettext("unread notices");
+ }
+ $menu_messages.="<div id='marquee-text' style='z-index:1001;'><a href='#' {$domtt}><b> .:. {$msg} .:. </b></a></div>\n";
+ $menu_messages.="</div>\n";
}
- else {
+ } else {
$menu_messages='<div id="hostname">';
- $menu_messages.=$config['system']['hostname'] . "." . $config['system']['domain'];
+ $menu_messages.=$config['system']['hostname'] . "." . $config['system']['domain'];
$menu_messages.='</div>';
- }
- return ($menu_messages);
}
+ return ($menu_messages);
+ }
}
-
-if(!function_exists("dom_title")) {
- function dom_title($title_msg,$width=NULL){
+
+if (!function_exists("dom_title")) {
+ function dom_title($title_msg,$width=NULL) {
$width=preg_replace("/\D+/","",$width);
- if (!empty($width)){
+ if (!empty($width)) {
$width=",'width',$width";
- }
- if (!empty($title_msg)){
+ }
+ if (!empty($title_msg)) {
$title_msg=preg_replace("/\s+/"," ",$title_msg);
- $title_msg=preg_replace("/'/","\'",$title_msg);
+ $title_msg=preg_replace("/'/","\'",$title_msg);
return "onmouseout=\"this.style.color = ''; domTT_mouseout(this, event);\" onmouseover=\"domTT_activate(this, event, 'content', '{$title_msg}', 'trail', true, 'delay', 250, 'fade', 'both', 'fadeMax', 93, 'styleClass', 'niceTitle' $width);\"";
- }
}
}
+}
/* include all configuration functions */
require_once("interfaces.inc");
require_once("gwlb.inc");
diff --git a/etc/inc/globals.inc b/etc/inc/globals.inc
index 1d16e70..2194de1 100644
--- a/etc/inc/globals.inc
+++ b/etc/inc/globals.inc
@@ -1,34 +1,34 @@
<?php
/* $Id$ */
/*
- globals.inc
- part of pfSense (https://www.pfsense.org)
- Copyright (C) 2004-2010 Scott Ullrich
-
- Originally Part of m0n0wall
- Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
+ globals.inc
+ part of pfSense (https://www.pfsense.org)
+ Copyright (C) 2004-2010 Scott Ullrich
+
+ Originally Part of m0n0wall
+ Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
pfSense_MODULE: utils
@@ -36,7 +36,7 @@
global $g;
$g = array(
- "base_packages" => "siproxd",
+ "base_packages" => "siproxd",
"event_address" => "unix:///var/run/check_reload_status",
"factory_shipped_username" => "admin",
"factory_shipped_password" => "pfsense",
@@ -77,7 +77,7 @@ $g = array(
"nopkg_platforms" => array("cdrom"),
"minimum_ram_warning" => "101",
"minimum_ram_warning_text" => "128 MB",
- "wan_interface_name" => "wan",
+ "wan_interface_name" => "wan",
"nopccard_platforms" => array("wrap", "net48xx"),
"xmlrpcbaseurl" => "https://packages.pfsense.org",
"captiveportal_path" => "/usr/local/captiveportal",
@@ -96,7 +96,7 @@ $iptos = array("lowdelay", "throughput", "reliability");
/* TCP flags */
$tcpflags = array("syn", "ack", "fin", "rst", "psh", "urg", "ece", "cwr");
-if(file_exists("/etc/platform")) {
+if (file_exists("/etc/platform")) {
$arch = php_uname("m");
$current_version = trim(file_get_contents("{$g['etc_path']}/version"));
@@ -113,7 +113,7 @@ if(file_exists("/etc/platform")) {
}
$g['platform'] = trim(file_get_contents("/etc/platform"));
- if($g['platform'] == "nanobsd") {
+ if ($g['platform'] == "nanobsd") {
$g['firmware_update_text']="pfSense-*.img.gz";
$g['hidedownloadbackup'] = true;
$g['hidebackupbeforeupgrade'] = true;
@@ -124,30 +124,30 @@ if(file_exists("/etc/platform")) {
}
/* Default sysctls */
-$sysctls = array("net.inet.ip.portrange.first" => "1024",
- "net.inet.tcp.blackhole" => "2",
- "net.inet.udp.blackhole" => "1",
- "net.inet.ip.random_id" => "1",
- "net.inet.tcp.drop_synfin" => "1",
- "net.inet.ip.redirect" => "1",
- "net.inet6.ip6.redirect" => "1",
+$sysctls = array("net.inet.ip.portrange.first" => "1024",
+ "net.inet.tcp.blackhole" => "2",
+ "net.inet.udp.blackhole" => "1",
+ "net.inet.ip.random_id" => "1",
+ "net.inet.tcp.drop_synfin" => "1",
+ "net.inet.ip.redirect" => "1",
+ "net.inet6.ip6.redirect" => "1",
"net.inet6.ip6.use_tempaddr" => "0",
"net.inet6.ip6.prefer_tempaddr" => "0",
- "net.inet.tcp.syncookies" => "1",
- "net.inet.tcp.recvspace" => "65228",
- "net.inet.tcp.sendspace" => "65228",
- "net.inet.ip.fastforwarding" => "0",
- "net.inet.tcp.delayed_ack" => "0",
- "net.inet.udp.maxdgram" => "57344",
- "net.link.bridge.pfil_onlyip" => "0",
- "net.link.bridge.pfil_member" => "1",
- "net.link.bridge.pfil_bridge" => "0",
- "net.link.tap.user_open" => "1",
- "kern.randompid" => "347",
- "net.inet.ip.intr_queue_maxlen" => "1000",
- "hw.syscons.kbd_reboot" => "0",
- "net.inet.tcp.log_debug" => "0",
- "net.inet.tcp.tso" => "1",
+ "net.inet.tcp.syncookies" => "1",
+ "net.inet.tcp.recvspace" => "65228",
+ "net.inet.tcp.sendspace" => "65228",
+ "net.inet.ip.fastforwarding" => "0",
+ "net.inet.tcp.delayed_ack" => "0",
+ "net.inet.udp.maxdgram" => "57344",
+ "net.link.bridge.pfil_onlyip" => "0",
+ "net.link.bridge.pfil_member" => "1",
+ "net.link.bridge.pfil_bridge" => "0",
+ "net.link.tap.user_open" => "1",
+ "kern.randompid" => "347",
+ "net.inet.ip.intr_queue_maxlen" => "1000",
+ "hw.syscons.kbd_reboot" => "0",
+ "net.inet.tcp.log_debug" => "0",
+ "net.inet.tcp.tso" => "1",
"net.inet.icmp.icmplim" => "0",
"vfs.read_max" => "32",
"kern.ipc.maxsockbuf" => "4262144",
@@ -169,21 +169,25 @@ $sysctls = array("net.inet.ip.portrange.first" => "1024",
);
/* Include override values for the above if needed. If the file doesn't exist, don't try to load it. */
-if (file_exists("/etc/inc/globals_override.inc"))
+if (file_exists("/etc/inc/globals_override.inc")) {
@include("globals_override.inc");
+}
function platform_booting($on_console = false) {
global $g;
- if ($g['booting'] || file_exists("{$g['varrun_path']}/booting"))
- if ($on_console == false || php_sapi_name() != 'fpm-fcgi')
+ if ($g['booting'] || file_exists("{$g['varrun_path']}/booting")) {
+ if ($on_console == false || php_sapi_name() != 'fpm-fcgi') {
return true;
+ }
+ }
return false;
}
-if (file_exists("{$g['cf_conf_path']}/enableserial_force"))
+if (file_exists("{$g['cf_conf_path']}/enableserial_force")) {
$g['enableserial_force'] = true;
+}
$config_parsed = false;
diff --git a/etc/inc/gmirror.inc b/etc/inc/gmirror.inc
index 01d21c4..9e26dfb 100644
--- a/etc/inc/gmirror.inc
+++ b/etc/inc/gmirror.inc
@@ -46,13 +46,14 @@ function gmirror_get_status() {
$currentmirror = basename($all[0]);
$mirrors[$currentmirror]['name'] = basename($all[0]);
$mirrors[$currentmirror]['status'] = $all[1];
- if (!is_array($mirrors[$currentmirror]['components']))
+ if (!is_array($mirrors[$currentmirror]['components'])) {
$mirrors[$currentmirror]['components'] = array();
+ }
$mirrors[$currentmirror]['components'][] = $all[2];
}
}
}
- /* Return an hash of mirrors and components */
+ /* Return an hash of mirrors and components */
return $mirrors;
}
@@ -113,8 +114,9 @@ function gmirror_get_unused_consumers() {
$all_consumers = array();
foreach ($consumerlist as $cl) {
$parts = explode(" ", $cl);
- foreach ($parts as $part)
+ foreach ($parts as $part) {
$all_consumers[] = $part;
+ }
}
foreach ($disklist as $d) {
if (!is_consumer_used($d) && !in_array($d, $all_consumers)) {
@@ -134,8 +136,9 @@ function gmirror_get_mirrors() {
/* List all consumers for a given mirror */
function gmirror_get_consumers_in_mirror($mirror) {
- if (!is_valid_mirror($mirror))
+ if (!is_valid_mirror($mirror)) {
return array();
+ }
$consumers = array();
exec("/sbin/gmirror status -s " . escapeshellarg($mirror) . " | /usr/bin/awk '{print $3;}'", $consumers);
@@ -144,8 +147,9 @@ function gmirror_get_consumers_in_mirror($mirror) {
/* Test if a given consumer is a member of an existing mirror */
function is_consumer_in_mirror($consumer, $mirror) {
- if (!is_valid_consumer($consumer) || !is_valid_mirror($mirror))
+ if (!is_valid_consumer($consumer) || !is_valid_mirror($mirror)) {
return false;
+ }
$mirrorconsumers = gmirror_get_consumers_in_mirror($mirror);
return in_array(basename($consumer), $mirrorconsumers);
@@ -169,8 +173,9 @@ function is_consumer_used($consumer) {
$mirrors = gmirror_get_mirrors();
foreach ($mirrors as $mirror) {
$consumers = gmirror_get_consumers_in_mirror($mirror);
- if (in_array($consumer, $consumers))
+ if (in_array($consumer, $consumers)) {
return true;
+ }
}
return false;
}
@@ -188,36 +193,41 @@ function is_valid_consumer($consumer) {
/* Remove all disconnected drives from a mirror */
function gmirror_forget_disconnected($mirror) {
- if (!is_valid_mirror($mirror))
+ if (!is_valid_mirror($mirror)) {
return false;
+ }
return mwexec("/sbin/gmirror forget " . escapeshellarg($mirror));
}
/* Insert another consumer into a mirror */
function gmirror_insert_consumer($mirror, $consumer) {
- if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer))
+ if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer)) {
return false;
+ }
return mwexec("/sbin/gmirror insert " . escapeshellarg($mirror) . " " . escapeshellarg($consumer));
}
/* Remove consumer from a mirror and clear its metadata */
function gmirror_remove_consumer($mirror, $consumer) {
- if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer))
+ if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer)) {
return false;
+ }
return mwexec("/sbin/gmirror remove " . escapeshellarg($mirror) . " " . escapeshellarg($consumer));
}
/* Wipe geom info from drive (if mirror is not running) */
function gmirror_clear_consumer($consumer) {
- if (!is_valid_consumer($consumer))
+ if (!is_valid_consumer($consumer)) {
return false;
+ }
return mwexec("/sbin/gmirror clear " . escapeshellarg($consumer));
}
/* Find the balance method used by a given mirror */
function gmirror_get_mirror_balance($mirror) {
- if (!is_valid_mirror($mirror))
+ if (!is_valid_mirror($mirror)) {
return false;
+ }
$balancemethod = "";
exec("/sbin/gmirror list " . escapeshellarg($mirror) . " | /usr/bin/grep '^Balance:' | /usr/bin/awk '{print $2;}'", $balancemethod);
return $balancemethod[0];
@@ -226,22 +236,25 @@ function gmirror_get_mirror_balance($mirror) {
/* Change balance algorithm of the mirror */
function gmirror_configure_balance($mirror, $balancemethod) {
global $balance_methods;
- if (!is_valid_mirror($mirror) || !in_array($balancemethod, $balance_methods))
+ if (!is_valid_mirror($mirror) || !in_array($balancemethod, $balance_methods)) {
return false;
+ }
return mwexec("/sbin/gmirror configure -b " . escapeshellarg($balancemethod) . " " . escapeshellarg($mirror));
}
/* Force a mirror member to rebuild */
function gmirror_force_rebuild($mirror, $consumer) {
- if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer))
+ if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer)) {
return false;
+ }
return mwexec("/sbin/gmirror rebuild " . escapeshellarg($mirror) . " " . escapeshellarg($consumer));
}
/* Show all metadata on the physical consumer */
function gmirror_get_consumer_metadata($consumer) {
- if (!is_valid_consumer($consumer))
+ if (!is_valid_consumer($consumer)) {
return array();
+ }
$output = "";
exec("/sbin/gmirror dump " . escapeshellarg($consumer), $output);
return array_map('trim', $output);
@@ -254,8 +267,9 @@ function gmirror_consumer_has_metadata($consumer) {
/* Find the mirror to which this consumer belongs */
function gmirror_get_consumer_metadata_mirror($consumer) {
- if (!is_valid_consumer($consumer))
+ if (!is_valid_consumer($consumer)) {
return array();
+ }
$metadata = gmirror_get_consumer_metadata($consumer);
foreach ($metadata as $line) {
if (substr($line, 0, 5) == "name:") {
@@ -267,22 +281,25 @@ function gmirror_get_consumer_metadata_mirror($consumer) {
/* Deactivate consumer, removing it from service in the mirror, but leave metadata intact */
function gmirror_deactivate_consumer($mirror, $consumer) {
- if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer))
+ if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer)) {
return false;
+ }
return mwexec("/sbin/gmirror deactivate " . escapeshellarg($mirror) . " " . escapeshellarg($consumer));
}
/* Reactivate a deactivated consumer */
function gmirror_activate_consumer($mirror, $consumer) {
- if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer))
+ if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer)) {
return false;
+ }
return mwexec("/sbin/gmirror activate " . escapeshellarg($mirror) . " " . escapeshellarg($consumer));
}
/* Find the size of the given mirror */
function gmirror_get_mirror_size($mirror) {
- if (!is_valid_mirror($mirror))
+ if (!is_valid_mirror($mirror)) {
return false;
+ }
$mirrorsize = "";
exec("/sbin/gmirror list " . escapeshellarg($mirror) . " | /usr/bin/grep 'Mediasize:' | /usr/bin/head -n 1 | /usr/bin/awk '{print $2;}'", $mirrorsize);
return $mirrorsize[0];
@@ -292,8 +309,9 @@ function gmirror_get_mirror_size($mirror) {
list output is a little odd, we can't get the output for just the disk, if the disk contains
slices those get output also. */
function gmirror_get_all_unused_consumer_sizes_on_disk($disk) {
- if (!is_valid_disk($disk) || !is_consumer_unused($disk))
+ if (!is_valid_disk($disk) || !is_consumer_unused($disk)) {
return array();
+ }
$output = "";
exec("/sbin/geom part list " . escapeshellarg($disk) . " | /usr/bin/egrep '(Name:|Mediasize:)' | /usr/bin/cut -c4- | /usr/bin/sed -l -e 'N;s/\\nMediasize://;P;D;' | /usr/bin/cut -c7-", $output);
if (empty($output)) {
@@ -315,8 +333,9 @@ function gmirror_get_all_unused_consumer_sizes_on_disk($disk) {
function gmirror_get_unused_consumer_size($consumer) {
$consumersizes = gmirror_get_all_unused_consumer_sizes_on_disk($consumer);
foreach ($consumersizes as $csize) {
- if ($csize['name'] == $consumer)
+ if ($csize['name'] == $consumer) {
return $csize['size'];
+ }
}
return -1;
}
diff --git a/etc/inc/growl.class b/etc/inc/growl.class
index 33650ca..8f639e5 100644
--- a/etc/inc/growl.class
+++ b/etc/inc/growl.class
@@ -3,100 +3,100 @@
pfSense_MODULE: notifications
*/
- class Growl
- {
- const GROWL_PRIORITY_LOW = -2;
- const GROWL_PRIORITY_MODERATE = -1;
- const GROWL_PRIORITY_NORMAL = 0;
- const GROWL_PRIORITY_HIGH = 1;
- const GROWL_PRIORITY_EMERGENCY = 2;
+ class Growl
+ {
+ const GROWL_PRIORITY_LOW = -2;
+ const GROWL_PRIORITY_MODERATE = -1;
+ const GROWL_PRIORITY_NORMAL = 0;
+ const GROWL_PRIORITY_HIGH = 1;
+ const GROWL_PRIORITY_EMERGENCY = 2;
- private $appName;
- private $address;
- private $notifications;
- private $password;
- private $port;
+ private $appName;
+ private $address;
+ private $notifications;
+ private $password;
+ private $port;
- public function __construct($address, $password = '', $app_name = 'PHP-Growl')
- {
- $this->appName = utf8_encode($app_name);
- $this->address = $address;
- $this->notifications = array();
- $this->password = $password;
- $this->port = 9887;
- }
-
- public function addNotification($name, $enabled = true)
- {
- $this->notifications[] = array('name' => utf8_encode($name), 'enabled' => $enabled);
- }
+ public function __construct($address, $password = '', $app_name = 'PHP-Growl')
+ {
+ $this->appName = utf8_encode($app_name);
+ $this->address = $address;
+ $this->notifications = array();
+ $this->password = $password;
+ $this->port = 9887;
+ }
- public function register()
- {
- $data = '';
- $defaults = '';
- $num_defaults = 0;
+ public function addNotification($name, $enabled = true)
+ {
+ $this->notifications[] = array('name' => utf8_encode($name), 'enabled' => $enabled);
+ }
- for($i = 0; $i < count($this->notifications); $i++)
- {
- $data .= pack('n', strlen($this->notifications[$i]['name'])) . $this->notifications[$i]['name'];
- if($this->notifications[$i]['enabled'])
- {
- $defaults .= pack('c', $i);
- $num_defaults++;
- }
- }
+ public function register()
+ {
+ $data = '';
+ $defaults = '';
+ $num_defaults = 0;
- // pack(Protocol version, type, app name, number of notifications to register)
- $data = pack('c2nc2', 1, 0, strlen($this->appName), count($this->notifications), $num_defaults) . $this->appName . $data . $defaults;
- $data .= pack('H32', md5($data . $this->password));
+ for ($i = 0; $i < count($this->notifications); $i++)
+ {
+ $data .= pack('n', strlen($this->notifications[$i]['name'])) . $this->notifications[$i]['name'];
+ if ($this->notifications[$i]['enabled'])
+ {
+ $defaults .= pack('c', $i);
+ $num_defaults++;
+ }
+ }
- return $this->send($data);
- }
+ // pack(Protocol version, type, app name, number of notifications to register)
+ $data = pack('c2nc2', 1, 0, strlen($this->appName), count($this->notifications), $num_defaults) . $this->appName . $data . $defaults;
+ $data .= pack('H32', md5($data . $this->password));
- public function notify($name, $title, $message, $priority = 0, $sticky = false)
- {
- $name = utf8_encode($name);
- $title = utf8_encode($title);
- $message = utf8_encode($message);
- $priority = intval($priority);
+ return $this->send($data);
+ }
- $flags = ($priority & 7) * 2;
- if($priority < 0) $flags |= 8;
- if($sticky) $flags |= 1;
+ public function notify($name, $title, $message, $priority = 0, $sticky = false)
+ {
+ $name = utf8_encode($name);
+ $title = utf8_encode($title);
+ $message = utf8_encode($message);
+ $priority = intval($priority);
- // pack(protocol version, type, priority/sticky flags, notification name length, title length, message length. app name length)
- $data = pack('c2n5', 1, 1, $flags, strlen($name), strlen($title), strlen($message), strlen($this->appName));
- $data .= $name . $title . $message . $this->appName;
- $data .= pack('H32', md5($data . $this->password));
+ $flags = ($priority & 7) * 2;
+ if ($priority < 0) $flags |= 8;
+ if ($sticky) $flags |= 1;
- return $this->send($data);
- }
+ // pack(protocol version, type, priority/sticky flags, notification name length, title length, message length. app name length)
+ $data = pack('c2n5', 1, 1, $flags, strlen($name), strlen($title), strlen($message), strlen($this->appName));
+ $data .= $name . $title . $message . $this->appName;
+ $data .= pack('H32', md5($data . $this->password));
- private function send($data)
- {
- if(function_exists('socket_create') && function_exists('socket_sendto'))
- {
- $sck = @socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
- if ($sck) {
- socket_sendto($sck, $data, strlen($data), 0x100, $this->address, $this->port);
- return true;
+ return $this->send($data);
}
- }
- elseif(function_exists('fsockopen'))
- {
- if ($this->address) {
- $fp = @fsockopen('udp://' . $this->address, $this->port);
- if ($fp) {
- fwrite($fp, $data);
- fclose($fp);
- return true;
+
+ private function send($data)
+ {
+ if (function_exists('socket_create') && function_exists('socket_sendto'))
+ {
+ $sck = @socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
+ if ($sck) {
+ socket_sendto($sck, $data, strlen($data), 0x100, $this->address, $this->port);
+ return true;
+ }
+ }
+ elseif (function_exists('fsockopen'))
+ {
+ if ($this->address) {
+ $fp = @fsockopen('udp://' . $this->address, $this->port);
+ if ($fp) {
+ fwrite($fp, $data);
+ fclose($fp);
+ return true;
+ }
+ }
}
- }
- }
- return false;
- }
- }
+ return false;
+ }
+ }
?> \ No newline at end of file
diff --git a/etc/inc/gwlb.inc b/etc/inc/gwlb.inc
index df6a613..68af1ff 100644
--- a/etc/inc/gwlb.inc
+++ b/etc/inc/gwlb.inc
@@ -63,8 +63,9 @@ function setup_gateways_monitor() {
}
$apinger_debug = "";
- if (isset($config['system']['apinger_debug']))
+ if (isset($config['system']['apinger_debug'])) {
$apinger_debug = "debug on";
+ }
$apinger_default = return_apinger_defaults();
$apingerconfig = <<<EOD
@@ -153,23 +154,26 @@ target default {
EOD;
$monitor_ips = array();
- foreach($gateways_arr as $name => $gateway) {
+ foreach ($gateways_arr as $name => $gateway) {
/* Do not monitor if such was requested */
- if (isset($gateway['monitor_disable']))
+ if (isset($gateway['monitor_disable'])) {
continue;
+ }
if (empty($gateway['monitor']) || !is_ipaddr($gateway['monitor'])) {
- if (is_ipaddr($gateway['gateway']))
+ if (is_ipaddr($gateway['gateway'])) {
$gateway['monitor'] = $gateway['gateway'];
- else /* No chance to get an ip to monitor skip target. */
+ } else { /* No chance to get an ip to monitor skip target. */
continue;
+ }
}
/* if the monitor address is already used before, skip */
- if(in_array($gateway['monitor'], $monitor_ips))
+ if (in_array($gateway['monitor'], $monitor_ips)) {
continue;
+ }
- /* Interface ip is needed since apinger will bind a socket to it.
- * However the config GUI should already have checked this and when
+ /* Interface ip is needed since apinger will bind a socket to it.
+ * However the config GUI should already have checked this and when
* PPoE is used the IP address is set to "dynamic". So using is_ipaddrv4
* or is_ipaddrv6 to identify packet type would be wrong, especially as
* further checks (that can cope with the "dynamic" case) are present inside
@@ -177,11 +181,13 @@ EOD;
*/
if ($gateway['ipprotocol'] == "inet") { // This is an IPv4 gateway...
$gwifip = find_interface_ip($gateway['interface'], true);
- if (!is_ipaddrv4($gwifip))
+ if (!is_ipaddrv4($gwifip)) {
continue; //Skip this target
+ }
- if ($gwifip == "0.0.0.0")
+ if ($gwifip == "0.0.0.0") {
continue; //Skip this target - the gateway is still waiting for DHCP
+ }
/*
* If the gateway is the same as the monitor we do not add a
@@ -191,12 +197,13 @@ EOD;
*/
if (is_ipaddrv4($gateway['gateway']) && $gateway['monitor'] != $gateway['gateway']) {
log_error("Removing static route for monitor {$gateway['monitor']} and adding a new route through {$gateway['gateway']}");
- if (interface_isppp_type($gateway['friendlyiface']))
+ if (interface_isppp_type($gateway['friendlyiface'])) {
mwexec("/sbin/route change -host " . escapeshellarg($gateway['monitor']) .
" -iface " . escapeshellarg($gateway['interface']), true);
- else
+ } else {
mwexec("/sbin/route change -host " . escapeshellarg($gateway['monitor']) .
" " . escapeshellarg($gateway['gateway']), true);
+ }
pfSense_kill_states("0.0.0.0/0", $gateway['monitor'], $gateway['interface'], "icmp");
}
@@ -204,8 +211,9 @@ EOD;
if ($gateway['monitor'] == $gateway['gateway']) {
/* link locals really need a different src ip */
if (is_linklocal($gateway['gateway'])) {
- if (!strpos($gateway['gateway'], '%'))
+ if (!strpos($gateway['gateway'], '%')) {
$gateway['gateway'] .= '%' . $gateway['interface'];
+ }
$gwifip = find_interface_ipv6_ll($gateway['interface'], true);
} else {
$gwifip = find_interface_ipv6($gateway['interface'], true);
@@ -220,13 +228,16 @@ EOD;
}
/* Make sure srcip and target have scope defined when they are ll */
- if (is_linklocal($gwifip) && !strpos($gwifip, '%'))
+ if (is_linklocal($gwifip) && !strpos($gwifip, '%')) {
$gwifip .= '%' . $gateway['interface'];
- if (is_linklocal($gateway['monitor']) && !strpos($gateway['monitor'], '%'))
+ }
+ if (is_linklocal($gateway['monitor']) && !strpos($gateway['monitor'], '%')) {
$gateway['monitor'] .= "%{$gateway['interface']}";
+ }
- if (!is_ipaddrv6($gwifip))
+ if (!is_ipaddrv6($gwifip)) {
continue; //Skip this target
+ }
/*
* If the gateway is the same as the monitor we do not add a
@@ -236,17 +247,19 @@ EOD;
*/
if ($gateway['gateway'] != $gateway['monitor']) {
log_error("Removing static route for monitor {$gateway['monitor']} and adding a new route through {$gateway['gateway']}");
- if (interface_isppp_type($gateway['friendlyiface']))
+ if (interface_isppp_type($gateway['friendlyiface'])) {
mwexec("/sbin/route change -host -inet6 " . escapeshellarg($gateway['monitor']) .
" -iface " . escapeshellarg($gateway['interface']), true);
- else
+ } else {
mwexec("/sbin/route change -host -inet6 " . escapeshellarg($gateway['monitor']) .
" " . escapeshellarg($gateway['gateway']), true);
+ }
pfSense_kill_states("::0.0.0.0/0", $gateway['monitor'], $gateway['interface'], "icmpv6");
}
- } else
+ } else {
continue;
+ }
$monitor_ips[] = $gateway['monitor'];
$apingercfg = "target \"{$gateway['monitor']}\" {\n";
@@ -256,35 +269,47 @@ EOD;
## How often the probe should be sent
if (!empty($gateway['interval']) && is_numeric($gateway['interval'])) {
$interval = intval($gateway['interval']); # Restrict to Integer
- if ($interval < 1) $interval = 1; # Minimum
- if ($interval != $apinger_default['interval']) # If not default value
+ if ($interval < 1) {
+ $interval = 1; # Minimum
+ }
+ if ($interval != $apinger_default['interval']) { # If not default value
$apingercfg .= " interval " . $interval . "s\n";
+ }
}
- ## How many replies should be used to compute average delay
+ ## How many replies should be used to compute average delay
## for controlling "delay" alarms
if (!empty($gateway['avg_delay_samples']) && is_numeric($gateway['avg_delay_samples'])) {
$avg_delay_samples = intval($gateway['avg_delay_samples']); # Restrict to Integer
- if ($avg_delay_samples < 1) $avg_delay_samples = 1; # Minimum
- if ($avg_delay_samples != $apinger_default['avg_delay_samples']) # If not default value
+ if ($avg_delay_samples < 1) {
+ $avg_delay_samples = 1; # Minimum
+ }
+ if ($avg_delay_samples != $apinger_default['avg_delay_samples']) { # If not default value
$apingercfg .= " avg_delay_samples " . $avg_delay_samples . "\n";
+ }
}
## How many probes should be used to compute average loss
if (!empty($gateway['avg_loss_samples']) && is_numeric($gateway['avg_loss_samples'])) {
$avg_loss_samples = intval($gateway['avg_loss_samples']); # Restrict to Integer
- if ($avg_loss_samples < 1) $avg_loss_samples = 1; # Minimum
- if ($avg_loss_samples != $apinger_default['avg_loss_samples']) # If not default value
+ if ($avg_loss_samples < 1) {
+ $avg_loss_samples = 1; # Minimum
+ }
+ if ($avg_loss_samples != $apinger_default['avg_loss_samples']) { # If not default value
$apingercfg .= " avg_loss_samples " . $avg_loss_samples . "\n";
+ }
}
## The delay (in samples) after which loss is computed
## without this delays larger than interval would be treated as loss
if (!empty($gateway['avg_loss_delay_samples']) && is_numeric($gateway['avg_loss_delay_samples'])) {
$avg_loss_delay_samples = intval($gateway['avg_loss_delay_samples']); # Restrict to Integer
- if ($avg_loss_delay_samples < 1) $avg_loss_delay_samples = 1; # Minimum
- if ($avg_loss_delay_samples != $apinger_default['avg_loss_delay_samples']) # If not default value
+ if ($avg_loss_delay_samples < 1) {
+ $avg_loss_delay_samples = 1; # Minimum
+ }
+ if ($avg_loss_delay_samples != $apinger_default['avg_loss_delay_samples']) { # If not default value
$apingercfg .= " avg_loss_delay_samples " . $avg_loss_delay_samples . "\n";
+ }
}
$alarms = "";
@@ -298,8 +323,9 @@ EOD;
$alarms .= "\"{$name}loss\"";
$override = true;
} else {
- if ($override == true)
+ if ($override == true) {
$alarms .= ",";
+ }
$alarms .= "\"loss\"";
$override = true;
}
@@ -308,13 +334,15 @@ EOD;
$alarmscfg .= "\tdelay_low {$gateway['latencylow']}ms\n";
$alarmscfg .= "\tdelay_high {$gateway['latencyhigh']}ms\n";
$alarmscfg .= "}\n";
- if ($override == true)
+ if ($override == true) {
$alarms .= ",";
+ }
$alarms .= "\"{$name}delay\"";
$override = true;
} else {
- if ($override == true)
+ if ($override == true) {
$alarms .= ",";
+ }
$alarms .= "\"delay\"";
$override = true;
}
@@ -322,21 +350,25 @@ EOD;
$alarmscfg .= "alarm down \"{$name}down\" {\n";
$alarmscfg .= "\ttime {$gateway['down']}s\n";
$alarmscfg .= "}\n";
- if ($override == true)
+ if ($override == true) {
$alarms .= ",";
+ }
$alarms .= "\"{$name}down\"";
$override = true;
} else {
- if ($override == true)
+ if ($override == true) {
$alarms .= ",";
+ }
$alarms .= "\"down\"";
$override = true;
}
- if ($override == true)
+ if ($override == true) {
$apingercfg .= "\talarms override {$alarms};\n";
+ }
- if (isset($gateway['force_down']))
+ if (isset($gateway['force_down'])) {
$apingercfg .= "\tforce_down on\n";
+ }
$apingercfg .= " rrd file \"{$g['vardb_path']}/rrd/{$gateway['name']}-quality.rrd\"\n";
$apingercfg .= "}\n";
@@ -345,18 +377,18 @@ EOD;
$apingerconfig .= $alarmscfg;
$apingerconfig .= $apingercfg;
- # Create gateway quality RRD with settings more suitable for pfSense graph set,
- # since apinger uses default step (300; 5 minutes) and other settings that don't
+ # Create gateway quality RRD with settings more suitable for pfSense graph set,
+ # since apinger uses default step (300; 5 minutes) and other settings that don't
# match the pfSense gateway quality graph set.
create_gateway_quality_rrd("{$g['vardb_path']}/rrd/{$gateway['name']}-quality.rrd");
}
@file_put_contents("{$g['varetc_path']}/apinger.conf", $apingerconfig);
unset($apingerconfig);
- /* Restart apinger process */
- if (isvalidpid("{$g['varrun_path']}/apinger.pid"))
+ /* Restart apinger process */
+ if (isvalidpid("{$g['varrun_path']}/apinger.pid")) {
sigkillbypid("{$g['varrun_path']}/apinger.pid", "HUP");
- else {
+ } else {
/* start a new apinger process */
@unlink("{$g['varrun_path']}/apinger.status");
sleep(1);
@@ -374,20 +406,23 @@ function return_gateways_status($byname = false) {
$apingerstatus = array();
/* Always get the latest status from apinger */
- if (file_exists("{$g['varrun_path']}/apinger.pid"))
- sigkillbypid("{$g['varrun_path']}/apinger.pid", "USR1");
+ if (file_exists("{$g['varrun_path']}/apinger.pid")) {
+ sigkillbypid("{$g['varrun_path']}/apinger.pid", "USR1");
+ }
if (file_exists("{$g['varrun_path']}/apinger.status")) {
$apingerstatus = file("{$g['varrun_path']}/apinger.status");
- } else
+ } else {
$apingerstatus = array();
+ }
$status = array();
- foreach($apingerstatus as $line) {
+ foreach ($apingerstatus as $line) {
$info = explode("|", $line);
- if ($byname == false)
+ if ($byname == false) {
$target = $info[0];
- else
+ } else {
$target = $info[2];
+ }
$status[$target] = array();
$status[$target]['monitorip'] = $info[0];
@@ -402,26 +437,29 @@ function return_gateways_status($byname = false) {
/* tack on any gateways that have monitoring disabled
* or are down, which could cause gateway groups to fail */
$gateways_arr = return_gateways_array();
- foreach($gateways_arr as $gwitem) {
- if(!isset($gwitem['monitor_disable']))
+ foreach ($gateways_arr as $gwitem) {
+ if (!isset($gwitem['monitor_disable'])) {
continue;
- if(!is_ipaddr($gwitem['monitorip'])) {
+ }
+ if (!is_ipaddr($gwitem['monitorip'])) {
$realif = $gwitem['interface'];
$tgtip = get_interface_gateway($realif);
- if (!is_ipaddr($tgtip))
+ if (!is_ipaddr($tgtip)) {
$tgtip = "none";
+ }
$srcip = find_interface_ip($realif);
} else {
$tgtip = $gwitem['monitorip'];
$srcip = find_interface_ip($realif);
}
- if($byname == true)
+ if ($byname == true) {
$target = $gwitem['name'];
- else
+ } else {
$target = $tgtip;
+ }
/* failsafe for down interfaces */
- if($target == "none") {
+ if ($target == "none") {
$target = $gwitem['name'];
$status[$target]['name'] = $gwitem['name'];
$status[$target]['lastcheck'] = date('r');
@@ -464,16 +502,18 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
$i++;
if (empty($config['interfaces'][$gateway['interface']])) {
- if ($inactive === false)
+ if ($inactive === false) {
continue;
- else
+ } else {
$gateway['inactive'] = true;
+ }
}
$wancfg = $config['interfaces'][$gateway['interface']];
/* skip disabled interfaces */
- if ($disabled === false && (!isset($wancfg['enable'])))
+ if ($disabled === false && (!isset($wancfg['enable']))) {
continue;
+ }
/* if the gateway is dynamic and we can find the IPv4, Great! */
if (empty($gateway['gateway']) || $gateway['gateway'] == "dynamic") {
@@ -481,8 +521,9 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
/* we know which interfaces is dynamic, this should be made a function */
$gateway['gateway'] = get_interface_gateway($gateway['interface']);
/* no IP address found, set to dynamic */
- if (!is_ipaddrv4($gateway['gateway']))
+ if (!is_ipaddrv4($gateway['gateway'])) {
$gateway['gateway'] = "dynamic";
+ }
$gateway['dynamic'] = true;
}
@@ -491,23 +532,26 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
/* we know which interfaces is dynamic, this should be made a function, and for v6 too */
$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
/* no IPv6 address found, set to dynamic */
- if (!is_ipaddrv6($gateway['gateway']))
+ if (!is_ipaddrv6($gateway['gateway'])) {
$gateway['gateway'] = "dynamic";
+ }
$gateway['dynamic'] = true;
}
} else {
/* getting this detection right is hard at this point because we still don't
* store the address family in the gateway item */
- if (is_ipaddrv4($gateway['gateway']))
+ if (is_ipaddrv4($gateway['gateway'])) {
$gateway['ipprotocol'] = "inet";
- else if(is_ipaddrv6($gateway['gateway']))
+ } else if (is_ipaddrv6($gateway['gateway'])) {
$gateway['ipprotocol'] = "inet6";
+ }
}
- if (isset($gateway['monitor_disable']))
+ if (isset($gateway['monitor_disable'])) {
$gateway['monitor_disable'] = true;
- else if (empty($gateway['monitor']))
+ } else if (empty($gateway['monitor'])) {
$gateway['monitor'] = $gateway['gateway'];
+ }
$gateway['friendlyiface'] = $gateway['interface'];
@@ -538,38 +582,45 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
$gateways_arr_temp[$gateway['name']] = $gateway;
/* skip disabled gateways if the caller has not asked for them to be returned. */
- if (!($disabled === false && isset($gateway['disabled'])))
+ if (!($disabled === false && isset($gateway['disabled']))) {
$gateways_arr[$gateway['name']] = $gateway;
+ }
}
}
unset($gateway);
/* Loop through all interfaces with a gateway and add it to a array */
- if ($disabled == false)
+ if ($disabled == false) {
$iflist = get_configured_interface_with_descr();
- else
+ } else {
$iflist = get_configured_interface_with_descr(false, true);
+ }
/* Process/add dynamic v4 gateways. */
- foreach($iflist as $ifname => $friendly ) {
- if(! interface_has_gateway($ifname))
+ foreach ($iflist as $ifname => $friendly ) {
+ if (! interface_has_gateway($ifname)) {
continue;
+ }
- if (empty($config['interfaces'][$ifname]))
+ if (empty($config['interfaces'][$ifname])) {
continue;
+ }
$ifcfg = &$config['interfaces'][$ifname];
- if(!isset($ifcfg['enable']))
+ if (!isset($ifcfg['enable'])) {
continue;
+ }
- if(!empty($ifcfg['ipaddr']) && is_ipaddrv4($ifcfg['ipaddr']))
+ if (!empty($ifcfg['ipaddr']) && is_ipaddrv4($ifcfg['ipaddr'])) {
continue;
+ }
- if (isset($interfaces_v4[$ifname]))
+ if (isset($interfaces_v4[$ifname])) {
continue;
+ }
$ctype = "";
- switch($ifcfg['ipaddr']) {
+ switch ($ifcfg['ipaddr']) {
case "dhcp":
case "pppoe":
case "pptp":
@@ -585,15 +636,17 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
if (is_array($config['openvpn']['openvpn-server'])) {
foreach ($config['openvpn']['openvpn-server'] as & $ovpnserverconf) {
if ($ovpnserverconf['vpnid'] == $ovpnid) {
- if ($ovpnserverconf['dev_mode'] == "tap")
+ if ($ovpnserverconf['dev_mode'] == "tap") {
continue 3;
+ }
}
}
}
}
$ctype = "VPNv4";
- } else if ($tunnelif == "gif" || $tunnelif == "gre")
+ } else if ($tunnelif == "gif" || $tunnelif == "gre") {
$ctype = "TUNNELv4";
+ }
break;
}
$ctype = "_". strtoupper($ctype);
@@ -613,18 +666,21 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
$found_defaultv4 = 1;
}
/* Loopback dummy for dynamic interfaces without a IP */
- if (!is_ipaddrv4($gateway['gateway']) && $gateway['dynamic'] == true)
+ if (!is_ipaddrv4($gateway['gateway']) && $gateway['dynamic'] == true) {
$gateway['gateway'] = "dynamic";
+ }
/* automatically skip known static and dynamic gateways that were previously processed */
- foreach($gateways_arr_temp as $gateway_item) {
+ foreach ($gateways_arr_temp as $gateway_item) {
if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name'])&& ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) ||
- ($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))
- continue 2;
+ (($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))) {
+ continue 2;
+ }
}
- if (is_ipaddrv4($gateway['gateway']))
+ if (is_ipaddrv4($gateway['gateway'])) {
$gateway['monitor'] = $gateway['gateway'];
+ }
$gateway['descr'] = "Interface {$friendly}{$ctype} Gateway";
$gateways_arr[$gateway['name']] = $gateway;
@@ -632,29 +688,35 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
unset($gateway);
/* Process/add dynamic v6 gateways. */
- foreach($iflist as $ifname => $friendly ) {
+ foreach ($iflist as $ifname => $friendly ) {
/* If the user has disabled IPv6, they probably don't want any IPv6 gateways. */
- if (!isset($config['system']['ipv6allow']))
+ if (!isset($config['system']['ipv6allow'])) {
break;
+ }
- if(! interface_has_gatewayv6($ifname))
+ if (! interface_has_gatewayv6($ifname)) {
continue;
+ }
- if (empty($config['interfaces'][$ifname]))
+ if (empty($config['interfaces'][$ifname])) {
continue;
+ }
$ifcfg = &$config['interfaces'][$ifname];
- if(!isset($ifcfg['enable']))
+ if (!isset($ifcfg['enable'])) {
continue;
+ }
- if(!empty($ifcfg['ipaddrv6']) && is_ipaddrv6($ifcfg['ipaddrv6']))
+ if (!empty($ifcfg['ipaddrv6']) && is_ipaddrv6($ifcfg['ipaddrv6'])) {
continue;
+ }
- if(isset($interfaces_v6[$ifname]))
+ if (isset($interfaces_v6[$ifname])) {
continue;
+ }
$ctype = "";
- switch($ifcfg['ipaddrv6']) {
+ switch ($ifcfg['ipaddrv6']) {
case "slaac":
case "dhcp6":
case "6to4":
@@ -670,15 +732,17 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
if (is_array($config['openvpn']['openvpn-server'])) {
foreach ($config['openvpn']['openvpn-server'] as & $ovpnserverconf) {
if ($ovpnserverconf['vpnid'] == $ovpnid) {
- if ($ovpnserverconf['dev_mode'] == "tap")
+ if ($ovpnserverconf['dev_mode'] == "tap") {
continue 3;
+ }
}
}
}
}
$ctype = "VPNv6";
- } else if ($tunnelif == "gif" || $tunnelif == "gre")
+ } else if ($tunnelif == "gif" || $tunnelif == "gre") {
$ctype = "TUNNELv6";
+ }
break;
}
$ctype = "_". strtoupper($ctype);
@@ -688,7 +752,7 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
$gateway['ipprotocol'] = "inet6";
$gateway['gateway'] = get_interface_gateway_v6($ifname, $gateway['dynamic']);
$gateway['interface'] = get_real_interface($ifname, "inet6");
- switch($ifcfg['ipaddrv6']) {
+ switch ($ifcfg['ipaddrv6']) {
case "6rd":
case "6to4":
$gateway['dynamic'] = "default";
@@ -705,18 +769,21 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
}
/* Loopback dummy for dynamic interfaces without a IP */
- if (!is_ipaddrv6($gateway['gateway']) && $gateway['dynamic'] == true)
+ if (!is_ipaddrv6($gateway['gateway']) && $gateway['dynamic'] == true) {
$gateway['gateway'] = "dynamic";
+ }
/* automatically skip known static and dynamic gateways that were previously processed */
- foreach($gateways_arr_temp as $gateway_item) {
+ foreach ($gateways_arr_temp as $gateway_item) {
if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name']) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) ||
- ($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))
- continue 2;
+ (($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))) {
+ continue 2;
+ }
}
- if (is_ipaddrv6($gateway['gateway']))
+ if (is_ipaddrv6($gateway['gateway'])) {
$gateway['monitor'] = $gateway['gateway'];
+ }
$gateway['descr'] = "Interface {$friendly}{$ctype} Gateway";
$gateways_arr[$gateway['name']] = $gateway;
@@ -744,7 +811,7 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
}
}
- if($localhost === true) {
+ if ($localhost === true) {
/* attach localhost for Null routes */
$gwlo4 = array();
$gwlo4['name'] = "Null4";
@@ -776,27 +843,32 @@ function fixup_default_gateway($ipprotocol, $gateways_status, $gateways_arr) {
if (($gwsttng['ipprotocol'] == $ipprotocol) && isset($gwsttng['defaultgw'])) {
$dfltgwfound = true;
$dfltgwname = $gwname;
- if (!isset($gwsttng['monitor_disable']) && stristr($gateways_status[$gwname]['status'], "down"))
+ if (!isset($gwsttng['monitor_disable']) && stristr($gateways_status[$gwname]['status'], "down")) {
$dfltgwdown = true;
+ }
}
/* Keep a record of the last up gateway */
/* XXX: Blacklist lan for now since it might cause issues to those who have a gateway set for it */
- if (empty($upgw) && ($gwsttng['ipprotocol'] == $ipprotocol) && (isset($gwsttng['monitor_disable']) || !stristr($gateways_status[$gwname]['status'], "down")) && $gwsttng[$gwname]['friendlyiface'] != "lan")
+ if (empty($upgw) && ($gwsttng['ipprotocol'] == $ipprotocol) && (isset($gwsttng['monitor_disable']) || !stristr($gateways_status[$gwname]['status'], "down")) && $gwsttng[$gwname]['friendlyiface'] != "lan") {
$upgw = $gwname;
- if ($dfltgwdown == true && !empty($upgw))
+ }
+ if ($dfltgwdown == true && !empty($upgw)) {
break;
+ }
}
if ($dfltgwfound == false) {
$gwname = convert_friendly_interface_to_friendly_descr("wan");
- if (!empty($gateways_status[$gwname]) && stristr($gateways_status[$gwname]['status'], "down"))
+ if (!empty($gateways_status[$gwname]) && stristr($gateways_status[$gwname]['status'], "down")) {
$dfltgwdown = true;
+ }
}
if ($dfltgwdown == true && !empty($upgw)) {
- if ($gateways_arr[$upgw]['gateway'] == "dynamic")
+ if ($gateways_arr[$upgw]['gateway'] == "dynamic") {
$gateways_arr[$upgw]['gateway'] = get_interface_gateway($gateways_arr[$upgw]['friendlyiface']);
+ }
if (is_ipaddr($gateways_arr[$upgw]['gateway'])) {
log_error("Default gateway down setting {$upgw} as default!");
- if(is_ipaddrv6($gateways_arr[$upgw]['gateway'])) {
+ if (is_ipaddrv6($gateways_arr[$upgw]['gateway'])) {
$inetfamily = "-inet6";
} else {
$inetfamily = "-inet";
@@ -805,12 +877,15 @@ function fixup_default_gateway($ipprotocol, $gateways_status, $gateways_arr) {
}
} else if (!empty($dfltgwname)) {
$defaultgw = trim(exec("/sbin/route -n get -{$ipprotocol} default | /usr/bin/awk '/gateway:/ {print $2}'"), " \n");
- if ($ipprotocol == 'inet6' && !is_ipaddrv6($gateways_arr[$dfltgwname]['gateway']))
+ if ($ipprotocol == 'inet6' && !is_ipaddrv6($gateways_arr[$dfltgwname]['gateway'])) {
return;
- if ($ipprotocol == 'inet' && !is_ipaddrv4($gateways_arr[$dfltgwname]['gateway']))
+ }
+ if ($ipprotocol == 'inet' && !is_ipaddrv4($gateways_arr[$dfltgwname]['gateway'])) {
return;
- if ($defaultgw != $gateways_arr[$dfltgwname]['gateway'])
+ }
+ if ($defaultgw != $gateways_arr[$dfltgwname]['gateway']) {
mwexec("/sbin/route change -{$ipprotocol} default {$gateways_arr[$dfltgwname]['gateway']}");
+ }
}
}
@@ -841,14 +916,16 @@ function return_gateway_groups_array() {
list($gwname, $tier, $vipname) = explode("|", $item);
if (is_ipaddr($carplist[$vipname])) {
- if (!is_array($gwvip_arr[$group['name']]))
+ if (!is_array($gwvip_arr[$group['name']])) {
$gwvip_arr[$group['name']] = array();
+ }
$gwvip_arr[$group['name']][$gwname] = $vipname;
}
/* Do it here rather than reiterating again the group in case no member is up. */
- if (!is_array($backupplan[$tier]))
+ if (!is_array($backupplan[$tier])) {
$backupplan[$tier] = array();
+ }
$backupplan[$tier][] = $gwname;
/* check if the gateway is available before adding it to the array */
@@ -873,12 +950,14 @@ function return_gateway_groups_array() {
notify_via_smtp($msg);
} else {
/* Online add member */
- if (!is_array($tiers[$tier]))
+ if (!is_array($tiers[$tier])) {
$tiers[$tier] = array();
+ }
$tiers[$tier][] = $gwname;
}
- } else if (isset($gateways_arr[$gwname]['monitor_disable']))
+ } else if (isset($gateways_arr[$gwname]['monitor_disable'])) {
$tiers[$tier][] = $gwname;
+ }
}
$tiers_count = count($tiers);
if ($tiers_count == 0) {
@@ -903,10 +982,11 @@ function return_gateway_groups_array() {
$gateway = $gateways_arr[$member];
$int = $gateway['interface'];
$gatewayip = "";
- if(is_ipaddr($gateway['gateway']))
+ if (is_ipaddr($gateway['gateway'])) {
$gatewayip = $gateway['gateway'];
- else if (!empty($int))
+ } else if (!empty($int)) {
$gatewayip = get_interface_gateway($gateway['friendlyiface']);
+ }
if (!empty($int)) {
$gateway_groups_array[$group['name']]['ipprotocol'] = $gateway['ipprotocol'];
@@ -915,18 +995,20 @@ function return_gateway_groups_array() {
$groupmember['int'] = $int;
$groupmember['gwip'] = $gatewayip;
$groupmember['weight'] = isset($gateway['weight']) ? $gateway['weight'] : 1;
- if (is_array($gwvip_arr[$group['name']])&& !empty($gwvip_arr[$group['name']][$member]))
+ if (is_array($gwvip_arr[$group['name']])&& !empty($gwvip_arr[$group['name']][$member])) {
$groupmember['vip'] = $gwvip_arr[$group['name']][$member];
+ }
$gateway_groups_array[$group['name']][] = $groupmember;
}
}
}
}
/* we should have the 1st available tier now, exit stage left */
- if (count($gateway_groups_array[$group['name']]) > 0)
+ if (count($gateway_groups_array[$group['name']]) > 0) {
break;
- else
+ } else {
log_error("GATEWAYS: Group {$group['name']} did not have any gateways up on tier {$tieridx}!");
+ }
}
}
}
@@ -937,25 +1019,27 @@ function return_gateway_groups_array() {
/* Update DHCP WAN Interface ip address in gateway group item */
function dhclient_update_gateway_groups_defaultroute($interface = "wan") {
global $config, $g;
- foreach($config['gateways']['gateway_item'] as & $gw) {
- if($gw['interface'] == $interface) {
+ foreach ($config['gateways']['gateway_item'] as & $gw) {
+ if ($gw['interface'] == $interface) {
$current_gw = get_interface_gateway($interface);
- if($gw['gateway'] <> $current_gw) {
+ if ($gw['gateway'] <> $current_gw) {
$gw['gateway'] = $current_gw;
$changed = true;
}
}
}
- if($changed && $current_gw)
+ if ($changed && $current_gw) {
write_config(sprintf(gettext('Updating gateway group gateway for %1$s - new gateway is %2$s'), $interfac, $current_gw));
+ }
}
function lookup_gateway_ip_by_name($name) {
$gateways_arr = return_gateways_array(false, true);
foreach ($gateways_arr as $gname => $gw) {
- if ($gw['name'] === $name || $gname === $name)
+ if ($gw['name'] === $name || $gname === $name) {
return $gw['gateway'];
+ }
}
return false;
@@ -966,8 +1050,9 @@ function lookup_gateway_monitor_ip_by_name($name) {
$gateways_arr = return_gateways_array(false, true);
if (!empty($gateways_arr[$name])) {
$gateway = $gateways_arr[$name];
- if(!is_ipaddr($gateway['monitor']))
+ if (!is_ipaddr($gateway['monitor'])) {
return $gateway['gateway'];
+ }
return $gateway['monitor'];
}
@@ -989,14 +1074,15 @@ function lookup_gateway_interface_by_name($name) {
function get_interface_gateway($interface, &$dynamic = false) {
global $config, $g;
- if (substr($interface, 0, 4) == '_vip')
+ if (substr($interface, 0, 4) == '_vip') {
$interface = get_configured_carp_interface_list($interface, 'inet', 'iface');
+ }
$gw = NULL;
$gwcfg = $config['interfaces'][$interface];
if (!empty($gwcfg['gateway']) && is_array($config['gateways']['gateway_item'])) {
- foreach($config['gateways']['gateway_item'] as $gateway) {
- if(($gateway['name'] == $gwcfg['gateway']) && (is_ipaddrv4($gateway['gateway']))) {
+ foreach ($config['gateways']['gateway_item'] as $gateway) {
+ if (($gateway['name'] == $gwcfg['gateway']) && (is_ipaddrv4($gateway['gateway']))) {
$gw = $gateway['gateway'];
break;
}
@@ -1007,11 +1093,12 @@ function get_interface_gateway($interface, &$dynamic = false) {
if (($gw == NULL || !is_ipaddrv4($gw)) && !is_ipaddrv4($gwcfg['ipaddr'])) {
$realif = get_real_interface($interface);
if (file_exists("{$g['tmp_path']}/{$realif}_router")) {
- $gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_router"), " \n");
+ $gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_router"), " \n");
$dynamic = true;
}
- if (file_exists("{$g['tmp_path']}/{$realif}_defaultgw"))
+ if (file_exists("{$g['tmp_path']}/{$realif}_defaultgw")) {
$dynamic = "default";
+ }
}
@@ -1022,14 +1109,15 @@ function get_interface_gateway($interface, &$dynamic = false) {
function get_interface_gateway_v6($interface, &$dynamic = false) {
global $config, $g;
- if (substr($interface, 0, 4) == '_vip')
+ if (substr($interface, 0, 4) == '_vip') {
$interface = get_configured_carp_interface_list($interface, 'inet6', 'iface');
+ }
$gw = NULL;
$gwcfg = $config['interfaces'][$interface];
if (!empty($gwcfg['gatewayv6']) && is_array($config['gateways']['gateway_item'])) {
- foreach($config['gateways']['gateway_item'] as $gateway) {
- if(($gateway['name'] == $gwcfg['gatewayv6']) && (is_ipaddrv6($gateway['gateway']))) {
+ foreach ($config['gateways']['gateway_item'] as $gateway) {
+ if (($gateway['name'] == $gwcfg['gatewayv6']) && (is_ipaddrv6($gateway['gateway']))) {
$gw = $gateway['gateway'];
break;
}
@@ -1038,14 +1126,14 @@ function get_interface_gateway_v6($interface, &$dynamic = false) {
// for dynamic interfaces we handle them through the $interface_router file.
if (($gw == NULL || !is_ipaddrv6($gw)) && !is_ipaddrv6($gwcfg['ipaddrv6'])) {
- $realif = get_real_interface($interface);
- if (file_exists("{$g['tmp_path']}/{$realif}_routerv6")) {
- $gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_routerv6"), " \n");
- $dynamic = true;
- }
- if (file_exists("{$g['tmp_path']}/{$realif}_defaultgwv6"))
- $dynamic = "default";
-
+ $realif = get_real_interface($interface);
+ if (file_exists("{$g['tmp_path']}/{$realif}_routerv6")) {
+ $gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_routerv6"), " \n");
+ $dynamic = true;
+ }
+ if (file_exists("{$g['tmp_path']}/{$realif}_defaultgwv6")) {
+ $dynamic = "default";
+ }
}
/* return gateway */
return ($gw);
@@ -1059,29 +1147,37 @@ function validate_address_family($ipaddr, $gwname) {
$v4gw = false;
$v6gw = false;
- if(is_ipaddrv4($ipaddr))
+ if (is_ipaddrv4($ipaddr)) {
$v4ip = true;
- if(is_ipaddrv6($ipaddr))
+ }
+ if (is_ipaddrv6($ipaddr)) {
$v6ip = true;
- if(is_ipaddrv4($gwname))
+ }
+ if (is_ipaddrv4($gwname)) {
$v4gw = true;
- if(is_ipaddrv6($gwname))
+ }
+ if (is_ipaddrv6($gwname)) {
$v6gw = true;
+ }
- if($v4ip && $v4gw)
+ if ($v4ip && $v4gw) {
return true;
- if($v6ip && $v6gw)
+ }
+ if ($v6ip && $v6gw) {
return true;
+ }
/* still no match, carry on, lookup gateways */
- if(is_ipaddrv4(lookup_gateway_ip_by_name($gwname)))
+ if (is_ipaddrv4(lookup_gateway_ip_by_name($gwname))) {
$v4gw = true;
- if(is_ipaddrv6(lookup_gateway_ip_by_name($gwname)))
+ }
+ if (is_ipaddrv6(lookup_gateway_ip_by_name($gwname))) {
$v6gw = true;
+ }
$gw_array = return_gateways_array();
- if(is_array($gw_array[$gwname])) {
- switch($gw_array[$gwname]['ipprotocol']) {
+ if (is_array($gw_array[$gwname])) {
+ switch ($gw_array[$gwname]['ipprotocol']) {
case "inet":
$v4gw = true;
break;
@@ -1091,10 +1187,12 @@ function validate_address_family($ipaddr, $gwname) {
}
}
- if($v4ip && $v4gw)
+ if ($v4ip && $v4gw) {
return true;
- if($v6ip && $v6gw)
+ }
+ if ($v6ip && $v6gw) {
return true;
+ }
return false;
}
@@ -1103,15 +1201,16 @@ function validate_address_family($ipaddr, $gwname) {
function interface_gateway_group_member($interface) {
global $config;
- if (is_array($config['gateways']['gateway_group']))
+ if (is_array($config['gateways']['gateway_group'])) {
$groups = $config['gateways']['gateway_group'];
- else
+ } else {
return false;
+ }
$gateways_arr = return_gateways_array(false, true);
- foreach($groups as $group) {
- if(is_array($group['item'])) {
- foreach($group['item'] as $item) {
+ foreach ($groups as $group) {
+ if (is_array($group['item'])) {
+ foreach ($group['item'] as $item) {
$elements = explode("|", $item);
$gwname = $elements[0];
if ($interface == $gateways_arr[$gwname]['interface']) {
@@ -1129,19 +1228,21 @@ function interface_gateway_group_member($interface) {
function gateway_is_gwgroup_member($name) {
global $config;
- if (is_array($config['gateways']['gateway_group']))
+ if (is_array($config['gateways']['gateway_group'])) {
$groups = $config['gateways']['gateway_group'];
- else
+ } else {
return false;
+ }
$members = array();
- foreach($groups as $group) {
+ foreach ($groups as $group) {
if (is_array($group['item'])) {
- foreach($group['item'] as $item) {
+ foreach ($group['item'] as $item) {
$elements = explode("|", $item);
$gwname = $elements[0];
- if ($name == $elements[0])
+ if ($name == $elements[0]) {
$members[] = $group['name'];
+ }
}
}
}
OpenPOWER on IntegriCloud