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