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