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