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 = (
62 my $NAT_MASK = 0x0f000000;
64 # Country code, which is used to mark hostile networks.
65 my $HOSTILE_CCODE = "XD";
69 my %defaultNetworks=();
73 my %configoutgoingfw=();
75 my %locationsettings = (
76 "LOCATIONBLOCK_ENABLED" => "off"
78 my %blocklistsettings= (
82 my %ipset_loaded_sets = ();
83 my @ipset_used_sets = ();
85 my $configfwdfw = "${General::swroot}/firewall/config";
86 my $configinput = "${General::swroot}/firewall/input";
87 my $configoutgoing = "${General::swroot}/firewall/outgoing";
88 my $locationfile = "${General::swroot}/firewall/locationblock";
89 my $configgrp = "${General::swroot}/fwhosts/customgroups";
90 my $netsettings = "${General::swroot}/ethernet/settings";
91 my $blocklistfile = "${General::swroot}/ipblocklist/settings";
93 &General
::readhash
("${General::swroot}/firewall/settings", \
%fwdfwsettings);
94 &General
::readhash
("${General::swroot}/optionsfw/settings", \
%fwoptions);
95 &General
::readhash
("$netsettings", \
%defaultNetworks);
96 &General
::readhasharray
($configfwdfw, \
%configfwdfw);
97 &General
::readhasharray
($configinput, \
%configinputfw);
98 &General
::readhasharray
($configoutgoing, \
%configoutgoingfw);
99 &General
::readhasharray
($configgrp, \
%customgrp);
101 # Check if the location settings file exists
102 if (-e
"$locationfile") {
104 &General
::readhash
("$locationfile", \
%locationsettings);
107 # Check if the ipblocklist settings file exits.
108 if (-e
"$blocklistfile") {
109 # Read-in settings file.
110 &General
::readhash
("$blocklistfile", \
%blocklistsettings);
113 # Get all available locations.
114 my @locations = &Location
::Functions
::get_locations
();
116 # Get all supported blocklists.
117 my @blocklists = &IPblocklist
::get_blocklists
();
119 # Name or the RED interface.
120 my $RED_DEV = &General
::get_red_interface
();
122 my @log_limit_options = &make_log_limit_options
();
124 my $POLICY_INPUT_ALLOWED = 0;
125 my $POLICY_FORWARD_ALLOWED = ($fwdfwsettings{"POLICY"} eq "MODE2");
126 my $POLICY_OUTPUT_ALLOWED = ($fwdfwsettings{"POLICY1"} eq "MODE2");
128 my $POLICY_INPUT_ACTION = $fwoptions{"FWPOLICY2"};
129 my $POLICY_FORWARD_ACTION = $fwoptions{"FWPOLICY"};
130 my $POLICY_OUTPUT_ACTION = $fwoptions{"FWPOLICY1"};
132 #workaround to suppress a warning when a variable is used only once
133 my @dummy = ( $Location::Functions
::ipset_db_directory
);
140 # Get currently used ipset sets.
141 @ipset_used_sets = &ipset_get_sets
();
146 # Prepare firewall rules.
147 if (! -z
"${General::swroot}/firewall/input"){
148 &buildrules
(\
%configinputfw);
150 if (! -z
"${General::swroot}/firewall/outgoing"){
151 &buildrules
(\
%configoutgoingfw);
153 if (! -z
"${General::swroot}/firewall/config"){
154 &buildrules
(\
%configfwdfw);
157 # Load Location block rules.
160 # Load rules to block hostile networks.
161 &drop_hostile_networks
();
163 # Handle ipblocklist.
166 # Reload firewall policy.
167 run
("/usr/sbin/firewall-policy");
169 # Cleanup not longer needed ipset sets.
172 #Reload firewall.local if present
173 if ( -f
'/etc/sysconfig/firewall.local'){
174 run
("/etc/sysconfig/firewall.local reload");
179 # Executes or prints the given shell command.
188 print_error
("ERROR: $command");
196 print STDERR
"$message\n";
206 printf(" %2d: %s", $i++, $_);
214 return scalar @
$hash;
218 run
("$IPTABLES -F $CHAIN_INPUT");
219 run
("$IPTABLES -F $CHAIN_FORWARD");
220 run
("$IPTABLES -F $CHAIN_OUTPUT");
221 run
("$IPTABLES -t nat -F $CHAIN_NAT_SOURCE");
222 run
("$IPTABLES -t nat -F $CHAIN_NAT_DESTINATION");
223 run
("$IPTABLES -t mangle -F $CHAIN_MANGLE_NAT_DESTINATION_FIX");
229 # Search for targets that need to be specially handled when adding
230 # forwarding rules. Additional rules will automatically get inserted
231 # into the INPUT/OUTPUT chains for these targets.
232 my @special_input_targets = ();
233 if (!$POLICY_FORWARD_ALLOWED) {
234 push(@special_input_targets, "ACCEPT");
237 if ($POLICY_INPUT_ACTION eq "DROP") {
238 push(@special_input_targets, ("ACCEPT", "REJECT"));
239 } elsif ($POLICY_INPUT_ACTION eq "REJECT") {
240 push(@special_input_targets, ("ACCEPT", "DROP"));
243 my @special_output_targets = ();
244 if ($POLICY_OUTPUT_ALLOWED) {
245 push(@special_output_targets, ("DROP", "REJECT"));
247 push(@special_output_targets, "ACCEPT");
249 if ($POLICY_OUTPUT_ACTION eq "DROP") {
250 push(@special_output_targets, ("ACCEPT", "REJECT"));
251 } elsif ($POLICY_OUTPUT_ACTION eq "REJECT") {
252 push(@special_output_targets, ("ACCEPT", "DROP"));
256 foreach my $key (sort {$a <=> $b} keys %$hash) {
257 # Skip disabled rules.
258 next unless ($$hash{$key}[2] eq 'ON');
260 # Count number of elements in this line
261 my $elements = &count_elements
($$hash{$key});
264 print_rule
($$hash{$key});
267 # Check if the target is valid.
268 my $target = $$hash{$key}[0];
269 if (!$target ~~ @VALID_TARGETS) {
270 print_error
("Invalid target '$target' for rule $key");
274 # Check if the chain is valid.
275 my $chain = $$hash{$key}[1];
276 if (!$chain ~~ @VALID_CHAINS) {
277 print_error
("Invalid chain '$chain' in rule $key");
281 # Collect all sources.
282 my @sources = &fwlib
::get_addresses
($hash, $key, "src");
284 # Collect all destinations.
285 my @destinations = &fwlib
::get_addresses
($hash, $key, "tgt");
287 # True if the destination is the firewall itself.
288 my $destination_is_firewall = ($$hash{$key}[5] eq "ipfire");
290 # Check if logging should be enabled.
291 my $LOG = ($$hash{$key}[17] eq 'ON');
293 # Check if NAT is enabled and initialize variables, that we use for that.
294 my $NAT = ($$hash{$key}[28] eq 'ON');
297 $NAT_MODE = uc($$hash{$key}[31]);
300 # Set up time constraints.
301 my @time_options = ();
302 if ($$hash{$key}[18] eq 'ON') {
303 push(@time_options, ("-m", "time"));
305 # Select all days of the week this match is active.
307 if ($$hash{$key}[19] ne '') {
308 push (@weekdays, "Mon");
310 if ($$hash{$key}[20] ne '') {
311 push (@weekdays, "Tue");
313 if ($$hash{$key}[21] ne '') {
314 push (@weekdays, "Wed");
316 if ($$hash{$key}[22] ne '') {
317 push (@weekdays, "Thu");
319 if ($$hash{$key}[23] ne '') {
320 push (@weekdays, "Fri");
322 if ($$hash{$key}[24] ne '') {
323 push (@weekdays, "Sat");
325 if ($$hash{$key}[25] ne '') {
326 push (@weekdays, "Sun");
329 push(@time_options, ("--weekdays", join(",", @weekdays)));
332 # Convert start time.
333 my $time_start = &format_time
($$hash{$key}[26]);
335 push(@time_options, ("--timestart", $time_start));
339 my $time_stop = &format_time
($$hash{$key}[27]);
341 push(@time_options, ("--timestop", $time_stop));
345 # Concurrent connection limit
346 my @ratelimit_options = ();
348 if (($elements ge 34) && ($$hash{$key}[32] eq 'ON')) {
349 my $conn_limit = $$hash{$key}[33];
351 if ($conn_limit ge 1) {
352 push(@ratelimit_options, ("-m", "connlimit"));
354 # Use the the entire source IP address
355 push(@ratelimit_options, "--connlimit-saddr");
356 push(@ratelimit_options, ("--connlimit-mask", "32"));
359 push(@ratelimit_options, ("--connlimit-upto", $conn_limit));
364 if (($elements ge 37) && ($$hash{$key}[34] eq 'ON')) {
365 my $rate_limit = "$$hash{$key}[35]/$$hash{$key}[36]";
368 push(@ratelimit_options, ("-m", "limit"));
369 push(@ratelimit_options, ("--limit", $rate_limit));
373 # Check which protocols are used in this rule and so that we can
374 # later group rules by protocols.
375 my @protocols = &get_protocols
($hash, $key);
377 print_error
("Invalid protocol configuration for rule $key");
381 foreach my $protocol (@protocols) {
382 # Check if the given protocol is supported.
383 if (($protocol ne "all") && (!$protocol ~~ @PROTOCOLS)) {
384 print_error
("Protocol $protocol is not supported (rule $key)");
388 # Prepare protocol options (like ICMP types, ports, etc...).
389 my @protocol_options = &get_protocol_options
($hash, $key, $protocol, 0);
391 # Check if this protocol knows ports.
392 my $protocol_has_ports = ($protocol ~~ @PROTOCOLS_WITH_PORTS);
394 foreach my $src (@sources) {
395 # Skip invalid source.
396 next unless (defined $src);
400 my $source = @
$src[0];
401 if ($source ~~ @ANY_ADDRESSES) {
405 # Make sure that $source is properly defined
406 next unless (defined $source);
408 my $source_intf = @
$src[1];
410 foreach my $dst (@destinations) {
411 # Skip invalid rules.
412 next unless (defined $dst);
413 next if (!$dst || ($dst eq "none"));
415 # Sanitize destination.
416 my $destination = @
$dst[0];
417 if ($destination ~~ @ANY_ADDRESSES) {
421 my $destination_intf = @
$dst[1];
423 # Array with iptables arguments.
427 if ($protocol ne "all") {
428 push(@options, @protocol_options);
431 # Prepare source options.
432 my @source_options = ();
433 if ($source =~ /mac/) {
434 push(@source_options, $source);
435 } elsif ($source =~ /-m set/) {
436 # Split given arguments into single chunks to
437 # obtain the set name.
438 my ($a, $b, $c, $loc_src, $e) = split(/ /, $source);
440 # Call function to load the networks list for this country.
441 &ipset_restore
($loc_src);
443 push(@source_options, $source);
445 push(@source_options, ("-s", $source));
448 # Prepare destination options.
449 my @destination_options = ();
450 if ($destination =~ /-m set/) {
451 # Split given arguments into single chunks to
452 # obtain the set name.
453 my ($a, $b, $c, $loc_dst, $e) = split(/ /, $destination);
455 # Call function to load the networks list for this country.
456 &ipset_restore
($loc_dst);
458 push(@destination_options, $destination);
459 } elsif ($destination) {
460 push(@destination_options, ("-d", $destination));
463 # Add source and destination interface to the filter rules.
464 # These are supposed to help filtering forged packets that originate
465 # from BLUE with an IP address from GREEN for instance.
466 my @source_intf_options = ();
468 push(@source_intf_options, ("-i", $source_intf));
471 my @destination_intf_options = ();
472 if ($destination_intf) {
473 push(@destination_intf_options, ("-o", $destination_intf));
476 # Add time constraint options.
477 push(@options, @time_options);
479 # Add ratelimiting option
480 push(@options, @ratelimit_options);
482 my $firewall_is_in_source_subnet = 1;
484 $firewall_is_in_source_subnet = &firewall_is_in_subnet
($source);
487 my $firewall_is_in_destination_subnet = 1;
489 $firewall_is_in_destination_subnet = &firewall_is_in_subnet
($destination);
494 my $nat_address = &fwlib
::get_nat_address
($$hash{$key}[29], $source);
496 # Skip NAT rules if the NAT address is unknown
497 # (i.e. no internet connection has been established, yet).
498 next unless ($nat_address);
501 if ($NAT_MODE eq "DNAT") {
502 my @nat_options = ();
503 if ($protocol ne "all") {
504 my @nat_protocol_options = &get_protocol_options
($hash, $key, $protocol, 1);
505 push(@nat_options, @nat_protocol_options);
509 push(@nat_options, @time_options);
511 # Determine if a REDIRECT rule should be created.
512 my $use_redirect = ($destination_is_firewall && !$destination && $protocol_has_ports);
514 # Make port-forwardings useable from the internal networks.
515 if (!$use_redirect) {
516 my @internal_addresses = &fwlib
::get_internal_firewall_ip_addresses
(1);
517 unless ($nat_address ~~ @internal_addresses) {
518 &add_dnat_mangle_rules
($nat_address, $source_intf, @nat_options);
522 # Add source options.
523 push(@nat_options, @source_options);
526 if (!$use_redirect) {
527 push(@nat_options, ("-d", $nat_address));
531 if ($protocol_has_ports) {
532 $dnat_port = &get_dnat_target_port
($hash, $key);
535 my @nat_action_options = ();
537 # Use iptables REDIRECT
539 push(@nat_action_options, ("-j", "REDIRECT"));
541 # Redirect to specified port if one has given.
543 push(@nat_action_options, ("--to-ports", $dnat_port));
548 if ($destination_is_firewall && !$destination) {
549 $destination = &fwlib
::get_external_address
();
551 next unless ($destination);
553 my ($dnat_address, $dnat_mask) = split("/", $destination);
554 @destination_options = ("-d", $dnat_address);
556 if ($protocol_has_ports) {
557 my $dnat_port = &get_dnat_target_port
($hash, $key);
560 $dnat_address .= ":$dnat_port";
564 push(@nat_action_options, ("-j", "DNAT", "--to-destination", $dnat_address));
568 run
("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @log_limit_options -j LOG --log-prefix 'DNAT '");
570 run
("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @nat_action_options");
573 } elsif ($NAT_MODE eq "SNAT") {
574 my @snat_options = ( "-m", "policy", "--dir", "out", "--pol", "none" );
575 my @nat_options = @options;
577 # Get addresses for the configured firewall interfaces.
578 my @local_addresses = &fwlib
::get_internal_firewall_ip_addresses
(1);
580 # Check if the nat_address is one of the local addresses.
581 foreach my $local_address (@local_addresses) {
582 if ($nat_address eq $local_address) {
583 # Clear SNAT options.
591 push(@nat_options, @destination_intf_options);
592 push(@nat_options, @source_options);
593 push(@nat_options, @destination_options);
596 run
("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options @snat_options @log_limit_options -j LOG --log-prefix 'SNAT '");
598 run
("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options @snat_options -j SNAT --to-source $nat_address");
602 push(@options, @source_options);
603 push(@options, @destination_options);
605 # Insert firewall rule.
607 run
("$IPTABLES -A $chain @options @source_intf_options @destination_intf_options @log_limit_options -j LOG --log-prefix '$chain '");
609 run
("$IPTABLES -A $chain @options @source_intf_options @destination_intf_options -j $target");
611 # Handle forwarding rules and add corresponding rules for firewall access.
612 if ($chain eq $CHAIN_FORWARD) {
613 # If the firewall is part of the destination subnet and access to the destination network
614 # is granted/forbidden for any network that the firewall itself is part of, we grant/forbid access
615 # for the firewall, too.
616 if ($firewall_is_in_destination_subnet && ($target ~~ @special_input_targets)) {
618 run
("$IPTABLES -A $CHAIN_INPUT @options @source_intf_options @log_limit_options -j LOG --log-prefix '$CHAIN_INPUT '");
620 run
("$IPTABLES -A $CHAIN_INPUT @options @source_intf_options -j $target");
624 if ($firewall_is_in_source_subnet && ($target ~~ @special_output_targets)) {
626 run
("$IPTABLES -A $CHAIN_OUTPUT @options @destination_intf_options @log_limit_options -j LOG --log-prefix '$CHAIN_OUTPUT '");
628 run
("$IPTABLES -A $CHAIN_OUTPUT @options @destination_intf_options -j $target");
637 # Formats the given timestamp into the iptables format which is "hh:mm" UTC.
641 # Convert the given time into minutes.
642 my $minutes = &time_convert_to_minutes
($val);
644 # Move the timestamp into UTC.
645 $minutes += &time_utc_offset
();
647 # Make sure $minutes is between 00:00 and 23:59.
652 if ($minutes > 1440) {
657 return sprintf("%02d:%02d", $minutes / 60, $minutes % 60);
660 # Calculates the offsets in minutes from the local timezone to UTC.
661 sub time_utc_offset
{
662 my @localtime = localtime(time);
663 my @gmtime = gmtime(time);
665 return ($gmtime[2] * 60 + $gmtime[1] % 60) - ($localtime[2] * 60 + $localtime[1] % 60);
668 # Takes a timestamp like "14:00" and converts it into minutes since midnight.
669 sub time_convert_to_minutes
{
670 my ($hrs, $min) = split(":", shift);
672 return ($hrs * 60) + $min;
676 # Flush LOCATIONBLOCK chain.
677 run
("$IPTABLES -F LOCATIONBLOCK");
679 # If location blocking is not enabled, we are finished here.
680 if ($locationsettings{'LOCATIONBLOCK_ENABLED'} ne "on") {
681 # Exit submodule. Process remaining script.
685 # Only check the RED interface, which is ppp0 in case of RED_TYPE being
686 # set to "PPPOE", and red0 in case of RED_TYPE not being empty otherwise.
687 if ($defaultNetworks{'RED_TYPE'} eq "PPPOE") {
688 run
("$IPTABLES -A LOCATIONBLOCK ! -i ppp0 -j RETURN");
689 } elsif ($defaultNetworks{'RED_DEV'} ne "") {
690 run
("$IPTABLES -A LOCATIONBLOCK ! -i $defaultNetworks{'RED_DEV'} -j RETURN");
693 # Do not check any private address space
694 foreach my $network (@PRIVATE_NETWORKS) {
695 run
("$IPTABLES -A LOCATIONBLOCK -s $network -j RETURN");
698 # Loop through all supported locations and
699 # create iptables rules, if blocking for this country
701 foreach my $location (@locations) {
702 if(exists $locationsettings{$location} && $locationsettings{$location} eq "on") {
703 # Call function to load the networks list for this country.
704 &ipset_restore
($location);
706 # Call iptables and create rule to use the loaded ipset list.
707 run
("$IPTABLES -A LOCATIONBLOCK -m set --match-set $location src -j DROP");
712 sub drop_hostile_networks
() {
713 # Flush the HOSTILE firewall chain.
714 run
("$IPTABLES -F HOSTILE");
716 # If dropping hostile networks is not enabled, we are finished here.
717 if ($fwoptions{'DROPHOSTILE'} ne "on") {
722 # Exit if there is no red interface.
723 return unless($RED_DEV);
725 # Call function to load the network list of hostile networks.
726 &ipset_restore
($HOSTILE_CCODE);
728 # Check traffic in incoming/outgoing direction and drop if it matches
729 run
("$IPTABLES -A HOSTILE -i $RED_DEV -m set --match-set $HOSTILE_CCODE src -j HOSTILE_DROP");
730 run
("$IPTABLES -A HOSTILE -o $RED_DEV -m set --match-set $HOSTILE_CCODE dst -j HOSTILE_DROP");
734 # Flush the ipblocklist chains.
735 run
("$IPTABLES -F BLOCKLISTIN");
736 run
("$IPTABLES -F BLOCKLISTOUT");
738 # Check if the blocklist feature is enabled.
739 if($blocklistsettings{'ENABLE'} eq "on") {
740 # Loop through the array of private networks.
741 foreach my $private_network (@PRIVATE_NETWORKS) {
742 # Create firewall rules to never block private networks.
743 run
("$IPTABLES -A BLOCKLISTIN -p ALL -i $RED_DEV -s $private_network -j RETURN");
744 run
("$IPTABLES -A BLOCKLISTOUT -p ALL -o $RED_DEV -d $private_network -j RETURN");
748 # Loop through the array of blocklists.
749 foreach my $blocklist (@blocklists) {
750 # Check if the blocklist feature and the current processed blocklist is enabled.
751 if(($blocklistsettings{'ENABLE'} eq "on") && ($blocklistsettings{$blocklist}) && ($blocklistsettings{$blocklist} eq "on")) {
752 # Call function to load the blocklist.
753 &ipset_restore
($blocklist);
755 # Call function to check if the corresponding iptables drop chain already has been created.
756 if(&firewall_chain_exists
("${blocklist}_DROP")) {
757 # Create iptables chain.
758 run
("$IPTABLES -N ${blocklist}_DROP");
761 run
("$IPTABLES -F ${blocklist}_DROP");
764 # Check if logging is enabled.
765 if(($blocklistsettings{'LOGGING'}) && ($blocklistsettings{'LOGGING'} eq "on")) {
766 # Create logging rule.
767 run
("$IPTABLES -A ${blocklist}_DROP -j LOG -m limit --limit 10/second --log-prefix \"BLKLST_$blocklist \"");
771 run
("$IPTABLES -A ${blocklist}_DROP -j DROP");
773 # Add the rules to check against the set
774 run
("$IPTABLES -A BLOCKLISTIN -p ALL -i $RED_DEV -m set --match-set $blocklist src -j ${blocklist}_DROP");
775 run
("$IPTABLES -A BLOCKLISTOUT -p ALL -o $RED_DEV -m set --match-set $blocklist dst -j ${blocklist}_DROP");
777 # IP blocklist or the blocklist is disabled.
779 # Check if the blocklist related iptables drop chain exits.
780 unless(&firewall_chain_exists
("${blocklist}_DROP")) {
782 run
("$IPTABLES -F ${blocklist}_DROP");
785 run
("$IPTABLES -X ${blocklist}_DROP");
795 my $uses_source_ports = ($$hash{$key}[7] eq "ON");
796 my $uses_services = ($$hash{$key}[11] eq "ON");
800 # Rules which don't have source ports or services (like ICMP, ESP, ...).
801 if (!$uses_source_ports && !$uses_services) {
802 push(@protocols, $$hash{$key}[8]);
804 # Rules which either use ports or services.
805 } elsif ($uses_source_ports || $uses_services) {
806 # Check if service group or service
807 if ($$hash{$key}[14] eq 'cust_srv') {
808 push(@protocols, &fwlib
::get_srv_prot
($$hash{$key}[15]));
810 } elsif($$hash{$key}[14] eq 'cust_srvgrp'){
811 my $protos = &fwlib
::get_srvgrp_prot
($$hash{$key}[15]);
812 push(@protocols, split(",", $protos));
815 # Fetch the protocol for this rule.
816 my $protocol = lc($$hash{$key}[8]);
818 # Fetch source and destination ports for this rule.
819 my $source_ports = $$hash{$key}[10];
820 my $destination_ports = $$hash{$key}[15];
822 # Check if ports are set for protocols which do not support ports.
823 if (!($protocol ~~ @PROTOCOLS_WITH_PORTS) && ($source_ports || $destination_ports)) {
824 print_error
("$protocol does not support ports");
828 push(@protocols, $protocol);
832 # Remove all empty elements
833 @protocols = map { $_ ?
$_ : () } @protocols;
835 # If no protocol has been defined, we assume "all".
837 push(@protocols, "all");
840 # Make all protocol names lowercase.
841 @protocols = map { lc } @protocols;
846 sub get_protocol_options
{
849 my $protocol = shift;
850 my $nat_options_wanted = shift;
853 # Nothing to do if no protocol is specified.
854 if ($protocol eq "all") {
857 push(@options, ("-p", $protocol));
860 if ($protocol ~~ @PROTOCOLS_WITH_PORTS) {
861 # Process source ports.
862 my $use_src_ports = ($$hash{$key}[7] eq "ON");
863 my $src_ports = $$hash{$key}[10];
865 if ($use_src_ports && $src_ports) {
866 push(@options, &format_ports
($src_ports, "src"));
869 # Process destination ports.
870 my $use_dst_ports = ($$hash{$key}[11] eq "ON");
871 my $use_dnat = (($$hash{$key}[28] eq "ON") && ($$hash{$key}[31] eq "dnat"));
873 if ($use_dst_ports) {
874 my $dst_ports_mode = $$hash{$key}[14];
875 my $dst_ports = $$hash{$key}[15];
877 if (($dst_ports_mode eq "TGT_PORT") && $dst_ports) {
878 if ($nat_options_wanted && $use_dnat && $$hash{$key}[30]) {
879 $dst_ports = $$hash{$key}[30];
881 push(@options, &format_ports
($dst_ports, "dst"));
883 } elsif ($dst_ports_mode eq "cust_srv") {
884 if ($protocol eq "ICMP") {
885 push(@options, ("--icmp-type", &fwlib
::get_srv_port
($dst_ports, 3, "ICMP")));
887 $dst_ports = &fwlib
::get_srv_port
($dst_ports, 1, uc($protocol));
888 push(@options, &format_ports
($dst_ports, "dst"));
891 } elsif ($dst_ports_mode eq "cust_srvgrp") {
892 push(@options, &fwlib
::get_srvgrp_port
($dst_ports, uc($protocol)));
897 # Check if a single ICMP type is selected.
898 if ($protocol eq "icmp") {
899 my $icmp_type = $$hash{$key}[9];
901 if (($icmp_type ne "All ICMP-Types") && $icmp_type) {
902 push(@options, ("--icmp-type", $icmp_type));
914 if ($type eq "src") {
916 } elsif ($type eq "dst") {
922 if ($ports =~ /\|/) {
924 push(@options, ("-m", "multiport"));
928 push(@options, ($arg, $ports));
934 sub get_dnat_target_port
{
938 if ($$hash{$key}[14] eq "TGT_PORT") {
939 my $port = $$hash{$key}[15];
940 my $external_port = $$hash{$key}[30];
942 if ($external_port && ($port ne $external_port)) {
943 return $$hash{$key}[15];
948 sub add_dnat_mangle_rules
{
949 my $nat_address = shift;
950 my $interface = shift;
953 my $mark = 0x01000000;
954 foreach my $zone ("GREEN", "BLUE", "ORANGE") {
955 # Skip rule if not all required information exists.
956 next unless (exists $defaultNetworks{$zone . "_NETADDRESS"});
957 next unless (exists $defaultNetworks{$zone . "_NETMASK"});
959 next if ($interface && $interface ne $defaultNetworks{$zone . "_DEV"});
961 my @mangle_options = @options;
963 my $netaddress = $defaultNetworks{$zone . "_NETADDRESS"};
964 $netaddress .= "/" . $defaultNetworks{$zone . "_NETMASK"};
966 push(@mangle_options, ("-s", $netaddress, "-d", $nat_address));
967 push(@mangle_options, ("-j", "MARK", "--set-xmark", "$mark/$NAT_MASK"));
969 run
("$IPTABLES -t mangle -A $CHAIN_MANGLE_NAT_DESTINATION_FIX @mangle_options");
975 sub make_log_limit_options
{
976 my @options = ("-m", "limit");
978 # Maybe we should get this from the configuration.
981 # We limit log messages to $limit messages per second.
982 push(@options, ("--limit", "$limit/second"));
984 # And we allow bursts of 2x $limit.
985 push(@options, ("--limit-burst", $limit * 2));
990 sub firewall_is_in_subnet
{
993 # ORANGE is missing here, because nothing may ever access
994 # the firewall from this network.
995 my $address = &fwlib
::get_internal_firewall_ip_address
($subnet, 0);
1004 sub firewall_chain_exists
($) {
1007 my $ret = &General
::system("iptables", "--wait", "-n", "-L", "$chain");
1012 sub ipset_get_sets
() {
1015 # Get all currently used ipset lists and store them in an array.
1016 my @output = `$IPSET -n list`;
1018 # Loop through the temporary array.
1019 foreach my $set (@output) {
1020 # Remove any newlines.
1023 # Add the set the array of used sets.
1027 # Display used sets in debug mode.
1029 print "Used ipset sets:\n";
1033 # Return the array of sets.
1037 sub ipset_restore
($) {
1040 # Empty variable to store the db file, which should be
1041 # restored by ipset.
1044 # Check if the set already has been loaded.
1045 if($ipset_loaded_sets{$set}) {
1046 # It already has been loaded - so there is nothing to do.
1050 # Check if the given set name is a country code.
1051 if($set ~~ @locations) {
1052 # Libloc adds the IP type (v4 or v6) as part of the set and file name.
1053 my $loc_set = "$set" . "v4";
1055 # The bare filename equals the set name.
1056 my $filename = $loc_set;
1058 # Libloc uses "ipset" as file extension.
1059 my $file_extension = "ipset";
1061 # Generate full path and filename for the ipset db file.
1062 my $db_file = "$Location::Functions::ipset_db_directory/$filename.$file_extension";
1064 # Call function to restore/load the set.
1065 &ipset_call_restore
($db_file);
1067 # Check if the set is already loaded (has been used before).
1068 if ($set ~~ @ipset_used_sets) {
1069 # The sets contains the IP type (v4 or v6) as part of the name.
1070 # The firewall rules matches against sets without that extension. So we safely
1071 # can swap or rename the sets to use the new ones.
1072 run
("$IPSET swap $loc_set $set");
1074 # If the set is not loaded, we have to rename it to proper use it.
1075 run
("$IPSET rename $loc_set $set");
1078 # Check if the given set name is a blocklist.
1079 } elsif ($set ~~ @blocklists) {
1080 # IPblocklist sets contains v4 as setname extension.
1081 my $set_name = "$set" . "v4";
1083 # Get the database file for the given blocklist.
1084 my $db_file = &IPblocklist
::get_ipset_db_file
($set);
1086 # Call function to restore/load the set.
1087 &ipset_call_restore
($db_file);
1089 # Check if the set is already loaded (has been used before).
1090 if ($set ~~ @ipset_used_sets) {
1092 run
("$IPSET swap $set_name $set");
1094 # Rename the set to proper use it.
1095 run
("$IPSET rename $set_name $set");
1099 # Store the restored set to the hash to prevent from loading it again.
1100 $ipset_loaded_sets{$set} = "1";
1103 sub ipset_call_restore
($) {
1106 # Check if the requested file exists.
1108 # Run ipset and restore the given set.
1109 run
("$IPSET restore -f $file");
1113 sub ipset_cleanup
() {
1114 # Reload the array of used sets.
1115 @ipset_used_sets = &ipset_get_sets
();
1117 # Loop through the array of used sets.
1118 foreach my $set (@ipset_used_sets) {
1119 # Check if this set is still in use.
1121 # In this case an entry in the loaded sets hash exists.
1122 unless($ipset_loaded_sets{$set}) {
1123 # Entry does not exist, so this set is not longer
1124 # used and can be destroyed.
1125 run
("$IPSET destroy $set");