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