. 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. */ /* include all configuration functions */ require_once("functions.inc"); require_once("pkg-utils.inc"); require_once("notices.inc"); require_once("shaper.inc"); function filter_pflog_start() { global $config, $g; if(isset($config['system']['developerspew'])) { $mt = microtime(); echo "filter_pflog_start() being called $mt\n"; } mute_kernel_msgs(); mwexec("/sbin/ifconfig pflog0 up && pflogd"); mwexec_bg("/usr/sbin/tcpdump -l -n -e -ttt -i pflog0 | logger -t pf -p local0.info"); unmute_kernel_msgs(); } /* reload filter async */ function filter_configure() { if(isset($config['system']['developerspew'])) { $mt = microtime(); echo "filter_configure() being called $mt\n"; } global $g; touch($g['tmp_path'] . "/filter_dirty"); } /* reload filter sync */ function filter_configure_sync() { global $config, $g; if(isset($config['system']['developerspew'])) { $mt = microtime(); echo "filter_configure_sync() being called $mt\n"; } unlink_if_exists("{$g['tmp_path']}/filter_dirty"); $lan_if = $config['interfaces']['lan']['if']; $wan_if = get_real_wan_interface(); /* generate aliases */ if($g['booting'] == true) echo " aliases "; $aliases = filter_generate_aliases(); /* generate nat rules */ if($g['booting'] == true) echo " rules "; $natrules = filter_nat_rules_generate(); /* generate pfctl rules */ if($g['booting'] == true) echo " filtering "; $pfrules = filter_rules_generate(); if(isset($config['shaper']['enable'])) { /* generate altq interface setup parms */ if($g['booting'] == true) echo " altq-interfaces "; $altq_ints = filter_setup_altq_interfaces(); /* generate altq queues */ if($g['booting'] == true) echo " altq-queues "; $altq_queues = filter_generate_altq_queues($altq_ints); /* generate altq rules */ if($g['booting'] == true) echo " altq-rules "; /* Setup a default rule that tags ALL packets as unshaped * we'll match only unshaped packets in the shaper code later * this allows the shaper to be first match */ $pf_altq_rules = "block all tag unshaped label \"SHAPER: first match rule\"\n"; $pf_altq_rules .= filter_generate_pf_altq_rules(); } /* enable pf if we need to, otherwise disable */ if( !isset( $config['system']['disablefilter'] ) ) { mwexec("/sbin/pfctl -e"); } else { mwexec("/sbin/pfctl -d"); return; } /* get our wan interface? */ $wanif = get_real_wan_interface(); /* set up MSS clamping */ if ($config['interfaces']['wan']['mtu'] <> "" and is_numeric($config['interfaces']['wan']['mtu'])) $mssclamp = "max-mss " . (intval($config['interfaces']['wan']['mtu'] - 40)); else if ($config['interfaces']['wan']['ipaddr'] == "pppoe") $mssclamp = "max-mss 1452"; else $mssclamp = ""; $fd = fopen("{$g['tmp_path']}/rules.debug", "w"); $rules = $aliases . " \n"; $rules .= setup_logging_interfaces(); if($config['system']['optimization'] <> "") $rules.= "set optimization {$config['system']['optimization']}\n"; else $rules.= "set optimization normal\n"; if($config['system']['maximumstates'] <> "" && is_numeric($config['system']['maximumstates'])) { /* User defined maximum states in Advanced menu. */ $rules.= "set limit states {$config['system']['maximumstates']}\n"; } $rules.= "\n"; $rules.= "scrub on {$wanif} all {$mssclamp}\n"; // reassemble all directions /* loop through optional interfaces. if a gateway is set, lets scrub em down! */ for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) { if($config['interfaces']["opt" . $j]['gateway'] <> "") { $if = convert_friendly_interface_to_real_interface_name("opt{$j}"); $rules.= "scrub on {$if} all {$mssclamp}\n"; // reassemble all directions } } $rules.= "{$altq_ints}\n"; $rules.= "{$altq_queues}\n"; $rules.= "{$natrules}\n"; $rules.= "{$pf_altq_rules}\n"; $rules.= "{$pfrules}\n"; fwrite($fd, $rules); fclose($fd); $rules_loading = mwexec("/sbin/pfctl -f {$g['tmp_path']}/rules.debug"); if (isset($config['shaper']['enable']) && is_array($config['shaper']['queue'])) { foreach ($config['shaper']['queue'] as $queue) { mwexec("/sbin/pfctl -a {$queue['name']} -f {$g['tmp_path']}/{$queue['name']}.rules"); } } /* check for a error while loading the rules file. if an error has occured then output the contents of the error to the caller */ if($rules_loading <> 0) { $rules_error = exec_command("/sbin/pfctl -f {$g['tmp_path']}/rules.debug"); $line_error = split("\:", $rules_error); $line_number = $line_error[1]; $rules_file = `/bin/cat {$g['tmp_path']}/rules.debug`; $line_split = split("\n", $rules_file); if(is_array($line_split)) $line_error = "The line in question reads [{$line_number}]: {$line_split[$line_number-1]}"; file_notice("filter_load", "There were error(s) loading the rules: {$rules_error} {$line_error}", "Filter Reload", ""); log_error("There were error(s) loading the rules: {$rules_error} - {$line_error}"); return; } unlink_if_exists("/usr/local/pkg/pf/carp_sync_client.php"); /* process packager manager custom rules */ $files = return_dir_as_array("/usr/local/pkg/pf/"); if($files <> "") { foreach ($files as $file) { if($file <> "") { $text = file_get_contents("/usr/local/pkg/pf/" . $file); if($text) { if(stristr($file, ".sh") == true) { mwexec("/usr/local/pkg/pf/" . $file . " start"); } else { if(stristr($file,"CVS") == false) { if($g['booting'] == true) echo "\t{$file}... "; eval($text); if($g['booting'] == true) echo "done.\n"; } } } } } } /* sync carp entries to other firewalls */ carp_sync_client(); /* we need a way to let a user run a shell cmd after each filter_configure() call. run this xml command after each change. */ if($config['system']['afterfilterchangeshellcmd'] <> "") { mwexec($config['system']['afterfilterchangeshellcmd']); } return 0; } function filter_get_rule_interface($associatedrulenumber) { global $config; if(isset($config['system']['developerspew'])) { $mt = microtime(); echo "filter_get_rule_interface() being called $mt\n"; } foreach ($config['shaper']['rule'] as $rule) { if($rule['descr'] == $associatedrule) return $rule['interface']; } return $config['shaper']['rule'][$associatedrulenumber]['interface']; } function filter_get_rule_real_interface($associatedrulenumber) { global $config; if(isset($config['system']['developerspew'])) { $mt = microtime(); echo "filter_get_rule_real_interface() being called $mt\n"; } $x=0; foreach($config['shaper']['rule'] as $rule) { if($x == $associatedrulenumber) return $rule['interface']; $x++; } } function filter_generate_aliases() { global $config; if(isset($config['system']['developerspew'])) { $mt = microtime(); echo "filter_generate_aliases() being called $mt\n"; } $aliases = ""; $i = 0; $lanip = find_interface_ip($config['interfaces']['lan']['if']); $wanip = find_interface_ip(get_real_wan_interface()); $lan_aliases = " " . link_ip_to_carp_interface($lanip); $wan_aliases = " " . link_ip_to_carp_interface($wanip); $aliases .= "# System Aliases \n"; $aliases .= "lan = \"{ {$config['interfaces']['lan']['if']}{$lan_aliases} }\"\n"; $aliases .= "wan = \"{ " . get_real_wan_interface() . "{$wan_aliases} }\"\n"; $aliases .= "pptp = \"{ ng1 ng2 ng3 ng4 ng5 ng6 ng7 ng8 ng9 ng10 ng11 ng12 ng13 ng14 }\"\n"; $aliases .= "pppoe = \"{ ng1 ng2 ng3 ng4 ng5 ng6 ng7 ng8 ng9 ng10 ng11 ng12 ng13 ng14 }\"\n"; $ifdescrs = array(); for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) { $ifdescrs['opt' . $j] = "opt" . $j; } $bridgetracker = 0; foreach ($ifdescrs as $ifdescr => $ifname) { /* do not process tun interfaces */ if(stristr(filter_opt_interface_to_real($ifname), "tun") == true) continue; $aliases .= filter_get_opt_interface_descr($ifname) . " = \"{ " . filter_opt_interface_to_real($ifname); if($config['interfaces'][$ifname]['bridge'] <> "") { $aliases .= " bridge{$bridgetracker} "; $bridgetracker++; } $aliases .= " }\"\n"; } $aliases .= "# User Aliases \n"; /* Setup pf groups */ if (isset($config['aliases']['alias'])) { foreach ($config['aliases']['alias'] as $alias) { $extraalias = ""; $ip = find_interface_ip($alias['address']); $extraalias = " " . link_ip_to_carp_interface($ip); $aliases .= "{$alias['name']} = \"{ {$alias['address']}{$extralias} }\"\n"; } } return $aliases; } function generate_optcfg_array(& $optcfg) { global $config; if(isset($config['system']['developerspew'])) { $mt = microtime(); echo "generate_optcfg_array() being called $mt\n"; } for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++) { $oc = $config['interfaces']['opt' . $i]; if (isset($oc['enable']) && $oc['if']) { $oic = array(); $oic['if'] = $oc['if']; if ($oc['bridge']) { if (!strstr($oc['bridge'], "opt") || isset($config['interfaces'][$oc['bridge']]['enable'])) { if (is_ipaddr($config['interfaces'][$oc['bridge']]['ipaddr'])) { $oic['ip'] = $config['interfaces'][$oc['bridge']]['ipaddr']; $oic['sn'] = $config['interfaces'][$oc['bridge']]['subnet']; $oic['sa'] = gen_subnet($oic['ip'], $oic['sn']); } } $oic['bridge'] = 1; } else { $oic['ip'] = $oc['ipaddr']; $oic['sn'] = $oc['subnet']; $oic['sa'] = gen_subnet($oic['ip'], $oic['sn']); } $optcfg['opt' . $i] = $oic; } } } function filter_flush_nat_table() { global $config, $g; if(isset($config['system']['developerspew'])) { $mt = microtime(); echo "filter_flush_nat_table() being called $mt\n"; } return mwexec("/sbin/pfctl -F nat"); } function filter_flush_state_table() { global $config, $g; return mwexec("/sbin/pfctl -F state"); } /* 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) { global $config; /* XXX: billm - any idea if this code is needed? */ if($src == "/32" || $src{0} == "/") return; /* Use interface name if IP isn't specified */ if ($natip != "") $tgt = "{$natip}/32"; else $tgt = "($if)"; /* Add the hard set source port (useful for ISAKMP) */ if ($natport != "") $tgt .= " port {$natport}"; /* sometimes this gets called with "" instead of a value */ if ($src == "") $src = "any"; /* Match on this source port */ if ($srcport != "") $src .= " port {$srcport}"; /* sometimes this gets called with "" instead of a value */ if ($dst == "") $dst = "any"; /* Match on this dest port */ if ($dstport != "") $dst .= " port {$dstport}"; /* Allow for negating NAT entries */ if ($nonat) { $nat = "no nat"; $target = ""; } else { $nat = "nat"; $target = "-> {$tgt}"; } /* Put all the pieces together */ $natrule = "{$nat} on {$if} from {$src} to {$dst} {$target}\n"; return $natrule; } function is_one_to_one_or_server_nat_rule($iptocheck) { global $config; if(isset($config['system']['developerspew'])) { $mt = microtime(); echo "is_one_to_one_or_server_nat_rule() being called $mt\n"; } if($config['nat']['onetoone'] <> "") foreach($config['nat']['onetoone'] as $onetoone) { if(ip_in_subnet($iptocheck,$onetoone['internal']."/".$onetoone['subnet']) == true) return true; if($onetoone['internal'] == $target) return true; } if($config['nat']['servernat'] <> "") foreach($config['nat']['servernat'] as $onetoone) { $int = explode("/", $onetoone['ipaddr']); if(ip_in_subnet($iptocheck,$onetoone['ipaddr']."/".$onetoone['subnet']) == true) return true; if($onetoone['ipaddr'] == $target) return true; } if($config['nat']['rule'] <> "") foreach($config['nat']['rule'] as $onetoone) { $int = explode("/", $onetoone['target']); if(ip_in_subnet($iptocheck,$onetoone['target']."/".$onetoone['subnet']) == true) return true; if($onetoone['target'] == $target) return true; } return FALSE; } function filter_nat_rules_generate() { global $config, $g; $wancfg = $config['interfaces']['wan']; $lancfg = $config['interfaces']['lan']; $pptpdcfg = $config['pptpd']; $pppoecfg = $config['pppoe']; $wanif = get_real_wan_interface(); $lanif = $config['interfaces']['lan']['if']; $lanip = $config['interfaces']['lan']['ipaddr']; $lansa = gen_subnet($lancfg['ipaddr'], $lancfg['subnet']); $natrules = ""; $natrules .= "nat-anchor \"pftpx/*\"\n"; $natrules .= "nat-anchor \"natearly/*\"\n"; $natrules .= "nat-anchor \"natrules/*\"\n"; /* any 1:1 mappings? */ if (is_array($config['nat']['onetoone'])) { foreach ($config['nat']['onetoone'] as $natent) { if (!is_numeric($natent['subnet'])) $sn = 32; else $sn = $natent['subnet']; if (!$natent['interface'] || ($natent['interface'] == "wan")) $natif = $wanif; else $natif = $config['interfaces'][$natent['interface']]['if']; $natrules .= "binat on {$natif} from {$natent['internal']}/{$sn} to any -> {$natent['external']}/{$sn}\n"; } } /* outbound rules - advanced or standard */ if (isset($config['nat']['advancedoutbound']['enable'])) { /* advanced outbound rules */ if (is_array($config['nat']['advancedoutbound']['rule'])) { foreach ($config['nat']['advancedoutbound']['rule'] as $obent) { $src = $obent['source']['network']; if (isset($obent['destination']['not']) && !isset($obent['destination']['any'])) $dst = "!" . $obent['destination']['address']; else $dst = $obent['destination']['address']; if (!$obent['interface'] || ($obent['interface'] == "wan")) $natif = $wanif; else $natif = $config['interfaces'][$obent['interface']]['if']; $natrules .= filter_nat_rules_generate_if($natif, $src, $obent['sourceport'], $dst, $obent['dstport'], $obent['target'], $obent['natport'], isset($obent['nonat'])); } } } else { /* standard outbound rules (one for each interface) */ /* create ipsec passthru rule if requested */ if (isset($config['nat']['ipsecpassthru']['enable'])) { $natrules .= filter_nat_rules_generate_if($wanif, "{$lansa}/{$lancfg['subnet']}", 500, "", 500, null, 500, false); } $natrules .= filter_nat_rules_generate_if($wanif, "{$lansa}/{$lancfg['subnet']}"); /* optional interfaces */ for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++) { $optcfg = $config['interfaces']['opt' . $i]; if (isset($optcfg['enable']) && !$optcfg['bridge']) { $optsa = gen_subnet($optcfg['ipaddr'], $optcfg['subnet']); /* setup nat mappings for lan -> opt[$i] * interface if a gateway is defined */ if($optcfg['gateway'] <> "") $natrules .= filter_nat_rules_generate_if($optcfg['if'], "{$lansa}/{$lancfg['subnet']}", null, "", null, null, null, isset($optcfg['nonat'])); $natrules .= filter_nat_rules_generate_if($wanif, "{$optsa}/{$optcfg['subnet']}", null, "", null, null, null, isset($optcfg['nonat'])); } } /* PPTP subnet */ if ($pptpdcfg['mode'] == "server") { $pptp_subnet = $g['pptp_subnet']; if($config['pptp']['pptp_subnet'] <> "") $pptp_subnet = $config['pptp']['pptp_subnet']; $natrules .= filter_nat_rules_generate_if($wanif, "{$pptpdcfg['remoteip']}/{$pptp_subnet}"); } /* PPPoE subnet */ if ($pppoecfg['mode'] == "server") { $pppoe_subnet = $g['pppoe_subnet']; if($config['pppoe']['pppoe_subnet'] <> "") $pppoe_subnet = $config['pppoe']['pppoe_subnet']; $natrules .= filter_nat_rules_generate_if($wanif, "{$pppoecfg['remoteip']}/{$pppoe_subnet}"); } /* static routes */ if (is_array($config['staticroutes']['route'])) { foreach ($config['staticroutes']['route'] as $route) { if ($route['interface'] != "wan") $natrules .= filter_nat_rules_generate_if($wanif, $route['network'], "", null); } } } $natrules .= "#SSH Lockout Table\n"; $natrules .= "table persist\n\n"; $natrules .= "\n# spam table \n"; $natrules .= "table persist\n\n"; /* load balancer anchor */ $natrules .= "\n# Load balancing anchor - slbd updates\n"; $natrules .= "rdr-anchor \"slb\"\n"; /* build an array of interfaces to work with */ $iflist = array("lan" => "LAN"); for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++) $iflist['opt' . $i] = $config['interfaces']['opt' . $i]['descr']; $natrules .= "# FTP proxy\n"; $natrules .= "rdr-anchor \"pftpx/*\"\n"; $interface_counter = 0; /* loop through all interfaces and handle pftpx redirections */ foreach ($iflist as $ifent => $ifname) { if(isset($config['interfaces'][strtolower($ifname)]['disableftpproxy'])) { $interface_counter++; continue; } $tmp_port = 8021 + $interface_counter; $tmp_interface = convert_friendly_interface_to_real_interface_name($ifname); $natrules .= "rdr on {$tmp_interface} proto tcp from any to any port 21 -> 127.0.0.1 port {$tmp_port}\n"; $interface_counter++; } $natrules .= "\n"; /* DIAG: add ipv6 NAT, if requested */ if (isset($config['diag']['ipv6nat']['enable']) and $config['diag']['ipv6nat']['ipaddr'] <> "") { /* XXX: FIX ME! IPV6 */ $natrules .= "rdr on $wanif proto ipv6 from any to any -> {$config['diag']['ipv6nat']['ipaddr']}\n"; } if(file_exists("/var/etc/inetd.conf")) mwexec("rm /var/etc/inetd.conf"); touch("/var/etc/inetd.conf"); if (isset($config['nat']['rule'])) { $natrules .= "# NAT Inbound Redirects\n"; if(!isset($config['system']['disablenatreflection'])) { $fd = fopen("/var/etc/inetd.conf","w"); /* start redirects on port 19000 of localhost */ $starting_localhost_port = 19000; } foreach ($config['nat']['rule'] as $rule) { /* if item is an alias, expand */ if(alias_expand($rule['external-port'])) $extport[0] = alias_expand_value($rule['external-port']); else $extport = explode("-", $rule['external-port']); /* if item is an alias, expand */ if(alias_expand($rule['local-port'])) $localport = ""; else $localport = " port {$rule['local-port']}"; $target = alias_expand_host($rule['target']); if (!$target) continue; /* unresolvable alias */ if ($rule['external-address']) if($rule['external-address'] <> "any") $extaddr = $rule['external-address'] . "/32"; else $extaddr = $rule['external-address']; else $extaddr = get_current_wan_address($rule['interface']); if (!$rule['interface'] || ($rule['interface'] == "wan")) $natif = $wanif; else if($rule['interface'] == "pptp") $natif = "pptp"; else if($rule['interface'] == "pppoe") $natif = "pppoe"; else $natif = $config['interfaces'][$rule['interface']]['if']; $lanif = $lancfg['if']; /* * Expand aliases * XXX: may want to integrate this into pf macros */ if(alias_expand($target)) $target = alias_expand($target); if(alias_expand($extaddr)) $extaddr = alias_expand($extaddr); /* * If FTP Proxy Helper is enabled and the * operator has requested a port forward to * a ftp server then launch a helper */ $dontinstallrdr = false; if($target <> "") { if($extport[0] == "21" and !isset($config['interfaces'][strtolower($rule['interface'])]['disableftpproxy'])) { $helpers = exec("/bin/ps awux | grep {$target} | grep -v grep"); if(!$helpers) { $external_address = $rule['external-address']; if($external_address == "") $external_address = find_interface_ip(get_real_wan_interface()); /* install a pftpx helper, do not set a rule */ mwexec("/usr/local/sbin/pftpx -f {$target} -b {$external_address} -c 21 -g 21"); } $dontinstallrdr = true; } } if($dontinstallrdr == false) { if ((!$extport[1]) || ($extport[0] == $extport[1])) { if($rule['protocol'] == "tcp/udp") $natrules .= "rdr on $natif proto { tcp udp } from any to {$extaddr} port { {$extport[0]} } -> {$target}{$localport}"; else if($extport[0]) $natrules .= "rdr on $natif proto {$rule['protocol']} from any to {$extaddr} port { {$extport[0]} } -> {$target}{$localport}"; else $natrules .= "rdr on $natif proto {$rule['protocol']} from any to {$extaddr} } -> {$target}{$localport}"; } else { if($rule['protocol'] == "tcp/udp") $natrules .= "rdr on $natif proto { tcp udp } from any to {$extaddr} port {$extport[0]}:{$extport[1]} -> {$target} port {$extport[0]}:*"; else $natrules .= "rdr on $natif proto {$rule['protocol']} from any to {$extaddr} port {$extport[0]}:{$extport[1]} -> {$target} port {$extport[0]}:*"; } } /* setup reflection rule for this item if requested * sponsored by Robin Greenhagen www.gsihosting.com */ if(!isset($config['system']['disablenatreflection'])) { $natrules .= "\n# Reflection redirects\n"; foreach ($iflist as $ifent => $ifname) { /* do not process interfaces with gateways*/ if($config['interfaces'][$ifname]['gateway'] <> "") continue; /* do not process interfaces that will end up with gateways */ if($config['interfaces'][$ifname]['ipaddr'] == "dhcp" or $config['interfaces'][$ifname]['ipaddr'] == "bigpond" or $config['interfaces'][$ifname]['ipaddr'] == "pppoe" or $config['interfaces'][$ifname]['ipaddr'] == "pptp") continue; $ifname_real = convert_friendly_interface_to_real_interface_name($ifname); if($extport[1]) $range_end = ($extport[1]); else $range_end = ($extport[0]); $range_end++; if($range_end - $extport[0] > 500) { $range_end = $extport[0]+1; log_error("Not installing nat reflection rules for a port range > 500"); } else { /* only install reflection rules for < 19991 items */ if($starting_localhost_port < 19991) { for($x=$extport[0]; $x<$range_end; $x++) { if($rule['protocol'] == "tcp/udp") { $protocol = "{ tcp udp }"; fwrite($fd, "{$starting_localhost_port}\tstream\ttcp/udp\tnowait\tnobody\t/usr/bin/nc nc -w 20 {$target} {$x}\n"); } else { $protocol = $rule['protocol']; fwrite($fd, "{$starting_localhost_port}\tstream\t{$protocol}\tnowait\tnobody\t/usr/bin/nc nc -w 20 {$target} {$x}\n"); } $natrules .= "rdr on {$ifname_real} proto {$protocol} from any to {$extaddr} port { {$x} } -> 127.0.0.1 port {$starting_localhost_port}\n"; $starting_localhost_port++; if($starting_localhost_port > 19990) { log_error("Not installing nat reflection rules. Maximum 1,000 reached."); $x = $range_end+1; } } } } } } $natrules .= "\n"; } if(!isset($config['system']['disablenatreflection'])) { fclose($fd); $helpers = trim(exec("/bin/ps ax | /usr/bin/grep inetd | /usr/bin/grep -v grep | /usr/bin/grep 127")); if(!$helpers) mwexec("/usr/sbin/inetd -a 127.0.0.1 /var/etc/inetd.conf"); else mwexec("/usr/bin/killall -HUP inetd"); } } if ($pptpdcfg['mode'] && $pptpdcfg['mode'] != "off") { if ($pptpdcfg['mode'] == "server") $pptpdtarget = "127.0.0.1"; else if ($pptpdcfg['mode'] == "redir") $pptpdtarget = $pptpdcfg['redir']; if ($pptpdcfg['mode'] == "redir") { $natrules .= << $pptpdtarget rdr on $wanif proto tcp from any to any port 1723 -> $pptpdtarget EOD; } } if (is_package_installed("squid") == 1) if(is_process_running("squid")) $natrules .= "rdr on {$lanif} inet proto tcp from any to !{$lanip} port www -> 127.0.0.1 port 3128\n"; $natrules .= process_carp_nat_rules(); return $natrules; } function run_command_return_string($cmd) { global $config; if(isset($config['system']['developerspew'])) { $mt = microtime(); echo "generate_user_filter_rule() being called $mt\n"; } $fd = popen($cmd, "r"); while(!feof($fd)) { $tmp .= fread($fd,49); } fclose($fd); return $tmp; } function generate_user_filter_rule_arr($rule, $ngcounter) { global $config; if(isset($config['system']['developerspew'])) { $mt = microtime(); echo "generate_user_filter_rule() being called $mt\n"; } $ret = array(); $line = generate_user_filter_rule($rule, $ngcounter); $ret['rule'] = $line; if($rule['descr'] != "" and $line != "") $ret['descr'] = "label \"USER_RULE: {$rule['descr']}\""; else $ret['descr'] = "label \"USER_RULE\""; $ret['ackq'] = get_ack_queue($rule['interface']); return $ret; } function generate_user_filter_rule($rule, $ngcounter) { global $config, $g; if(isset($config['system']['developerspew'])) { $mt = microtime(); echo "generate_user_filter_rule() being called $mt\n"; } $wancfg = $config['interfaces']['wan']; $lancfg = $config['interfaces']['lan']; $pptpdcfg = $config['pptpd']; $pppoecfg = $config['pppoe']; $lanif = $lancfg['if']; $wanif = get_real_wan_interface(); $lanip = $lancfg['ipaddr']; $lansa = gen_subnet($lancfg['ipaddr'], $lancfg['subnet']); $lansn = $lancfg['subnet']; $optcfg = array(); generate_optcfg_array($optcfg); $curwanip = get_current_wan_address(); /* don't include disabled rules */ if (isset($rule['disabled'])) { return "# rule " . $rule['descr'] . " disabled \n"; } $pptpdcfg = $config['pptpd']; $pppoecfg = $config['pppoe']; if ($pptpdcfg['mode'] == "server") { $pptpip = $pptpdcfg['localip']; $pptpsa = $pptpdcfg['remoteip']; $pptpsn = $g['pptp_subnet']; if($config['pptp']['pptp_subnet'] <> "") $pptpsn = $config['pptp']['pptp_subnet']; } if ($pppoecfg['mode'] == "server") { $pppoeip = $pppoecfg['localip']; $pppoesa = $pppoecfg['remoteip']; $pppoesn = $g['pppoe_subnet']; if($config['pppoe']['pppoe_subnet'] <> "") $pppoesn = $config['pppoe']['pppoe_subnet']; } /* does the rule deal with a PPTP interface? */ if ($rule['interface'] == "pptp") { if ($pptpdcfg['mode'] != "server") return ""; $nif = $g['n_pptp_units']; if($config['pptp']['n_pptp_units'] <> "") $nif = $config['pptp']['n_pptp_units']; $ispptp = true; } else if($rule['interface'] == "pppoe") { if ($pppoecfg['mode'] != "server") { return ""; } $nif = $g['n_pppoe_units']; if($config['pppoe']['n_pppoe_units'] <> "") $nif = $config['pppoe']['n_pppoe_units']; $ispppoe = true; } else { /* Check to see if the interface is opt and in our opt list */ if (strstr($rule['interface'], "opt")) { if (!array_key_exists($rule['interface'], $optcfg)) { $item = ""; foreach($optcfg as $oc) $item .= $oc['if']; return "# {$real_int} {$item} {$rule['interface']} array key does not exist for " . $rule['descr']; } } $nif = 1; $ispptp = false; $ispppoe = false; } if ($pptpdcfg['mode'] != "server") { if (($rule['source']['network'] == "pptp") || ($rule['destination']['network'] == "pptp")) { return "# source network or destination network == pptp on " . $rule['descr']; } } if ($rule['source']['network'] && strstr($rule['source']['network'], "opt")) { if (!array_key_exists($rule['source']['network'], $optcfg)) { return "# {$rule['source']['network']} !array_key_exists source network " . $rule['descr']; } } if ($rule['destination']['network'] && strstr($rule['destination']['network'], "opt")) { if (!array_key_exists($rule['destination']['network'], $optcfg)) { $item = ""; foreach($optcfg as $oc) $item .= $oc; return "# {$item} {$rule['destination']['network']} !array_key_exists dest network " . $rule['descr']; } } /* check for unresolvable aliases */ if ($rule['source']['address'] && !alias_expand($rule['source']['address'])) { return "# unresolvable source aliases {$rule['descr']}"; } if ($rule['destination']['address'] && !alias_expand($rule['destination']['address'])) { return "# unresolvable dest aliases {$rule['descr']}"; } $ifdescrs = array(); for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++) $ifdescrs[] = "opt" . $i; for ($iif = 0; $iif < $nif; $iif++) { $type = $rule['type']; if ($type != "pass" && $type != "block" && $type != "reject") { /* default (for older rules) is pass */ $type = "pass"; } if ($type == "reject") { /* special reject packet */ if ($rule['protocol'] == "tcp") { $line = "block return-rst"; } else if ($rule['protocol'] == "udp") { $line = "block return-icmp"; } else if ($rule['protocol'] == "tcp/udp") { $line = "block return"; } else { $line = "block"; } } else { $line = $type; } /* ensure the direction is in */ $line .= " in "; if (isset($rule['log'])) $line .= "log "; $line .= "quick "; if ($ispptp) { $line .= "on ng" . (intval($ngcounter)+1) . " "; } else if ($ispppoe) { $line .= "on ng" . (intval($ngcounter)+1) . " "; } else { // translate wan, man, lan, opt to real interface. $interface = $rule['interface']; $temp = filter_get_opt_interface_descr($interface); if($temp <> "") $interface = $temp; if(isset($rule['destination']['address'])) { $canadd = 0; // XXX: billm - eh? this is a nice little noop /* because pf will not allow a interface for proxyARP type traffic lets check if its in use and if so leave off the interface */ if(is_one_to_one_or_server_nat_rule($rule['destination']['address'])) $canadd = 0; } if($canadd == 0) $line .= "on \$" . $interface . " "; } /* set the gateway interface */ $ri = filter_translate_type_to_real_interface($rule['interface']); /* * check to see if /tmp/{${ri}_router exists. This file * is created by dhclient for 2nd wan interfaces, etc. * else get gateway from the interface config */ if(file_exists("{$g['tmp_path']}/{$ri}_router")) { $rg = file_get_contents("{$g['tmp_path']}/{$ri}_router"); $rg = rtrim($rg); } elseif ($config['interfaces'][$rule['interface']]['gateway'] <> "") { $rg = $config['interfaces'][$rule['interface']]['gateway']; } /* do not process reply-to for gateway'd rules */ if(($rule['gateway'] == "") and ($ri != "") and ($rg != "") and (stristr($rule['interface'],"opt") == true)) { $line .= "reply-to (" . $ri . " " . $rg . ") "; } /* if user has selected a custom gateway, lets work with it */ if($rule['gateway'] <> "") { $foundlb = 0; if(is_array($config['load_balancer']['lbpool'])) { foreach($config['load_balancer']['lbpool'] as $lb) { if($lb['name'] == $rule['gateway']) { $gateway = $rule['gateway']; /* * is $gateway a interface name? * if so, lets find out the gateway address * from /tmp/router_bleh.router */ if(in_array($gateway, $ifdescrs)==true) { if(is_file("{$g['tmp_path']}/{$gateway}_router")) { $return_gateway = file_get_contents("{$g['tmp_path']}/{$gateway}_router"); } else { log_error("Could not find {$g['tmp_path']}/{$gateway}_router. Needed for dhcp gateway information"); continue; } } $line .= " route-to { "; /* if /tmp/$lbname.pool exists then read in our gateway hints from slbd */ if(file_exists("{$g['tmp_path']}/{$lb['name']}.pool")) { $lbs = split("\n", file_get_contents("{$g['tmp_path']}/{$lb['name']}.pool")); } else { $lbs = $lb['servers']; } /* iterate through $lbs and setup items accordingly */ foreach($lbs as $server) { if($foundlb == 1) $line .= ", "; /* we are seperating the monitor address from the gateway * using the | character */ if(stristr($server, "|") == true) { $split_ip = split("\|", $server); $rule['gateway'] = $split_ip[0]; $gateway = $split_ip[0]; } /* determine interface from gateway address */ $int = guess_interface_from_ip($gateway); $line .= "( {$int} {$gateway} ) "; if($int == "") { $line = "# error resolving load balancing {$gateway}"; } $foundlb = 1; } $line .= "} round-robin "; } } } /* we're not using load balancing, just setup gateway */ if($foundlb == 0) { $gateway = $rule['gateway']; /* * is $gateway a interface name? * if so, lets find out the gateway address * from /tmp/router_bleh.router */ if(in_array($gateway, $ifdescrs)==true) { $int=filter_opt_interface_to_real($gateway); if(is_file("{$g['tmp_path']}/{$int}_router")) { $gatewayip = file_get_contents("{$g['tmp_path']}/{$int}_router"); $gatewayip = rtrim($gatewayip); $line .= " route-to ( {$int} {$gatewayip} ) "; } else { log_error("Could not find {$g['tmp_path']}/{$int}_router. Needed for dhcp gateway information"); continue; } } else { /* user picked a real gateway ip */ $gatewayip = $rule['gateway']; $int = guess_interface_from_ip($gatewayip); $line .= " route-to ( {$int} {$gatewayip} ) "; } } } if (isset($rule['protocol'])) { if($rule['protocol'] == "tcp/udp") $line .= "proto { tcp udp } "; elseif($rule['protocol'] == "icmp") $line .= "inet proto icmp "; else $line .= "proto {$rule['protocol']} "; } else { if($rule['source']['port'] <> "" || $rule['destination']['port'] <> "") { $line .= "proto tcp "; } } /* source address */ if (isset($rule['source']['any'])) { $src = "any"; } else if ($rule['source']['network']) { if (strstr($rule['source']['network'], "opt")) { $src = $optcfg[$rule['source']['network']]['sa'] . "/" . $optcfg[$rule['source']['network']]['sn']; if (isset($rule['source']['not'])) $src = " !{$src}"; } else { switch ($rule['source']['network']) { case 'wanip': $src = $curwanip; break; case 'lan': $src = "{$lansa}/{$lansn}"; break; case 'pptp': $src = "{$pptpsa}/{$pptpsn}"; break; case 'pppoe': $src = "{$pppoesa}/{$pppoesn}"; break; } if (isset($rule['source']['not'])) $src = "!{$src}"; } } else if ($rule['source']['address']) { $expsrc = alias_expand($rule['source']['address']); if (isset($rule['source']['not'])) $not = "!"; else $not = ""; if (stristr($expsrc, "$")) $src = "{ {$not} " . alias_expand_value($rule['source']['address']) . " } "; else $src = "{ {$not} {$expsrc} }"; } if (!$src || ($src == "/")) { return "# at the break!"; } $line .= "from $src "; if (in_array($rule['protocol'], array("tcp","udp","tcp/udp"))) { if ($rule['source']['port']) { $srcport = explode("-", $rule['source']['port']); if(alias_expand($srcport[0])) $srcporta = alias_expand($srcport[0]); else $srcporta = $srcport[0]; if ((!$srcport[1]) || ($srcport[0] == $srcport[1])) { if(alias_expand($srcport[0])) $line .= "port { {$srcporta} } "; else $line .= "port = {$srcporta} "; } else if (($srcport[0] == 1) && ($srcport[1] == 65535)) { /* no need for a port statement here */ } else if ($srcport[1] == 65535) { $line .= "port >= {$srcport[0]} "; } else if ($srcport[0] == 1) { $line .= "port <= {$srcport[1]} "; } else { $srcport[0]--; $srcport[1]++; $line .= "port {$srcport[0]} >< {$srcport[1]} "; } } /* OS signatures */ if (($rule['protocol'] == "tcp") && ($rule['os'] <> "")) $line .= "os {$rule['os']} "; } /* destination address */ if (isset($rule['destination']['any'])) { $dst = "any"; } else if ($rule['destination']['network']) { if (strstr($rule['destination']['network'], "opt")) { $dst = $optcfg[$rule['destination']['network']]['sa'] . "/" . $optcfg[$rule['destination']['network']]['sn']; if (isset($rule['destination']['not'])) $dst = " !{$dst}"; } else { switch ($rule['destination']['network']) { case 'wanip': $dst = $curwanip; break; case 'lan': $dst = "{$lansa}/{$lansn}"; break; case 'pptp': $dst = "{$pptpsa}/{$pptpsn}"; break; case 'pppoe': $dst = "{$ppoesa}/{$pppoesn}"; break; } if (isset($rule['destination']['not'])) $dst = " !{$dst}"; } } else if ($rule['destination']['address']) { $expdst = alias_expand($rule['destination']['address']); if (isset($rule['destination']['not'])) $not = "! "; else $not = ""; if (stristr($expdst, "$")) $dst = "{ {$not} " . alias_expand_value($rule['destination']['address']) . " } "; else $dst = "{ {$not} {$expdst} }"; } if (!$dst || ($dst == "/")) { return "# returning at $dst == \"/\""; break; } $line .= "to $dst "; if (in_array($rule['protocol'], array("tcp","udp","tcp/udp"))) { if ($rule['destination']['port']) { $dstport = explode("-", $rule['destination']['port']); if(alias_expand($dstport[0])) $dstporta = alias_expand($dstport[0]); else $dstporta = $dstport[0]; if ((!$dstport[1]) || ($dstport[0] == $dstport[1])) { if(alias_expand($dstport[0])) $line .= "port {$dstporta} "; else $line .= "port = {$dstporta} "; } else if (($dstport[0] == 1) && ($dstport[1] == 65535)) { /* no need for a port statement here */ } else if ($dstport[1] == 65535) { $line .= "port >= {$dstport[0]} "; } else if ($dstport[0] == 1) { $line .= "port <= {$dstport[1]} "; } else { $dstport[0]--; $dstport[1]++; $line .= "port {$dstport[0]} >< {$dstport[1]} "; } } } if (($rule['protocol'] == "icmp") && $rule['icmptype']) { $line .= "icmp-type {$rule['icmptype']} "; } if ($type == "pass") { if( isset($rule['source-track']) or isset($rule['max-src-nodes']) or isset($rule['max-src-states']) ) if($rule['protocol'] == "tcp") $line .= "flags S/SA "; /* # keep state works with TCP, UDP, and ICMP. # modulate state works only with TCP. pfSense will generate strong Initial Sequence Numbers (ISNs) for packets matching this rule. # synproxy state proxies incoming TCP connections to help protect servers from spoofed TCP SYN floods. This option includes the functionality of keep state and modulate state combined. # none do not use state mechanisms to keep track. this is only useful if your doing advanced queueing in certain situations. please check the faq. */ if(isset($rule['statetype']) && $rule['statetype'] <> "") { switch($rule['statetype']) { case "none": break; case "modulate state": case "synproxy state": if($rule['protocol'] == "tcp") $line .= "{$rule['statetype']} "; break; default: $line .= "{$rule['statetype']} "; } } else { $line .= "keep state "; } if( isset($rule['source-track']) and $rule['source-track'] <> "" or isset($rule['max-src-nodes']) and $rule['max-src-nodes'] <> "" 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['max-src-states']) and $rule['max-src-states'] <> "" ) { $line .= "( "; if(isset($rule['source-track']) and $rule['source-track'] <> "") $line .= "source-track rule "; if(isset($rule['max-src-nodes']) and $rule['max-src-nodes'] <> "") $line .= "max-src-nodes " . $rule['max-src-nodes'] . " "; if(isset($rule['max-src-states']) and $rule['max-src-states'] <> "") $line .= "max-src-states " . $rule['max-src-states'] . " "; if(isset($rule['statetimeout']) and $rule['statetimeout'] <> "") $line .= "tcp.established " . $rule['statetimeout'] . " "; if(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'] <> "") { $line .= "max-src-conn-rate " . $rule['max-src-conn-rate'] . " "; $line .= "/" . $rule['max-src-conn-rates'] . ", overload flush global "; } $line .= " ) "; } } if ($type == "reject" && $rule['protocol'] == "tcp") { /* special reject packet */ $line .= "flags S/SA "; } } return $line; } function filter_rules_generate() { global $config, $g; if(isset($config['system']['developerspew'])) { $mt = microtime(); echo "filter_rules_generate() being called $mt\n"; } $wancfg = $config['interfaces']['wan']; $lancfg = $config['interfaces']['lan']; $pptpdcfg = $config['pptpd']; $pppoecfg = $config['pppoe']; $lanif = $lancfg['if']; $wanif = get_real_wan_interface(); $lanip = $lancfg['ipaddr']; $lansa = gen_subnet($lancfg['ipaddr'], $lancfg['subnet']); $lansn = $lancfg['subnet']; if($lansa) $lansa_sn_combo = "{$lansa}/{$lansn}"; else $lansa_sn_combo = "192.168.1.1/32"; /* optional interfaces */ $optcfg = array(); generate_optcfg_array($optcfg); # BEGIN OF firewall rules $ipfrules="anchor \"firewallrules\"\n"; if ($pptpdcfg['mode'] == "server") { $pptpip = $pptpdcfg['localip']; $pptpsa = $pptpdcfg['remoteip']; $pptpsn = $g['pptp_subnet']; if($config['pptp']['pptp_subnet'] <> "") $pptpsn = $config['pptp']['pptp_subnet']; } if ($pppoecfg['mode'] == "server") { $pppoeip = $pppoecfg['localip']; $pppoesa = $pppoecfg['remoteip']; $pppoesn = $g['pppoe_subnet']; if($config['pppoe']['pppoe_subnet'] <> "") $pppoesn = $config['pppoe']['pppoe_subnet']; } /* default block logging? */ if (!isset($config['syslog']['nologdefaultblock'])) $log = "log"; else $log = ""; /* if squid is installed, lets install its rule */ if (is_package_installed("squid") == 1) { $ipfrules .= "pass in quick on {$lanif} inet proto tcp from any to 127.0.0.1 port 3128 flags S/SA keep state label \"transparent proxy\"\n"; $ipfrules .= "pass out quick on {$wanif} inet proto tcp from ($wanif) to any port www flags S/SA keep state label \"transparent proxy\"\n"; } $ipfrules .= << 49000 user proxy flags S/SA keep state label "FTP PROXY: PASV mode data connection" EOD; if(isset($config['system']['rfc959workaround'])) { $ipfrules .= << 49000 user proxy flags S/SA keep state label "FTP PROXY: RFC959 violation workaround" EOD; $optcfg = array(); generate_optcfg_array($optcfg); foreach($optcfg as $oc) { if($oc['gateway'] <> "") $ipfrules .= "pass in quick on {$oc['if']} inet proto tcp from any to ({$oc['if']}) port > 49000 user proxy flags S/SA keep state label \"FTP PROXY: RFC959 violation workaround\" \n"; } } } $ipfrules .= << $oc) { if (isset($config['dhcpd'][$on]['enable']) && (!$oc['bridge'])) { $ipfrules .= << "") $ipfrules .= "block in $log quick on $wanif from {$oc['sa']}/{$oc['sn']} to any label \"interface spoof check\"\n"; } /* allow PPTP traffic if PPTP client is enabled on WAN */ if ($wancfg['ipaddr'] == "pptp") { $ipfrules .= << "wan" and $config['interfaces']['wan']['bridge'] <> "lan") $ipfrules .= "block in $log quick on $wanif proto udp from any port = 67 to {$lansa_sn_combo} port = 68 label \"allow dhcp client out wan\"\n"; $ipfrules .= << $oc) { if ($oc['ip']) $ipfrules .= filter_rules_spoofcheck_generate($on, $oc['if'], $oc['sa'], $oc['sn'], $log); } /* block private networks on WAN? */ if (isset($config['interfaces']['wan']['blockpriv'])) { $ipfrules .= << EODF; /* block bogon networks on WAN */ /* http://www.cymru.com/Documents/bogon-bn-nonagg.txt */ /* file is automatically in cron every 3000 minutes */ if (isset($config['interfaces']['wan']['blockbogons'])) { $ipfrules .= << persist file "/etc/bogons" block in $log quick on $wanif from to any label "block bogon networks from wan" EOD; } $ipfrules .= << $oc) { $ipfrules .= << "") $nif = $config['pptp']['n_pptp_units']; for($xxx=0; $xxx < $n_pptp_units; $xxx++) { /* * now that PPTP server are user rules, detect * that user is setting the pptp server rule * and setup for all netgraph interfaces */ $rule_arr[] = generate_user_filter_rule_arr($rule, $xxx); } } else if($rule['interface'] == "pppoe") { $n_pppoe_units = $g['n_pppoe_units']; if($config['pppoe']['n_pppoe_units'] <> "") $nif = $config['pppoe']['n_pppoe_units']; for($xxx=0; $xxx < $n_pppoe_units; $xxx++) { /* * now that pppoe server are user rules, detect * that user is setting the pppoe server rule * and setup for all netgraph interfaces */ $rule_arr[] = generate_user_filter_rule_arr($rule, $xxx); } } else { $rule_arr[] = generate_user_filter_rule_arr($rule, 0); } } } /* This is ugly, but we generate one anchor per queue */ foreach ($config['shaper']['queue'] as $queue) { /* Add anchor to rules */ $ipfrules .= "anchor {$queue['name']} tagged {$queue['name']}\n"; /* Create rules for anchors */ $fd = fopen("{$g['tmp_path']}/{$queue['name']}.rules", "w"); /* aliases don't recurse to anchors */ $line = filter_generate_aliases(); fwrite($fd, $line); foreach($rule_arr as $rule) { if($rule['ackq'] != "") $line = "{$rule['rule'] } queue ({$queue['name']}, {$rule['ackq']}) {$rule['descr']}\n"; else $line = "{$rule['rule'] } queue {$queue['name']} {$rule['descr']}\n"; fwrite($fd, $line); } fclose($fd); } } if (isset($config['filter']['rule'])) { foreach ($config['filter']['rule'] as $rule) { $line = ""; if (!isset($rule['disabled'])) { if ($rule['interface'] == "pptp") { $n_pptp_units = $g['n_pptp_units']; if($config['pptp']['n_pptp_units'] <> "") $nif = $config['pptp']['n_pptp_units']; for($xxx=0; $xxx < $n_pptp_units; $xxx++) { /* * now that PPTP server are user rules, detect * that user is setting the pptp server rule * and setup for all netgraph interfaces */ $line = generate_user_filter_rule($rule, $xxx); if($line <> "") { if (isset($config['shaper']['enable']) && is_array($config['shaper']['queue'])) { $defq = find_default_queue($rule['interface']); $ackq = get_ack_queue($rule['interface']); if (($defq != "") and ($ackq != "")) $line .= " queue ({$defq}, {$ackq}) "; } $ipfrules .= $line . "\n"; } } } else if($rule['interface'] == "pppoe") { $n_pppoe_units = $g['n_pppoe_units']; if($config['pppoe']['n_pppoe_units'] <> "") $nif = $config['pppoe']['n_pppoe_units']; for($xxx=0; $xxx < $n_pppoe_units; $xxx++) { /* * now that pppoe server are user rules, detect * that user is setting the pppoe server rule * and setup for all netgraph interfaces */ $line = generate_user_filter_rule($rule, $xxx); if($line <> "") { if (isset($config['shaper']['enable']) && is_array($config['shaper']['queue'])) { $defq = find_default_queue($rule['interface']); $ackq = get_ack_queue($rule['interface']); if (($defq != "") and ($ackq != "")) $line .= " queue ({$defq}, {$ackq}) "; } $ipfrules .= $line . "\n"; } else { $ipfrules .= "# Error creating {$rule['descr']} \n"; } } } else { $line = generate_user_filter_rule($rule, 0); if($line <> "") if (isset($config['shaper']['enable']) && is_array($config['shaper']['queue'])) { $defq = find_default_queue($rule['interface']); $ackq = get_ack_queue($rule['interface']); if (($defq != "") and ($ackq != "")) $line .= " queue ({$defq}, {$ackq}) "; } // label if($rule['descr'] <> "" and $line <> "") $line .= " label \"USER_RULE: {$rule['descr']}\" "; else $line .= " label \"USER_RULE\" "; } } $line .= "\n"; $ipfrules .= $line; } } $ipfrules .= process_carp_rules(); $ipfrules .= "\n# VPN Rules\n"; $lan_ip = $config['interfaces']['lan']['ipaddr']; $lan_subnet = $config['interfaces']['lan']['subnet']; $wanif = get_real_wan_interface(); $wan_ip = find_interface_ip($wanif); $internal_subnet = gen_subnet($lan_ip, $lan_subnet) . "/" . $config['interfaces']['lan']['subnet']; /* Is IP Compression enabled? */ if(isset($config['ipsec']['ipcomp'])) exec("/sbin/sysctl net.inet.ipcomp.ipcomp_enable=1"); else exec("/sbin/sysctl net.inet.ipcomp.ipcomp_enable=0"); /* determine ipsec address */ $ipsec_ip = $wan_ip; /* set failover ip if defined */ if(isset($config['installedpackages']['sasyncd']['config'])) foreach($config['installedpackages']['sasyncd']['config'] as $sasyncd) { if($sasyncd['ip'] <> "") $ipsec_ip = $sasyncd['ip']; } if(is_array($config['ipsec']['tunnel']) && isset($config['ipsec']['enable'])) { foreach ($config['ipsec']['tunnel'] as $tunnel) { /* if tunnel is disabled, lets skip to next item */ if(isset($tunnel['disabled'])) continue; /* is this a dynamic dns hostname? */ $remote_gateway = gethostbyname($tunnel['remote-gateway']); if($remote_gateway == "") $remote_gateway = $tunnel['remote-gateway']; /* do not add items with blank remote_gateway */ if(!$remote_gateway) { $ipfrules .= "# ERROR! Remote gateway not found on ... pass quick on {$wanif} proto udp from {$ipsec_ip} to {$remote_gateway} port = 500 keep state label \"IPSEC: {$tunnel['descr']} udp\"\n"; continue; } $local_subnet = return_vpn_subnet($tunnel['local-subnet']); $ipfrules .= "pass out quick on {$wanif} proto udp from {$ipsec_ip} to {$remote_gateway} port = 500 keep state label \"IPSEC: {$tunnel['descr']} - outbound isakmp\"\n"; $ipfrules .= "pass in quick on {$wanif} proto udp from {$remote_gateway} to {$ipsec_ip} port = 500 keep state label \"IPSEC: {$tunnel['descr']} - inbound isakmp\"\n"; $ipfrules .= "pass out quick on {$wanif} proto esp from {$ipsec_ip} to {$remote_gateway} keep state label \"IPSEC: {$tunnel['descr']} - outbound esp proto\"\n"; $ipfrules .= "pass in quick on {$wanif} proto esp from {$remote_gateway} to {$ipsec_ip} keep state label \"IPSEC: {$tunnel['descr']} - inbound esp proto\"\n"; $ipfrules .= "pass out quick on {$wanif} proto ah from {$ipsec_ip} to {$remote_gateway} keep state label \"IPSEC: {$tunnel['descr']} - outbound ah proto\"\n"; $ipfrules .= "pass in quick on {$wanif} proto ah from {$remote_gateway} to {$ipsec_ip} keep state label \"IPSEC: {$tunnel['descr']} - inbound ah proto\"\n"; //$ipfrules .= "pass out quick on {$lanif} from {$tunnel['remote-subnet']} to {$local_subnet} keep state label \"IPSEC: {$tunnel['descr']} - remote to local\"\n"; //$ipfrules .= "pass in quick on {$lanif} from {$local_subnet} to {$tunnel['remote-subnet']} keep state label \"IPSEC: {$tunnel['descr']} - local to remote\"\n"; } } /* is mobile ipsec enabled? if so lets allow some pretty * loose rules to allow mobile clients to phone in. */ $ipseccfg = $config['ipsec']; if (isset($ipseccfg['mobileclients']['enable'])) { $ipfrules .= "pass in quick on {$wanif} proto udp from any to any port = 500 keep state label \"IPSEC: Mobile - inbound isakmp\"\n"; $ipfrules .= "pass in quick on {$wanif} proto esp from any to any keep state label \"IPSEC: Mobile - inbound esp proto\"\n"; $ipfrules .= "pass in quick on {$wanif} proto ah from any to any keep state label \"IPSEC: Mobile - inbound ah proto\"\n"; } $ipfrules .= << $ifname) { /* do not work with tun interfaces */ if(stristr(filter_translate_type_to_real_interface($ifname), "tun") == true) continue; $int = filter_translate_type_to_real_interface($ifname); $rules .= "set loginterface {$int}\n"; } return $rules; } function create_firewall_outgoing_rules_to_itself() { global $config, $g; if(isset($config['system']['developerspew'])) { $mt = microtime(); echo "create_firewall_outgoing_rules_to_itself() being called $mt\n"; } $i = 0; $rule .= "# pass traffic from firewall -> out\n"; $rule .= "anchor \"firewallout\"\n"; $ifdescrs = array('wan', 'lan'); for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) $ifdescrs['opt' . $j] = "opt" . $j; /* go through primary and optional interfaces */ foreach ($ifdescrs as $ifdescr => $ifname) { $return_gateway = $config['interfaces'][$ifname]['gateway']; $ints = array(); $int = filter_translate_type_to_real_interface($ifname); /* if the interface is pppoe, set the ng0 interface */ $ip = find_interface_ip($int); if ($config['interfaces'][$ifname]['ipaddr'] == "pppoe") $int = " { " . filter_translate_type_to_real_interface($ifname) . " ng0 } "; if (isset($config['shaper']['enable']) && is_array($config['shaper']['queue'])) { $ackq = get_ack_queue($ifname); $defq = find_default_queue($ifname); /* Handle all tagged packets */ foreach ($config['shaper']['queue'] as $queue) { if ($ackq == "" || $defq == "") { /* Shaper must not be enabled on this interface */ $q = ""; } else { $q = "queue ({$queue['name']}, {$ackq})"; } $rule .="pass out quick on {$int} all keep state tagged {$queue['name']} {$q} label \"let out anything from firewall host itself\"\n"; } /* Handle untagged packets */ if ($ackq == "" || $defq == "") { /* Shaper must not be enabled on this interface */ $q = ""; } else { $q = "queue ({$defq}, {$ackq})"; } $rule .="pass out quick on {$int} all keep state {$q} label \"let out anything from firewall host itself\"\n"; } else { /* first add a rule for the real interface, then for ng0 */ $rule .="pass out quick on {$int} all keep state label \"let out anything from firewall host itself\"\n"; } } /* is bridging turned on? */ for($x=0; $x<10; $x++) { if(does_interface_exist("bridge{$x}") == true) $rule .="pass out quick on bridge{$x} all keep state label \"let out anything from firewall host itself\"\n"; } /* netgraph pptp outgoing */ $n_pptp_units = $g['n_pptp_units']; if($config['pptp']['n_pptp_units'] <> "") $n_pptp_units = $config['pptp']['n_pptp_units']; for($x=0; $x<$n_pptp_units; $x++) { if(does_interface_exist("ng{$x}") == true) $rule .="pass out quick on ng{$x} all keep state label \"let out anything from firewall host itself pptp\"\n"; } /* netgraph pppoe outgoing */ $n_pppoe_units = $g['n_pppoe_units']; if($config['pppoe']['n_pppoe_units'] <> "") $n_pppoe_units = $config['pppoe']['n_pppoe_units']; for($x=0; $x<$n_pppoe_units; $x++) { if(does_interface_exist("ng{$x}") == true) $rule .="pass out quick on ng{$x} all keep state label \"let out anything from firewall host itself pppoe\"\n"; } /* setup outgoing gif tunnels */ $number_of_gifs = find_last_gif_device(); $number_of_gifs++; for($x=0; $x<$number_of_gifs; $x++) { if(does_interface_exist("gif{$x}") == true) $rule .="pass out quick on gif{$x} all keep state label \"let out anything from firewall host itself ipsec gif\"\n"; } return $rule; } function process_carp_nat_rules() { global $g, $config; if(isset($config['system']['developerspew'])) { $mt = microtime(); echo "process_carp_nat_rules() being called $mt\n"; } $lines = ""; if($config['installedpackages']['carp']['config'] != "") foreach($config['installedpackages']['carp']['config'] as $carp) { $ip = $carp['ipaddress']; if($ip <> "any") { $ipnet = "any"; } else { $int = find_ip_interface($ip); $carp_int = find_carp_interface($ip); } if($int != false and $int != $wan_interface) { $ipnet = convert_ip_to_network_format($ip, $carp['netmask']); $lines .= "nat on {$int} inet from {$ipnet} to any -> ({$carp_int}) \n"; } } return $lines; } function process_carp_rules() { global $g, $config; if(isset($config['system']['developerspew'])) { $mt = microtime(); echo "process_carp_rules() being called $mt\n"; } $lines = ""; /* return if there are no carp configured items */ if($config['installedpackages']['carpsettings']['config'] <> "" or $config['virtualip']['vip'] <> "") { $lines .= "pass quick proto carp keep state\n"; $lines .= "pass quick proto pfsync"; } return $lines; } function carp_sync_xml($url, $password, $sections, $port = 80, $method = 'pfsense.restore_config_section') { global $config, $g; if($g['booting']) return; foreach($sections as $section) { /* we can't use array_intersect_key() due to the vip 'special case' */ if($section != 'virtualip') { $xml[$section] = $config[$section]; } else { $xml[$section] = backup_vip_config_section(); } } $params = array( XML_RPC_encode($password), XML_RPC_encode($xml) ); log_error("Beginning XMLRPC sync to {$url}:{$port}."); $msg = new XML_RPC_Message($method, $params); $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); $cli->setCredentials('admin', $password); if($g['debug']) $cli->setDebug(1); /* send our XMLRPC message and timeout after 240 seconds */ $resp = $cli->send($msg, "240"); if(!$resp) { $error = "A communications error occured while attempting XMLRPC sync with {$url}:{$port}."; log_error($error); file_notice("sync_settings", $error, "Settings Sync", ""); } elseif($resp->faultCode()) { $error = "An error code was received while attempting XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("sync_settings", $error, "Settings Sync", ""); } else { log_error("XMLRPC sync successfully completed with {$url}:{$port}."); } } function carp_sync_client() { global $config, $g; if($g['booting']) return; if(is_array($config['installedpackages']['carpsettings']['config'])) { foreach($config['installedpackages']['carpsettings']['config'] as $carp) { if($carp['synchronizetoip'] != "" ) { /* * XXX: The way we're finding the port right now is really suboptimal - * we can't assume that the other machine is setup identically. */ if($config['system']['webgui']['protocol'] != "") { $synchronizetoip = $config['system']['webgui']['protocol']; $synchronizetoip .= "://"; } $port = $config['system']['webgui']['port']; /* if port is empty lets rely on the protocol selection */ if($port == "") { if($config['system']['webgui']['protocol'] == "http") { $port = "80"; } else { $port = "443"; } } $synchronizetoip .= $carp['synchronizetoip']; if($carp['synchronizerules'] != "" and is_array($config['filter'])) { $sections[] = 'filter'; } if($carp['synchronizenat'] != "" and is_array($config['nat'])) { $sections[] = 'nat'; } if($carp['synchronizealiases'] != "" and is_array($config['aliases'])) { $sections[] = 'aliases'; } if($carp['synchronizedhcpd'] != "" and is_array($config['dhcpd'])) { $sections[] = 'dhcpd'; } if($carp['synchronizewol'] != "" and is_array($config['wol'])) { $sections[] = 'wol'; } if($carp['synchronizetrafficshaper'] != "" and is_array($config['shaper'])) { $sections[] = 'shaper'; } if($carp['synchronizestaticroutes'] != "" and is_array($config['staticroutes'])) { $sections[] = 'staticroutes'; } if($carp['synchronizevirtualip'] != "" and is_array($config['virtualip'])) { $sections[] = 'virtualip'; } if($carp['synchronizelb'] != "" and is_array($config['load_balancer'])) { $sections[] = 'load_balancer'; } if($carp['synchronizeipsec'] != "" and is_array($config['ipsec'])) { $sections[] = 'ipsec'; } if(count($sections) > 0) { carp_sync_xml($synchronizetoip, $carp['password'], $sections, $port); $cli = new XML_RPC_Client('/xmlrpc.php', $synchronizetoip, $port); $msg = new XML_RPC_Message('pfsense.filter_configure', array(new XML_RPC_Value($carp['password'], 'string'))); $cli->setCredentials('admin', $carp['password']); $cli->send($msg, "900"); /* signal a carp reload */ $msg = new XML_RPC_Message('pfsense.interfaces_carp_configure', array(new XML_RPC_Value($carp['password'], 'string'))); $cli->send($msg, "900"); } } } } } function return_vpn_subnet($adr) { global $config; if(isset($config['system']['developerspew'])) { $mt = microtime(); echo "return_vpn_subnet() being called $mt\n"; } if ($adr['address']) { list($padr, $pmask) = explode("/", $adr['address']); if (is_null($pmask)) return "{$padr}/32"; return "{$padr}/{$pmask}"; } /* XXX: do not return wan, lan, etc */ if(strstr($adr['network'], "wan") or strstr($adr['network'], "lan") or strstr($adr['network'], "opt")) return convert_ip_to_network_format($config['interfaces'][$adr['network']]['ipaddr'], $config['interfaces'][$adr['network']]['subnet']); /* fallback - error */ return " # error - {$adr['network']} "; } ?>