]> git.ipfire.org Git - ipfire-2.x.git/blob - config/firewall/rules.pl
update-contributors
[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 require "${General::swroot}/ipblocklist-functions.pl";
30
31 # Set to one to enable debugging mode.
32 my $DEBUG = 0;
33
34 my $IPTABLES = "iptables --wait";
35 my $IPSET = "ipset";
36
37 # iptables chains
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");
47
48 my @PROTOCOLS = ("tcp", "udp", "icmp", "igmp", "ah", "esp", "gre", "ipv6", "ipip");
49 my @PROTOCOLS_WITH_PORTS = ("tcp", "udp");
50
51 my @VALID_TARGETS = ("ACCEPT", "DROP", "REJECT");
52
53 my @PRIVATE_NETWORKS = (
54 "10.0.0.0/8",
55 "172.16.0.0/12",
56 "192.168.0.0/16",
57 "100.64.0.0/10",
58 "224.0.0.0/4",
59 );
60
61 # MARK masks
62 my $NAT_MASK = 0x0f000000;
63
64 # Country code, which is used to mark hostile networks.
65 my $HOSTILE_CCODE = "XD";
66
67 my %fwdfwsettings=();
68 my %fwoptions = ();
69 my %defaultNetworks=();
70 my %configfwdfw=();;
71 my %customgrp=();
72 my %configinputfw=();
73 my %configoutgoingfw=();
74 my %confignatfw=();
75 my %locationsettings = (
76 "LOCATIONBLOCK_ENABLED" => "off"
77 );
78 my %blocklistsettings= (
79 "ENABLE" => "off",
80 );
81
82 my %ipset_loaded_sets = ();
83 my @ipset_used_sets = ();
84
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";
92
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);
100
101 # Check if the location settings file exists
102 if (-e "$locationfile") {
103 # Read settings file
104 &General::readhash("$locationfile", \%locationsettings);
105 }
106
107 # Check if the ipblocklist settings file exits.
108 if (-e "$blocklistfile") {
109 # Read-in settings file.
110 &General::readhash("$blocklistfile", \%blocklistsettings);
111 }
112
113 # Get all available locations.
114 my @locations = &Location::Functions::get_locations();
115
116 # Get all supported blocklists.
117 my @blocklists = &IPblocklist::get_blocklists();
118
119 # Name or the RED interface.
120 my $RED_DEV = &General::get_red_interface();
121
122 my @log_limit_options = &make_log_limit_options();
123
124 my $POLICY_INPUT_ALLOWED = 0;
125 my $POLICY_FORWARD_ALLOWED = ($fwdfwsettings{"POLICY"} eq "MODE2");
126 my $POLICY_OUTPUT_ALLOWED = ($fwdfwsettings{"POLICY1"} eq "MODE2");
127
128 my $POLICY_INPUT_ACTION = $fwoptions{"FWPOLICY2"};
129 my $POLICY_FORWARD_ACTION = $fwoptions{"FWPOLICY"};
130 my $POLICY_OUTPUT_ACTION = $fwoptions{"FWPOLICY1"};
131
132 #workaround to suppress a warning when a variable is used only once
133 my @dummy = ( $Location::Functions::ipset_db_directory );
134 undef (@dummy);
135
136 # MAIN
137 &main();
138
139 sub main {
140 # Get currently used ipset sets.
141 @ipset_used_sets = &ipset_get_sets();
142
143 # Flush all chains.
144 &flush();
145
146 # Prepare firewall rules.
147 if (! -z "${General::swroot}/firewall/input"){
148 &buildrules(\%configinputfw);
149 }
150 if (! -z "${General::swroot}/firewall/outgoing"){
151 &buildrules(\%configoutgoingfw);
152 }
153 if (! -z "${General::swroot}/firewall/config"){
154 &buildrules(\%configfwdfw);
155 }
156
157 # Load Location block rules.
158 &locationblock();
159
160 # Load rules to block hostile networks.
161 &drop_hostile_networks();
162
163 # Handle ipblocklist.
164 &ipblocklist();
165
166 # Reload firewall policy.
167 run("/usr/sbin/firewall-policy");
168
169 # Cleanup not longer needed ipset sets.
170 &ipset_cleanup();
171
172 #Reload firewall.local if present
173 if ( -f '/etc/sysconfig/firewall.local'){
174 run("/etc/sysconfig/firewall.local reload");
175 }
176 }
177
178 sub run {
179 # Executes or prints the given shell command.
180 my $command = shift;
181
182 if ($DEBUG) {
183 print "$command\n";
184 } else {
185 system "$command";
186
187 if ($?) {
188 print_error("ERROR: $command");
189 }
190 }
191 }
192
193 sub print_error {
194 my $message = shift;
195
196 print STDERR "$message\n";
197 }
198
199 sub print_rule {
200 my $hash = shift;
201
202 print "\nRULE:";
203
204 my $i = 0;
205 foreach (@$hash) {
206 printf(" %2d: %s", $i++, $_);
207 }
208 print "\n";
209 }
210
211 sub count_elements {
212 my $hash = shift;
213
214 return scalar @$hash;
215 }
216
217 sub flush {
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");
224 }
225
226 sub buildrules {
227 my $hash = shift;
228
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");
235 }
236
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"));
241 }
242
243 my @special_output_targets = ();
244 if ($POLICY_OUTPUT_ALLOWED) {
245 push(@special_output_targets, ("DROP", "REJECT"));
246 } else {
247 push(@special_output_targets, "ACCEPT");
248
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"));
253 }
254 }
255
256 foreach my $key (sort {$a <=> $b} keys %$hash) {
257 # Skip disabled rules.
258 next unless ($$hash{$key}[2] eq 'ON');
259
260 # Count number of elements in this line
261 my $elements = &count_elements($$hash{$key});
262
263 if ($DEBUG) {
264 print_rule($$hash{$key});
265 }
266
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");
271 next;
272 }
273
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");
278 next;
279 }
280
281 # Collect all sources.
282 my @sources = &fwlib::get_addresses($hash, $key, "src");
283
284 # Collect all destinations.
285 my @destinations = &fwlib::get_addresses($hash, $key, "tgt");
286
287 # True if the destination is the firewall itself.
288 my $destination_is_firewall = ($$hash{$key}[5] eq "ipfire");
289
290 # Check if logging should be enabled.
291 my $LOG = ($$hash{$key}[17] eq 'ON');
292
293 # Check if NAT is enabled and initialize variables, that we use for that.
294 my $NAT = ($$hash{$key}[28] eq 'ON');
295 my $NAT_MODE;
296 if ($NAT) {
297 $NAT_MODE = uc($$hash{$key}[31]);
298 }
299
300 # Set up time constraints.
301 my @time_options = ();
302 if ($$hash{$key}[18] eq 'ON') {
303 push(@time_options, ("-m", "time"));
304
305 # Select all days of the week this match is active.
306 my @weekdays = ();
307 if ($$hash{$key}[19] ne '') {
308 push (@weekdays, "Mon");
309 }
310 if ($$hash{$key}[20] ne '') {
311 push (@weekdays, "Tue");
312 }
313 if ($$hash{$key}[21] ne '') {
314 push (@weekdays, "Wed");
315 }
316 if ($$hash{$key}[22] ne '') {
317 push (@weekdays, "Thu");
318 }
319 if ($$hash{$key}[23] ne '') {
320 push (@weekdays, "Fri");
321 }
322 if ($$hash{$key}[24] ne '') {
323 push (@weekdays, "Sat");
324 }
325 if ($$hash{$key}[25] ne '') {
326 push (@weekdays, "Sun");
327 }
328 if (@weekdays) {
329 push(@time_options, ("--weekdays", join(",", @weekdays)));
330 }
331
332 # Convert start time.
333 my $time_start = &format_time($$hash{$key}[26]);
334 if ($time_start) {
335 push(@time_options, ("--timestart", $time_start));
336 }
337
338 # Convert end time.
339 my $time_stop = &format_time($$hash{$key}[27]);
340 if ($time_stop) {
341 push(@time_options, ("--timestop", $time_stop));
342 }
343 }
344
345 # Concurrent connection limit
346 my @ratelimit_options = ();
347
348 if (($elements ge 34) && ($$hash{$key}[32] eq 'ON')) {
349 my $conn_limit = $$hash{$key}[33];
350
351 if ($conn_limit ge 1) {
352 push(@ratelimit_options, ("-m", "connlimit"));
353
354 # Use the the entire source IP address
355 push(@ratelimit_options, "--connlimit-saddr");
356 push(@ratelimit_options, ("--connlimit-mask", "32"));
357
358 # Apply the limit
359 push(@ratelimit_options, ("--connlimit-upto", $conn_limit));
360 }
361 }
362
363 # Ratelimit
364 if (($elements ge 37) && ($$hash{$key}[34] eq 'ON')) {
365 my $rate_limit = "$$hash{$key}[35]/$$hash{$key}[36]";
366
367 if ($rate_limit) {
368 push(@ratelimit_options, ("-m", "limit"));
369 push(@ratelimit_options, ("--limit", $rate_limit));
370 }
371 }
372
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);
376 if (!@protocols) {
377 print_error("Invalid protocol configuration for rule $key");
378 next;
379 }
380
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)");
385 next;
386 }
387
388 # Prepare protocol options (like ICMP types, ports, etc...).
389 my @protocol_options = &get_protocol_options($hash, $key, $protocol, 0);
390
391 # Check if this protocol knows ports.
392 my $protocol_has_ports = ($protocol ~~ @PROTOCOLS_WITH_PORTS);
393
394 foreach my $src (@sources) {
395 # Skip invalid source.
396 next unless (defined $src);
397 next unless ($src);
398
399 # Sanitize source.
400 my $source = @$src[0];
401 if ($source ~~ @ANY_ADDRESSES) {
402 $source = "";
403 }
404
405 # Make sure that $source is properly defined
406 next unless (defined $source);
407
408 my $source_intf = @$src[1];
409
410 foreach my $dst (@destinations) {
411 # Skip invalid rules.
412 next unless (defined $dst);
413 next if (!$dst || ($dst eq "none"));
414
415 # Sanitize destination.
416 my $destination = @$dst[0];
417 if ($destination ~~ @ANY_ADDRESSES) {
418 $destination = "";
419 }
420
421 my $destination_intf = @$dst[1];
422
423 # Array with iptables arguments.
424 my @options = ();
425
426 # Append protocol.
427 if ($protocol ne "all") {
428 push(@options, @protocol_options);
429 }
430
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);
439
440 # Call function to load the networks list for this country.
441 &ipset_restore($loc_src);
442
443 push(@source_options, $source);
444 } elsif($source) {
445 push(@source_options, ("-s", $source));
446 }
447
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);
454
455 # Call function to load the networks list for this country.
456 &ipset_restore($loc_dst);
457
458 push(@destination_options, $destination);
459 } elsif ($destination) {
460 push(@destination_options, ("-d", $destination));
461 }
462
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 = ();
467 if ($source_intf) {
468 push(@source_intf_options, ("-i", $source_intf));
469 }
470
471 my @destination_intf_options = ();
472 if ($destination_intf) {
473 push(@destination_intf_options, ("-o", $destination_intf));
474 }
475
476 # Add time constraint options.
477 push(@options, @time_options);
478
479 # Add ratelimiting option
480 push(@options, @ratelimit_options);
481
482 my $firewall_is_in_source_subnet = 1;
483 if ($source) {
484 $firewall_is_in_source_subnet = &firewall_is_in_subnet($source);
485 }
486
487 my $firewall_is_in_destination_subnet = 1;
488 if ($destination) {
489 $firewall_is_in_destination_subnet = &firewall_is_in_subnet($destination);
490 }
491
492 # Process NAT rules.
493 if ($NAT) {
494 my $nat_address = &fwlib::get_nat_address($$hash{$key}[29], $source);
495
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);
499
500 # Destination NAT
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);
506 }
507
508 # Add time options.
509 push(@nat_options, @time_options);
510
511 # Determine if a REDIRECT rule should be created.
512 my $use_redirect = ($destination_is_firewall && !$destination && $protocol_has_ports);
513
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);
519 }
520 }
521
522 # Add source options.
523 push(@nat_options, @source_options);
524
525 # Add NAT address.
526 if (!$use_redirect) {
527 push(@nat_options, ("-d", $nat_address));
528 }
529
530 my $dnat_port;
531 if ($protocol_has_ports) {
532 $dnat_port = &get_dnat_target_port($hash, $key);
533 }
534
535 my @nat_action_options = ();
536
537 # Use iptables REDIRECT
538 if ($use_redirect) {
539 push(@nat_action_options, ("-j", "REDIRECT"));
540
541 # Redirect to specified port if one has given.
542 if ($dnat_port) {
543 push(@nat_action_options, ("--to-ports", $dnat_port));
544 }
545
546 # Use iptables DNAT
547 } else {
548 if ($destination_is_firewall && !$destination) {
549 $destination = &fwlib::get_external_address();
550 }
551 next unless ($destination);
552
553 my ($dnat_address, $dnat_mask) = split("/", $destination);
554 @destination_options = ("-d", $dnat_address);
555
556 if ($protocol_has_ports) {
557 my $dnat_port = &get_dnat_target_port($hash, $key);
558
559 if ($dnat_port) {
560 $dnat_address .= ":$dnat_port";
561 }
562 }
563
564 push(@nat_action_options, ("-j", "DNAT", "--to-destination", $dnat_address));
565 }
566
567 if ($LOG) {
568 run("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @log_limit_options -j LOG --log-prefix 'DNAT '");
569 }
570 run("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @nat_action_options");
571
572 # Source NAT
573 } elsif ($NAT_MODE eq "SNAT") {
574 my @snat_options = ( "-m", "policy", "--dir", "out", "--pol", "none" );
575 my @nat_options = @options;
576
577 # Get addresses for the configured firewall interfaces.
578 my @local_addresses = &fwlib::get_internal_firewall_ip_addresses(1);
579
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.
584 @snat_options = ();
585
586 # Finish loop.
587 last;
588 }
589 }
590
591 push(@nat_options, @destination_intf_options);
592 push(@nat_options, @source_options);
593 push(@nat_options, @destination_options);
594
595 if ($LOG) {
596 run("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options @snat_options @log_limit_options -j LOG --log-prefix 'SNAT '");
597 }
598 run("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options @snat_options -j SNAT --to-source $nat_address");
599 }
600 }
601
602 push(@options, @source_options);
603 push(@options, @destination_options);
604
605 # Insert firewall rule.
606 if ($LOG) {
607 run("$IPTABLES -A $chain @options @source_intf_options @destination_intf_options @log_limit_options -j LOG --log-prefix '$chain '");
608 }
609 run("$IPTABLES -A $chain @options @source_intf_options @destination_intf_options -j $target");
610
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)) {
617 if ($LOG) {
618 run("$IPTABLES -A $CHAIN_INPUT @options @source_intf_options @log_limit_options -j LOG --log-prefix '$CHAIN_INPUT '");
619 }
620 run("$IPTABLES -A $CHAIN_INPUT @options @source_intf_options -j $target");
621 }
622
623 # Likewise.
624 if ($firewall_is_in_source_subnet && ($target ~~ @special_output_targets)) {
625 if ($LOG) {
626 run("$IPTABLES -A $CHAIN_OUTPUT @options @destination_intf_options @log_limit_options -j LOG --log-prefix '$CHAIN_OUTPUT '");
627 }
628 run("$IPTABLES -A $CHAIN_OUTPUT @options @destination_intf_options -j $target");
629 }
630 }
631 }
632 }
633 }
634 }
635 }
636
637 # Formats the given timestamp into the iptables format which is "hh:mm" UTC.
638 sub format_time {
639 my $val = shift;
640
641 # Convert the given time into minutes.
642 my $minutes = &time_convert_to_minutes($val);
643
644 # Move the timestamp into UTC.
645 $minutes += &time_utc_offset();
646
647 # Make sure $minutes is between 00:00 and 23:59.
648 if ($minutes < 0) {
649 $minutes += 1440;
650 }
651
652 if ($minutes > 1440) {
653 $minutes -= 1440;
654 }
655
656 # Format as hh:mm.
657 return sprintf("%02d:%02d", $minutes / 60, $minutes % 60);
658 }
659
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);
664
665 return ($gmtime[2] * 60 + $gmtime[1] % 60) - ($localtime[2] * 60 + $localtime[1] % 60);
666 }
667
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);
671
672 return ($hrs * 60) + $min;
673 }
674
675 sub locationblock {
676 # Flush LOCATIONBLOCK chain.
677 run("$IPTABLES -F LOCATIONBLOCK");
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 # Call function to load the networks list for this country.
704 &ipset_restore($location);
705
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");
708 }
709 }
710 }
711
712 sub drop_hostile_networks () {
713 # Flush the HOSTILE firewall chain.
714 run("$IPTABLES -F HOSTILE");
715
716 # If dropping hostile networks is not enabled, we are finished here.
717 if ($fwoptions{'DROPHOSTILE'} ne "on") {
718 # Exit function.
719 return;
720 }
721
722 # Exit if there is no red interface.
723 return unless($RED_DEV);
724
725 # Call function to load the network list of hostile networks.
726 &ipset_restore($HOSTILE_CCODE);
727
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");
731 }
732
733 sub ipblocklist () {
734 # Flush the ipblocklist chains.
735 run("$IPTABLES -F BLOCKLISTIN");
736 run("$IPTABLES -F BLOCKLISTOUT");
737
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");
745 }
746 }
747
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);
754
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");
759 } else {
760 # Flush the chain.
761 run("$IPTABLES -F ${blocklist}_DROP");
762 }
763
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 \"");
768 }
769
770 # Create Drop rule.
771 run("$IPTABLES -A ${blocklist}_DROP -j DROP");
772
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");
776
777 # IP blocklist or the blocklist is disabled.
778 } else {
779 # Check if the blocklist related iptables drop chain exits.
780 unless(&firewall_chain_exists("${blocklist}_DROP")) {
781 # Flush the chain.
782 run("$IPTABLES -F ${blocklist}_DROP");
783
784 # Drop the chain.
785 run("$IPTABLES -X ${blocklist}_DROP");
786 }
787 }
788 }
789 }
790
791 sub get_protocols {
792 my $hash = shift;
793 my $key = shift;
794
795 my $uses_source_ports = ($$hash{$key}[7] eq "ON");
796 my $uses_services = ($$hash{$key}[11] eq "ON");
797
798 my @protocols = ();
799
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]);
803
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]));
809
810 } elsif($$hash{$key}[14] eq 'cust_srvgrp'){
811 my $protos = &fwlib::get_srvgrp_prot($$hash{$key}[15]);
812 push(@protocols, split(",", $protos));
813
814 } else {
815 # Fetch the protocol for this rule.
816 my $protocol = lc($$hash{$key}[8]);
817
818 # Fetch source and destination ports for this rule.
819 my $source_ports = $$hash{$key}[10];
820 my $destination_ports = $$hash{$key}[15];
821
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");
825 return ();
826 }
827
828 push(@protocols, $protocol);
829 }
830 }
831
832 # Remove all empty elements
833 @protocols = map { $_ ? $_ : () } @protocols;
834
835 # If no protocol has been defined, we assume "all".
836 if (!@protocols) {
837 push(@protocols, "all");
838 }
839
840 # Make all protocol names lowercase.
841 @protocols = map { lc } @protocols;
842
843 return @protocols;
844 }
845
846 sub get_protocol_options {
847 my $hash = shift;
848 my $key = shift;
849 my $protocol = shift;
850 my $nat_options_wanted = shift;
851 my @options = ();
852
853 # Nothing to do if no protocol is specified.
854 if ($protocol eq "all") {
855 return @options;
856 } else {
857 push(@options, ("-p", $protocol));
858 }
859
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];
864
865 if ($use_src_ports && $src_ports) {
866 push(@options, &format_ports($src_ports, "src"));
867 }
868
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"));
872
873 if ($use_dst_ports) {
874 my $dst_ports_mode = $$hash{$key}[14];
875 my $dst_ports = $$hash{$key}[15];
876
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];
880 }
881 push(@options, &format_ports($dst_ports, "dst"));
882
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")));
886 } else {
887 $dst_ports = &fwlib::get_srv_port($dst_ports, 1, uc($protocol));
888 push(@options, &format_ports($dst_ports, "dst"));
889 }
890
891 } elsif ($dst_ports_mode eq "cust_srvgrp") {
892 push(@options, &fwlib::get_srvgrp_port($dst_ports, uc($protocol)));
893 }
894 }
895 }
896
897 # Check if a single ICMP type is selected.
898 if ($protocol eq "icmp") {
899 my $icmp_type = $$hash{$key}[9];
900
901 if (($icmp_type ne "All ICMP-Types") && $icmp_type) {
902 push(@options, ("--icmp-type", $icmp_type));
903 }
904 }
905
906 return @options;
907 }
908
909 sub format_ports {
910 my $ports = shift;
911 my $type = shift;
912
913 my $arg;
914 if ($type eq "src") {
915 $arg = "--sport";
916 } elsif ($type eq "dst") {
917 $arg = "--dport";
918 }
919
920 my @options = ();
921
922 if ($ports =~ /\|/) {
923 $ports =~ s/\|/,/g;
924 push(@options, ("-m", "multiport"));
925 }
926
927 if ($ports) {
928 push(@options, ($arg, $ports));
929 }
930
931 return @options;
932 }
933
934 sub get_dnat_target_port {
935 my $hash = shift;
936 my $key = shift;
937
938 if ($$hash{$key}[14] eq "TGT_PORT") {
939 my $port = $$hash{$key}[15];
940 my $external_port = $$hash{$key}[30];
941
942 if ($external_port && ($port ne $external_port)) {
943 return $$hash{$key}[15];
944 }
945 }
946 }
947
948 sub add_dnat_mangle_rules {
949 my $nat_address = shift;
950 my $interface = shift;
951 my @options = @_;
952
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"});
958
959 next if ($interface && $interface ne $defaultNetworks{$zone . "_DEV"});
960
961 my @mangle_options = @options;
962
963 my $netaddress = $defaultNetworks{$zone . "_NETADDRESS"};
964 $netaddress .= "/" . $defaultNetworks{$zone . "_NETMASK"};
965
966 push(@mangle_options, ("-s", $netaddress, "-d", $nat_address));
967 push(@mangle_options, ("-j", "MARK", "--set-xmark", "$mark/$NAT_MASK"));
968
969 run("$IPTABLES -t mangle -A $CHAIN_MANGLE_NAT_DESTINATION_FIX @mangle_options");
970
971 $mark <<= 1;
972 }
973 }
974
975 sub make_log_limit_options {
976 my @options = ("-m", "limit");
977
978 # Maybe we should get this from the configuration.
979 my $limit = 10;
980
981 # We limit log messages to $limit messages per second.
982 push(@options, ("--limit", "$limit/second"));
983
984 # And we allow bursts of 2x $limit.
985 push(@options, ("--limit-burst", $limit * 2));
986
987 return @options;
988 }
989
990 sub firewall_is_in_subnet {
991 my $subnet = shift;
992
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);
996
997 if ($address) {
998 return 1;
999 }
1000
1001 return 0;
1002 }
1003
1004 sub firewall_chain_exists ($) {
1005 my ($chain) = @_;
1006
1007 my $ret = &General::system("iptables", "--wait", "-n", "-L", "$chain");
1008
1009 return $ret;
1010 }
1011
1012 sub ipset_get_sets () {
1013 my @sets;
1014
1015 # Get all currently used ipset lists and store them in an array.
1016 my @output = `$IPSET -n list`;
1017
1018 # Loop through the temporary array.
1019 foreach my $set (@output) {
1020 # Remove any newlines.
1021 chomp($set);
1022
1023 # Add the set the array of used sets.
1024 push(@sets, $set);
1025 }
1026
1027 # Display used sets in debug mode.
1028 if($DEBUG) {
1029 print "Used ipset sets:\n";
1030 print "@sets\n\n";
1031 }
1032
1033 # Return the array of sets.
1034 return @sets;
1035 }
1036
1037 sub ipset_restore ($) {
1038 my ($set) = @_;
1039
1040 # Empty variable to store the db file, which should be
1041 # restored by ipset.
1042 my $db_file;
1043
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.
1047 return;
1048 }
1049
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";
1054
1055 # The bare filename equals the set name.
1056 my $filename = $loc_set;
1057
1058 # Libloc uses "ipset" as file extension.
1059 my $file_extension = "ipset";
1060
1061 # Generate full path and filename for the ipset db file.
1062 my $db_file = "$Location::Functions::ipset_db_directory/$filename.$file_extension";
1063
1064 # Call function to restore/load the set.
1065 &ipset_call_restore($db_file);
1066
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");
1073 } else {
1074 # If the set is not loaded, we have to rename it to proper use it.
1075 run("$IPSET rename $loc_set $set");
1076 }
1077
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";
1082
1083 # Get the database file for the given blocklist.
1084 my $db_file = &IPblocklist::get_ipset_db_file($set);
1085
1086 # Call function to restore/load the set.
1087 &ipset_call_restore($db_file);
1088
1089 # Check if the set is already loaded (has been used before).
1090 if ($set ~~ @ipset_used_sets) {
1091 # Swap the sets.
1092 run("$IPSET swap $set_name $set");
1093 } else {
1094 # Rename the set to proper use it.
1095 run("$IPSET rename $set_name $set");
1096 }
1097 }
1098
1099 # Store the restored set to the hash to prevent from loading it again.
1100 $ipset_loaded_sets{$set} = "1";
1101 }
1102
1103 sub ipset_call_restore ($) {
1104 my ($file) = @_;
1105
1106 # Check if the requested file exists.
1107 if (-f $file) {
1108 # Run ipset and restore the given set.
1109 run("$IPSET restore -f $file");
1110 }
1111 }
1112
1113 sub ipset_cleanup () {
1114 # Reload the array of used sets.
1115 @ipset_used_sets = &ipset_get_sets();
1116
1117 # Loop through the array of used sets.
1118 foreach my $set (@ipset_used_sets) {
1119 # Check if this set is still in use.
1120 #
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");
1126 }
1127 }
1128 }