. 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"); function filter_resync() { global $config, $g; mwexec("/sbin/pfctl -y"); /* XXX */ } function filter_pflog_start() { global $config, $g; mwexec("ifconfig pflog0 up && pflogd -sD"); } function filter_configure() { global $config, $g; $lan_if = $config['interfaces']['lan']['if']; $wan_if = get_real_wan_interface(); if(does_interface_exist($lan_if) == false) return; if(does_interface_exist($wan_if) == false) return; if ($g['booting']) echo "Configuring firewall... "; /* generate aliases */ $aliases = filter_generate_aliases(); /* generate nat rules */ $natrules = filter_nat_rules_generate(); /* generate pfctl rules */ $pfrules = filter_rules_generate(); if(isset($config['shaper']['enable'])) { /* generate altq interface setup parms */ $altq_ints = filter_setup_altq_interfaces(); /* generate altq queues */ $altq_queues = filter_generate_altq_queues($altq_ints); /* generate altq rules */ $altq_rules = filter_generate_altq_rules(); } if (isset($config['nat']['outgoingloadbalancing']['enable'])) /* generate altq rules */ $lb_rules = filter_generate_lb_rules(); if( !isset( $config['system']['disablefilter'] ) ) { mwexec("/sbin/pfctl -e"); mwexec("/sbin/pfctl -F nat"); mwexec("/sbin/pfctl -F rules"); } 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_integer($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(); $optimization = "normal"; if($config['system']['optimization'] <> "") $optimization = $config['system']['optimization']; $rules.= "set optimization " . $optimization . "\n"; if($config['system']['maximumstates'] <> "" && is_numeric($config['system']['maximumstates'])) { /* User defined maximum states in Advanced menu. */ $maximumstates = $config['system']['maximumstates']; $rules.= "set limit states " . $maximumstates . "\n"; } $rules.= "\nscrub all " . $mssclamp ."\n"; // reassemble all directions $rules.= $altq_ints . "\n"; $rules.= $altq_queues . "\n"; $rules.= $natrules . "\n"; $rules.= $pfrules . "\n"; fwrite($fd, $rules); fclose($fd); $rules_loading = mwexec("/sbin/pfctl -f {$g['tmp_path']}/rules.debug"); /* load ipfw+altq module */ if (isset($config['shaper']['enable']) || isset($config['nat']['outgoingloadbalancing']['enable'])) { mwexec("/sbin/kldload ipfw"); /* change one_pass to 1 so ipfw stops checking after a rule has matched */ mwexec("/sbin/sysctl net.inet.ip.fw.one_pass=1"); /* load shaper rules */ if (isset($config['shaper']['enable'])) { mwexec("/sbin/ipfw -f delete set 4"); /* XXX - seems like ipfw cannot accept rules directly on stdin, so we have to write them to a temporary file first */ $fd = fopen("{$g['tmp_path']}/ipfw.rules", "w"); if (!$fd) { printf("Cannot open ipfw.rules in filter_configure()\n"); return 1; } fwrite($fd, $altq_rules); fclose($fd); mwexec("/sbin/ipfw {$g['tmp_path']}/ipfw.rules"); mwexec("/sbin/ipfw enable altq"); mwexec("/bin/mv {$g['tmp_path']}/ipfw.rules {$g['tmp_path']}/ipfw.rules_old"); } /*load lb rules */ if (isset($config['nat']['outgoingloadbalancing']['enable'])) { mwexec("/sbin/ipfw -f delete set 5"); /* this uses ~32MB for session states */ mwexec("/sbin/sysctl net.inet.ip.fw.dyn_max=65536"); mwexec("/sbin/sysctl net.inet.ip.fw.dyn_buckets=32768"); /* XXX - seems like ipfw cannot accept rules directly on stdin, so we have to write them to a temporary file first */ $fd = fopen("{$g['tmp_path']}/ipfw_lb.rules", "w"); if (!$fd) { printf("Cannot open ipfw.rules in filter_configure()\n"); return 1; } fwrite($fd, $lb_rules); fclose($fd); mwexec("/sbin/ipfw {$g['tmp_path']}/ipfw_lb.rules"); mwexec("/bin/mv {$g['tmp_path']}/ipfw_lb.rules {$g['tmp_path']}/ipfw_lb.rules_old"); } } else { mwexec("/sbin/ipfw -f flush"); if(!isset($config['captiveportal']['enable'])) mwexec("/sbin/kldunload ipfw.ko"); } 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 /tmp/rules.debug`; $line_split = split("\n", $rules_file); if(is_array($line_split)) $line_error = "The line in question reads: " . $line_split[$line_number]; return "There was an error loading the rules.
" . $rules_error . "\n" . $line_error . ""; } else { /* process packager manager custom rules */ $files = return_dir_as_array("/usr/local/pkg/pf/"); if($files <> "") { foreach ($files as $file) { if($file <> "") { $text = return_filename_as_string("/usr/local/pkg/pf/" . $file); if($text != "") eval($text); } } } if ($g['booting']) echo "done\n"; return 0; } } function filter_get_altq_queue_scheduler_type($associatedrule) { global $config; return $config['system']['schedulertype']; } function filter_get_rule_interface($associatedrulenumber) { global $config; foreach ($config['shaper']['rule'] as $rule) { if($rule['descr'] == $associatedrule) return $rule['interface']; } return $config['shaper']['rule'][$associatedrulenumber]['interface']; } function filter_generate_altq_queues($altq_ints) { global $config; $altq_rules = ""; if (is_array($config['shaper']['queue'])) { foreach ($config['shaper']['queue'] as $rule) { $options = ""; // check to make sure we're actually using this queue. if(stristr($altq_ints, $rule['name']) !== FALSE) { $altq_rules .= "queue " . $rule['name'] . " "; if (isset($rule['bandwidth']) and $rule['bandwidth'] <> "") $altq_rules .= "bandwidth " . $rule['bandwidth'] . $rule['bandwidthtype'] . " "; if (isset($rule['priority']) and $rule['priority'] <> "") $altq_rules .= "priority " . $rule['priority'] . " "; if(isset($rule['red']) and $rule['red'] <> "") $options .= " red"; if(isset($rule['borrow']) and $rule['borrow'] <> "") $options .= " borrow"; if(isset($rule['ecn']) and $rule['ecn'] <> "") $options .= " ecn"; if(isset($rule['rio']) and $rule['rio'] <> "") $options .= " rio"; if(isset($rule['defaultqueue']) and $rule['defaultqueue'] <> "") $options .= " default"; if(isset($rule['upperlimit']) and $rule['upperlimit'] <> "") { $options .= " upperlimit(" . $rule['upperlimit1'] . " " . $rule['upperlimit2'] . " " . $rule['upperlimit3'] . ")"; } if(isset($rule['linkshare']) and $rule['linkshare'] <> "") { $options .= " linkshare(" . $rule['linkshare1'] . " " . $rule['linkshare2'] . " " . $rule['linkshare3'] . ")"; } if(isset($rule['realtime']) and $rule['realtime'] <> "") { $options .= " realtime(" . $rule['realtime1'] . " " . $rule['realtime2'] . " " . $rule['realtime3'] . ")"; } $scheduler_type = $config['system']['schedulertype']; $altq_rules .= $scheduler_type . " "; if($options) $altq_rules .= "(". $options . " )"; if (isset($rule['subqueue'])) { $altq_rules .= "{ "; $fsq = ""; foreach ($rule['subqueue'] as $sq) { if($fsq) $altq_rules .= ","; $altq_rules .= $sq['name']; $fsq = "1"; } $altq_rules .= " }"; } $altq_rules .= "\n"; } } } return $altq_rules; } function filter_translate_type_to_real_interface($interface) { global $config; return $config['interfaces'][$interface]['if']; } function filter_get_rule_real_interface($associatedrulenumber) { global $config; $x=0; foreach($config['shaper']['rule'] as $rule) { if($x == $associatedrulenumber) return $rule['interface']; $x++; } } function filter_is_queue_being_used_on_interface($queuename, $interface) { global $config; if(!is_array($config['shaper']['rule'])) return; foreach($config['shaper']['rule'] as $rule) { if($rule['targetqueue'] == $queuename && $rule['interface'] == $interface) return $interface; } return; } function filter_setup_altq_interfaces() { global $config; $altq_rules = ""; $queue_names = ""; $is_first = ""; if(!is_array($config['shaper']['queue'])) return; $i = 0; $ifdescrs = array('wan', 'lan'); for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) { $ifdescrs['opt' . $j] = "opt" . $j; } foreach ($ifdescrs as $ifdescr => $ifname) { $queue_names = ""; $is_first = ""; $workting_with_interface = $ifname; foreach ($config['shaper']['queue'] as $queue) { $rule_interface = filter_is_queue_being_used_on_interface($queue['name'], $workting_with_interface); if ($rule_interface == $workting_with_interface) { if(is_subqueue($queue['name']) == 0) { if($is_first) $queue_names .= ", "; $queue_names .= $queue['name']; $is_first = "1"; } } } $subnet = $ifname['ipaddr'] . "/" . $config['interfaces'][$ifname]['subnet']; if($queue_names <> ""){ $altq_rules .= "altq on " . $config['interfaces'][$ifname]['if'] . " "; if($config['interfaces'][$ifname]['bandwidth'] <> "") $bandwidth = " bandwidth " . $config['interfaces'][$ifname]['bandwidth'] . $config['interfaces'][$ifname]['bandwidthtype']; $altq_rules .= $config['system']['schedulertype'] . $bandwidth . " "; $altq_rules .= "queue { " . $queue_names . " }"; } $altq_rules .= "\n"; } return $altq_rules; } function is_subqueue($name) { global $config; $status = ""; if (is_array($config['shaper']['queue'])) { foreach ($config['shaper']['queue'] as $queue) { if(is_array($queue['subqueue'])) { foreach ($queue['subqueue'] as $sq) { if($sq['name'] == $name) return 1; } } } } return 0; } function filter_generate_aliases() { global $config; $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 = \"{ }\"\n"; $ifdescrs = array(); for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) { $ifdescrs['opt' . $j] = "opt" . $j; } foreach ($ifdescrs as $ifdescr => $ifname) { $aliases .= filter_get_opt_interface_descr($ifname) . " = \"{ " . filter_opt_interface_to_real($ifname) . " }\"\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 filter_generate_lb_rules() { global $config, $g; $wancfg = $config['interfaces']['wan']; $lancfg = $config['interfaces']['lan']; $lanif = $lancfg['if']; $wanif = get_real_wan_interface(); $lanip = $lancfg['ipaddr']; $lansa = gen_subnet($lancfg['ipaddr'], $lancfg['subnet']); $lansn = $lancfg['subnet']; $ruleconf = &$config['nat']['outgoingloadbalancing']['rule']; /* Lets turn away some rule writting */ $out_flow = ' ip from '.$lancfg['ipaddr'].'/'.$lancfg['subnet'].' to not '. $lancfg['ipaddr'].'/'.$lancfg['subnet']; $in_flow = 'ip from not '.$lancfg['ipaddr'].'/'.$lancfg['subnet'].' to '.$lancfg['ipaddr'].'/'.$lancfg['subnet']; /* LB Rules Return Script */ $lbrules = ""; // print_r($ruleconf); /* generate rules */ if (isset($ruleconf)) { $i = 0; $gatenum = count($ruleconf); reset($ruleconf); foreach ($ruleconf as $rule) { $gwmac = arp_get_mac_by_ip($rule['gatewayip']); print_r($rule); print_r($gwmac); /* don't include disabled rules and non reachable gateways*/ if (($rule['enabled']===0) || ($gwmac===false)) { $i++; continue; } $rulelines = ""; $in_num = 10000 + $i; $out_num = 11000 + $i; $skipto_num = 50000 + $i*10; /* Compute denominator of probability value (consist of enabled|reachable gateways) */ $denom[$i] = 0; for($j=$i;$j<$gatenum;$j++) if (($ruleconf[$j]['enabled']==1) && (arp_get_mac_by_ip($ruleconf[$j]['gatewayip'])!==false)) $denom[$i]++; $prob = round(1/$denom[$i],2); $rulelines .= "add $in_num set 5 skipto $skipto_num $in_flow mac any $gwmac in recv $wanif keep-state\n"; $rulelines .= "add $out_num set 5 prob $prob skipto $skipto_num $out_flow in recv $lanif keep-state\n"; $rulelines .= "add $skipto_num set 5 fwd ".$rule['gatewayip']." $out_flow in recv $lanif\n"; $skipto_num++; $rulelines .= "add $skipto_num set 5 skipto 65535 ip from any to any\n"; $lbrules .=$rulelines; $i++; } // foreach } // if return $lbrules; } function filter_generate_altq_rules() { global $config, $g; $wancfg = $config['interfaces']['wan']; $lancfg = $config['interfaces']['lan']; $pptpdcfg = $config['pptpd']; $lanif = $lancfg['if']; $wanif = get_real_wan_interface(); $lanip = $lancfg['ipaddr']; $lansa = gen_subnet($lancfg['ipaddr'], $lancfg['subnet']); $lansn = $lancfg['subnet']; /* optional interfaces */ $optcfg = array(); for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++) { $oc = $config['interfaces']['opt' . $i]; if (isset($oc['enable']) && $oc['if']) { $oic = array(); $oic['ip'] = $oc['ipaddr']; $oic['if'] = $oc['if']; $oic['sa'] = gen_subnet($oc['ipaddr'], $oc['subnet']); $oic['sn'] = $oc['subnet']; $optcfg['opt' . $i] = $oic; } } if ($pptpdcfg['mode'] == "server") { $pptpip = $pptpdcfg['localip']; $pptpsa = $pptpdcfg['remoteip']; $pptpsn = $g['pptp_subnet']; } $rulei = 1000; /* add a rule to pass all traffic from/to the firewall, so the user cannot lock himself out of the webGUI */ $shaperrules = "add $rulei set 4 pass all from $lanip to any\n"; $rulei++; $shaperrules .= "add $rulei set 4 pass all from any to $lanip\n"; $rulei++; /* generate rules */ if (isset($config['shaper']['rule'])) foreach ($config['shaper']['rule'] as $rule) { /* don't include disabled rules */ if (isset($rule['disabled'])) { $i++; continue; } /* does the rule deal with a PPTP interface? */ if ($rule['interface'] == "pptp") { if ($pptpdcfg['mode'] != "server") { $i++; continue; } $nif = $g['n_pptp_units']; $ispptp = true; } else { if (strstr($rule['interface'], "opt")) { if (!array_key_exists($rule['interface'], $optcfg)) { $i++; continue; } } $nif = 1; $ispptp = false; } if ($pptpdcfg['mode'] != "server") { if (($rule['source']['network'] == "pptp") || ($rule['destination']['network'] == "pptp")) { $i++; continue; } } if (strstr($rule['source']['network'], "opt")) { if (!array_key_exists($rule['source']['network'], $optcfg)) { $i++; continue; } } if (strstr($rule['destination']['network'], "opt")) { if (!array_key_exists($rule['destination']['network'], $optcfg)) { $i++; continue; } } /* check for unresolvable aliases */ if ($rule['source']['address'] && !alias_expand($rule['source']['address'])) { $i++; continue; } if ($rule['destination']['address'] && !alias_expand($rule['destination']['address'])) { $i++; continue; } for ($iif = 0; $iif < $nif; $iif++) { $queuename = filter_altq_get_queuename($rule['targetqueue']); $line = "add $rulei set 4 pass altq " . $rule['targetqueue'] . " "; $rulei++; if (isset($rule['protocol'])) { $line .= "{$rule['protocol']} "; } else { $line .= "all "; } /* 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']; } else { switch ($rule['source']['network']) { case 'lan': $src = "$lansa/$lansn"; break; case 'pptp': $src = "$pptpsa/$pptpsn"; break; } } } else if ($rule['source']['address']) { $src = $rule['source']['address']; } if (!$src) { printf("No source address found in rule $i\n"); break; } if (isset($rule['source']['not'])) { $line .= "from not $src "; } else { $line .= "from $src "; } if (!isset($rule['protocol']) || in_array($rule['protocol'], array("tcp","udp"))) { if ($rule['source']['port']) { /* * Check to see if port is a alias. If so grab it and * enclose it in { } to pass to pf. * * Otherwise combine the portrange into one if its only * one item. */ $src = alias_expand($rule['source']['port']); if($src <> "") { $line .= $rule['destination']['port']; } else { $srcport = explode("-", $rule['source']['port']); if ((!$srcport[1]) || ($srcport[0] == $srcport[1])) { $line .= "{$srcport[0]} "; } else { $line .= "{$srcport[0]}-{$srcport[1]} "; } } } } /* 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']; } else { switch ($rule['destination']['network']) { case 'lan': $dst = "$lansa/$lansn"; break; case 'pptp': $dst = "$pptpsa/$pptpsn"; break; } } } else if ($rule['destination']['address']) { $dst = $rule['destination']['address']; } if (!$dst) { printf("No destination address found in rule $i\n"); break; } if (isset($rule['destination']['not'])) { $line .= "to not $dst "; } else { $line .= "to $dst "; } if (!isset($rule['protocol']) || in_array($rule['protocol'], array("tcp","udp"))) { if ($rule['destination']['port']) { $dst = alias_expand($rule['destination']['port']); /* * Check to see if port is a alias. If so grab it and * enclose it in { } to pass to pf. * * Otherwise combine the portrange into one if its only * one item. */ if($dst <> "") { $line .= $rule['destination']['port']; } else { $dstport = explode("-", $rule['destination']['port']); if ((!$dstport[1]) || ($dstport[0] == $dstport[1])) { $line .= "{$dstport[0]} "; } else { $line .= "{$dstport[0]}-{$dstport[1]} "; } } } } if ($rule['iplen']) $line .= "iplen {$rule['iplen']} "; if ($rule['iptos']) $line .= "iptos {$rule['iptos']} "; if ($rule['tcpflags']) $line .= "tcpflags {$rule['tcpflags']} "; if ($rule['direction'] == "in") $line .= "in "; else if ($rule['direction'] == "out") $line .= "out "; if ($ispptp) { $line .= "via ng" . ($iif+1); } else { if ($rule['interface'] == "wan") $if = $wanif; else $if = $config['interfaces'][$rule['interface']]['if']; $line .= "via {$if}"; } $line .= "\n"; $shaperrules .= $line; } $i++; } $rulei++; //$shaperrules .= $line; return $shaperrules; } function filter_altq_get_queuename($queuenum) { global $config; $x=0; foreach($config['shaper']['queue'] as $rule) { if($x == $queuenum) return $rule['name']; $x++; } } function filter_flush_nat_table() { global $config, $g; return mwexec("/sbin/pfctl -F nat"); } function filter_flush_state_table() { global $config, $g; return mwexec("/sbin/pfctl -F state"); } function filter_nat_rules_generate_if($if, $src, $srcport, $dst, $natport, $target) { global $config; if ($target) $tgt = $target . "/32"; else $tgt = "($if)"; if ($dst == "") $dst = "any"; if ($srcport) $src .= " port " . $srcport; if ($natport) $tgt .= " port " . $natport; $natrule = <<