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