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