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