2 ###############################################################################
4 # IPFire.org - A linux based firewall #
5 # Copyright (C) 2007-2019 IPFire Team <info@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 ###############################################################################
23 use experimental
'smartmatch';
25 require '/var/ipfire/general-functions.pl';
26 require "${General::swroot}/lang.pl";
27 require "/usr/lib/firewall/firewall-lib.pl";
28 require "${General::swroot}/location-functions.pl";
30 # Set to one to enable debugging mode.
33 my $IPTABLES = "iptables --wait";
36 my $CHAIN_INPUT = "INPUTFW";
37 my $CHAIN_FORWARD = "FORWARDFW";
38 my $CHAIN_OUTPUT = "OUTGOINGFW";
39 my $CHAIN = $CHAIN_FORWARD;
40 my $CHAIN_NAT_SOURCE = "NAT_SOURCE";
41 my $CHAIN_NAT_DESTINATION = "NAT_DESTINATION";
42 my $CHAIN_MANGLE_NAT_DESTINATION_FIX = "NAT_DESTINATION";
43 my @VALID_CHAINS = ($CHAIN_INPUT, $CHAIN_FORWARD, $CHAIN_OUTPUT);
44 my @ANY_ADDRESSES = ("0.0.0.0/0.0.0.0", "0.0.0.0/0", "0/0");
46 my @PROTOCOLS = ("tcp", "udp", "icmp", "igmp", "ah", "esp", "gre", "ipv6", "ipip");
47 my @PROTOCOLS_WITH_PORTS = ("tcp", "udp");
49 my @VALID_TARGETS = ("ACCEPT", "DROP", "REJECT");
53 my %defaultNetworks=();
57 my %configoutgoingfw=();
59 my %locationsettings = (
60 "LOCATIONBLOCK_ENABLED" => "off"
65 my $configfwdfw = "${General::swroot}/firewall/config";
66 my $configinput = "${General::swroot}/firewall/input";
67 my $configoutgoing = "${General::swroot}/firewall/outgoing";
68 my $p2pfile = "${General::swroot}/firewall/p2protocols";
69 my $locationfile = "${General::swroot}/firewall/locationblock";
70 my $configgrp = "${General::swroot}/fwhosts/customgroups";
71 my $netsettings = "${General::swroot}/ethernet/settings";
73 &General
::readhash
("${General::swroot}/firewall/settings", \
%fwdfwsettings);
74 &General
::readhash
("${General::swroot}/optionsfw/settings", \
%fwoptions);
75 &General
::readhash
("$netsettings", \
%defaultNetworks);
76 &General
::readhasharray
($configfwdfw, \
%configfwdfw);
77 &General
::readhasharray
($configinput, \
%configinputfw);
78 &General
::readhasharray
($configoutgoing, \
%configoutgoingfw);
79 &General
::readhasharray
($configgrp, \
%customgrp);
81 # Check if the location settings file exists
82 if (-e
"$locationfile") {
84 &General
::readhash
("$locationfile", \
%locationsettings);
87 # Get all available locations.
88 my @locations = &Location
::Functions
::get_locations
();
90 my @log_limit_options = &make_log_limit_options
();
92 my $POLICY_INPUT_ALLOWED = 0;
93 my $POLICY_FORWARD_ALLOWED = ($fwdfwsettings{"POLICY"} eq "MODE2");
94 my $POLICY_OUTPUT_ALLOWED = ($fwdfwsettings{"POLICY1"} eq "MODE2");
96 my $POLICY_INPUT_ACTION = $fwoptions{"FWPOLICY2"};
97 my $POLICY_FORWARD_ACTION = $fwoptions{"FWPOLICY"};
98 my $POLICY_OUTPUT_ACTION = $fwoptions{"FWPOLICY1"};
107 # Prepare firewall rules.
108 if (! -z
"${General::swroot}/firewall/input"){
109 &buildrules
(\
%configinputfw);
111 if (! -z
"${General::swroot}/firewall/outgoing"){
112 &buildrules
(\
%configoutgoingfw);
114 if (! -z
"${General::swroot}/firewall/config"){
115 &buildrules
(\
%configfwdfw);
118 # Load P2P block rules.
121 # Load Location block rules.
124 # Reload firewall policy.
125 run
("/usr/sbin/firewall-policy");
127 #Reload firewall.local if present
128 if ( -f
'/etc/sysconfig/firewall.local'){
129 run
("/etc/sysconfig/firewall.local reload");
134 # Executes or prints the given shell command.
143 print_error
("ERROR: $command");
151 print STDERR
"$message\n";
161 printf(" %2d: %s", $i++, $_);
169 return scalar @
$hash;
173 run
("$IPTABLES -F $CHAIN_INPUT");
174 run
("$IPTABLES -F $CHAIN_FORWARD");
175 run
("$IPTABLES -F $CHAIN_OUTPUT");
176 run
("$IPTABLES -t nat -F $CHAIN_NAT_SOURCE");
177 run
("$IPTABLES -t nat -F $CHAIN_NAT_DESTINATION");
178 run
("$IPTABLES -t mangle -F $CHAIN_MANGLE_NAT_DESTINATION_FIX");
184 # Search for targets that need to be specially handled when adding
185 # forwarding rules. Additional rules will automatically get inserted
186 # into the INPUT/OUTPUT chains for these targets.
187 my @special_input_targets = ();
188 if (!$POLICY_FORWARD_ALLOWED) {
189 push(@special_input_targets, "ACCEPT");
192 if ($POLICY_INPUT_ACTION eq "DROP") {
193 push(@special_input_targets, ("ACCEPT", "REJECT"));
194 } elsif ($POLICY_INPUT_ACTION eq "REJECT") {
195 push(@special_input_targets, ("ACCEPT", "DROP"));
198 my @special_output_targets = ();
199 if ($POLICY_OUTPUT_ALLOWED) {
200 push(@special_output_targets, ("DROP", "REJECT"));
202 push(@special_output_targets, "ACCEPT");
204 if ($POLICY_OUTPUT_ACTION eq "DROP") {
205 push(@special_output_targets, ("ACCEPT", "REJECT"));
206 } elsif ($POLICY_OUTPUT_ACTION eq "REJECT") {
207 push(@special_output_targets, ("ACCEPT", "DROP"));
211 foreach my $key (sort {$a <=> $b} keys %$hash) {
212 # Skip disabled rules.
213 next unless ($$hash{$key}[2] eq 'ON');
215 # Count number of elements in this line
216 my $elements = &count_elements
($$hash{$key});
219 print_rule
($$hash{$key});
222 # Check if the target is valid.
223 my $target = $$hash{$key}[0];
224 if (!$target ~~ @VALID_TARGETS) {
225 print_error
("Invalid target '$target' for rule $key");
229 # Check if the chain is valid.
230 my $chain = $$hash{$key}[1];
231 if (!$chain ~~ @VALID_CHAINS) {
232 print_error
("Invalid chain '$chain' in rule $key");
236 # Collect all sources.
237 my @sources = &fwlib
::get_addresses
($hash, $key, "src");
239 # Collect all destinations.
240 my @destinations = &fwlib
::get_addresses
($hash, $key, "tgt");
242 # True if the destination is the firewall itself.
243 my $destination_is_firewall = ($$hash{$key}[5] eq "ipfire");
245 # Check if logging should be enabled.
246 my $LOG = ($$hash{$key}[17] eq 'ON');
248 # Check if NAT is enabled and initialize variables, that we use for that.
249 my $NAT = ($$hash{$key}[28] eq 'ON');
252 $NAT_MODE = uc($$hash{$key}[31]);
255 # Set up time constraints.
256 my @time_options = ();
257 if ($$hash{$key}[18] eq 'ON') {
258 push(@time_options, ("-m", "time"));
260 # Select all days of the week this match is active.
262 if ($$hash{$key}[19] ne '') {
263 push (@weekdays, "Mon");
265 if ($$hash{$key}[20] ne '') {
266 push (@weekdays, "Tue");
268 if ($$hash{$key}[21] ne '') {
269 push (@weekdays, "Wed");
271 if ($$hash{$key}[22] ne '') {
272 push (@weekdays, "Thu");
274 if ($$hash{$key}[23] ne '') {
275 push (@weekdays, "Fri");
277 if ($$hash{$key}[24] ne '') {
278 push (@weekdays, "Sat");
280 if ($$hash{$key}[25] ne '') {
281 push (@weekdays, "Sun");
284 push(@time_options, ("--weekdays", join(",", @weekdays)));
287 # Convert start time.
288 my $time_start = &format_time
($$hash{$key}[26]);
290 push(@time_options, ("--timestart", $time_start));
294 my $time_stop = &format_time
($$hash{$key}[27]);
296 push(@time_options, ("--timestop", $time_stop));
300 # Concurrent connection limit
301 my @ratelimit_options = ();
303 if (($elements ge 34) && ($$hash{$key}[32] eq 'ON')) {
304 my $conn_limit = $$hash{$key}[33];
306 if ($conn_limit ge 1) {
307 push(@ratelimit_options, ("-m", "connlimit"));
309 # Use the the entire source IP address
310 push(@ratelimit_options, "--connlimit-saddr");
311 push(@ratelimit_options, ("--connlimit-mask", "32"));
314 push(@ratelimit_options, ("--connlimit-upto", $conn_limit));
319 if (($elements ge 37) && ($$hash{$key}[34] eq 'ON')) {
320 my $rate_limit = "$$hash{$key}[35]/$$hash{$key}[36]";
323 push(@ratelimit_options, ("-m", "limit"));
324 push(@ratelimit_options, ("--limit", $rate_limit));
328 # Check which protocols are used in this rule and so that we can
329 # later group rules by protocols.
330 my @protocols = &get_protocols
($hash, $key);
332 print_error
("Invalid protocol configuration for rule $key");
336 foreach my $protocol (@protocols) {
337 # Check if the given protocol is supported.
338 if (($protocol ne "all") && (!$protocol ~~ @PROTOCOLS)) {
339 print_error
("Protocol $protocol is not supported (rule $key)");
343 # Prepare protocol options (like ICMP types, ports, etc...).
344 my @protocol_options = &get_protocol_options
($hash, $key, $protocol, 0);
346 # Check if this protocol knows ports.
347 my $protocol_has_ports = ($protocol ~~ @PROTOCOLS_WITH_PORTS);
349 foreach my $src (@sources) {
350 # Skip invalid source.
351 next unless (defined $src);
355 my $source = @
$src[0];
356 if ($source ~~ @ANY_ADDRESSES) {
360 my $source_intf = @
$src[1];
362 foreach my $dst (@destinations) {
363 # Skip invalid rules.
364 next unless (defined $dst);
365 next if (!$dst || ($dst eq "none"));
367 # Sanitize destination.
368 my $destination = @
$dst[0];
369 if ($destination ~~ @ANY_ADDRESSES) {
373 my $destination_intf = @
$dst[1];
375 # Array with iptables arguments.
379 if ($protocol ne "all") {
380 push(@options, @protocol_options);
383 # Prepare source options.
384 my @source_options = ();
385 if ($source =~ /mac/) {
386 push(@source_options, $source);
387 } elsif ($source =~ /-m geoip/) {
388 push(@source_options, $source);
390 push(@source_options, ("-s", $source));
393 # Prepare destination options.
394 my @destination_options = ();
395 if ($destination =~ /-m geoip/) {
396 push(@destination_options, $destination);
397 } elsif ($destination) {
398 push(@destination_options, ("-d", $destination));
401 # Add source and destination interface to the filter rules.
402 # These are supposed to help filtering forged packets that originate
403 # from BLUE with an IP address from GREEN for instance.
404 my @source_intf_options = ();
406 push(@source_intf_options, ("-i", $source_intf));
409 my @destination_intf_options = ();
410 if ($destination_intf) {
411 push(@destination_intf_options, ("-o", $destination_intf));
414 # Add time constraint options.
415 push(@options, @time_options);
417 # Add ratelimiting option
418 push(@options, @ratelimit_options);
420 my $firewall_is_in_source_subnet = 1;
422 $firewall_is_in_source_subnet = &firewall_is_in_subnet
($source);
425 my $firewall_is_in_destination_subnet = 1;
427 $firewall_is_in_destination_subnet = &firewall_is_in_subnet
($destination);
432 my $nat_address = &fwlib
::get_nat_address
($$hash{$key}[29], $source);
434 # Skip NAT rules if the NAT address is unknown
435 # (i.e. no internet connection has been established, yet).
436 next unless ($nat_address);
439 if ($NAT_MODE eq "DNAT") {
440 my @nat_options = ();
441 if ($protocol ne "all") {
442 my @nat_protocol_options = &get_protocol_options
($hash, $key, $protocol, 1);
443 push(@nat_options, @nat_protocol_options);
445 push(@nat_options, @time_options);
447 # Make port-forwardings useable from the internal networks.
448 my @internal_addresses = &fwlib
::get_internal_firewall_ip_addresses
(1);
449 unless ($nat_address ~~ @internal_addresses) {
450 &add_dnat_mangle_rules
($nat_address, $source_intf, @nat_options);
453 push(@nat_options, @source_options);
454 push(@nat_options, ("-d", $nat_address));
457 if ($protocol_has_ports) {
458 $dnat_port = &get_dnat_target_port
($hash, $key);
461 my @nat_action_options = ();
463 # Use iptables REDIRECT
464 my $use_redirect = ($destination_is_firewall && !$destination && $protocol_has_ports && $dnat_port);
466 push(@nat_action_options, ("-j", "REDIRECT", "--to-ports", $dnat_port));
470 if ($destination_is_firewall && !$destination) {
471 $destination = &fwlib
::get_external_address
();
473 next unless ($destination);
475 my ($dnat_address, $dnat_mask) = split("/", $destination);
476 @destination_options = ("-d", $dnat_address);
478 if ($protocol_has_ports) {
479 my $dnat_port = &get_dnat_target_port
($hash, $key);
482 $dnat_address .= ":$dnat_port";
486 push(@nat_action_options, ("-j", "DNAT", "--to-destination", $dnat_address));
490 run
("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @log_limit_options -j LOG --log-prefix 'DNAT '");
492 run
("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @nat_action_options");
495 } elsif ($NAT_MODE eq "SNAT") {
496 my @snat_options = ( "-m", "policy", "--dir", "out", "--pol", "none" );
497 my @nat_options = @options;
499 # Get addresses for the configured firewall interfaces.
500 my @local_addresses = &fwlib
::get_internal_firewall_ip_addresses
(1);
502 # Check if the nat_address is one of the local addresses.
503 foreach my $local_address (@local_addresses) {
504 if ($nat_address eq $local_address) {
505 # Clear SNAT options.
513 push(@nat_options, @destination_intf_options);
514 push(@nat_options, @source_options);
515 push(@nat_options, @destination_options);
518 run
("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options @snat_options @log_limit_options -j LOG --log-prefix 'SNAT '");
520 run
("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options @snat_options -j SNAT --to-source $nat_address");
524 push(@options, @source_options);
525 push(@options, @destination_options);
527 # Insert firewall rule.
529 run
("$IPTABLES -A $chain @options @source_intf_options @destination_intf_options @log_limit_options -j LOG --log-prefix '$chain '");
531 run
("$IPTABLES -A $chain @options @source_intf_options @destination_intf_options -j $target");
533 # Handle forwarding rules and add corresponding rules for firewall access.
534 if ($chain eq $CHAIN_FORWARD) {
535 # If the firewall is part of the destination subnet and access to the destination network
536 # is granted/forbidden for any network that the firewall itself is part of, we grant/forbid access
537 # for the firewall, too.
538 if ($firewall_is_in_destination_subnet && ($target ~~ @special_input_targets)) {
540 run
("$IPTABLES -A $CHAIN_INPUT @options @source_intf_options @log_limit_options -j LOG --log-prefix '$CHAIN_INPUT '");
542 run
("$IPTABLES -A $CHAIN_INPUT @options @source_intf_options -j $target");
546 if ($firewall_is_in_source_subnet && ($target ~~ @special_output_targets)) {
548 run
("$IPTABLES -A $CHAIN_OUTPUT @options @destination_intf_options @log_limit_options -j LOG --log-prefix '$CHAIN_OUTPUT '");
550 run
("$IPTABLES -A $CHAIN_OUTPUT @options @destination_intf_options -j $target");
559 # Formats the given timestamp into the iptables format which is "hh:mm" UTC.
563 # Convert the given time into minutes.
564 my $minutes = &time_convert_to_minutes
($val);
566 # Move the timestamp into UTC.
567 $minutes += &time_utc_offset
();
569 # Make sure $minutes is between 00:00 and 23:59.
574 if ($minutes > 1440) {
579 return sprintf("%02d:%02d", $minutes / 60, $minutes % 60);
582 # Calculates the offsets in minutes from the local timezone to UTC.
583 sub time_utc_offset
{
584 my @localtime = localtime(time);
585 my @gmtime = gmtime(time);
587 return ($gmtime[2] * 60 + $gmtime[1] % 60) - ($localtime[2] * 60 + $localtime[1] % 60);
590 # Takes a timestamp like "14:00" and converts it into minutes since midnight.
591 sub time_convert_to_minutes
{
592 my ($hrs, $min) = split(":", shift);
594 return ($hrs * 60) + $min;
598 open(FILE
, "<$p2pfile") or die "Unable to read $p2pfile";
600 foreach my $p2pentry (<FILE
>) {
601 my @p2pline = split(/\;/, $p2pentry);
602 next unless ($p2pline[2] eq "off");
604 push(@protocols, "--$p2pline[1]");
608 run
("$IPTABLES -F P2PBLOCK");
610 run
("$IPTABLES -A P2PBLOCK -m ipp2p @protocols -j DROP");
615 # Flush iptables chain.
616 run
("$IPTABLES -F LOCATIONBLOCK");
618 # If location blocking is not enabled, we are finished here.
619 if ($locationsettings{'LOCATIONBLOCK_ENABLED'} ne "on") {
620 # Exit submodule. Process remaining script.
624 # Loop through all supported locations and
625 # create iptables rules, if blocking for this country
627 foreach my $location (@locations) {
628 if(exists $locationsettings{$location} && $locationsettings{$location} eq "on") {
629 run
("$IPTABLES -A LOCATIONBLOCK -m geoip --src-cc $location -j DROP");
638 my $uses_source_ports = ($$hash{$key}[7] eq "ON");
639 my $uses_services = ($$hash{$key}[11] eq "ON");
643 # Rules which don't have source ports or services (like ICMP, ESP, ...).
644 if (!$uses_source_ports && !$uses_services) {
645 push(@protocols, $$hash{$key}[8]);
647 # Rules which either use ports or services.
648 } elsif ($uses_source_ports || $uses_services) {
649 # Check if service group or service
650 if ($$hash{$key}[14] eq 'cust_srv') {
651 push(@protocols, &fwlib
::get_srv_prot
($$hash{$key}[15]));
653 } elsif($$hash{$key}[14] eq 'cust_srvgrp'){
654 my $protos = &fwlib
::get_srvgrp_prot
($$hash{$key}[15]);
655 push(@protocols, split(",", $protos));
658 # Fetch the protocol for this rule.
659 my $protocol = lc($$hash{$key}[8]);
661 # Fetch source and destination ports for this rule.
662 my $source_ports = $$hash{$key}[10];
663 my $destination_ports = $$hash{$key}[15];
665 # Check if ports are set for protocols which do not support ports.
666 if (!($protocol ~~ @PROTOCOLS_WITH_PORTS) && ($source_ports || $destination_ports)) {
667 print_error
("$protocol does not support ports");
671 push(@protocols, $protocol);
675 # Remove all empty elements
676 @protocols = map { $_ ?
$_ : () } @protocols;
678 # If no protocol has been defined, we assume "all".
680 push(@protocols, "all");
683 # Make all protocol names lowercase.
684 @protocols = map { lc } @protocols;
689 sub get_protocol_options
{
692 my $protocol = shift;
693 my $nat_options_wanted = shift;
696 # Nothing to do if no protocol is specified.
697 if ($protocol eq "all") {
700 push(@options, ("-p", $protocol));
703 if ($protocol ~~ @PROTOCOLS_WITH_PORTS) {
704 # Process source ports.
705 my $use_src_ports = ($$hash{$key}[7] eq "ON");
706 my $src_ports = $$hash{$key}[10];
708 if ($use_src_ports && $src_ports) {
709 push(@options, &format_ports
($src_ports, "src"));
712 # Process destination ports.
713 my $use_dst_ports = ($$hash{$key}[11] eq "ON");
714 my $use_dnat = (($$hash{$key}[28] eq "ON") && ($$hash{$key}[31] eq "dnat"));
716 if ($use_dst_ports) {
717 my $dst_ports_mode = $$hash{$key}[14];
718 my $dst_ports = $$hash{$key}[15];
720 if (($dst_ports_mode eq "TGT_PORT") && $dst_ports) {
721 if ($nat_options_wanted && $use_dnat && $$hash{$key}[30]) {
722 $dst_ports = $$hash{$key}[30];
724 push(@options, &format_ports
($dst_ports, "dst"));
726 } elsif ($dst_ports_mode eq "cust_srv") {
727 if ($protocol eq "ICMP") {
728 push(@options, ("--icmp-type", &fwlib
::get_srv_port
($dst_ports, 3, "ICMP")));
730 $dst_ports = &fwlib
::get_srv_port
($dst_ports, 1, uc($protocol));
731 push(@options, &format_ports
($dst_ports, "dst"));
734 } elsif ($dst_ports_mode eq "cust_srvgrp") {
735 push(@options, &fwlib
::get_srvgrp_port
($dst_ports, uc($protocol)));
740 # Check if a single ICMP type is selected.
741 if ($protocol eq "icmp") {
742 my $icmp_type = $$hash{$key}[9];
744 if (($icmp_type ne "All ICMP-Types") && $icmp_type) {
745 push(@options, ("--icmp-type", $icmp_type));
757 if ($type eq "src") {
759 } elsif ($type eq "dst") {
765 if ($ports =~ /\|/) {
767 push(@options, ("-m", "multiport"));
771 push(@options, ($arg, $ports));
777 sub get_dnat_target_port
{
781 if ($$hash{$key}[14] eq "TGT_PORT") {
782 my $port = $$hash{$key}[15];
783 my $external_port = $$hash{$key}[30];
785 if ($external_port && ($port ne $external_port)) {
786 return $$hash{$key}[15];
791 sub add_dnat_mangle_rules
{
792 my $nat_address = shift;
793 my $interface = shift;
797 foreach my $zone ("GREEN", "BLUE", "ORANGE") {
800 # Skip rule if not all required information exists.
801 next unless (exists $defaultNetworks{$zone . "_NETADDRESS"});
802 next unless (exists $defaultNetworks{$zone . "_NETMASK"});
804 next if ($interface && $interface ne $defaultNetworks{$zone . "_DEV"});
806 my @mangle_options = @options;
808 my $netaddress = $defaultNetworks{$zone . "_NETADDRESS"};
809 $netaddress .= "/" . $defaultNetworks{$zone . "_NETMASK"};
811 push(@mangle_options, ("-s", $netaddress, "-d", $nat_address));
812 push(@mangle_options, ("-j", "MARK", "--set-mark", $mark));
814 run
("$IPTABLES -t mangle -A $CHAIN_MANGLE_NAT_DESTINATION_FIX @mangle_options");
818 sub make_log_limit_options
{
819 my @options = ("-m", "limit");
821 # Maybe we should get this from the configuration.
824 # We limit log messages to $limit messages per second.
825 push(@options, ("--limit", "$limit/second"));
827 # And we allow bursts of 2x $limit.
828 push(@options, ("--limit-burst", $limit * 2));
833 sub firewall_is_in_subnet
{
836 # ORANGE is missing here, because nothing may ever access
837 # the firewall from this network.
838 my $address = &fwlib
::get_internal_firewall_ip_address
($subnet, 0);