]> git.ipfire.org Git - ipfire-2.x.git/blob - config/firewall/rules.pl
rules.pl: Do not try to restore the same ipset multiple times.
[ipfire-2.x.git] / config / firewall / rules.pl
1 #!/usr/bin/perl -w
2 ###############################################################################
3 # #
4 # IPFire.org - A linux based firewall #
5 # Copyright (C) 2007-2020 IPFire Team <info@ipfire.org> #
6 # #
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. #
11 # #
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. #
16 # #
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/>. #
19 # #
20 ###############################################################################
21
22 use strict;
23 use experimental 'smartmatch';
24
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
30 # Set to one to enable debugging mode.
31 my $DEBUG = 0;
32
33 my $IPTABLES = "iptables --wait";
34 my $IPSET = "ipset";
35
36 # iptables chains
37 my $CHAIN_INPUT = "INPUTFW";
38 my $CHAIN_FORWARD = "FORWARDFW";
39 my $CHAIN_OUTPUT = "OUTGOINGFW";
40 my $CHAIN = $CHAIN_FORWARD;
41 my $CHAIN_NAT_SOURCE = "NAT_SOURCE";
42 my $CHAIN_NAT_DESTINATION = "NAT_DESTINATION";
43 my $CHAIN_MANGLE_NAT_DESTINATION_FIX = "NAT_DESTINATION";
44 my @VALID_CHAINS = ($CHAIN_INPUT, $CHAIN_FORWARD, $CHAIN_OUTPUT);
45 my @ANY_ADDRESSES = ("0.0.0.0/0.0.0.0", "0.0.0.0/0", "0/0");
46
47 my @PROTOCOLS = ("tcp", "udp", "icmp", "igmp", "ah", "esp", "gre", "ipv6", "ipip");
48 my @PROTOCOLS_WITH_PORTS = ("tcp", "udp");
49
50 my @VALID_TARGETS = ("ACCEPT", "DROP", "REJECT");
51
52 my @PRIVATE_NETWORKS = (
53 "10.0.0.0/8",
54 "172.16.0.0/12",
55 "192.168.0.0/16",
56 "100.64.0.0/10",
57 );
58
59 # MARK masks
60 my $NAT_MASK = 0x0f000000;
61
62 my %fwdfwsettings=();
63 my %fwoptions = ();
64 my %defaultNetworks=();
65 my %configfwdfw=();;
66 my %customgrp=();
67 my %configinputfw=();
68 my %configoutgoingfw=();
69 my %confignatfw=();
70 my %locationsettings = (
71 "LOCATIONBLOCK_ENABLED" => "off"
72 );
73 my %loaded_ipset_lists=();
74
75 my @p2ps=();
76
77 my $configfwdfw = "${General::swroot}/firewall/config";
78 my $configinput = "${General::swroot}/firewall/input";
79 my $configoutgoing = "${General::swroot}/firewall/outgoing";
80 my $p2pfile = "${General::swroot}/firewall/p2protocols";
81 my $locationfile = "${General::swroot}/firewall/locationblock";
82 my $configgrp = "${General::swroot}/fwhosts/customgroups";
83 my $netsettings = "${General::swroot}/ethernet/settings";
84
85 &General::readhash("${General::swroot}/firewall/settings", \%fwdfwsettings);
86 &General::readhash("${General::swroot}/optionsfw/settings", \%fwoptions);
87 &General::readhash("$netsettings", \%defaultNetworks);
88 &General::readhasharray($configfwdfw, \%configfwdfw);
89 &General::readhasharray($configinput, \%configinputfw);
90 &General::readhasharray($configoutgoing, \%configoutgoingfw);
91 &General::readhasharray($configgrp, \%customgrp);
92
93 # Check if the location settings file exists
94 if (-e "$locationfile") {
95 # Read settings file
96 &General::readhash("$locationfile", \%locationsettings);
97 }
98
99 # Get all available locations.
100 my @locations = &Location::Functions::get_locations();
101
102 my @log_limit_options = &make_log_limit_options();
103
104 my $POLICY_INPUT_ALLOWED = 0;
105 my $POLICY_FORWARD_ALLOWED = ($fwdfwsettings{"POLICY"} eq "MODE2");
106 my $POLICY_OUTPUT_ALLOWED = ($fwdfwsettings{"POLICY1"} eq "MODE2");
107
108 my $POLICY_INPUT_ACTION = $fwoptions{"FWPOLICY2"};
109 my $POLICY_FORWARD_ACTION = $fwoptions{"FWPOLICY"};
110 my $POLICY_OUTPUT_ACTION = $fwoptions{"FWPOLICY1"};
111
112 # MAIN
113 &main();
114
115 sub main {
116 # Flush all chains.
117 &flush();
118
119 # Destroy all existing ipsets.
120 run("$IPSET destroy");
121
122 # Prepare firewall rules.
123 if (! -z "${General::swroot}/firewall/input"){
124 &buildrules(\%configinputfw);
125 }
126 if (! -z "${General::swroot}/firewall/outgoing"){
127 &buildrules(\%configoutgoingfw);
128 }
129 if (! -z "${General::swroot}/firewall/config"){
130 &buildrules(\%configfwdfw);
131 }
132
133 # Load P2P block rules.
134 &p2pblock();
135
136 # Load Location block rules.
137 &locationblock();
138
139 # Reload firewall policy.
140 run("/usr/sbin/firewall-policy");
141
142 #Reload firewall.local if present
143 if ( -f '/etc/sysconfig/firewall.local'){
144 run("/etc/sysconfig/firewall.local reload");
145 }
146 }
147
148 sub run {
149 # Executes or prints the given shell command.
150 my $command = shift;
151
152 if ($DEBUG) {
153 print "$command\n";
154 } else {
155 system "$command";
156
157 if ($?) {
158 print_error("ERROR: $command");
159 }
160 }
161 }
162
163 sub print_error {
164 my $message = shift;
165
166 print STDERR "$message\n";
167 }
168
169 sub print_rule {
170 my $hash = shift;
171
172 print "\nRULE:";
173
174 my $i = 0;
175 foreach (@$hash) {
176 printf(" %2d: %s", $i++, $_);
177 }
178 print "\n";
179 }
180
181 sub count_elements {
182 my $hash = shift;
183
184 return scalar @$hash;
185 }
186
187 sub flush {
188 run("$IPTABLES -F $CHAIN_INPUT");
189 run("$IPTABLES -F $CHAIN_FORWARD");
190 run("$IPTABLES -F $CHAIN_OUTPUT");
191 run("$IPTABLES -t nat -F $CHAIN_NAT_SOURCE");
192 run("$IPTABLES -t nat -F $CHAIN_NAT_DESTINATION");
193 run("$IPTABLES -t mangle -F $CHAIN_MANGLE_NAT_DESTINATION_FIX");
194
195 # Flush LOCATIONBLOCK chain.
196 run("$IPTABLES -F LOCATIONBLOCK");
197 }
198
199 sub buildrules {
200 my $hash = shift;
201
202 # Search for targets that need to be specially handled when adding
203 # forwarding rules. Additional rules will automatically get inserted
204 # into the INPUT/OUTPUT chains for these targets.
205 my @special_input_targets = ();
206 if (!$POLICY_FORWARD_ALLOWED) {
207 push(@special_input_targets, "ACCEPT");
208 }
209
210 if ($POLICY_INPUT_ACTION eq "DROP") {
211 push(@special_input_targets, ("ACCEPT", "REJECT"));
212 } elsif ($POLICY_INPUT_ACTION eq "REJECT") {
213 push(@special_input_targets, ("ACCEPT", "DROP"));
214 }
215
216 my @special_output_targets = ();
217 if ($POLICY_OUTPUT_ALLOWED) {
218 push(@special_output_targets, ("DROP", "REJECT"));
219 } else {
220 push(@special_output_targets, "ACCEPT");
221
222 if ($POLICY_OUTPUT_ACTION eq "DROP") {
223 push(@special_output_targets, ("ACCEPT", "REJECT"));
224 } elsif ($POLICY_OUTPUT_ACTION eq "REJECT") {
225 push(@special_output_targets, ("ACCEPT", "DROP"));
226 }
227 }
228
229 foreach my $key (sort {$a <=> $b} keys %$hash) {
230 # Skip disabled rules.
231 next unless ($$hash{$key}[2] eq 'ON');
232
233 # Count number of elements in this line
234 my $elements = &count_elements($$hash{$key});
235
236 if ($DEBUG) {
237 print_rule($$hash{$key});
238 }
239
240 # Check if the target is valid.
241 my $target = $$hash{$key}[0];
242 if (!$target ~~ @VALID_TARGETS) {
243 print_error("Invalid target '$target' for rule $key");
244 next;
245 }
246
247 # Check if the chain is valid.
248 my $chain = $$hash{$key}[1];
249 if (!$chain ~~ @VALID_CHAINS) {
250 print_error("Invalid chain '$chain' in rule $key");
251 next;
252 }
253
254 # Collect all sources.
255 my @sources = &fwlib::get_addresses($hash, $key, "src");
256
257 # Collect all destinations.
258 my @destinations = &fwlib::get_addresses($hash, $key, "tgt");
259
260 # True if the destination is the firewall itself.
261 my $destination_is_firewall = ($$hash{$key}[5] eq "ipfire");
262
263 # Check if logging should be enabled.
264 my $LOG = ($$hash{$key}[17] eq 'ON');
265
266 # Check if NAT is enabled and initialize variables, that we use for that.
267 my $NAT = ($$hash{$key}[28] eq 'ON');
268 my $NAT_MODE;
269 if ($NAT) {
270 $NAT_MODE = uc($$hash{$key}[31]);
271 }
272
273 # Set up time constraints.
274 my @time_options = ();
275 if ($$hash{$key}[18] eq 'ON') {
276 push(@time_options, ("-m", "time"));
277
278 # Select all days of the week this match is active.
279 my @weekdays = ();
280 if ($$hash{$key}[19] ne '') {
281 push (@weekdays, "Mon");
282 }
283 if ($$hash{$key}[20] ne '') {
284 push (@weekdays, "Tue");
285 }
286 if ($$hash{$key}[21] ne '') {
287 push (@weekdays, "Wed");
288 }
289 if ($$hash{$key}[22] ne '') {
290 push (@weekdays, "Thu");
291 }
292 if ($$hash{$key}[23] ne '') {
293 push (@weekdays, "Fri");
294 }
295 if ($$hash{$key}[24] ne '') {
296 push (@weekdays, "Sat");
297 }
298 if ($$hash{$key}[25] ne '') {
299 push (@weekdays, "Sun");
300 }
301 if (@weekdays) {
302 push(@time_options, ("--weekdays", join(",", @weekdays)));
303 }
304
305 # Convert start time.
306 my $time_start = &format_time($$hash{$key}[26]);
307 if ($time_start) {
308 push(@time_options, ("--timestart", $time_start));
309 }
310
311 # Convert end time.
312 my $time_stop = &format_time($$hash{$key}[27]);
313 if ($time_stop) {
314 push(@time_options, ("--timestop", $time_stop));
315 }
316 }
317
318 # Concurrent connection limit
319 my @ratelimit_options = ();
320
321 if (($elements ge 34) && ($$hash{$key}[32] eq 'ON')) {
322 my $conn_limit = $$hash{$key}[33];
323
324 if ($conn_limit ge 1) {
325 push(@ratelimit_options, ("-m", "connlimit"));
326
327 # Use the the entire source IP address
328 push(@ratelimit_options, "--connlimit-saddr");
329 push(@ratelimit_options, ("--connlimit-mask", "32"));
330
331 # Apply the limit
332 push(@ratelimit_options, ("--connlimit-upto", $conn_limit));
333 }
334 }
335
336 # Ratelimit
337 if (($elements ge 37) && ($$hash{$key}[34] eq 'ON')) {
338 my $rate_limit = "$$hash{$key}[35]/$$hash{$key}[36]";
339
340 if ($rate_limit) {
341 push(@ratelimit_options, ("-m", "limit"));
342 push(@ratelimit_options, ("--limit", $rate_limit));
343 }
344 }
345
346 # Check which protocols are used in this rule and so that we can
347 # later group rules by protocols.
348 my @protocols = &get_protocols($hash, $key);
349 if (!@protocols) {
350 print_error("Invalid protocol configuration for rule $key");
351 next;
352 }
353
354 foreach my $protocol (@protocols) {
355 # Check if the given protocol is supported.
356 if (($protocol ne "all") && (!$protocol ~~ @PROTOCOLS)) {
357 print_error("Protocol $protocol is not supported (rule $key)");
358 next;
359 }
360
361 # Prepare protocol options (like ICMP types, ports, etc...).
362 my @protocol_options = &get_protocol_options($hash, $key, $protocol, 0);
363
364 # Check if this protocol knows ports.
365 my $protocol_has_ports = ($protocol ~~ @PROTOCOLS_WITH_PORTS);
366
367 foreach my $src (@sources) {
368 # Skip invalid source.
369 next unless (defined $src);
370 next unless ($src);
371
372 # Sanitize source.
373 my $source = @$src[0];
374 if ($source ~~ @ANY_ADDRESSES) {
375 $source = "";
376 }
377
378 my $source_intf = @$src[1];
379
380 foreach my $dst (@destinations) {
381 # Skip invalid rules.
382 next unless (defined $dst);
383 next if (!$dst || ($dst eq "none"));
384
385 # Sanitize destination.
386 my $destination = @$dst[0];
387 if ($destination ~~ @ANY_ADDRESSES) {
388 $destination = "";
389 }
390
391 my $destination_intf = @$dst[1];
392
393 # Array with iptables arguments.
394 my @options = ();
395
396 # Append protocol.
397 if ($protocol ne "all") {
398 push(@options, @protocol_options);
399 }
400
401 # Prepare source options.
402 my @source_options = ();
403 if ($source =~ /mac/) {
404 push(@source_options, $source);
405 } elsif ($source =~ /-m set/) {
406 # Grab location code from hash.
407 my $loc_src = $$hash{$key}[4];
408
409 # Check if the network list for this country already has been loaded.
410 unless($loaded_ipset_lists{$loc_src}) {
411 # Call function to load the networks list for this country.
412 &ipset_restore($loc_src);
413
414 # Store to the hash that this list has been loaded.
415 $loaded_ipset_lists{$loc_src} = "1";
416 }
417
418 push(@source_options, $source);
419 } elsif($source) {
420 push(@source_options, ("-s", $source));
421 }
422
423 # Prepare destination options.
424 my @destination_options = ();
425 if ($destination =~ /-m set/) {
426 # Grab location code from hash.
427 my $loc_dst = $$hash{$key}[6];
428
429 # Check if the network list for this country already has been loaded.
430 unless($loaded_ipset_lists{$loc_dst}) {
431 # Call function to load the networks list for this country.
432 &ipset_restore($loc_dst);
433
434 # Store to the hash that this list has been loaded.
435 $loaded_ipset_lists{$loc_dst} = "1";
436 }
437
438 push(@destination_options, $destination);
439 } elsif ($destination) {
440 push(@destination_options, ("-d", $destination));
441 }
442
443 # Add source and destination interface to the filter rules.
444 # These are supposed to help filtering forged packets that originate
445 # from BLUE with an IP address from GREEN for instance.
446 my @source_intf_options = ();
447 if ($source_intf) {
448 push(@source_intf_options, ("-i", $source_intf));
449 }
450
451 my @destination_intf_options = ();
452 if ($destination_intf) {
453 push(@destination_intf_options, ("-o", $destination_intf));
454 }
455
456 # Add time constraint options.
457 push(@options, @time_options);
458
459 # Add ratelimiting option
460 push(@options, @ratelimit_options);
461
462 my $firewall_is_in_source_subnet = 1;
463 if ($source) {
464 $firewall_is_in_source_subnet = &firewall_is_in_subnet($source);
465 }
466
467 my $firewall_is_in_destination_subnet = 1;
468 if ($destination) {
469 $firewall_is_in_destination_subnet = &firewall_is_in_subnet($destination);
470 }
471
472 # Process NAT rules.
473 if ($NAT) {
474 my $nat_address = &fwlib::get_nat_address($$hash{$key}[29], $source);
475
476 # Skip NAT rules if the NAT address is unknown
477 # (i.e. no internet connection has been established, yet).
478 next unless ($nat_address);
479
480 # Destination NAT
481 if ($NAT_MODE eq "DNAT") {
482 my @nat_options = ();
483 if ($protocol ne "all") {
484 my @nat_protocol_options = &get_protocol_options($hash, $key, $protocol, 1);
485 push(@nat_options, @nat_protocol_options);
486 }
487
488 # Add time options.
489 push(@nat_options, @time_options);
490
491 # Determine if a REDIRECT rule should be created.
492 my $use_redirect = ($destination_is_firewall && !$destination && $protocol_has_ports);
493
494 # Make port-forwardings useable from the internal networks.
495 if (!$use_redirect) {
496 my @internal_addresses = &fwlib::get_internal_firewall_ip_addresses(1);
497 unless ($nat_address ~~ @internal_addresses) {
498 &add_dnat_mangle_rules($nat_address, $source_intf, @nat_options);
499 }
500 }
501
502 # Add source options.
503 push(@nat_options, @source_options);
504
505 # Add NAT address.
506 if (!$use_redirect) {
507 push(@nat_options, ("-d", $nat_address));
508 }
509
510 my $dnat_port;
511 if ($protocol_has_ports) {
512 $dnat_port = &get_dnat_target_port($hash, $key);
513 }
514
515 my @nat_action_options = ();
516
517 # Use iptables REDIRECT
518 if ($use_redirect) {
519 push(@nat_action_options, ("-j", "REDIRECT"));
520
521 # Redirect to specified port if one has given.
522 if ($dnat_port) {
523 push(@nat_action_options, ("--to-ports", $dnat_port));
524 }
525
526 # Use iptables DNAT
527 } else {
528 if ($destination_is_firewall && !$destination) {
529 $destination = &fwlib::get_external_address();
530 }
531 next unless ($destination);
532
533 my ($dnat_address, $dnat_mask) = split("/", $destination);
534 @destination_options = ("-d", $dnat_address);
535
536 if ($protocol_has_ports) {
537 my $dnat_port = &get_dnat_target_port($hash, $key);
538
539 if ($dnat_port) {
540 $dnat_address .= ":$dnat_port";
541 }
542 }
543
544 push(@nat_action_options, ("-j", "DNAT", "--to-destination", $dnat_address));
545 }
546
547 if ($LOG) {
548 run("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @log_limit_options -j LOG --log-prefix 'DNAT '");
549 }
550 run("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @nat_action_options");
551
552 # Source NAT
553 } elsif ($NAT_MODE eq "SNAT") {
554 my @snat_options = ( "-m", "policy", "--dir", "out", "--pol", "none" );
555 my @nat_options = @options;
556
557 # Get addresses for the configured firewall interfaces.
558 my @local_addresses = &fwlib::get_internal_firewall_ip_addresses(1);
559
560 # Check if the nat_address is one of the local addresses.
561 foreach my $local_address (@local_addresses) {
562 if ($nat_address eq $local_address) {
563 # Clear SNAT options.
564 @snat_options = ();
565
566 # Finish loop.
567 last;
568 }
569 }
570
571 push(@nat_options, @destination_intf_options);
572 push(@nat_options, @source_options);
573 push(@nat_options, @destination_options);
574
575 if ($LOG) {
576 run("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options @snat_options @log_limit_options -j LOG --log-prefix 'SNAT '");
577 }
578 run("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options @snat_options -j SNAT --to-source $nat_address");
579 }
580 }
581
582 push(@options, @source_options);
583 push(@options, @destination_options);
584
585 # Insert firewall rule.
586 if ($LOG) {
587 run("$IPTABLES -A $chain @options @source_intf_options @destination_intf_options @log_limit_options -j LOG --log-prefix '$chain '");
588 }
589 run("$IPTABLES -A $chain @options @source_intf_options @destination_intf_options -j $target");
590
591 # Handle forwarding rules and add corresponding rules for firewall access.
592 if ($chain eq $CHAIN_FORWARD) {
593 # If the firewall is part of the destination subnet and access to the destination network
594 # is granted/forbidden for any network that the firewall itself is part of, we grant/forbid access
595 # for the firewall, too.
596 if ($firewall_is_in_destination_subnet && ($target ~~ @special_input_targets)) {
597 if ($LOG) {
598 run("$IPTABLES -A $CHAIN_INPUT @options @source_intf_options @log_limit_options -j LOG --log-prefix '$CHAIN_INPUT '");
599 }
600 run("$IPTABLES -A $CHAIN_INPUT @options @source_intf_options -j $target");
601 }
602
603 # Likewise.
604 if ($firewall_is_in_source_subnet && ($target ~~ @special_output_targets)) {
605 if ($LOG) {
606 run("$IPTABLES -A $CHAIN_OUTPUT @options @destination_intf_options @log_limit_options -j LOG --log-prefix '$CHAIN_OUTPUT '");
607 }
608 run("$IPTABLES -A $CHAIN_OUTPUT @options @destination_intf_options -j $target");
609 }
610 }
611 }
612 }
613 }
614 }
615 }
616
617 # Formats the given timestamp into the iptables format which is "hh:mm" UTC.
618 sub format_time {
619 my $val = shift;
620
621 # Convert the given time into minutes.
622 my $minutes = &time_convert_to_minutes($val);
623
624 # Move the timestamp into UTC.
625 $minutes += &time_utc_offset();
626
627 # Make sure $minutes is between 00:00 and 23:59.
628 if ($minutes < 0) {
629 $minutes += 1440;
630 }
631
632 if ($minutes > 1440) {
633 $minutes -= 1440;
634 }
635
636 # Format as hh:mm.
637 return sprintf("%02d:%02d", $minutes / 60, $minutes % 60);
638 }
639
640 # Calculates the offsets in minutes from the local timezone to UTC.
641 sub time_utc_offset {
642 my @localtime = localtime(time);
643 my @gmtime = gmtime(time);
644
645 return ($gmtime[2] * 60 + $gmtime[1] % 60) - ($localtime[2] * 60 + $localtime[1] % 60);
646 }
647
648 # Takes a timestamp like "14:00" and converts it into minutes since midnight.
649 sub time_convert_to_minutes {
650 my ($hrs, $min) = split(":", shift);
651
652 return ($hrs * 60) + $min;
653 }
654
655 sub p2pblock {
656 open(FILE, "<$p2pfile") or die "Unable to read $p2pfile";
657 my @protocols = ();
658 foreach my $p2pentry (<FILE>) {
659 my @p2pline = split(/\;/, $p2pentry);
660 next unless ($p2pline[2] eq "off");
661
662 push(@protocols, "--$p2pline[1]");
663 }
664 close(FILE);
665
666 run("$IPTABLES -F P2PBLOCK");
667 if (@protocols) {
668 run("$IPTABLES -A P2PBLOCK -m ipp2p @protocols -j DROP");
669 }
670 }
671
672 sub locationblock {
673 # The LOCATIONBLOCK chain now gets flushed by the flush() function.
674
675 # If location blocking is not enabled, we are finished here.
676 if ($locationsettings{'LOCATIONBLOCK_ENABLED'} ne "on") {
677 # Exit submodule. Process remaining script.
678 return;
679 }
680
681 # Only check the RED interface, which is ppp0 in case of RED_TYPE being
682 # set to "PPPOE", and red0 in case of RED_TYPE not being empty otherwise.
683 if ($defaultNetworks{'RED_TYPE'} eq "PPPOE") {
684 run("$IPTABLES -A LOCATIONBLOCK ! -i ppp0 -j RETURN");
685 } elsif ($defaultNetworks{'RED_DEV'} ne "") {
686 run("$IPTABLES -A LOCATIONBLOCK ! -i $defaultNetworks{'RED_DEV'} -j RETURN");
687 }
688
689 # Do not check any private address space
690 foreach my $network (@PRIVATE_NETWORKS) {
691 run("$IPTABLES -A LOCATIONBLOCK -s $network -j RETURN");
692 }
693
694 # Loop through all supported locations and
695 # create iptables rules, if blocking for this country
696 # is enabled.
697 foreach my $location (@locations) {
698 if(exists $locationsettings{$location} && $locationsettings{$location} eq "on") {
699 # Check if the network list for this country already has been loaded.
700 unless($loaded_ipset_lists{$location}) {
701 # Call function to load the networks list for this country.
702 &ipset_restore($location);
703
704 # Store to the hash that this list has been loaded.
705 $loaded_ipset_lists{$location} = "1";
706 }
707
708 # Call iptables and create rule to use the loaded ipset list.
709 run("$IPTABLES -A LOCATIONBLOCK -m set --match-set CC_$location src -j DROP");
710 }
711 }
712 }
713
714 sub get_protocols {
715 my $hash = shift;
716 my $key = shift;
717
718 my $uses_source_ports = ($$hash{$key}[7] eq "ON");
719 my $uses_services = ($$hash{$key}[11] eq "ON");
720
721 my @protocols = ();
722
723 # Rules which don't have source ports or services (like ICMP, ESP, ...).
724 if (!$uses_source_ports && !$uses_services) {
725 push(@protocols, $$hash{$key}[8]);
726
727 # Rules which either use ports or services.
728 } elsif ($uses_source_ports || $uses_services) {
729 # Check if service group or service
730 if ($$hash{$key}[14] eq 'cust_srv') {
731 push(@protocols, &fwlib::get_srv_prot($$hash{$key}[15]));
732
733 } elsif($$hash{$key}[14] eq 'cust_srvgrp'){
734 my $protos = &fwlib::get_srvgrp_prot($$hash{$key}[15]);
735 push(@protocols, split(",", $protos));
736
737 } else {
738 # Fetch the protocol for this rule.
739 my $protocol = lc($$hash{$key}[8]);
740
741 # Fetch source and destination ports for this rule.
742 my $source_ports = $$hash{$key}[10];
743 my $destination_ports = $$hash{$key}[15];
744
745 # Check if ports are set for protocols which do not support ports.
746 if (!($protocol ~~ @PROTOCOLS_WITH_PORTS) && ($source_ports || $destination_ports)) {
747 print_error("$protocol does not support ports");
748 return ();
749 }
750
751 push(@protocols, $protocol);
752 }
753 }
754
755 # Remove all empty elements
756 @protocols = map { $_ ? $_ : () } @protocols;
757
758 # If no protocol has been defined, we assume "all".
759 if (!@protocols) {
760 push(@protocols, "all");
761 }
762
763 # Make all protocol names lowercase.
764 @protocols = map { lc } @protocols;
765
766 return @protocols;
767 }
768
769 sub get_protocol_options {
770 my $hash = shift;
771 my $key = shift;
772 my $protocol = shift;
773 my $nat_options_wanted = shift;
774 my @options = ();
775
776 # Nothing to do if no protocol is specified.
777 if ($protocol eq "all") {
778 return @options;
779 } else {
780 push(@options, ("-p", $protocol));
781 }
782
783 if ($protocol ~~ @PROTOCOLS_WITH_PORTS) {
784 # Process source ports.
785 my $use_src_ports = ($$hash{$key}[7] eq "ON");
786 my $src_ports = $$hash{$key}[10];
787
788 if ($use_src_ports && $src_ports) {
789 push(@options, &format_ports($src_ports, "src"));
790 }
791
792 # Process destination ports.
793 my $use_dst_ports = ($$hash{$key}[11] eq "ON");
794 my $use_dnat = (($$hash{$key}[28] eq "ON") && ($$hash{$key}[31] eq "dnat"));
795
796 if ($use_dst_ports) {
797 my $dst_ports_mode = $$hash{$key}[14];
798 my $dst_ports = $$hash{$key}[15];
799
800 if (($dst_ports_mode eq "TGT_PORT") && $dst_ports) {
801 if ($nat_options_wanted && $use_dnat && $$hash{$key}[30]) {
802 $dst_ports = $$hash{$key}[30];
803 }
804 push(@options, &format_ports($dst_ports, "dst"));
805
806 } elsif ($dst_ports_mode eq "cust_srv") {
807 if ($protocol eq "ICMP") {
808 push(@options, ("--icmp-type", &fwlib::get_srv_port($dst_ports, 3, "ICMP")));
809 } else {
810 $dst_ports = &fwlib::get_srv_port($dst_ports, 1, uc($protocol));
811 push(@options, &format_ports($dst_ports, "dst"));
812 }
813
814 } elsif ($dst_ports_mode eq "cust_srvgrp") {
815 push(@options, &fwlib::get_srvgrp_port($dst_ports, uc($protocol)));
816 }
817 }
818 }
819
820 # Check if a single ICMP type is selected.
821 if ($protocol eq "icmp") {
822 my $icmp_type = $$hash{$key}[9];
823
824 if (($icmp_type ne "All ICMP-Types") && $icmp_type) {
825 push(@options, ("--icmp-type", $icmp_type));
826 }
827 }
828
829 return @options;
830 }
831
832 sub format_ports {
833 my $ports = shift;
834 my $type = shift;
835
836 my $arg;
837 if ($type eq "src") {
838 $arg = "--sport";
839 } elsif ($type eq "dst") {
840 $arg = "--dport";
841 }
842
843 my @options = ();
844
845 if ($ports =~ /\|/) {
846 $ports =~ s/\|/,/g;
847 push(@options, ("-m", "multiport"));
848 }
849
850 if ($ports) {
851 push(@options, ($arg, $ports));
852 }
853
854 return @options;
855 }
856
857 sub get_dnat_target_port {
858 my $hash = shift;
859 my $key = shift;
860
861 if ($$hash{$key}[14] eq "TGT_PORT") {
862 my $port = $$hash{$key}[15];
863 my $external_port = $$hash{$key}[30];
864
865 if ($external_port && ($port ne $external_port)) {
866 return $$hash{$key}[15];
867 }
868 }
869 }
870
871 sub add_dnat_mangle_rules {
872 my $nat_address = shift;
873 my $interface = shift;
874 my @options = @_;
875
876 my $mark = 0x01000000;
877 foreach my $zone ("GREEN", "BLUE", "ORANGE") {
878 # Skip rule if not all required information exists.
879 next unless (exists $defaultNetworks{$zone . "_NETADDRESS"});
880 next unless (exists $defaultNetworks{$zone . "_NETMASK"});
881
882 next if ($interface && $interface ne $defaultNetworks{$zone . "_DEV"});
883
884 my @mangle_options = @options;
885
886 my $netaddress = $defaultNetworks{$zone . "_NETADDRESS"};
887 $netaddress .= "/" . $defaultNetworks{$zone . "_NETMASK"};
888
889 push(@mangle_options, ("-s", $netaddress, "-d", $nat_address));
890 push(@mangle_options, ("-j", "MARK", "--set-xmark", "$mark/$NAT_MASK"));
891
892 run("$IPTABLES -t mangle -A $CHAIN_MANGLE_NAT_DESTINATION_FIX @mangle_options");
893
894 $mark <<= 1;
895 }
896 }
897
898 sub make_log_limit_options {
899 my @options = ("-m", "limit");
900
901 # Maybe we should get this from the configuration.
902 my $limit = 10;
903
904 # We limit log messages to $limit messages per second.
905 push(@options, ("--limit", "$limit/second"));
906
907 # And we allow bursts of 2x $limit.
908 push(@options, ("--limit-burst", $limit * 2));
909
910 return @options;
911 }
912
913 sub firewall_is_in_subnet {
914 my $subnet = shift;
915
916 # ORANGE is missing here, because nothing may ever access
917 # the firewall from this network.
918 my $address = &fwlib::get_internal_firewall_ip_address($subnet, 0);
919
920 if ($address) {
921 return 1;
922 }
923
924 return 0;
925 }
926
927 sub ipset_restore ($) {
928 my ($ccode) = @_;
929
930 # Run ipset and restore the list of the given country code.
931 run("$IPSET restore < $Location::Functions::ipset_db_directory/$ccode.ipset4");
932 }