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