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