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