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