2 ###############################################################################
4 # IPFire.org - A linux based firewall #
5 # Copyright (C) 2013 Alexander Marx <amarx@ipfire.org> #
7 # This program is free software: you can redistribute it and/or modify #
8 # it under the terms of the GNU General Public License as published by #
9 # the Free Software Foundation, either version 3 of the License, or #
10 # (at your option) any later version. #
12 # This program is distributed in the hope that it will be useful, #
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
15 # GNU General Public License for more details. #
17 # You should have received a copy of the GNU General Public License #
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. #
20 ###############################################################################
24 require '/var/ipfire/general-functions.pl';
25 require "${General::swroot}/lang.pl";
26 require "/usr/lib/firewall/firewall-lib.pl";
28 # Set to one to enable debugging mode.
31 my $IPTABLES = "iptables --wait";
34 my $CHAIN_INPUT = "INPUTFW";
35 my $CHAIN_FORWARD = "FORWARDFW";
36 my $CHAIN_OUTPUT = "OUTGOINGFW";
37 my $CHAIN = $CHAIN_FORWARD;
38 my $CHAIN_NAT_SOURCE = "NAT_SOURCE";
39 my $CHAIN_NAT_DESTINATION = "NAT_DESTINATION";
40 my $CHAIN_MANGLE_NAT_DESTINATION_FIX = "NAT_DESTINATION";
41 my @VALID_CHAINS = ($CHAIN_INPUT, $CHAIN_FORWARD, $CHAIN_OUTPUT);
42 my @ANY_ADDRESSES = ("0.0.0.0/0.0.0.0", "0.0.0.0/0", "0/0");
44 my @PROTOCOLS = ("tcp", "udp", "icmp", "igmp", "ah", "esp", "gre", "ipv6", "ipip");
45 my @PROTOCOLS_WITH_PORTS = ("tcp", "udp");
47 my @VALID_TARGETS = ("ACCEPT", "DROP", "REJECT");
50 my %defaultNetworks=();
54 my %configoutgoingfw=();
59 my $configfwdfw = "${General::swroot}/firewall/config";
60 my $configinput = "${General::swroot}/firewall/input";
61 my $configoutgoing = "${General::swroot}/firewall/outgoing";
62 my $p2pfile = "${General::swroot}/firewall/p2protocols";
63 my $configgrp = "${General::swroot}/fwhosts/customgroups";
64 my $netsettings = "${General::swroot}/ethernet/settings";
66 &General
::readhash
("${General::swroot}/firewall/settings", \
%fwdfwsettings);
67 &General
::readhash
("$netsettings", \
%defaultNetworks);
68 &General
::readhasharray
($configfwdfw, \
%configfwdfw);
69 &General
::readhasharray
($configinput, \
%configinputfw);
70 &General
::readhasharray
($configoutgoing, \
%configoutgoingfw);
71 &General
::readhasharray
($configgrp, \
%customgrp);
72 &General
::get_aliases
(\
%aliases);
74 my @log_limit_options = &make_log_limit_options
();
83 # Reload firewall rules.
86 # Load P2P block rules.
89 # Reload firewall policy.
90 run
("/usr/sbin/firewall-policy");
94 # Executes or prints the given shell command.
103 print_error
("ERROR: $command");
111 print STDERR
"$message\n";
121 printf(" %2d: %s", $i++, $_);
127 run
("$IPTABLES -F $CHAIN_INPUT");
128 run
("$IPTABLES -F $CHAIN_FORWARD");
129 run
("$IPTABLES -F $CHAIN_OUTPUT");
130 run
("$IPTABLES -t nat -F $CHAIN_NAT_SOURCE");
131 run
("$IPTABLES -t nat -F $CHAIN_NAT_DESTINATION");
132 run
("$IPTABLES -t mangle -F $CHAIN_MANGLE_NAT_DESTINATION_FIX");
136 if (! -z
"${General::swroot}/firewall/config"){
137 &buildrules
(\
%configfwdfw);
139 if (! -z
"${General::swroot}/firewall/input"){
140 &buildrules
(\
%configinputfw);
142 if (! -z
"${General::swroot}/firewall/outgoing"){
143 &buildrules
(\
%configoutgoingfw);
150 foreach my $key (sort {$a <=> $b} keys %$hash) {
151 # Skip disabled rules.
152 next unless ($$hash{$key}[2] eq 'ON');
155 print_rule
($$hash{$key});
158 # Check if the target is valid.
159 my $target = $$hash{$key}[0];
160 if (!$target ~~ @VALID_TARGETS) {
161 print_error
("Invalid target '$target' for rule $key");
165 # Check if the chain is valid.
166 my $chain = $$hash{$key}[1];
167 if (!$chain ~~ @VALID_CHAINS) {
168 print_error
("Invalid chain '$chain' in rule $key");
172 # Collect all sources.
173 my @sources = &fwlib
::get_addresses
($hash, $key, "src");
175 # Collect all destinations.
176 my @destinations = &fwlib
::get_addresses
($hash, $key, "tgt");
178 # True if the destination is the firewall itself.
179 my $destination_is_firewall = ($$hash{$key}[5] eq "ipfire");
181 # Check if logging should be enabled.
182 my $LOG = ($$hash{$key}[17] eq 'ON');
184 # Check if NAT is enabled and initialize variables, that we use for that.
185 my $NAT = ($$hash{$key}[28] eq 'ON');
188 $NAT_MODE = uc($$hash{$key}[31]);
191 # Set up time constraints.
192 my @time_options = ();
193 if ($$hash{$key}[18] eq 'ON') {
194 push(@time_options, ("-m", "time"));
196 # Select all days of the week this match is active.
198 if ($$hash{$key}[19] ne '') {
199 push (@weekdays, "Mon");
201 if ($$hash{$key}[20] ne '') {
202 push (@weekdays, "Tue");
204 if ($$hash{$key}[21] ne '') {
205 push (@weekdays, "Wed");
207 if ($$hash{$key}[22] ne '') {
208 push (@weekdays, "Thu");
210 if ($$hash{$key}[23] ne '') {
211 push (@weekdays, "Fri");
213 if ($$hash{$key}[24] ne '') {
214 push (@weekdays, "Sat");
216 if ($$hash{$key}[25] ne '') {
217 push (@weekdays, "Sun");
220 push(@time_options, ("--weekdays", join(",", @weekdays)));
223 # Convert start time.
224 my $time_start = &format_time
($$hash{$key}[26]);
226 push(@time_options, ("--timestart", $time_start));
230 my $time_stop = &format_time
($$hash{$key}[27]);
232 push(@time_options, ("--timestop", $time_stop));
236 # Check which protocols are used in this rule and so that we can
237 # later group rules by protocols.
238 my @protocols = &get_protocols
($hash, $key);
240 print_error
("Invalid protocol configuration for rule $key");
244 foreach my $protocol (@protocols) {
245 # Check if the given protocol is supported.
246 if (($protocol ne "all") && (!$protocol ~~ @PROTOCOLS)) {
247 print_error
("Protocol $protocol is not supported (rule $key)");
251 # Prepare protocol options (like ICMP types, ports, etc...).
252 my @protocol_options = &get_protocol_options
($hash, $key, $protocol, 0);
254 # Check if this protocol knows ports.
255 my $protocol_has_ports = ($protocol ~~ @PROTOCOLS_WITH_PORTS);
257 foreach my $source (@sources) {
258 foreach my $destination (@destinations) {
259 # Skip invalid rules.
260 next if (!$source || !$destination || ($destination eq "none"));
263 if ($source ~~ @ANY_ADDRESSES) {
267 # Sanitize destination.
268 if ($destination ~~ @ANY_ADDRESSES) {
272 # Array with iptables arguments.
276 if ($protocol ne "all") {
277 push(@options, @protocol_options);
280 # Prepare source options.
281 my @source_options = ();
282 if ($source =~ /mac/) {
283 push(@source_options, $source);
285 push(@source_options, ("-s", $source));
288 # Prepare destination options.
289 my @destination_options = ();
291 push(@destination_options, ("-d", $destination));
294 # Add time constraint options.
295 push(@options, @time_options);
297 my $firewall_is_in_source_subnet = 0;
299 $firewall_is_in_source_subnet = &firewall_is_in_subnet
($source);
304 my $nat_address = &fwlib
::get_nat_address
($$hash{$key}[29], $source);
306 # Skip NAT rules if the NAT address is unknown
307 # (i.e. no internet connection has been established, yet).
308 next unless ($nat_address);
311 if ($NAT_MODE eq "DNAT") {
312 # Make port-forwardings useable from the internal networks.
313 my @internal_addresses = &fwlib
::get_internal_firewall_ip_addresses
(1);
314 unless ($nat_address ~~ @internal_addresses) {
315 &add_dnat_mangle_rules
($nat_address, @options);
318 my @nat_options = ();
319 if ($protocol ne "all") {
320 my @nat_protocol_options = &get_protocol_options
($hash, $key, $protocol, 1);
321 push(@nat_options, @nat_protocol_options);
323 push(@nat_options, @source_options);
324 push(@nat_options, ("-d", $nat_address));
325 push(@nat_options, @time_options);
328 if ($protocol_has_ports) {
329 $dnat_port = &get_dnat_target_port
($hash, $key);
332 my @nat_action_options = ();
334 # Use iptables REDIRECT
335 my $use_redirect = ($destination_is_firewall && !$destination && $protocol_has_ports && $dnat_port);
337 push(@nat_action_options, ("-j", "REDIRECT", "--to-ports", $dnat_port));
341 if ($destination_is_firewall && !$destination) {
342 $destination = &fwlib
::get_external_address
();
344 next unless ($destination);
346 my ($dnat_address, $dnat_mask) = split("/", $destination);
347 @destination_options = ("-d", $dnat_address);
349 if ($protocol_has_ports) {
350 my $dnat_port = &get_dnat_target_port
($hash, $key);
353 $dnat_address .= ":$dnat_port";
357 push(@nat_action_options, ("-j", "DNAT", "--to-destination", $dnat_address));
361 run
("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @log_limit_options -j LOG --log-prefix 'DNAT '");
363 run
("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @nat_action_options");
366 } elsif ($NAT_MODE eq "SNAT") {
367 my @nat_options = @options;
369 push(@nat_options, @source_options);
370 push(@nat_options, @destination_options);
373 run
("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options @log_limit_options -j LOG --log-prefix 'SNAT '");
375 run
("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options -j SNAT --to-source $nat_address");
379 push(@options, @source_options);
381 if ($firewall_is_in_source_subnet && ($fwdfwsettings{"POLICY"} eq "MODE1") && ($chain eq $CHAIN_FORWARD)) {
383 run
("$IPTABLES -A $CHAIN_INPUT @options @log_limit_options -j LOG --log-prefix '$CHAIN_INPUT '");
385 run
("$IPTABLES -A $CHAIN_INPUT @options -j $target");
388 push(@options, @destination_options);
390 # Insert firewall rule.
392 run
("$IPTABLES -A $chain @options @log_limit_options -j LOG --log-prefix '$chain '");
394 run
("$IPTABLES -A $chain @options -j $target");
401 # Formats the given timestamp into the iptables format which is "hh:mm" UTC.
405 # Convert the given time into minutes.
406 my $minutes = &time_convert_to_minutes
($val);
408 # Move the timestamp into UTC.
409 $minutes += &time_utc_offset
();
411 # Make sure $minutes is between 00:00 and 23:59.
416 if ($minutes > 1440) {
421 return sprintf("%02d:%02d", $minutes / 60, $minutes % 60);
424 # Calculates the offsets in minutes from the local timezone to UTC.
425 sub time_utc_offset
{
426 my @localtime = localtime(time);
427 my @gmtime = gmtime(time);
429 return ($gmtime[2] * 60 + $gmtime[1] % 60) - ($localtime[2] * 60 + $localtime[1] % 60);
432 # Takes a timestamp like "14:00" and converts it into minutes since midnight.
433 sub time_convert_to_minutes
{
434 my ($hrs, $min) = split(":", shift);
436 return ($hrs * 60) + $min;
442 open( FILE
, "< $p2pfile" ) or die "Unable to read $p2pfile";
445 my $CMD = "-m ipp2p";
446 foreach my $p2pentry (sort @p2ps) {
447 my @p2pline = split( /\;/, $p2pentry );
448 if ( $fwdfwsettings{'POLICY'} eq 'MODE1' ) {
450 if ("$p2pline[2]" eq "on") {
451 $P2PSTRING = "$P2PSTRING --$p2pline[1]";
455 if ("$p2pline[2]" eq "off") {
456 $P2PSTRING = "$P2PSTRING --$p2pline[1]";
462 run
("$IPTABLES -A FORWARDFW $CMD $P2PSTRING -j $DO");
470 my $uses_source_ports = ($$hash{$key}[7] eq "ON");
471 my $uses_services = ($$hash{$key}[11] eq "ON");
475 # Rules which don't have source ports or services (like ICMP, ESP, ...).
476 if (!$uses_source_ports && !$uses_services) {
477 push(@protocols, $$hash{$key}[8]);
479 # Rules which either use ports or services.
480 } elsif ($uses_source_ports || $uses_services) {
481 # Check if service group or service
482 if ($$hash{$key}[14] eq 'cust_srv') {
483 push(@protocols, &fwlib
::get_srv_prot
($$hash{$key}[15]));
485 } elsif($$hash{$key}[14] eq 'cust_srvgrp'){
486 my $protos = &fwlib
::get_srvgrp_prot
($$hash{$key}[15]);
487 push(@protocols, split(",", $protos));
490 # Fetch the protocol for this rule.
491 my $protocol = lc($$hash{$key}[8]);
493 # Fetch source and destination ports for this rule.
494 my $source_ports = $$hash{$key}[10];
495 my $destination_ports = $$hash{$key}[15];
497 # Check if ports are set for protocols which do not support ports.
498 if (!($protocol ~~ @PROTOCOLS_WITH_PORTS) && ($source_ports || $destination_ports)) {
499 print_error
("$protocol does not support ports");
503 push(@protocols, $protocol);
507 # Remove all empty elements
508 @protocols = map { $_ ?
$_ : () } @protocols;
510 # If no protocol has been defined, we assume "all".
512 push(@protocols, "all");
515 # Make all protocol names lowercase.
516 @protocols = map { lc } @protocols;
521 sub get_protocol_options
{
524 my $protocol = shift;
525 my $nat_options_wanted = shift;
528 # Nothing to do if no protocol is specified.
529 if ($protocol eq "all") {
532 push(@options, ("-p", $protocol));
535 # Process source ports.
536 my $use_src_ports = ($$hash{$key}[7] eq "ON");
537 my $src_ports = $$hash{$key}[10];
539 if ($use_src_ports && $src_ports) {
540 push(@options, &format_ports
($src_ports, "src"));
543 # Process destination ports.
544 my $use_dst_ports = ($$hash{$key}[11] eq "ON");
545 my $use_dnat = (($$hash{$key}[28] eq "ON") && ($$hash{$key}[31] eq "dnat"));
547 if ($use_dst_ports) {
548 my $dst_ports_mode = $$hash{$key}[14];
549 my $dst_ports = $$hash{$key}[15];
551 if (($dst_ports_mode eq "TGT_PORT") && $dst_ports) {
552 if ($nat_options_wanted && $use_dnat && $$hash{$key}[30]) {
553 $dst_ports = $$hash{$key}[30];
555 push(@options, &format_ports
($dst_ports, "dst"));
557 } elsif ($dst_ports_mode eq "cust_srv") {
558 if ($protocol eq "ICMP") {
559 push(@options, ("--icmp-type", &fwlib
::get_srv_port
($dst_ports, 3, "ICMP")));
561 $dst_ports = &fwlib
::get_srv_port
($dst_ports, 1, uc($protocol));
562 push(@options, &format_ports
($dst_ports, "dst"));
565 } elsif ($dst_ports_mode eq "cust_srvgrp") {
566 push(@options, &fwlib
::get_srvgrp_port
($dst_ports, uc($protocol)));
570 # Check if a single ICMP type is selected.
571 if (!$use_src_ports && !$use_dst_ports && $protocol eq "icmp") {
572 my $icmp_type = $$hash{$key}[9];
574 if (($icmp_type ne "All ICMP-Types") && $icmp_type) {
575 push(@options, ("--icmp-type", $icmp_type));
587 if ($type eq "src") {
589 } elsif ($type eq "dst") {
595 if ($ports =~ /\|/) {
597 push(@options, ("-m", "multiport"));
601 push(@options, ($arg, $ports));
607 sub get_dnat_target_port
{
611 if ($$hash{$key}[14] eq "TGT_PORT") {
612 my $port = $$hash{$key}[15];
613 my $external_port = $$hash{$key}[30];
615 if ($external_port && ($port ne $external_port)) {
616 return $$hash{$key}[15];
621 sub add_dnat_mangle_rules
{
622 my $nat_address = shift;
626 foreach my $zone ("GREEN", "BLUE", "ORANGE") {
629 # Skip rule if not all required information exists.
630 next unless (exists $defaultNetworks{$zone . "_NETADDRESS"});
631 next unless (exists $defaultNetworks{$zone . "_NETMASK"});
633 my @mangle_options = @options;
635 my $netaddress = $defaultNetworks{$zone . "_NETADDRESS"};
636 $netaddress .= "/" . $defaultNetworks{$zone . "_NETMASK"};
638 push(@mangle_options, ("-s", $netaddress, "-d", $nat_address));
639 push(@mangle_options, ("-j", "MARK", "--set-mark", $mark));
641 run
("$IPTABLES -t mangle -A $CHAIN_MANGLE_NAT_DESTINATION_FIX @mangle_options");
645 sub make_log_limit_options
{
646 my @options = ("-m", "limit");
648 # Maybe we should get this from the configuration.
651 # We limit log messages to $limit messages per minute.
652 push(@options, ("--limit", "$limit/min"));
654 # And we allow bursts of 2x $limit.
655 push(@options, ("--limit-burst", $limit * 2));
660 sub firewall_is_in_subnet
{
663 # ORANGE is missing here, because nothing may ever access
664 # the firewall from this network.
665 my $address = &fwlib
::get_internal_firewall_ip_address
($subnet, 0);