]> git.ipfire.org Git - ipfire-2.x.git/blame - config/firewall/rules.pl
rules.pl: Destroy all ipset lists on rule reload.
[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
SS
72);
73
36196d0d 74my @p2ps=();
2a81ab0d 75
6d8eb5de
AM
76my $configfwdfw = "${General::swroot}/firewall/config";
77my $configinput = "${General::swroot}/firewall/input";
78my $configoutgoing = "${General::swroot}/firewall/outgoing";
79my $p2pfile = "${General::swroot}/firewall/p2protocols";
5730a5bc 80my $locationfile = "${General::swroot}/firewall/locationblock";
2a81ab0d 81my $configgrp = "${General::swroot}/fwhosts/customgroups";
210ee67b 82my $netsettings = "${General::swroot}/ethernet/settings";
86a921ee 83
6d8eb5de 84&General::readhash("${General::swroot}/firewall/settings", \%fwdfwsettings);
aa5f4b65 85&General::readhash("${General::swroot}/optionsfw/settings", \%fwoptions);
210ee67b 86&General::readhash("$netsettings", \%defaultNetworks);
2a81ab0d
AM
87&General::readhasharray($configfwdfw, \%configfwdfw);
88&General::readhasharray($configinput, \%configinputfw);
5d7faa45 89&General::readhasharray($configoutgoing, \%configoutgoingfw);
2a81ab0d 90&General::readhasharray($configgrp, \%customgrp);
2a81ab0d 91
5730a5bc
SS
92# Check if the location settings file exists
93if (-e "$locationfile") {
f5ad4246 94 # Read settings file
5730a5bc 95 &General::readhash("$locationfile", \%locationsettings);
f5ad4246
SS
96}
97
5730a5bc
SS
98# Get all available locations.
99my @locations = &Location::Functions::get_locations();
f5ad4246 100
3bb4bb3f
MT
101my @log_limit_options = &make_log_limit_options();
102
aa5f4b65
MT
103my $POLICY_INPUT_ALLOWED = 0;
104my $POLICY_FORWARD_ALLOWED = ($fwdfwsettings{"POLICY"} eq "MODE2");
105my $POLICY_OUTPUT_ALLOWED = ($fwdfwsettings{"POLICY1"} eq "MODE2");
106
107my $POLICY_INPUT_ACTION = $fwoptions{"FWPOLICY2"};
108my $POLICY_FORWARD_ACTION = $fwoptions{"FWPOLICY"};
109my $POLICY_OUTPUT_ACTION = $fwoptions{"FWPOLICY1"};
110
8531b94a
MT
111# MAIN
112&main();
113
114sub main {
115 # Flush all chains.
116 &flush();
117
3d886880
SS
118 # Destroy all existing ipsets.
119 run("$IPSET destroy");
120
2d0c7a9f
AM
121 # Prepare firewall rules.
122 if (! -z "${General::swroot}/firewall/input"){
123 &buildrules(\%configinputfw);
124 }
125 if (! -z "${General::swroot}/firewall/outgoing"){
126 &buildrules(\%configoutgoingfw);
127 }
128 if (! -z "${General::swroot}/firewall/config"){
129 &buildrules(\%configfwdfw);
130 }
8531b94a
MT
131
132 # Load P2P block rules.
133 &p2pblock();
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
AM
140
141 #Reload firewall.local if present
142 if ( -f '/etc/sysconfig/firewall.local'){
143 run("/etc/sysconfig/firewall.local reload");
144 }
2a81ab0d 145}
97ab0569 146
68d1eb10
MT
147sub run {
148 # Executes or prints the given shell command.
149 my $command = shift;
150
151 if ($DEBUG) {
152 print "$command\n";
153 } else {
154 system "$command";
6e87f0aa
MT
155
156 if ($?) {
157 print_error("ERROR: $command");
158 }
68d1eb10
MT
159 }
160}
161
6178953b
MT
162sub print_error {
163 my $message = shift;
164
165 print STDERR "$message\n";
166}
167
8f4f4634
MT
168sub print_rule {
169 my $hash = shift;
170
171 print "\nRULE:";
172
173 my $i = 0;
174 foreach (@$hash) {
175 printf(" %2d: %s", $i++, $_);
176 }
177 print "\n";
178}
179
791c2b45
MT
180sub count_elements {
181 my $hash = shift;
182
183 return scalar @$hash;
184}
185
97ab0569 186sub flush {
d98aa95a
MT
187 run("$IPTABLES -F $CHAIN_INPUT");
188 run("$IPTABLES -F $CHAIN_FORWARD");
189 run("$IPTABLES -F $CHAIN_OUTPUT");
190 run("$IPTABLES -t nat -F $CHAIN_NAT_SOURCE");
191 run("$IPTABLES -t nat -F $CHAIN_NAT_DESTINATION");
6e87f0aa 192 run("$IPTABLES -t mangle -F $CHAIN_MANGLE_NAT_DESTINATION_FIX");
bbeb2a50
SS
193
194 # Flush LOCATIONBLOCK chain.
195 run("$IPTABLES -F LOCATIONBLOCK");
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);
b9ca2fa6
AM
404 } elsif ($source =~ /-m geoip/) {
405 push(@source_options, $source);
406 } elsif($source) {
6e87f0aa 407 push(@source_options, ("-s", $source));
2a81ab0d 408 }
14f7cb87 409
6e87f0aa 410 # Prepare destination options.
c2a1af75 411 my @destination_options = ();
b9ca2fa6
AM
412 if ($destination =~ /-m geoip/) {
413 push(@destination_options, $destination);
414 } elsif ($destination) {
c2a1af75
MT
415 push(@destination_options, ("-d", $destination));
416 }
14f7cb87 417
249839b0
MT
418 # Add source and destination interface to the filter rules.
419 # These are supposed to help filtering forged packets that originate
420 # from BLUE with an IP address from GREEN for instance.
421 my @source_intf_options = ();
422 if ($source_intf) {
423 push(@source_intf_options, ("-i", $source_intf));
424 }
425
426 my @destination_intf_options = ();
427 if ($destination_intf) {
428 push(@destination_intf_options, ("-o", $destination_intf));
429 }
430
8f4f4634
MT
431 # Add time constraint options.
432 push(@options, @time_options);
14f7cb87 433
d2793ea8
AM
434 # Add ratelimiting option
435 push(@options, @ratelimit_options);
436
aa5f4b65 437 my $firewall_is_in_source_subnet = 1;
e9b5ba41 438 if ($source) {
da7a2208 439 $firewall_is_in_source_subnet = &firewall_is_in_subnet($source);
e9b5ba41
MT
440 }
441
aa5f4b65
MT
442 my $firewall_is_in_destination_subnet = 1;
443 if ($destination) {
444 $firewall_is_in_destination_subnet = &firewall_is_in_subnet($destination);
445 }
446
8f4f4634
MT
447 # Process NAT rules.
448 if ($NAT) {
4e54e3c6 449 my $nat_address = &fwlib::get_nat_address($$hash{$key}[29], $source);
b05ec50a 450
8f4f4634
MT
451 # Skip NAT rules if the NAT address is unknown
452 # (i.e. no internet connection has been established, yet).
453 next unless ($nat_address);
b05ec50a 454
8f4f4634
MT
455 # Destination NAT
456 if ($NAT_MODE eq "DNAT") {
d7a14d01
MT
457 my @nat_options = ();
458 if ($protocol ne "all") {
459 my @nat_protocol_options = &get_protocol_options($hash, $key, $protocol, 1);
460 push(@nat_options, @nat_protocol_options);
461 }
21b37391
SS
462
463 # Add time options.
ff7cb6d6
MT
464 push(@nat_options, @time_options);
465
21b37391
SS
466 # Determine if a REDIRECT rule should be created.
467 my $use_redirect = ($destination_is_firewall && !$destination && $protocol_has_ports);
468
ff7cb6d6 469 # Make port-forwardings useable from the internal networks.
21b37391
SS
470 if (!$use_redirect) {
471 my @internal_addresses = &fwlib::get_internal_firewall_ip_addresses(1);
472 unless ($nat_address ~~ @internal_addresses) {
473 &add_dnat_mangle_rules($nat_address, $source_intf, @nat_options);
474 }
ff7cb6d6
MT
475 }
476
21b37391 477 # Add source options.
6e87f0aa 478 push(@nat_options, @source_options);
21b37391
SS
479
480 # Add NAT address.
481 if (!$use_redirect) {
482 push(@nat_options, ("-d", $nat_address));
483 }
6e87f0aa 484
c0ce9206 485 my $dnat_port;
8f4f4634 486 if ($protocol_has_ports) {
c0ce9206
MT
487 $dnat_port = &get_dnat_target_port($hash, $key);
488 }
489
490 my @nat_action_options = ();
b05ec50a 491
c0ce9206 492 # Use iptables REDIRECT
c0ce9206 493 if ($use_redirect) {
21b37391
SS
494 push(@nat_action_options, ("-j", "REDIRECT"));
495
496 # Redirect to specified port if one has given.
497 if ($dnat_port) {
498 push(@nat_action_options, ("--to-ports", $dnat_port));
499 }
c0ce9206
MT
500
501 # Use iptables DNAT
502 } else {
f98bb538
MT
503 if ($destination_is_firewall && !$destination) {
504 $destination = &fwlib::get_external_address();
505 }
506 next unless ($destination);
507
c0ce9206
MT
508 my ($dnat_address, $dnat_mask) = split("/", $destination);
509 @destination_options = ("-d", $dnat_address);
510
511 if ($protocol_has_ports) {
512 my $dnat_port = &get_dnat_target_port($hash, $key);
513
514 if ($dnat_port) {
515 $dnat_address .= ":$dnat_port";
516 }
86a921ee 517 }
c0ce9206
MT
518
519 push(@nat_action_options, ("-j", "DNAT", "--to-destination", $dnat_address));
2a81ab0d 520 }
8f4f4634
MT
521
522 if ($LOG) {
3bb4bb3f 523 run("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @log_limit_options -j LOG --log-prefix 'DNAT '");
8f4f4634 524 }
c0ce9206 525 run("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @nat_action_options");
8f4f4634
MT
526
527 # Source NAT
528 } elsif ($NAT_MODE eq "SNAT") {
c4b7692a 529 my @snat_options = ( "-m", "policy", "--dir", "out", "--pol", "none" );
6e87f0aa
MT
530 my @nat_options = @options;
531
c4b7692a
SS
532 # Get addresses for the configured firewall interfaces.
533 my @local_addresses = &fwlib::get_internal_firewall_ip_addresses(1);
534
535 # Check if the nat_address is one of the local addresses.
536 foreach my $local_address (@local_addresses) {
537 if ($nat_address eq $local_address) {
538 # Clear SNAT options.
539 @snat_options = ();
540
541 # Finish loop.
542 last;
543 }
544 }
545
249839b0 546 push(@nat_options, @destination_intf_options);
6e87f0aa
MT
547 push(@nat_options, @source_options);
548 push(@nat_options, @destination_options);
549
8f4f4634 550 if ($LOG) {
c4b7692a 551 run("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options @snat_options @log_limit_options -j LOG --log-prefix 'SNAT '");
8f4f4634 552 }
c4b7692a 553 run("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options @snat_options -j SNAT --to-source $nat_address");
2a81ab0d
AM
554 }
555 }
8f4f4634 556
6e87f0aa
MT
557 push(@options, @source_options);
558 push(@options, @destination_options);
559
8f4f4634 560 # Insert firewall rule.
c22369a9 561 if ($LOG) {
249839b0 562 run("$IPTABLES -A $chain @options @source_intf_options @destination_intf_options @log_limit_options -j LOG --log-prefix '$chain '");
8f4f4634 563 }
249839b0 564 run("$IPTABLES -A $chain @options @source_intf_options @destination_intf_options -j $target");
aa5f4b65
MT
565
566 # Handle forwarding rules and add corresponding rules for firewall access.
567 if ($chain eq $CHAIN_FORWARD) {
568 # If the firewall is part of the destination subnet and access to the destination network
569 # is granted/forbidden for any network that the firewall itself is part of, we grant/forbid access
570 # for the firewall, too.
571 if ($firewall_is_in_destination_subnet && ($target ~~ @special_input_targets)) {
c22369a9 572 if ($LOG) {
249839b0 573 run("$IPTABLES -A $CHAIN_INPUT @options @source_intf_options @log_limit_options -j LOG --log-prefix '$CHAIN_INPUT '");
aa5f4b65 574 }
249839b0 575 run("$IPTABLES -A $CHAIN_INPUT @options @source_intf_options -j $target");
aa5f4b65
MT
576 }
577
578 # Likewise.
579 if ($firewall_is_in_source_subnet && ($target ~~ @special_output_targets)) {
c22369a9 580 if ($LOG) {
249839b0 581 run("$IPTABLES -A $CHAIN_OUTPUT @options @destination_intf_options @log_limit_options -j LOG --log-prefix '$CHAIN_OUTPUT '");
aa5f4b65 582 }
249839b0 583 run("$IPTABLES -A $CHAIN_OUTPUT @options @destination_intf_options -j $target");
aa5f4b65
MT
584 }
585 }
2a81ab0d
AM
586 }
587 }
588 }
2a81ab0d
AM
589 }
590}
97ab0569 591
b05ec50a
MT
592# Formats the given timestamp into the iptables format which is "hh:mm" UTC.
593sub format_time {
594 my $val = shift;
595
596 # Convert the given time into minutes.
597 my $minutes = &time_convert_to_minutes($val);
598
599 # Move the timestamp into UTC.
600 $minutes += &time_utc_offset();
601
602 # Make sure $minutes is between 00:00 and 23:59.
603 if ($minutes < 0) {
604 $minutes += 1440;
605 }
606
607 if ($minutes > 1440) {
608 $minutes -= 1440;
609 }
610
611 # Format as hh:mm.
612 return sprintf("%02d:%02d", $minutes / 60, $minutes % 60);
472136c9 613}
97ab0569 614
b05ec50a
MT
615# Calculates the offsets in minutes from the local timezone to UTC.
616sub time_utc_offset {
617 my @localtime = localtime(time);
618 my @gmtime = gmtime(time);
619
620 return ($gmtime[2] * 60 + $gmtime[1] % 60) - ($localtime[2] * 60 + $localtime[1] % 60);
472136c9 621}
97ab0569 622
b05ec50a
MT
623# Takes a timestamp like "14:00" and converts it into minutes since midnight.
624sub time_convert_to_minutes {
625 my ($hrs, $min) = split(":", shift);
626
627 return ($hrs * 60) + $min;
472136c9 628}
97ab0569
MT
629
630sub p2pblock {
766c2f60
MT
631 open(FILE, "<$p2pfile") or die "Unable to read $p2pfile";
632 my @protocols = ();
633 foreach my $p2pentry (<FILE>) {
634 my @p2pline = split(/\;/, $p2pentry);
2a5b19c5 635 next unless ($p2pline[2] eq "off");
766c2f60
MT
636
637 push(@protocols, "--$p2pline[1]");
36196d0d 638 }
766c2f60 639 close(FILE);
68d1eb10 640
24d36c80 641 run("$IPTABLES -F P2PBLOCK");
766c2f60 642 if (@protocols) {
2a5b19c5 643 run("$IPTABLES -A P2PBLOCK -m ipp2p @protocols -j DROP");
36196d0d
AM
644 }
645}
97ab0569 646
5730a5bc 647sub locationblock {
bbeb2a50 648 # The LOCATIONBLOCK chain now gets flushed by the flush() function.
211694e5 649
5730a5bc
SS
650 # If location blocking is not enabled, we are finished here.
651 if ($locationsettings{'LOCATIONBLOCK_ENABLED'} ne "on") {
211694e5
SS
652 # Exit submodule. Process remaining script.
653 return;
654 }
655
2293e1de
PM
656 # Only check the RED interface, which is ppp0 in case of RED_TYPE being
657 # set to "PPPOE", and red0 in case of RED_TYPE not being empty otherwise.
658 if ($defaultNetworks{'RED_TYPE'} eq "PPPOE") {
659 run("$IPTABLES -A LOCATIONBLOCK ! -i ppp0 -j RETURN");
660 } elsif ($defaultNetworks{'RED_DEV'} ne "") {
c69c8200
MT
661 run("$IPTABLES -A LOCATIONBLOCK ! -i $defaultNetworks{'RED_DEV'} -j RETURN");
662 }
663
664 # Do not check any private address space
665 foreach my $network (@PRIVATE_NETWORKS) {
666 run("$IPTABLES -A LOCATIONBLOCK -s $network -j RETURN");
667 }
668
5730a5bc
SS
669 # Loop through all supported locations and
670 # create iptables rules, if blocking for this country
211694e5
SS
671 # is enabled.
672 foreach my $location (@locations) {
5730a5bc 673 if(exists $locationsettings{$location} && $locationsettings{$location} eq "on") {
0e6eca78 674 run("$IPTABLES -A LOCATIONBLOCK -m geoip --src-cc $location -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}