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");
51 my %defaultNetworks=();
55 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
("${General::swroot}/optionsfw/settings", \
%fwoptions);
68 &General
::readhash
("$netsettings", \
%defaultNetworks);
69 &General
::readhasharray
($configfwdfw, \
%configfwdfw);
70 &General
::readhasharray
($configinput, \
%configinputfw);
71 &General
::readhasharray
($configoutgoing, \
%configoutgoingfw);
72 &General
::readhasharray
($configgrp, \
%customgrp);
74 my @log_limit_options = &make_log_limit_options
();
76 my $POLICY_INPUT_ALLOWED = 0;
77 my $POLICY_FORWARD_ALLOWED = ($fwdfwsettings{"POLICY"} eq "MODE2");
78 my $POLICY_OUTPUT_ALLOWED = ($fwdfwsettings{"POLICY1"} eq "MODE2");
80 my $POLICY_INPUT_ACTION = $fwoptions{"FWPOLICY2"};
81 my $POLICY_FORWARD_ACTION = $fwoptions{"FWPOLICY"};
82 my $POLICY_OUTPUT_ACTION = $fwoptions{"FWPOLICY1"};
91 # Reload firewall rules.
94 # Load P2P block rules.
97 # Reload firewall policy.
98 run
("/usr/sbin/firewall-policy");
102 # Executes or prints the given shell command.
111 print_error
("ERROR: $command");
119 print STDERR
"$message\n";
129 printf(" %2d: %s", $i++, $_);
135 run
("$IPTABLES -F $CHAIN_INPUT");
136 run
("$IPTABLES -F $CHAIN_FORWARD");
137 run
("$IPTABLES -F $CHAIN_OUTPUT");
138 run
("$IPTABLES -t nat -F $CHAIN_NAT_SOURCE");
139 run
("$IPTABLES -t nat -F $CHAIN_NAT_DESTINATION");
140 run
("$IPTABLES -t mangle -F $CHAIN_MANGLE_NAT_DESTINATION_FIX");
144 if (! -z
"${General::swroot}/firewall/input"){
145 &buildrules
(\
%configinputfw);
147 if (! -z
"${General::swroot}/firewall/outgoing"){
148 &buildrules
(\
%configoutgoingfw);
150 if (! -z
"${General::swroot}/firewall/config"){
151 &buildrules
(\
%configfwdfw);
158 # Search for targets that need to be specially handled when adding
159 # forwarding rules. Additional rules will automatically get inserted
160 # into the INPUT/OUTPUT chains for these targets.
161 my @special_input_targets = ();
162 if (!$POLICY_FORWARD_ALLOWED) {
163 push(@special_input_targets, "ACCEPT");
166 if ($POLICY_INPUT_ACTION eq "DROP") {
167 push(@special_input_targets, "REJECT");
168 } elsif ($POLICY_INPUT_ACTION eq "REJECT") {
169 push(@special_input_targets, "DROP");
172 my @special_output_targets = ();
173 if ($POLICY_OUTPUT_ALLOWED) {
174 push(@special_output_targets, ("DROP", "REJECT"));
176 push(@special_output_targets, "ACCEPT");
178 if ($POLICY_OUTPUT_ACTION eq "DROP") {
179 push(@special_output_targets, "REJECT");
180 } elsif ($POLICY_OUTPUT_ACTION eq "REJECT") {
181 push(@special_output_targets, "DROP");
185 foreach my $key (sort {$a <=> $b} keys %$hash) {
186 # Skip disabled rules.
187 next unless ($$hash{$key}[2] eq 'ON');
190 print_rule
($$hash{$key});
193 # Check if the target is valid.
194 my $target = $$hash{$key}[0];
195 if (!$target ~~ @VALID_TARGETS) {
196 print_error
("Invalid target '$target' for rule $key");
200 # Check if the chain is valid.
201 my $chain = $$hash{$key}[1];
202 if (!$chain ~~ @VALID_CHAINS) {
203 print_error
("Invalid chain '$chain' in rule $key");
207 # Collect all sources.
208 my @sources = &fwlib
::get_addresses
($hash, $key, "src");
210 # Collect all destinations.
211 my @destinations = &fwlib
::get_addresses
($hash, $key, "tgt");
213 # True if the destination is the firewall itself.
214 my $destination_is_firewall = ($$hash{$key}[5] eq "ipfire");
216 # Check if logging should be enabled.
217 my $LOG = ($$hash{$key}[17] eq 'ON');
219 # Check if NAT is enabled and initialize variables, that we use for that.
220 my $NAT = ($$hash{$key}[28] eq 'ON');
223 $NAT_MODE = uc($$hash{$key}[31]);
226 # Set up time constraints.
227 my @time_options = ();
228 if ($$hash{$key}[18] eq 'ON') {
229 push(@time_options, ("-m", "time"));
231 # Select all days of the week this match is active.
233 if ($$hash{$key}[19] ne '') {
234 push (@weekdays, "Mon");
236 if ($$hash{$key}[20] ne '') {
237 push (@weekdays, "Tue");
239 if ($$hash{$key}[21] ne '') {
240 push (@weekdays, "Wed");
242 if ($$hash{$key}[22] ne '') {
243 push (@weekdays, "Thu");
245 if ($$hash{$key}[23] ne '') {
246 push (@weekdays, "Fri");
248 if ($$hash{$key}[24] ne '') {
249 push (@weekdays, "Sat");
251 if ($$hash{$key}[25] ne '') {
252 push (@weekdays, "Sun");
255 push(@time_options, ("--weekdays", join(",", @weekdays)));
258 # Convert start time.
259 my $time_start = &format_time
($$hash{$key}[26]);
261 push(@time_options, ("--timestart", $time_start));
265 my $time_stop = &format_time
($$hash{$key}[27]);
267 push(@time_options, ("--timestop", $time_stop));
271 # Check which protocols are used in this rule and so that we can
272 # later group rules by protocols.
273 my @protocols = &get_protocols
($hash, $key);
275 print_error
("Invalid protocol configuration for rule $key");
279 foreach my $protocol (@protocols) {
280 # Check if the given protocol is supported.
281 if (($protocol ne "all") && (!$protocol ~~ @PROTOCOLS)) {
282 print_error
("Protocol $protocol is not supported (rule $key)");
286 # Prepare protocol options (like ICMP types, ports, etc...).
287 my @protocol_options = &get_protocol_options
($hash, $key, $protocol, 0);
289 # Check if this protocol knows ports.
290 my $protocol_has_ports = ($protocol ~~ @PROTOCOLS_WITH_PORTS);
292 foreach my $src (@sources) {
293 # Skip invalid source.
294 next unless (defined $src);
298 my $source = @
$src[0];
299 if ($source ~~ @ANY_ADDRESSES) {
303 my $source_intf = @
$src[1];
305 foreach my $dst (@destinations) {
306 # Skip invalid rules.
307 next unless (defined $dst);
308 next if (!$dst || ($dst eq "none"));
310 # Sanitize destination.
311 my $destination = @
$dst[0];
312 if ($destination ~~ @ANY_ADDRESSES) {
316 my $destination_intf = @
$dst[1];
318 # Array with iptables arguments.
322 if ($protocol ne "all") {
323 push(@options, @protocol_options);
326 # Prepare source options.
327 my @source_options = ();
328 if ($source =~ /mac/) {
329 push(@source_options, $source);
331 push(@source_options, ("-s", $source));
335 push(@source_options, ("-i", $source_intf));
338 # Prepare destination options.
339 my @destination_options = ();
341 push(@destination_options, ("-d", $destination));
344 if ($destination_intf) {
345 push(@destination_options, ("-o", $destination_intf));
348 # Add time constraint options.
349 push(@options, @time_options);
351 my $firewall_is_in_source_subnet = 1;
353 $firewall_is_in_source_subnet = &firewall_is_in_subnet
($source);
356 my $firewall_is_in_destination_subnet = 1;
358 $firewall_is_in_destination_subnet = &firewall_is_in_subnet
($destination);
363 my $nat_address = &fwlib
::get_nat_address
($$hash{$key}[29], $source);
365 # Skip NAT rules if the NAT address is unknown
366 # (i.e. no internet connection has been established, yet).
367 next unless ($nat_address);
370 if ($NAT_MODE eq "DNAT") {
371 my @nat_options = ();
372 if ($protocol ne "all") {
373 my @nat_protocol_options = &get_protocol_options
($hash, $key, $protocol, 1);
374 push(@nat_options, @nat_protocol_options);
376 push(@nat_options, @time_options);
378 # Make port-forwardings useable from the internal networks.
379 my @internal_addresses = &fwlib
::get_internal_firewall_ip_addresses
(1);
380 unless ($nat_address ~~ @internal_addresses) {
381 &add_dnat_mangle_rules
($nat_address, $source_intf, @nat_options);
384 push(@nat_options, @source_options);
385 push(@nat_options, ("-d", $nat_address));
388 if ($protocol_has_ports) {
389 $dnat_port = &get_dnat_target_port
($hash, $key);
392 my @nat_action_options = ();
394 # Use iptables REDIRECT
395 my $use_redirect = ($destination_is_firewall && !$destination && $protocol_has_ports && $dnat_port);
397 push(@nat_action_options, ("-j", "REDIRECT", "--to-ports", $dnat_port));
401 if ($destination_is_firewall && !$destination) {
402 $destination = &fwlib
::get_external_address
();
404 next unless ($destination);
406 my ($dnat_address, $dnat_mask) = split("/", $destination);
407 @destination_options = ("-d", $dnat_address);
409 if ($protocol_has_ports) {
410 my $dnat_port = &get_dnat_target_port
($hash, $key);
413 $dnat_address .= ":$dnat_port";
417 push(@nat_action_options, ("-j", "DNAT", "--to-destination", $dnat_address));
421 run
("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @log_limit_options -j LOG --log-prefix 'DNAT '");
423 run
("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @nat_action_options");
426 } elsif ($NAT_MODE eq "SNAT") {
427 my @nat_options = @options;
429 push(@nat_options, @source_options);
430 push(@nat_options, @destination_options);
433 run
("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options @log_limit_options -j LOG --log-prefix 'SNAT '");
435 run
("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options -j SNAT --to-source $nat_address");
439 push(@options, @source_options);
440 push(@options, @destination_options);
442 # Insert firewall rule.
444 run
("$IPTABLES -A $chain @options @log_limit_options -j LOG --log-prefix '$chain '");
446 run
("$IPTABLES -A $chain @options -j $target");
448 # Handle forwarding rules and add corresponding rules for firewall access.
449 if ($chain eq $CHAIN_FORWARD) {
450 # If the firewall is part of the destination subnet and access to the destination network
451 # is granted/forbidden for any network that the firewall itself is part of, we grant/forbid access
452 # for the firewall, too.
453 if ($firewall_is_in_destination_subnet && ($target ~~ @special_input_targets)) {
455 run
("$IPTABLES -A $CHAIN_INPUT @options @log_limit_options -j LOG --log-prefix '$CHAIN_INPUT '");
457 run
("$IPTABLES -A $CHAIN_INPUT @options -j $target");
461 if ($firewall_is_in_source_subnet && ($target ~~ @special_output_targets)) {
463 run
("$IPTABLES -A $CHAIN_OUTPUT @options @log_limit_options -j LOG --log-prefix '$CHAIN_OUTPUT '");
465 run
("$IPTABLES -A $CHAIN_OUTPUT @options -j $target");
474 # Formats the given timestamp into the iptables format which is "hh:mm" UTC.
478 # Convert the given time into minutes.
479 my $minutes = &time_convert_to_minutes
($val);
481 # Move the timestamp into UTC.
482 $minutes += &time_utc_offset
();
484 # Make sure $minutes is between 00:00 and 23:59.
489 if ($minutes > 1440) {
494 return sprintf("%02d:%02d", $minutes / 60, $minutes % 60);
497 # Calculates the offsets in minutes from the local timezone to UTC.
498 sub time_utc_offset
{
499 my @localtime = localtime(time);
500 my @gmtime = gmtime(time);
502 return ($gmtime[2] * 60 + $gmtime[1] % 60) - ($localtime[2] * 60 + $localtime[1] % 60);
505 # Takes a timestamp like "14:00" and converts it into minutes since midnight.
506 sub time_convert_to_minutes
{
507 my ($hrs, $min) = split(":", shift);
509 return ($hrs * 60) + $min;
516 if ($fwdfwsettings{"POLICY"} eq "MODE1") {
517 $search_action = "on";
520 $search_action = "off";
524 open(FILE
, "<$p2pfile") or die "Unable to read $p2pfile";
526 foreach my $p2pentry (<FILE
>) {
527 my @p2pline = split(/\;/, $p2pentry);
528 next unless ($p2pline[2] eq $search_action);
530 push(@protocols, "--$p2pline[1]");
535 run
("$IPTABLES -A FORWARDFW -m ipp2p @protocols -j $target");
543 my $uses_source_ports = ($$hash{$key}[7] eq "ON");
544 my $uses_services = ($$hash{$key}[11] eq "ON");
548 # Rules which don't have source ports or services (like ICMP, ESP, ...).
549 if (!$uses_source_ports && !$uses_services) {
550 push(@protocols, $$hash{$key}[8]);
552 # Rules which either use ports or services.
553 } elsif ($uses_source_ports || $uses_services) {
554 # Check if service group or service
555 if ($$hash{$key}[14] eq 'cust_srv') {
556 push(@protocols, &fwlib
::get_srv_prot
($$hash{$key}[15]));
558 } elsif($$hash{$key}[14] eq 'cust_srvgrp'){
559 my $protos = &fwlib
::get_srvgrp_prot
($$hash{$key}[15]);
560 push(@protocols, split(",", $protos));
563 # Fetch the protocol for this rule.
564 my $protocol = lc($$hash{$key}[8]);
566 # Fetch source and destination ports for this rule.
567 my $source_ports = $$hash{$key}[10];
568 my $destination_ports = $$hash{$key}[15];
570 # Check if ports are set for protocols which do not support ports.
571 if (!($protocol ~~ @PROTOCOLS_WITH_PORTS) && ($source_ports || $destination_ports)) {
572 print_error
("$protocol does not support ports");
576 push(@protocols, $protocol);
580 # Remove all empty elements
581 @protocols = map { $_ ?
$_ : () } @protocols;
583 # If no protocol has been defined, we assume "all".
585 push(@protocols, "all");
588 # Make all protocol names lowercase.
589 @protocols = map { lc } @protocols;
594 sub get_protocol_options
{
597 my $protocol = shift;
598 my $nat_options_wanted = shift;
601 # Nothing to do if no protocol is specified.
602 if ($protocol eq "all") {
605 push(@options, ("-p", $protocol));
608 if ($protocol ~~ @PROTOCOLS_WITH_PORTS) {
609 # Process source ports.
610 my $use_src_ports = ($$hash{$key}[7] eq "ON");
611 my $src_ports = $$hash{$key}[10];
613 if ($use_src_ports && $src_ports) {
614 push(@options, &format_ports
($src_ports, "src"));
617 # Process destination ports.
618 my $use_dst_ports = ($$hash{$key}[11] eq "ON");
619 my $use_dnat = (($$hash{$key}[28] eq "ON") && ($$hash{$key}[31] eq "dnat"));
621 if ($use_dst_ports) {
622 my $dst_ports_mode = $$hash{$key}[14];
623 my $dst_ports = $$hash{$key}[15];
625 if (($dst_ports_mode eq "TGT_PORT") && $dst_ports) {
626 if ($nat_options_wanted && $use_dnat && $$hash{$key}[30]) {
627 $dst_ports = $$hash{$key}[30];
629 push(@options, &format_ports
($dst_ports, "dst"));
631 } elsif ($dst_ports_mode eq "cust_srv") {
632 if ($protocol eq "ICMP") {
633 push(@options, ("--icmp-type", &fwlib
::get_srv_port
($dst_ports, 3, "ICMP")));
635 $dst_ports = &fwlib
::get_srv_port
($dst_ports, 1, uc($protocol));
636 push(@options, &format_ports
($dst_ports, "dst"));
639 } elsif ($dst_ports_mode eq "cust_srvgrp") {
640 push(@options, &fwlib
::get_srvgrp_port
($dst_ports, uc($protocol)));
645 # Check if a single ICMP type is selected.
646 if ($protocol eq "icmp") {
647 my $icmp_type = $$hash{$key}[9];
649 if (($icmp_type ne "All ICMP-Types") && $icmp_type) {
650 push(@options, ("--icmp-type", $icmp_type));
662 if ($type eq "src") {
664 } elsif ($type eq "dst") {
670 if ($ports =~ /\|/) {
672 push(@options, ("-m", "multiport"));
676 push(@options, ($arg, $ports));
682 sub get_dnat_target_port
{
686 if ($$hash{$key}[14] eq "TGT_PORT") {
687 my $port = $$hash{$key}[15];
688 my $external_port = $$hash{$key}[30];
690 if ($external_port && ($port ne $external_port)) {
691 return $$hash{$key}[15];
696 sub add_dnat_mangle_rules
{
697 my $nat_address = shift;
698 my $interface = shift;
702 foreach my $zone ("GREEN", "BLUE", "ORANGE") {
705 # Skip rule if not all required information exists.
706 next unless (exists $defaultNetworks{$zone . "_NETADDRESS"});
707 next unless (exists $defaultNetworks{$zone . "_NETMASK"});
709 next if ($interface && $interface ne $defaultNetworks{$zone . "_DEV"});
711 my @mangle_options = @options;
713 my $netaddress = $defaultNetworks{$zone . "_NETADDRESS"};
714 $netaddress .= "/" . $defaultNetworks{$zone . "_NETMASK"};
716 push(@mangle_options, ("-s", $netaddress, "-d", $nat_address));
717 push(@mangle_options, ("-j", "MARK", "--set-mark", $mark));
719 run
("$IPTABLES -t mangle -A $CHAIN_MANGLE_NAT_DESTINATION_FIX @mangle_options");
723 sub make_log_limit_options
{
724 my @options = ("-m", "limit");
726 # Maybe we should get this from the configuration.
729 # We limit log messages to $limit messages per minute.
730 push(@options, ("--limit", "$limit/min"));
732 # And we allow bursts of 2x $limit.
733 push(@options, ("--limit-burst", $limit * 2));
738 sub firewall_is_in_subnet
{
741 # ORANGE is missing here, because nothing may ever access
742 # the firewall from this network.
743 my $address = &fwlib
::get_internal_firewall_ip_address
($subnet, 0);