]> git.ipfire.org Git - ipfire-2.x.git/blame - config/firewall/rules.pl
rules.pl: Allow dynamic destory of loaded but unused ipset sets.
[ipfire-2.x.git] / config / firewall / rules.pl
CommitLineData
6178953b 1#!/usr/bin/perl -w
2a81ab0d
AM
2###############################################################################
3# #
4# IPFire.org - A linux based firewall #
2293e1de 5# Copyright (C) 2007-2020 IPFire Team <info@ipfire.org> #
2a81ab0d
AM
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###############################################################################
2a81ab0d 21
2a81ab0d 22use strict;
5653e551 23use experimental 'smartmatch';
2a81ab0d 24
97ab0569
MT
25require '/var/ipfire/general-functions.pl';
26require "${General::swroot}/lang.pl";
27require "/usr/lib/firewall/firewall-lib.pl";
5730a5bc 28require "${General::swroot}/location-functions.pl";
2a81ab0d 29
68d1eb10
MT
30# Set to one to enable debugging mode.
31my $DEBUG = 0;
32
1f9e7b53 33my $IPTABLES = "iptables --wait";
3d886880 34my $IPSET = "ipset";
1f9e7b53 35
6178953b 36# iptables chains
8f4f4634
MT
37my $CHAIN_INPUT = "INPUTFW";
38my $CHAIN_FORWARD = "FORWARDFW";
d98aa95a 39my $CHAIN_OUTPUT = "OUTGOINGFW";
8f4f4634 40my $CHAIN = $CHAIN_FORWARD;
6178953b
MT
41my $CHAIN_NAT_SOURCE = "NAT_SOURCE";
42my $CHAIN_NAT_DESTINATION = "NAT_DESTINATION";
6e87f0aa 43my $CHAIN_MANGLE_NAT_DESTINATION_FIX = "NAT_DESTINATION";
8f4f4634 44my @VALID_CHAINS = ($CHAIN_INPUT, $CHAIN_FORWARD, $CHAIN_OUTPUT);
c2a1af75 45my @ANY_ADDRESSES = ("0.0.0.0/0.0.0.0", "0.0.0.0/0", "0/0");
8f4f4634
MT
46
47my @PROTOCOLS = ("tcp", "udp", "icmp", "igmp", "ah", "esp", "gre", "ipv6", "ipip");
48my @PROTOCOLS_WITH_PORTS = ("tcp", "udp");
49
50my @VALID_TARGETS = ("ACCEPT", "DROP", "REJECT");
6178953b 51
c69c8200
MT
52my @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
ce31144c
MT
59# MARK masks
60my $NAT_MASK = 0x0f000000;
61
2a81ab0d 62my %fwdfwsettings=();
aa5f4b65 63my %fwoptions = ();
2a81ab0d 64my %defaultNetworks=();
8f4f4634 65my %configfwdfw=();;
2a81ab0d 66my %customgrp=();
2a81ab0d 67my %configinputfw=();
5d7faa45 68my %configoutgoingfw=();
a6edca5a 69my %confignatfw=();
5730a5bc
SS
70my %locationsettings = (
71 "LOCATIONBLOCK_ENABLED" => "off"
f5ad4246 72);
2801213d
SS
73my %ipset_loaded_sets = ();
74my @ipset_used_sets = ();
f5ad4246 75
6d8eb5de
AM
76my $configfwdfw = "${General::swroot}/firewall/config";
77my $configinput = "${General::swroot}/firewall/input";
78my $configoutgoing = "${General::swroot}/firewall/outgoing";
5730a5bc 79my $locationfile = "${General::swroot}/firewall/locationblock";
2a81ab0d 80my $configgrp = "${General::swroot}/fwhosts/customgroups";
210ee67b 81my $netsettings = "${General::swroot}/ethernet/settings";
86a921ee 82
6d8eb5de 83&General::readhash("${General::swroot}/firewall/settings", \%fwdfwsettings);
aa5f4b65 84&General::readhash("${General::swroot}/optionsfw/settings", \%fwoptions);
210ee67b 85&General::readhash("$netsettings", \%defaultNetworks);
2a81ab0d
AM
86&General::readhasharray($configfwdfw, \%configfwdfw);
87&General::readhasharray($configinput, \%configinputfw);
5d7faa45 88&General::readhasharray($configoutgoing, \%configoutgoingfw);
2a81ab0d 89&General::readhasharray($configgrp, \%customgrp);
2a81ab0d 90
5730a5bc
SS
91# Check if the location settings file exists
92if (-e "$locationfile") {
f5ad4246 93 # Read settings file
5730a5bc 94 &General::readhash("$locationfile", \%locationsettings);
f5ad4246
SS
95}
96
5730a5bc
SS
97# Get all available locations.
98my @locations = &Location::Functions::get_locations();
f5ad4246 99
3bb4bb3f
MT
100my @log_limit_options = &make_log_limit_options();
101
aa5f4b65
MT
102my $POLICY_INPUT_ALLOWED = 0;
103my $POLICY_FORWARD_ALLOWED = ($fwdfwsettings{"POLICY"} eq "MODE2");
104my $POLICY_OUTPUT_ALLOWED = ($fwdfwsettings{"POLICY1"} eq "MODE2");
105
106my $POLICY_INPUT_ACTION = $fwoptions{"FWPOLICY2"};
107my $POLICY_FORWARD_ACTION = $fwoptions{"FWPOLICY"};
108my $POLICY_OUTPUT_ACTION = $fwoptions{"FWPOLICY1"};
109
0564b0c7
SS
110#workaround to suppress a warning when a variable is used only once
111my @dummy = ( $Location::Functions::ipset_db_directory );
112undef (@dummy);
113
8531b94a
MT
114# MAIN
115&main();
116
117sub main {
2801213d
SS
118 # Get currently used ipset sets.
119 &ipset_get_sets();
120
8531b94a
MT
121 # Flush all chains.
122 &flush();
123
2d0c7a9f
AM
124 # Prepare firewall rules.
125 if (! -z "${General::swroot}/firewall/input"){
126 &buildrules(\%configinputfw);
127 }
128 if (! -z "${General::swroot}/firewall/outgoing"){
129 &buildrules(\%configoutgoingfw);
130 }
131 if (! -z "${General::swroot}/firewall/config"){
132 &buildrules(\%configfwdfw);
133 }
8531b94a 134
5730a5bc
SS
135 # Load Location block rules.
136 &locationblock();
211694e5 137
8531b94a
MT
138 # Reload firewall policy.
139 run("/usr/sbin/firewall-policy");
2d0c7a9f 140
2801213d
SS
141 # Cleanup not longer needed ipset sets.
142 &ipset_cleanup();
143
2d0c7a9f
AM
144 #Reload firewall.local if present
145 if ( -f '/etc/sysconfig/firewall.local'){
146 run("/etc/sysconfig/firewall.local reload");
147 }
2a81ab0d 148}
97ab0569 149
68d1eb10
MT
150sub run {
151 # Executes or prints the given shell command.
152 my $command = shift;
153
154 if ($DEBUG) {
155 print "$command\n";
156 } else {
157 system "$command";
6e87f0aa
MT
158
159 if ($?) {
160 print_error("ERROR: $command");
161 }
68d1eb10
MT
162 }
163}
164
6178953b
MT
165sub print_error {
166 my $message = shift;
167
168 print STDERR "$message\n";
169}
170
8f4f4634
MT
171sub print_rule {
172 my $hash = shift;
173
174 print "\nRULE:";
175
176 my $i = 0;
177 foreach (@$hash) {
178 printf(" %2d: %s", $i++, $_);
179 }
180 print "\n";
181}
182
791c2b45
MT
183sub count_elements {
184 my $hash = shift;
185
186 return scalar @$hash;
187}
188
97ab0569 189sub flush {
d98aa95a
MT
190 run("$IPTABLES -F $CHAIN_INPUT");
191 run("$IPTABLES -F $CHAIN_FORWARD");
192 run("$IPTABLES -F $CHAIN_OUTPUT");
193 run("$IPTABLES -t nat -F $CHAIN_NAT_SOURCE");
194 run("$IPTABLES -t nat -F $CHAIN_NAT_DESTINATION");
6e87f0aa 195 run("$IPTABLES -t mangle -F $CHAIN_MANGLE_NAT_DESTINATION_FIX");
86a921ee 196}
97ab0569 197
97ab0569 198sub buildrules {
8f4f4634
MT
199 my $hash = shift;
200
aa5f4b65
MT
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") {
ae93dd3d 210 push(@special_input_targets, ("ACCEPT", "REJECT"));
aa5f4b65 211 } elsif ($POLICY_INPUT_ACTION eq "REJECT") {
ae93dd3d 212 push(@special_input_targets, ("ACCEPT", "DROP"));
aa5f4b65
MT
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") {
ae93dd3d 222 push(@special_output_targets, ("ACCEPT", "REJECT"));
aa5f4b65 223 } elsif ($POLICY_OUTPUT_ACTION eq "REJECT") {
ae93dd3d 224 push(@special_output_targets, ("ACCEPT", "DROP"));
aa5f4b65
MT
225 }
226 }
227
8f4f4634
MT
228 foreach my $key (sort {$a <=> $b} keys %$hash) {
229 # Skip disabled rules.
230 next unless ($$hash{$key}[2] eq 'ON');
231
791c2b45
MT
232 # Count number of elements in this line
233 my $elements = &count_elements($$hash{$key});
234
8f4f4634
MT
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.
4e54e3c6 254 my @sources = &fwlib::get_addresses($hash, $key, "src");
8f4f4634
MT
255
256 # Collect all destinations.
4e54e3c6 257 my @destinations = &fwlib::get_addresses($hash, $key, "tgt");
6178953b 258
c0ce9206
MT
259 # True if the destination is the firewall itself.
260 my $destination_is_firewall = ($$hash{$key}[5] eq "ipfire");
261
6178953b 262 # Check if logging should be enabled.
8f4f4634 263 my $LOG = ($$hash{$key}[17] eq 'ON');
6178953b 264
8f4f4634
MT
265 # Check if NAT is enabled and initialize variables, that we use for that.
266 my $NAT = ($$hash{$key}[28] eq 'ON');
6178953b 267 my $NAT_MODE;
8f4f4634
MT
268 if ($NAT) {
269 $NAT_MODE = uc($$hash{$key}[31]);
270 }
6178953b 271
8f4f4634
MT
272 # Set up time constraints.
273 my @time_options = ();
274 if ($$hash{$key}[18] eq 'ON') {
275 push(@time_options, ("-m", "time"));
6178953b 276
8f4f4634
MT
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 }
6178953b 303
8f4f4634
MT
304 # Convert start time.
305 my $time_start = &format_time($$hash{$key}[26]);
306 if ($time_start) {
307 push(@time_options, ("--timestart", $time_start));
a6edca5a 308 }
6178953b 309
8f4f4634
MT
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 }
a6edca5a 315 }
6178953b 316
d2793ea8
AM
317 # Concurrent connection limit
318 my @ratelimit_options = ();
791c2b45 319
d840d02a 320 if (($elements ge 34) && ($$hash{$key}[32] eq 'ON')) {
d2793ea8
AM
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
d840d02a 336 if (($elements ge 37) && ($$hash{$key}[34] eq 'ON')) {
d2793ea8
AM
337 my $rate_limit = "$$hash{$key}[35]/$$hash{$key}[36]";
338
d840d02a
MT
339 if ($rate_limit) {
340 push(@ratelimit_options, ("-m", "limit"));
341 push(@ratelimit_options, ("--limit", $rate_limit));
342 }
d2793ea8
AM
343 }
344
8f4f4634
MT
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;
2a81ab0d 358 }
8f4f4634
MT
359
360 # Prepare protocol options (like ICMP types, ports, etc...).
d7a14d01 361 my @protocol_options = &get_protocol_options($hash, $key, $protocol, 0);
8f4f4634
MT
362
363 # Check if this protocol knows ports.
364 my $protocol_has_ports = ($protocol ~~ @PROTOCOLS_WITH_PORTS);
365
02574191
MT
366 foreach my $src (@sources) {
367 # Skip invalid source.
4e9a2b57 368 next unless (defined $src);
02574191 369 next unless ($src);
8f4f4634 370
02574191 371 # Sanitize source.
48f07c19 372 my $source = @$src[0];
02574191
MT
373 if ($source ~~ @ANY_ADDRESSES) {
374 $source = "";
375 }
376
48f07c19
AM
377 my $source_intf = @$src[1];
378
02574191
MT
379 foreach my $dst (@destinations) {
380 # Skip invalid rules.
4e9a2b57 381 next unless (defined $dst);
02574191 382 next if (!$dst || ($dst eq "none"));
c2a1af75
MT
383
384 # Sanitize destination.
48f07c19 385 my $destination = @$dst[0];
c2a1af75
MT
386 if ($destination ~~ @ANY_ADDRESSES) {
387 $destination = "";
388 }
389
48f07c19
AM
390 my $destination_intf = @$dst[1];
391
8f4f4634
MT
392 # Array with iptables arguments.
393 my @options = ();
394
395 # Append protocol.
396 if ($protocol ne "all") {
8f4f4634 397 push(@options, @protocol_options);
2a81ab0d 398 }
8f4f4634 399
6e87f0aa
MT
400 # Prepare source options.
401 my @source_options = ();
8f4f4634 402 if ($source =~ /mac/) {
6e87f0aa 403 push(@source_options, $source);
07106467
SS
404 } elsif ($source =~ /-m set/) {
405 # Grab location code from hash.
406 my $loc_src = $$hash{$key}[4];
407
bae9b5dc
SS
408 # Call function to load the networks list for this country.
409 &ipset_restore($loc_src);
07106467 410
b9ca2fa6
AM
411 push(@source_options, $source);
412 } elsif($source) {
6e87f0aa 413 push(@source_options, ("-s", $source));
2a81ab0d 414 }
14f7cb87 415
6e87f0aa 416 # Prepare destination options.
c2a1af75 417 my @destination_options = ();
07106467
SS
418 if ($destination =~ /-m set/) {
419 # Grab location code from hash.
420 my $loc_dst = $$hash{$key}[6];
421
bae9b5dc
SS
422 # Call function to load the networks list for this country.
423 &ipset_restore($loc_dst);
07106467 424
b9ca2fa6
AM
425 push(@destination_options, $destination);
426 } elsif ($destination) {
c2a1af75
MT
427 push(@destination_options, ("-d", $destination));
428 }
14f7cb87 429
249839b0
MT
430 # Add source and destination interface to the filter rules.
431 # These are supposed to help filtering forged packets that originate
432 # from BLUE with an IP address from GREEN for instance.
433 my @source_intf_options = ();
434 if ($source_intf) {
435 push(@source_intf_options, ("-i", $source_intf));
436 }
437
438 my @destination_intf_options = ();
439 if ($destination_intf) {
440 push(@destination_intf_options, ("-o", $destination_intf));
441 }
442
8f4f4634
MT
443 # Add time constraint options.
444 push(@options, @time_options);
14f7cb87 445
d2793ea8
AM
446 # Add ratelimiting option
447 push(@options, @ratelimit_options);
448
aa5f4b65 449 my $firewall_is_in_source_subnet = 1;
e9b5ba41 450 if ($source) {
da7a2208 451 $firewall_is_in_source_subnet = &firewall_is_in_subnet($source);
e9b5ba41
MT
452 }
453
aa5f4b65
MT
454 my $firewall_is_in_destination_subnet = 1;
455 if ($destination) {
456 $firewall_is_in_destination_subnet = &firewall_is_in_subnet($destination);
457 }
458
8f4f4634
MT
459 # Process NAT rules.
460 if ($NAT) {
4e54e3c6 461 my $nat_address = &fwlib::get_nat_address($$hash{$key}[29], $source);
b05ec50a 462
8f4f4634
MT
463 # Skip NAT rules if the NAT address is unknown
464 # (i.e. no internet connection has been established, yet).
465 next unless ($nat_address);
b05ec50a 466
8f4f4634
MT
467 # Destination NAT
468 if ($NAT_MODE eq "DNAT") {
d7a14d01
MT
469 my @nat_options = ();
470 if ($protocol ne "all") {
471 my @nat_protocol_options = &get_protocol_options($hash, $key, $protocol, 1);
472 push(@nat_options, @nat_protocol_options);
473 }
21b37391
SS
474
475 # Add time options.
ff7cb6d6
MT
476 push(@nat_options, @time_options);
477
21b37391
SS
478 # Determine if a REDIRECT rule should be created.
479 my $use_redirect = ($destination_is_firewall && !$destination && $protocol_has_ports);
480
ff7cb6d6 481 # Make port-forwardings useable from the internal networks.
21b37391
SS
482 if (!$use_redirect) {
483 my @internal_addresses = &fwlib::get_internal_firewall_ip_addresses(1);
484 unless ($nat_address ~~ @internal_addresses) {
485 &add_dnat_mangle_rules($nat_address, $source_intf, @nat_options);
486 }
ff7cb6d6
MT
487 }
488
21b37391 489 # Add source options.
6e87f0aa 490 push(@nat_options, @source_options);
21b37391
SS
491
492 # Add NAT address.
493 if (!$use_redirect) {
494 push(@nat_options, ("-d", $nat_address));
495 }
6e87f0aa 496
c0ce9206 497 my $dnat_port;
8f4f4634 498 if ($protocol_has_ports) {
c0ce9206
MT
499 $dnat_port = &get_dnat_target_port($hash, $key);
500 }
501
502 my @nat_action_options = ();
b05ec50a 503
c0ce9206 504 # Use iptables REDIRECT
c0ce9206 505 if ($use_redirect) {
21b37391
SS
506 push(@nat_action_options, ("-j", "REDIRECT"));
507
508 # Redirect to specified port if one has given.
509 if ($dnat_port) {
510 push(@nat_action_options, ("--to-ports", $dnat_port));
511 }
c0ce9206
MT
512
513 # Use iptables DNAT
514 } else {
f98bb538
MT
515 if ($destination_is_firewall && !$destination) {
516 $destination = &fwlib::get_external_address();
517 }
518 next unless ($destination);
519
c0ce9206
MT
520 my ($dnat_address, $dnat_mask) = split("/", $destination);
521 @destination_options = ("-d", $dnat_address);
522
523 if ($protocol_has_ports) {
524 my $dnat_port = &get_dnat_target_port($hash, $key);
525
526 if ($dnat_port) {
527 $dnat_address .= ":$dnat_port";
528 }
86a921ee 529 }
c0ce9206
MT
530
531 push(@nat_action_options, ("-j", "DNAT", "--to-destination", $dnat_address));
2a81ab0d 532 }
8f4f4634
MT
533
534 if ($LOG) {
3bb4bb3f 535 run("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @log_limit_options -j LOG --log-prefix 'DNAT '");
8f4f4634 536 }
c0ce9206 537 run("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @nat_action_options");
8f4f4634
MT
538
539 # Source NAT
540 } elsif ($NAT_MODE eq "SNAT") {
c4b7692a 541 my @snat_options = ( "-m", "policy", "--dir", "out", "--pol", "none" );
6e87f0aa
MT
542 my @nat_options = @options;
543
c4b7692a
SS
544 # Get addresses for the configured firewall interfaces.
545 my @local_addresses = &fwlib::get_internal_firewall_ip_addresses(1);
546
547 # Check if the nat_address is one of the local addresses.
548 foreach my $local_address (@local_addresses) {
549 if ($nat_address eq $local_address) {
550 # Clear SNAT options.
551 @snat_options = ();
552
553 # Finish loop.
554 last;
555 }
556 }
557
249839b0 558 push(@nat_options, @destination_intf_options);
6e87f0aa
MT
559 push(@nat_options, @source_options);
560 push(@nat_options, @destination_options);
561
8f4f4634 562 if ($LOG) {
c4b7692a 563 run("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options @snat_options @log_limit_options -j LOG --log-prefix 'SNAT '");
8f4f4634 564 }
c4b7692a 565 run("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options @snat_options -j SNAT --to-source $nat_address");
2a81ab0d
AM
566 }
567 }
8f4f4634 568
6e87f0aa
MT
569 push(@options, @source_options);
570 push(@options, @destination_options);
571
8f4f4634 572 # Insert firewall rule.
c22369a9 573 if ($LOG) {
249839b0 574 run("$IPTABLES -A $chain @options @source_intf_options @destination_intf_options @log_limit_options -j LOG --log-prefix '$chain '");
8f4f4634 575 }
249839b0 576 run("$IPTABLES -A $chain @options @source_intf_options @destination_intf_options -j $target");
aa5f4b65
MT
577
578 # Handle forwarding rules and add corresponding rules for firewall access.
579 if ($chain eq $CHAIN_FORWARD) {
580 # If the firewall is part of the destination subnet and access to the destination network
581 # is granted/forbidden for any network that the firewall itself is part of, we grant/forbid access
582 # for the firewall, too.
583 if ($firewall_is_in_destination_subnet && ($target ~~ @special_input_targets)) {
c22369a9 584 if ($LOG) {
249839b0 585 run("$IPTABLES -A $CHAIN_INPUT @options @source_intf_options @log_limit_options -j LOG --log-prefix '$CHAIN_INPUT '");
aa5f4b65 586 }
249839b0 587 run("$IPTABLES -A $CHAIN_INPUT @options @source_intf_options -j $target");
aa5f4b65
MT
588 }
589
590 # Likewise.
591 if ($firewall_is_in_source_subnet && ($target ~~ @special_output_targets)) {
c22369a9 592 if ($LOG) {
249839b0 593 run("$IPTABLES -A $CHAIN_OUTPUT @options @destination_intf_options @log_limit_options -j LOG --log-prefix '$CHAIN_OUTPUT '");
aa5f4b65 594 }
249839b0 595 run("$IPTABLES -A $CHAIN_OUTPUT @options @destination_intf_options -j $target");
aa5f4b65
MT
596 }
597 }
2a81ab0d
AM
598 }
599 }
600 }
2a81ab0d
AM
601 }
602}
97ab0569 603
b05ec50a
MT
604# Formats the given timestamp into the iptables format which is "hh:mm" UTC.
605sub format_time {
606 my $val = shift;
607
608 # Convert the given time into minutes.
609 my $minutes = &time_convert_to_minutes($val);
610
611 # Move the timestamp into UTC.
612 $minutes += &time_utc_offset();
613
614 # Make sure $minutes is between 00:00 and 23:59.
615 if ($minutes < 0) {
616 $minutes += 1440;
617 }
618
619 if ($minutes > 1440) {
620 $minutes -= 1440;
621 }
622
623 # Format as hh:mm.
624 return sprintf("%02d:%02d", $minutes / 60, $minutes % 60);
472136c9 625}
97ab0569 626
b05ec50a
MT
627# Calculates the offsets in minutes from the local timezone to UTC.
628sub time_utc_offset {
629 my @localtime = localtime(time);
630 my @gmtime = gmtime(time);
631
632 return ($gmtime[2] * 60 + $gmtime[1] % 60) - ($localtime[2] * 60 + $localtime[1] % 60);
472136c9 633}
97ab0569 634
b05ec50a
MT
635# Takes a timestamp like "14:00" and converts it into minutes since midnight.
636sub time_convert_to_minutes {
637 my ($hrs, $min) = split(":", shift);
638
639 return ($hrs * 60) + $min;
472136c9 640}
97ab0569 641
5730a5bc 642sub locationblock {
2801213d
SS
643 # Flush LOCATIONBLOCK chain.
644 run("$IPTABLES -F LOCATIONBLOCK");
211694e5 645
5730a5bc
SS
646 # If location blocking is not enabled, we are finished here.
647 if ($locationsettings{'LOCATIONBLOCK_ENABLED'} ne "on") {
211694e5
SS
648 # Exit submodule. Process remaining script.
649 return;
650 }
651
2293e1de
PM
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 "") {
c69c8200
MT
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
5730a5bc
SS
665 # Loop through all supported locations and
666 # create iptables rules, if blocking for this country
211694e5
SS
667 # is enabled.
668 foreach my $location (@locations) {
5730a5bc 669 if(exists $locationsettings{$location} && $locationsettings{$location} eq "on") {
bae9b5dc
SS
670 # Call function to load the networks list for this country.
671 &ipset_restore($location);
0df1d268
SS
672
673 # Call iptables and create rule to use the loaded ipset list.
2801213d 674 run("$IPTABLES -A LOCATIONBLOCK -m set --match-set $location src -j DROP");
211694e5
SS
675 }
676 }
677}
678
8f4f4634
MT
679sub get_protocols {
680 my $hash = shift;
681 my $key = shift;
682
683 my $uses_source_ports = ($$hash{$key}[7] eq "ON");
684 my $uses_services = ($$hash{$key}[11] eq "ON");
685
686 my @protocols = ();
687
688 # Rules which don't have source ports or services (like ICMP, ESP, ...).
689 if (!$uses_source_ports && !$uses_services) {
690 push(@protocols, $$hash{$key}[8]);
691
692 # Rules which either use ports or services.
693 } elsif ($uses_source_ports || $uses_services) {
694 # Check if service group or service
695 if ($$hash{$key}[14] eq 'cust_srv') {
696 push(@protocols, &fwlib::get_srv_prot($$hash{$key}[15]));
697
698 } elsif($$hash{$key}[14] eq 'cust_srvgrp'){
699 my $protos = &fwlib::get_srvgrp_prot($$hash{$key}[15]);
700 push(@protocols, split(",", $protos));
701
702 } else {
703 # Fetch the protocol for this rule.
704 my $protocol = lc($$hash{$key}[8]);
705
706 # Fetch source and destination ports for this rule.
707 my $source_ports = $$hash{$key}[10];
708 my $destination_ports = $$hash{$key}[15];
709
710 # Check if ports are set for protocols which do not support ports.
711 if (!($protocol ~~ @PROTOCOLS_WITH_PORTS) && ($source_ports || $destination_ports)) {
712 print_error("$protocol does not support ports");
713 return ();
714 }
715
716 push(@protocols, $protocol);
2a81ab0d
AM
717 }
718 }
8f4f4634
MT
719
720 # Remove all empty elements
721 @protocols = map { $_ ? $_ : () } @protocols;
722
723 # If no protocol has been defined, we assume "all".
724 if (!@protocols) {
725 push(@protocols, "all");
98cee89f 726 }
8f4f4634
MT
727
728 # Make all protocol names lowercase.
729 @protocols = map { lc } @protocols;
730
731 return @protocols;
2a81ab0d 732}
97ab0569 733
8f4f4634
MT
734sub get_protocol_options {
735 my $hash = shift;
736 my $key = shift;
737 my $protocol = shift;
d7a14d01 738 my $nat_options_wanted = shift;
8f4f4634
MT
739 my @options = ();
740
d7a14d01
MT
741 # Nothing to do if no protocol is specified.
742 if ($protocol eq "all") {
743 return @options;
744 } else {
745 push(@options, ("-p", $protocol));
746 }
747
fcc68a42
MT
748 if ($protocol ~~ @PROTOCOLS_WITH_PORTS) {
749 # Process source ports.
750 my $use_src_ports = ($$hash{$key}[7] eq "ON");
751 my $src_ports = $$hash{$key}[10];
8f4f4634 752
fcc68a42
MT
753 if ($use_src_ports && $src_ports) {
754 push(@options, &format_ports($src_ports, "src"));
755 }
8f4f4634 756
fcc68a42
MT
757 # Process destination ports.
758 my $use_dst_ports = ($$hash{$key}[11] eq "ON");
759 my $use_dnat = (($$hash{$key}[28] eq "ON") && ($$hash{$key}[31] eq "dnat"));
8f4f4634 760
fcc68a42
MT
761 if ($use_dst_ports) {
762 my $dst_ports_mode = $$hash{$key}[14];
763 my $dst_ports = $$hash{$key}[15];
8f4f4634 764
fcc68a42
MT
765 if (($dst_ports_mode eq "TGT_PORT") && $dst_ports) {
766 if ($nat_options_wanted && $use_dnat && $$hash{$key}[30]) {
767 $dst_ports = $$hash{$key}[30];
768 }
8f4f4634 769 push(@options, &format_ports($dst_ports, "dst"));
8f4f4634 770
fcc68a42
MT
771 } elsif ($dst_ports_mode eq "cust_srv") {
772 if ($protocol eq "ICMP") {
773 push(@options, ("--icmp-type", &fwlib::get_srv_port($dst_ports, 3, "ICMP")));
774 } else {
775 $dst_ports = &fwlib::get_srv_port($dst_ports, 1, uc($protocol));
776 push(@options, &format_ports($dst_ports, "dst"));
777 }
778
779 } elsif ($dst_ports_mode eq "cust_srvgrp") {
780 push(@options, &fwlib::get_srvgrp_port($dst_ports, uc($protocol)));
781 }
2a81ab0d
AM
782 }
783 }
8f4f4634
MT
784
785 # Check if a single ICMP type is selected.
fcc68a42 786 if ($protocol eq "icmp") {
8f4f4634
MT
787 my $icmp_type = $$hash{$key}[9];
788
789 if (($icmp_type ne "All ICMP-Types") && $icmp_type) {
790 push(@options, ("--icmp-type", $icmp_type));
a4c7bf6b
AM
791 }
792 }
8f4f4634
MT
793
794 return @options;
795}
796
797sub format_ports {
798 my $ports = shift;
799 my $type = shift;
800
801 my $arg;
802 if ($type eq "src") {
803 $arg = "--sport";
804 } elsif ($type eq "dst") {
805 $arg = "--dport";
806 }
807
808 my @options = ();
809
810 if ($ports =~ /\|/) {
811 $ports =~ s/\|/,/g;
812 push(@options, ("-m", "multiport"));
813 }
814
1c3044d7
MT
815 if ($ports) {
816 push(@options, ($arg, $ports));
817 }
8f4f4634
MT
818
819 return @options;
820}
821
822sub get_dnat_target_port {
823 my $hash = shift;
824 my $key = shift;
825
826 if ($$hash{$key}[14] eq "TGT_PORT") {
1c3044d7
MT
827 my $port = $$hash{$key}[15];
828 my $external_port = $$hash{$key}[30];
829
830 if ($external_port && ($port ne $external_port)) {
831 return $$hash{$key}[15];
832 }
8f4f4634 833 }
2a81ab0d 834}
6e87f0aa
MT
835
836sub add_dnat_mangle_rules {
837 my $nat_address = shift;
48f07c19 838 my $interface = shift;
6e87f0aa
MT
839 my @options = @_;
840
ce31144c 841 my $mark = 0x01000000;
6e87f0aa 842 foreach my $zone ("GREEN", "BLUE", "ORANGE") {
6e87f0aa
MT
843 # Skip rule if not all required information exists.
844 next unless (exists $defaultNetworks{$zone . "_NETADDRESS"});
845 next unless (exists $defaultNetworks{$zone . "_NETMASK"});
846
48f07c19
AM
847 next if ($interface && $interface ne $defaultNetworks{$zone . "_DEV"});
848
6e87f0aa
MT
849 my @mangle_options = @options;
850
851 my $netaddress = $defaultNetworks{$zone . "_NETADDRESS"};
852 $netaddress .= "/" . $defaultNetworks{$zone . "_NETMASK"};
853
854 push(@mangle_options, ("-s", $netaddress, "-d", $nat_address));
ce31144c 855 push(@mangle_options, ("-j", "MARK", "--set-xmark", "$mark/$NAT_MASK"));
6e87f0aa
MT
856
857 run("$IPTABLES -t mangle -A $CHAIN_MANGLE_NAT_DESTINATION_FIX @mangle_options");
ce31144c
MT
858
859 $mark <<= 1;
6e87f0aa
MT
860 }
861}
3bb4bb3f
MT
862
863sub make_log_limit_options {
864 my @options = ("-m", "limit");
865
866 # Maybe we should get this from the configuration.
867 my $limit = 10;
868
a85a7a60 869 # We limit log messages to $limit messages per second.
870 push(@options, ("--limit", "$limit/second"));
3bb4bb3f
MT
871
872 # And we allow bursts of 2x $limit.
873 push(@options, ("--limit-burst", $limit * 2));
874
875 return @options;
876}
e9b5ba41 877
da7a2208
MT
878sub firewall_is_in_subnet {
879 my $subnet = shift;
5cf8c8c1 880
e9b5ba41
MT
881 # ORANGE is missing here, because nothing may ever access
882 # the firewall from this network.
4e54e3c6 883 my $address = &fwlib::get_internal_firewall_ip_address($subnet, 0);
e9b5ba41 884
da7a2208
MT
885 if ($address) {
886 return 1;
e9b5ba41 887 }
da7a2208
MT
888
889 return 0;
e9b5ba41 890}
6babb404 891
2801213d
SS
892sub ipset_get_sets () {
893 # Get all currently used ipset lists and store them in an array.
894 my @output = `$IPSET -n list`;
895
896 # Loop through the temporary array.
897 foreach my $set (@output) {
898 # Remove any newlines.
899 chomp($set);
900
901 # Add the set the array of used sets.
902 push(@ipset_used_sets, $set);
903 }
904
905 # Display used sets in debug mode.
906 if($DEBUG) {
907 print "Used ipset sets:\n";
908 print "@ipset_used_sets\n\n";
909 }
910}
911
6babb404 912sub ipset_restore ($) {
2801213d 913 my ($set) = @_;
6babb404 914
50e43059 915 my $file_prefix = "ipset4";
2801213d 916 my $db_file = "$Location::Functions::ipset_db_directory/$set.$file_prefix";
bae9b5dc 917
2801213d
SS
918 # Check if the set already has been loaded.
919 if($ipset_loaded_sets{$set}) {
bae9b5dc
SS
920 # It already has been loaded - so there is nothing to do.
921 return;
922 }
50e43059
SS
923
924 # Check if the generated file exists.
925 if (-f $db_file) {
2801213d 926 # Run ipset and restore the given set.
50e43059 927 run("$IPSET restore < $db_file");
bae9b5dc 928
2801213d
SS
929 # Store the restored set to the hash to prevent from loading it again.
930 $ipset_loaded_sets{$set} = "1";
931 }
932}
933
934sub ipset_cleanup () {
935 # Loop through the array of used sets.
936 foreach my $set (@ipset_used_sets) {
937 # Check if this set is still in use.
938 #
939 # In this case an entry in the loaded sets hash exists.
940 unless($ipset_loaded_sets{$set}) {
941 # Entry does not exist, so this set is not longer
942 # used and can be destroyed.
943 run("$IPSET destroy $set");
944 }
50e43059 945 }
6babb404 946}