2 ###############################################################################
4 # IPFire.org - A linux based firewall #
5 # Copyright (C) 2007-2020 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";
29 require "${General::swroot}/ipblocklist-functions.pl";
31 # Set to one to enable debugging mode.
34 my $IPTABLES = "iptables --wait";
38 my $CHAIN_INPUT = "INPUTFW";
39 my $CHAIN_FORWARD = "FORWARDFW";
40 my $CHAIN_OUTPUT = "OUTGOINGFW";
41 my $CHAIN = $CHAIN_FORWARD;
42 my $CHAIN_NAT_SOURCE = "NAT_SOURCE";
43 my $CHAIN_NAT_DESTINATION = "NAT_DESTINATION";
44 my $CHAIN_MANGLE_NAT_DESTINATION_FIX = "NAT_DESTINATION";
45 my @VALID_CHAINS = ($CHAIN_INPUT, $CHAIN_FORWARD, $CHAIN_OUTPUT);
46 my @ANY_ADDRESSES = ("0.0.0.0/0.0.0.0", "0.0.0.0/0", "0/0");
48 my @PROTOCOLS = ("tcp", "udp", "icmp", "igmp", "ah", "esp", "gre", "ipv6", "ipip");
49 my @PROTOCOLS_WITH_PORTS = ("tcp", "udp");
51 my @VALID_TARGETS = ("ACCEPT", "DROP", "REJECT");
53 my @PRIVATE_NETWORKS = (
61 my $NAT_MASK = 0x0f000000;
63 # Country code, which is used to mark hostile networks.
64 my $HOSTILE_CCODE = "XD";
68 my %defaultNetworks=();
72 my %configoutgoingfw=();
74 my %locationsettings = (
75 "LOCATIONBLOCK_ENABLED" => "off"
77 my %blocklistsettings= (
81 my %ipset_loaded_sets = ();
82 my @ipset_used_sets = ();
84 my $configfwdfw = "${General::swroot}/firewall/config";
85 my $configinput = "${General::swroot}/firewall/input";
86 my $configoutgoing = "${General::swroot}/firewall/outgoing";
87 my $locationfile = "${General::swroot}/firewall/locationblock";
88 my $configgrp = "${General::swroot}/fwhosts/customgroups";
89 my $netsettings = "${General::swroot}/ethernet/settings";
90 my $blocklistfile = "${General::swroot}/ipblocklist/settings";
92 &General
::readhash
("${General::swroot}/firewall/settings", \
%fwdfwsettings);
93 &General
::readhash
("${General::swroot}/optionsfw/settings", \
%fwoptions);
94 &General
::readhash
("$netsettings", \
%defaultNetworks);
95 &General
::readhasharray
($configfwdfw, \
%configfwdfw);
96 &General
::readhasharray
($configinput, \
%configinputfw);
97 &General
::readhasharray
($configoutgoing, \
%configoutgoingfw);
98 &General
::readhasharray
($configgrp, \
%customgrp);
100 # Check if the location settings file exists
101 if (-e
"$locationfile") {
103 &General
::readhash
("$locationfile", \
%locationsettings);
106 # Check if the ipblocklist settings file exits.
107 if (-e
"$blocklistfile") {
108 # Read-in settings file.
109 &General
::readhash
("$blocklistfile", \
%blocklistsettings);
112 # Get all available locations.
113 my @locations = &Location
::Functions
::get_locations
();
115 # Get all supported blocklists.
116 my @blocklists = &IPblocklist
::get_blocklists
();
118 # Name or the RED interface.
119 my $RED_DEV = &General
::get_red_interface
();
121 my @log_limit_options = &make_log_limit_options
();
123 my $POLICY_INPUT_ALLOWED = 0;
124 my $POLICY_FORWARD_ALLOWED = ($fwdfwsettings{"POLICY"} eq "MODE2");
125 my $POLICY_OUTPUT_ALLOWED = ($fwdfwsettings{"POLICY1"} eq "MODE2");
127 my $POLICY_INPUT_ACTION = $fwoptions{"FWPOLICY2"};
128 my $POLICY_FORWARD_ACTION = $fwoptions{"FWPOLICY"};
129 my $POLICY_OUTPUT_ACTION = $fwoptions{"FWPOLICY1"};
131 #workaround to suppress a warning when a variable is used only once
132 my @dummy = ( $Location::Functions
::ipset_db_directory
);
139 # Get currently used ipset sets.
140 @ipset_used_sets = &ipset_get_sets
();
145 # Prepare firewall rules.
146 if (! -z
"${General::swroot}/firewall/input"){
147 &buildrules
(\
%configinputfw);
149 if (! -z
"${General::swroot}/firewall/outgoing"){
150 &buildrules
(\
%configoutgoingfw);
152 if (! -z
"${General::swroot}/firewall/config"){
153 &buildrules
(\
%configfwdfw);
156 # Load Location block rules.
159 # Load rules to block hostile networks.
160 &drop_hostile_networks
();
162 # Handle ipblocklist.
165 # Reload firewall policy.
166 run
("/usr/sbin/firewall-policy");
168 # Cleanup not longer needed ipset sets.
171 #Reload firewall.local if present
172 if ( -f
'/etc/sysconfig/firewall.local'){
173 run
("/etc/sysconfig/firewall.local reload");
178 # Executes or prints the given shell command.
187 print_error
("ERROR: $command");
195 print STDERR
"$message\n";
205 printf(" %2d: %s", $i++, $_);
213 return scalar @
$hash;
217 run
("$IPTABLES -F $CHAIN_INPUT");
218 run
("$IPTABLES -F $CHAIN_FORWARD");
219 run
("$IPTABLES -F $CHAIN_OUTPUT");
220 run
("$IPTABLES -t nat -F $CHAIN_NAT_SOURCE");
221 run
("$IPTABLES -t nat -F $CHAIN_NAT_DESTINATION");
222 run
("$IPTABLES -t mangle -F $CHAIN_MANGLE_NAT_DESTINATION_FIX");
228 # Search for targets that need to be specially handled when adding
229 # forwarding rules. Additional rules will automatically get inserted
230 # into the INPUT/OUTPUT chains for these targets.
231 my @special_input_targets = ();
232 if (!$POLICY_FORWARD_ALLOWED) {
233 push(@special_input_targets, "ACCEPT");
236 if ($POLICY_INPUT_ACTION eq "DROP") {
237 push(@special_input_targets, ("ACCEPT", "REJECT"));
238 } elsif ($POLICY_INPUT_ACTION eq "REJECT") {
239 push(@special_input_targets, ("ACCEPT", "DROP"));
242 my @special_output_targets = ();
243 if ($POLICY_OUTPUT_ALLOWED) {
244 push(@special_output_targets, ("DROP", "REJECT"));
246 push(@special_output_targets, "ACCEPT");
248 if ($POLICY_OUTPUT_ACTION eq "DROP") {
249 push(@special_output_targets, ("ACCEPT", "REJECT"));
250 } elsif ($POLICY_OUTPUT_ACTION eq "REJECT") {
251 push(@special_output_targets, ("ACCEPT", "DROP"));
255 foreach my $key (sort {$a <=> $b} keys %$hash) {
256 # Skip disabled rules.
257 next unless ($$hash{$key}[2] eq 'ON');
259 # Count number of elements in this line
260 my $elements = &count_elements
($$hash{$key});
263 print_rule
($$hash{$key});
266 # Check if the target is valid.
267 my $target = $$hash{$key}[0];
268 if (!$target ~~ @VALID_TARGETS) {
269 print_error
("Invalid target '$target' for rule $key");
273 # Check if the chain is valid.
274 my $chain = $$hash{$key}[1];
275 if (!$chain ~~ @VALID_CHAINS) {
276 print_error
("Invalid chain '$chain' in rule $key");
280 # Collect all sources.
281 my @sources = &fwlib
::get_addresses
($hash, $key, "src");
283 # Collect all destinations.
284 my @destinations = &fwlib
::get_addresses
($hash, $key, "tgt");
286 # True if the destination is the firewall itself.
287 my $destination_is_firewall = ($$hash{$key}[5] eq "ipfire");
289 # Check if logging should be enabled.
290 my $LOG = ($$hash{$key}[17] eq 'ON');
292 # Check if NAT is enabled and initialize variables, that we use for that.
293 my $NAT = ($$hash{$key}[28] eq 'ON');
296 $NAT_MODE = uc($$hash{$key}[31]);
299 # Set up time constraints.
300 my @time_options = ();
301 if ($$hash{$key}[18] eq 'ON') {
302 push(@time_options, ("-m", "time"));
304 # Select all days of the week this match is active.
306 if ($$hash{$key}[19] ne '') {
307 push (@weekdays, "Mon");
309 if ($$hash{$key}[20] ne '') {
310 push (@weekdays, "Tue");
312 if ($$hash{$key}[21] ne '') {
313 push (@weekdays, "Wed");
315 if ($$hash{$key}[22] ne '') {
316 push (@weekdays, "Thu");
318 if ($$hash{$key}[23] ne '') {
319 push (@weekdays, "Fri");
321 if ($$hash{$key}[24] ne '') {
322 push (@weekdays, "Sat");
324 if ($$hash{$key}[25] ne '') {
325 push (@weekdays, "Sun");
328 push(@time_options, ("--weekdays", join(",", @weekdays)));
331 # Convert start time.
332 my $time_start = &format_time
($$hash{$key}[26]);
334 push(@time_options, ("--timestart", $time_start));
338 my $time_stop = &format_time
($$hash{$key}[27]);
340 push(@time_options, ("--timestop", $time_stop));
344 # Concurrent connection limit
345 my @ratelimit_options = ();
347 if (($elements ge 34) && ($$hash{$key}[32] eq 'ON')) {
348 my $conn_limit = $$hash{$key}[33];
350 if ($conn_limit ge 1) {
351 push(@ratelimit_options, ("-m", "connlimit"));
353 # Use the the entire source IP address
354 push(@ratelimit_options, "--connlimit-saddr");
355 push(@ratelimit_options, ("--connlimit-mask", "32"));
358 push(@ratelimit_options, ("--connlimit-upto", $conn_limit));
363 if (($elements ge 37) && ($$hash{$key}[34] eq 'ON')) {
364 my $rate_limit = "$$hash{$key}[35]/$$hash{$key}[36]";
367 push(@ratelimit_options, ("-m", "limit"));
368 push(@ratelimit_options, ("--limit", $rate_limit));
372 # Check which protocols are used in this rule and so that we can
373 # later group rules by protocols.
374 my @protocols = &get_protocols
($hash, $key);
376 print_error
("Invalid protocol configuration for rule $key");
380 foreach my $protocol (@protocols) {
381 # Check if the given protocol is supported.
382 if (($protocol ne "all") && (!$protocol ~~ @PROTOCOLS)) {
383 print_error
("Protocol $protocol is not supported (rule $key)");
387 # Prepare protocol options (like ICMP types, ports, etc...).
388 my @protocol_options = &get_protocol_options
($hash, $key, $protocol, 0);
390 # Check if this protocol knows ports.
391 my $protocol_has_ports = ($protocol ~~ @PROTOCOLS_WITH_PORTS);
393 foreach my $src (@sources) {
394 # Skip invalid source.
395 next unless (defined $src);
399 my $source = @
$src[0];
400 if ($source ~~ @ANY_ADDRESSES) {
404 # Make sure that $source is properly defined
405 next unless (defined $source);
407 my $source_intf = @
$src[1];
409 foreach my $dst (@destinations) {
410 # Skip invalid rules.
411 next unless (defined $dst);
412 next if (!$dst || ($dst eq "none"));
414 # Sanitize destination.
415 my $destination = @
$dst[0];
416 if ($destination ~~ @ANY_ADDRESSES) {
420 my $destination_intf = @
$dst[1];
422 # Array with iptables arguments.
426 if ($protocol ne "all") {
427 push(@options, @protocol_options);
430 # Prepare source options.
431 my @source_options = ();
432 if ($source =~ /mac/) {
433 push(@source_options, $source);
434 } elsif ($source =~ /-m set/) {
435 # Split given arguments into single chunks to
436 # obtain the set name.
437 my ($a, $b, $c, $loc_src, $e) = split(/ /, $source);
439 # Call function to load the networks list for this country.
440 &ipset_restore
($loc_src);
442 push(@source_options, $source);
444 push(@source_options, ("-s", $source));
447 # Prepare destination options.
448 my @destination_options = ();
449 if ($destination =~ /-m set/) {
450 # Split given arguments into single chunks to
451 # obtain the set name.
452 my ($a, $b, $c, $loc_dst, $e) = split(/ /, $destination);
454 # Call function to load the networks list for this country.
455 &ipset_restore
($loc_dst);
457 push(@destination_options, $destination);
458 } elsif ($destination) {
459 push(@destination_options, ("-d", $destination));
462 # Add source and destination interface to the filter rules.
463 # These are supposed to help filtering forged packets that originate
464 # from BLUE with an IP address from GREEN for instance.
465 my @source_intf_options = ();
467 push(@source_intf_options, ("-i", $source_intf));
470 my @destination_intf_options = ();
471 if ($destination_intf) {
472 push(@destination_intf_options, ("-o", $destination_intf));
475 # Add time constraint options.
476 push(@options, @time_options);
478 # Add ratelimiting option
479 push(@options, @ratelimit_options);
481 my $firewall_is_in_source_subnet = 1;
483 $firewall_is_in_source_subnet = &firewall_is_in_subnet
($source);
486 my $firewall_is_in_destination_subnet = 1;
488 $firewall_is_in_destination_subnet = &firewall_is_in_subnet
($destination);
493 my $nat_address = &fwlib
::get_nat_address
($$hash{$key}[29], $source);
495 # Skip NAT rules if the NAT address is unknown
496 # (i.e. no internet connection has been established, yet).
497 next unless ($nat_address);
500 if ($NAT_MODE eq "DNAT") {
501 my @nat_options = ();
502 if ($protocol ne "all") {
503 my @nat_protocol_options = &get_protocol_options
($hash, $key, $protocol, 1);
504 push(@nat_options, @nat_protocol_options);
508 push(@nat_options, @time_options);
510 # Determine if a REDIRECT rule should be created.
511 my $use_redirect = ($destination_is_firewall && !$destination && $protocol_has_ports);
513 # Make port-forwardings useable from the internal networks.
514 if (!$use_redirect) {
515 my @internal_addresses = &fwlib
::get_internal_firewall_ip_addresses
(1);
516 unless ($nat_address ~~ @internal_addresses) {
517 &add_dnat_mangle_rules
($nat_address, $source_intf, @nat_options);
521 # Add source options.
522 push(@nat_options, @source_options);
525 if (!$use_redirect) {
526 push(@nat_options, ("-d", $nat_address));
530 if ($protocol_has_ports) {
531 $dnat_port = &get_dnat_target_port
($hash, $key);
534 my @nat_action_options = ();
536 # Use iptables REDIRECT
538 push(@nat_action_options, ("-j", "REDIRECT"));
540 # Redirect to specified port if one has given.
542 push(@nat_action_options, ("--to-ports", $dnat_port));
547 if ($destination_is_firewall && !$destination) {
548 $destination = &fwlib
::get_external_address
();
550 next unless ($destination);
552 my ($dnat_address, $dnat_mask) = split("/", $destination);
553 @destination_options = ("-d", $dnat_address);
555 if ($protocol_has_ports) {
556 my $dnat_port = &get_dnat_target_port
($hash, $key);
559 $dnat_address .= ":$dnat_port";
563 push(@nat_action_options, ("-j", "DNAT", "--to-destination", $dnat_address));
567 run
("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @log_limit_options -j LOG --log-prefix 'DNAT '");
569 run
("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @nat_action_options");
572 } elsif ($NAT_MODE eq "SNAT") {
573 my @snat_options = ( "-m", "policy", "--dir", "out", "--pol", "none" );
574 my @nat_options = @options;
576 # Get addresses for the configured firewall interfaces.
577 my @local_addresses = &fwlib
::get_internal_firewall_ip_addresses
(1);
579 # Check if the nat_address is one of the local addresses.
580 foreach my $local_address (@local_addresses) {
581 if ($nat_address eq $local_address) {
582 # Clear SNAT options.
590 push(@nat_options, @destination_intf_options);
591 push(@nat_options, @source_options);
592 push(@nat_options, @destination_options);
595 run
("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options @snat_options @log_limit_options -j LOG --log-prefix 'SNAT '");
597 run
("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options @snat_options -j SNAT --to-source $nat_address");
601 push(@options, @source_options);
602 push(@options, @destination_options);
604 # Insert firewall rule.
606 run
("$IPTABLES -A $chain @options @source_intf_options @destination_intf_options @log_limit_options -j LOG --log-prefix '$chain '");
608 run
("$IPTABLES -A $chain @options @source_intf_options @destination_intf_options -j $target");
610 # Handle forwarding rules and add corresponding rules for firewall access.
611 if ($chain eq $CHAIN_FORWARD) {
612 # If the firewall is part of the destination subnet and access to the destination network
613 # is granted/forbidden for any network that the firewall itself is part of, we grant/forbid access
614 # for the firewall, too.
615 if ($firewall_is_in_destination_subnet && ($target ~~ @special_input_targets)) {
617 run
("$IPTABLES -A $CHAIN_INPUT @options @source_intf_options @log_limit_options -j LOG --log-prefix '$CHAIN_INPUT '");
619 run
("$IPTABLES -A $CHAIN_INPUT @options @source_intf_options -j $target");
623 if ($firewall_is_in_source_subnet && ($target ~~ @special_output_targets)) {
625 run
("$IPTABLES -A $CHAIN_OUTPUT @options @destination_intf_options @log_limit_options -j LOG --log-prefix '$CHAIN_OUTPUT '");
627 run
("$IPTABLES -A $CHAIN_OUTPUT @options @destination_intf_options -j $target");
636 # Formats the given timestamp into the iptables format which is "hh:mm" UTC.
640 # Convert the given time into minutes.
641 my $minutes = &time_convert_to_minutes
($val);
643 # Move the timestamp into UTC.
644 $minutes += &time_utc_offset
();
646 # Make sure $minutes is between 00:00 and 23:59.
651 if ($minutes > 1440) {
656 return sprintf("%02d:%02d", $minutes / 60, $minutes % 60);
659 # Calculates the offsets in minutes from the local timezone to UTC.
660 sub time_utc_offset
{
661 my @localtime = localtime(time);
662 my @gmtime = gmtime(time);
664 return ($gmtime[2] * 60 + $gmtime[1] % 60) - ($localtime[2] * 60 + $localtime[1] % 60);
667 # Takes a timestamp like "14:00" and converts it into minutes since midnight.
668 sub time_convert_to_minutes
{
669 my ($hrs, $min) = split(":", shift);
671 return ($hrs * 60) + $min;
675 # Flush LOCATIONBLOCK chain.
676 run
("$IPTABLES -F LOCATIONBLOCK");
678 # If location blocking is not enabled, we are finished here.
679 if ($locationsettings{'LOCATIONBLOCK_ENABLED'} ne "on") {
680 # Exit submodule. Process remaining script.
684 # Only check the RED interface, which is ppp0 in case of RED_TYPE being
685 # set to "PPPOE", and red0 in case of RED_TYPE not being empty otherwise.
686 if ($defaultNetworks{'RED_TYPE'} eq "PPPOE") {
687 run
("$IPTABLES -A LOCATIONBLOCK ! -i ppp0 -j RETURN");
688 } elsif ($defaultNetworks{'RED_DEV'} ne "") {
689 run
("$IPTABLES -A LOCATIONBLOCK ! -i $defaultNetworks{'RED_DEV'} -j RETURN");
692 # Do not check any private address space
693 foreach my $network (@PRIVATE_NETWORKS) {
694 run
("$IPTABLES -A LOCATIONBLOCK -s $network -j RETURN");
697 # Loop through all supported locations and
698 # create iptables rules, if blocking for this country
700 foreach my $location (@locations) {
701 if(exists $locationsettings{$location} && $locationsettings{$location} eq "on") {
702 # Call function to load the networks list for this country.
703 &ipset_restore
($location);
705 # Call iptables and create rule to use the loaded ipset list.
706 run
("$IPTABLES -A LOCATIONBLOCK -m set --match-set $location src -j DROP");
711 sub drop_hostile_networks
() {
712 # Flush the HOSTILE firewall chain.
713 run
("$IPTABLES -F HOSTILE");
715 # If dropping hostile networks is not enabled, we are finished here.
716 if ($fwoptions{'DROPHOSTILE'} ne "on") {
721 # Exit if there is no red interface.
722 return unless($RED_DEV);
724 # Call function to load the network list of hostile networks.
725 &ipset_restore
($HOSTILE_CCODE);
727 # Check traffic in incoming/outgoing direction and drop if it matches
728 run
("$IPTABLES -A HOSTILE -i $RED_DEV -m set --match-set $HOSTILE_CCODE src -j HOSTILE_DROP");
729 run
("$IPTABLES -A HOSTILE -o $RED_DEV -m set --match-set $HOSTILE_CCODE dst -j HOSTILE_DROP");
733 # Flush the ipblocklist chains.
734 run
("$IPTABLES -F BLOCKLISTIN");
735 run
("$IPTABLES -F BLOCKLISTOUT");
737 # Check if the blocklist feature is enabled.
738 if($blocklistsettings{'ENABLE'} eq "on") {
739 # Loop through the array of private networks.
740 foreach my $private_network (@PRIVATE_NETWORKS) {
741 # Create firewall rules to never block private networks.
742 run
("$IPTABLES -A BLOCKLISTIN -p ALL -i $RED_DEV -s $private_network -j RETURN");
743 run
("$IPTABLES -A BLOCKLISTOUT -p ALL -o $RED_DEV -d $private_network -j RETURN");
747 # Loop through the array of blocklists.
748 foreach my $blocklist (@blocklists) {
749 # Check if the blocklist feature and the current processed blocklist is enabled.
750 if(($blocklistsettings{'ENABLE'} eq "on") && ($blocklistsettings{$blocklist}) && ($blocklistsettings{$blocklist} eq "on")) {
751 # Call function to load the blocklist.
752 &ipset_restore
($blocklist);
754 # Call function to check if the corresponding iptables drop chain already has been created.
755 if(&firewall_chain_exists
("${blocklist}_DROP")) {
756 # Create iptables chain.
757 run
("$IPTABLES -N ${blocklist}_DROP");
760 run
("$IPTABLES -F ${blocklist}_DROP");
763 # Check if logging is enabled.
764 if(($blocklistsettings{'LOGGING'}) && ($blocklistsettings{'LOGGING'} eq "on")) {
765 # Create logging rule.
766 run
("$IPTABLES -A ${blocklist}_DROP -j LOG -m limit --limit 10/second --log-prefix \"BLKLST_$blocklist \"");
770 run
("$IPTABLES -A ${blocklist}_DROP -j DROP");
772 # Add the rules to check against the set
773 run
("$IPTABLES -A BLOCKLISTIN -p ALL -i $RED_DEV -m set --match-set $blocklist src -j ${blocklist}_DROP");
774 run
("$IPTABLES -A BLOCKLISTOUT -p ALL -o $RED_DEV -m set --match-set $blocklist dst -j ${blocklist}_DROP");
776 # IP blocklist or the blocklist is disabled.
778 # Check if the blocklist related iptables drop chain exits.
779 unless(&firewall_chain_exists
("${blocklist}_DROP")) {
781 run
("$IPTABLES -F ${blocklist}_DROP");
784 run
("$IPTABLES -X ${blocklist}_DROP");
794 my $uses_source_ports = ($$hash{$key}[7] eq "ON");
795 my $uses_services = ($$hash{$key}[11] eq "ON");
799 # Rules which don't have source ports or services (like ICMP, ESP, ...).
800 if (!$uses_source_ports && !$uses_services) {
801 push(@protocols, $$hash{$key}[8]);
803 # Rules which either use ports or services.
804 } elsif ($uses_source_ports || $uses_services) {
805 # Check if service group or service
806 if ($$hash{$key}[14] eq 'cust_srv') {
807 push(@protocols, &fwlib
::get_srv_prot
($$hash{$key}[15]));
809 } elsif($$hash{$key}[14] eq 'cust_srvgrp'){
810 my $protos = &fwlib
::get_srvgrp_prot
($$hash{$key}[15]);
811 push(@protocols, split(",", $protos));
814 # Fetch the protocol for this rule.
815 my $protocol = lc($$hash{$key}[8]);
817 # Fetch source and destination ports for this rule.
818 my $source_ports = $$hash{$key}[10];
819 my $destination_ports = $$hash{$key}[15];
821 # Check if ports are set for protocols which do not support ports.
822 if (!($protocol ~~ @PROTOCOLS_WITH_PORTS) && ($source_ports || $destination_ports)) {
823 print_error
("$protocol does not support ports");
827 push(@protocols, $protocol);
831 # Remove all empty elements
832 @protocols = map { $_ ?
$_ : () } @protocols;
834 # If no protocol has been defined, we assume "all".
836 push(@protocols, "all");
839 # Make all protocol names lowercase.
840 @protocols = map { lc } @protocols;
845 sub get_protocol_options
{
848 my $protocol = shift;
849 my $nat_options_wanted = shift;
852 # Nothing to do if no protocol is specified.
853 if ($protocol eq "all") {
856 push(@options, ("-p", $protocol));
859 if ($protocol ~~ @PROTOCOLS_WITH_PORTS) {
860 # Process source ports.
861 my $use_src_ports = ($$hash{$key}[7] eq "ON");
862 my $src_ports = $$hash{$key}[10];
864 if ($use_src_ports && $src_ports) {
865 push(@options, &format_ports
($src_ports, "src"));
868 # Process destination ports.
869 my $use_dst_ports = ($$hash{$key}[11] eq "ON");
870 my $use_dnat = (($$hash{$key}[28] eq "ON") && ($$hash{$key}[31] eq "dnat"));
872 if ($use_dst_ports) {
873 my $dst_ports_mode = $$hash{$key}[14];
874 my $dst_ports = $$hash{$key}[15];
876 if (($dst_ports_mode eq "TGT_PORT") && $dst_ports) {
877 if ($nat_options_wanted && $use_dnat && $$hash{$key}[30]) {
878 $dst_ports = $$hash{$key}[30];
880 push(@options, &format_ports
($dst_ports, "dst"));
882 } elsif ($dst_ports_mode eq "cust_srv") {
883 if ($protocol eq "ICMP") {
884 push(@options, ("--icmp-type", &fwlib
::get_srv_port
($dst_ports, 3, "ICMP")));
886 $dst_ports = &fwlib
::get_srv_port
($dst_ports, 1, uc($protocol));
887 push(@options, &format_ports
($dst_ports, "dst"));
890 } elsif ($dst_ports_mode eq "cust_srvgrp") {
891 push(@options, &fwlib
::get_srvgrp_port
($dst_ports, uc($protocol)));
896 # Check if a single ICMP type is selected.
897 if ($protocol eq "icmp") {
898 my $icmp_type = $$hash{$key}[9];
900 if (($icmp_type ne "All ICMP-Types") && $icmp_type) {
901 push(@options, ("--icmp-type", $icmp_type));
913 if ($type eq "src") {
915 } elsif ($type eq "dst") {
921 if ($ports =~ /\|/) {
923 push(@options, ("-m", "multiport"));
927 push(@options, ($arg, $ports));
933 sub get_dnat_target_port
{
937 if ($$hash{$key}[14] eq "TGT_PORT") {
938 my $port = $$hash{$key}[15];
939 my $external_port = $$hash{$key}[30];
941 if ($external_port && ($port ne $external_port)) {
942 return $$hash{$key}[15];
947 sub add_dnat_mangle_rules
{
948 my $nat_address = shift;
949 my $interface = shift;
952 my $mark = 0x01000000;
953 foreach my $zone ("GREEN", "BLUE", "ORANGE") {
954 # Skip rule if not all required information exists.
955 next unless (exists $defaultNetworks{$zone . "_NETADDRESS"});
956 next unless (exists $defaultNetworks{$zone . "_NETMASK"});
958 next if ($interface && $interface ne $defaultNetworks{$zone . "_DEV"});
960 my @mangle_options = @options;
962 my $netaddress = $defaultNetworks{$zone . "_NETADDRESS"};
963 $netaddress .= "/" . $defaultNetworks{$zone . "_NETMASK"};
965 push(@mangle_options, ("-s", $netaddress, "-d", $nat_address));
966 push(@mangle_options, ("-j", "MARK", "--set-xmark", "$mark/$NAT_MASK"));
968 run
("$IPTABLES -t mangle -A $CHAIN_MANGLE_NAT_DESTINATION_FIX @mangle_options");
974 sub make_log_limit_options
{
975 my @options = ("-m", "limit");
977 # Maybe we should get this from the configuration.
980 # We limit log messages to $limit messages per second.
981 push(@options, ("--limit", "$limit/second"));
983 # And we allow bursts of 2x $limit.
984 push(@options, ("--limit-burst", $limit * 2));
989 sub firewall_is_in_subnet
{
992 # ORANGE is missing here, because nothing may ever access
993 # the firewall from this network.
994 my $address = &fwlib
::get_internal_firewall_ip_address
($subnet, 0);
1003 sub firewall_chain_exists
($) {
1006 my $ret = &General
::system("iptables", "--wait", "-n", "-L", "$chain");
1011 sub ipset_get_sets
() {
1014 # Get all currently used ipset lists and store them in an array.
1015 my @output = `$IPSET -n list`;
1017 # Loop through the temporary array.
1018 foreach my $set (@output) {
1019 # Remove any newlines.
1022 # Add the set the array of used sets.
1026 # Display used sets in debug mode.
1028 print "Used ipset sets:\n";
1032 # Return the array of sets.
1036 sub ipset_restore
($) {
1039 # Empty variable to store the db file, which should be
1040 # restored by ipset.
1043 # Check if the set already has been loaded.
1044 if($ipset_loaded_sets{$set}) {
1045 # It already has been loaded - so there is nothing to do.
1049 # Check if the given set name is a country code.
1050 if($set ~~ @locations) {
1051 # Libloc adds the IP type (v4 or v6) as part of the set and file name.
1052 my $loc_set = "$set" . "v4";
1054 # The bare filename equals the set name.
1055 my $filename = $loc_set;
1057 # Libloc uses "ipset" as file extension.
1058 my $file_extension = "ipset";
1060 # Generate full path and filename for the ipset db file.
1061 my $db_file = "$Location::Functions::ipset_db_directory/$filename.$file_extension";
1063 # Call function to restore/load the set.
1064 &ipset_call_restore
($db_file);
1066 # Check if the set is already loaded (has been used before).
1067 if ($set ~~ @ipset_used_sets) {
1068 # The sets contains the IP type (v4 or v6) as part of the name.
1069 # The firewall rules matches against sets without that extension. So we safely
1070 # can swap or rename the sets to use the new ones.
1071 run
("$IPSET swap $loc_set $set");
1073 # If the set is not loaded, we have to rename it to proper use it.
1074 run
("$IPSET rename $loc_set $set");
1077 # Check if the given set name is a blocklist.
1078 } elsif ($set ~~ @blocklists) {
1079 # IPblocklist sets contains v4 as setname extension.
1080 my $set_name = "$set" . "v4";
1082 # Get the database file for the given blocklist.
1083 my $db_file = &IPblocklist
::get_ipset_db_file
($set);
1085 # Call function to restore/load the set.
1086 &ipset_call_restore
($db_file);
1088 # Check if the set is already loaded (has been used before).
1089 if ($set ~~ @ipset_used_sets) {
1091 run
("$IPSET swap $set_name $set");
1093 # Rename the set to proper use it.
1094 run
("$IPSET rename $set_name $set");
1098 # Store the restored set to the hash to prevent from loading it again.
1099 $ipset_loaded_sets{$set} = "1";
1102 sub ipset_call_restore
($) {
1105 # Check if the requested file exists.
1107 # Run ipset and restore the given set.
1108 run
("$IPSET restore -f $file");
1112 sub ipset_cleanup
() {
1113 # Reload the array of used sets.
1114 @ipset_used_sets = &ipset_get_sets
();
1116 # Loop through the array of used sets.
1117 foreach my $set (@ipset_used_sets) {
1118 # Check if this set is still in use.
1120 # In this case an entry in the loaded sets hash exists.
1121 unless($ipset_loaded_sets{$set}) {
1122 # Entry does not exist, so this set is not longer
1123 # used and can be destroyed.
1124 run
("$IPSET destroy $set");