firewall: Fix perl coding error.
[people/teissler/ipfire-2.x.git] / config / firewall / rules.pl
1 #!/usr/bin/perl -w
2 ###############################################################################
3 # #
4 # IPFire.org - A linux based firewall #
5 # Copyright (C) 2013 Alexander Marx <amarx@ipfire.org> #
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 ###############################################################################
21
22 use strict;
23
24 require '/var/ipfire/general-functions.pl';
25 require "${General::swroot}/lang.pl";
26 require "/usr/lib/firewall/firewall-lib.pl";
27
28 # Set to one to enable debugging mode.
29 my $DEBUG = 0;
30
31 my $IPTABLES = "iptables --wait";
32
33 # iptables chains
34 my $CHAIN_INPUT = "INPUTFW";
35 my $CHAIN_FORWARD = "FORWARDFW";
36 my $CHAIN_OUTPUT = "OUTGOINGFW";
37 my $CHAIN = $CHAIN_FORWARD;
38 my $CHAIN_NAT_SOURCE = "NAT_SOURCE";
39 my $CHAIN_NAT_DESTINATION = "NAT_DESTINATION";
40 my $CHAIN_MANGLE_NAT_DESTINATION_FIX = "NAT_DESTINATION";
41 my @VALID_CHAINS = ($CHAIN_INPUT, $CHAIN_FORWARD, $CHAIN_OUTPUT);
42 my @ANY_ADDRESSES = ("0.0.0.0/0.0.0.0", "0.0.0.0/0", "0/0");
43
44 my @PROTOCOLS = ("tcp", "udp", "icmp", "igmp", "ah", "esp", "gre", "ipv6", "ipip");
45 my @PROTOCOLS_WITH_PORTS = ("tcp", "udp");
46
47 my @VALID_TARGETS = ("ACCEPT", "DROP", "REJECT");
48
49 my %fwdfwsettings=();
50 my %defaultNetworks=();
51 my %configfwdfw=();;
52 my %customgrp=();
53 my %configinputfw=();
54 my %configoutgoingfw=();
55 my %confignatfw=();
56 my %aliases=();
57 my @p2ps=();
58
59 my $configfwdfw = "${General::swroot}/firewall/config";
60 my $configinput = "${General::swroot}/firewall/input";
61 my $configoutgoing = "${General::swroot}/firewall/outgoing";
62 my $p2pfile = "${General::swroot}/firewall/p2protocols";
63 my $configgrp = "${General::swroot}/fwhosts/customgroups";
64 my $netsettings = "${General::swroot}/ethernet/settings";
65
66 &General::readhash("${General::swroot}/firewall/settings", \%fwdfwsettings);
67 &General::readhash("$netsettings", \%defaultNetworks);
68 &General::readhasharray($configfwdfw, \%configfwdfw);
69 &General::readhasharray($configinput, \%configinputfw);
70 &General::readhasharray($configoutgoing, \%configoutgoingfw);
71 &General::readhasharray($configgrp, \%customgrp);
72 &General::get_aliases(\%aliases);
73
74 my @log_limit_options = &make_log_limit_options();
75
76 # MAIN
77 &main();
78
79 sub main {
80 # Flush all chains.
81 &flush();
82
83 # Reload firewall rules.
84 &preparerules();
85
86 # Load P2P block rules.
87 &p2pblock();
88
89 # Reload firewall policy.
90 run("/usr/sbin/firewall-policy");
91 }
92
93 sub run {
94 # Executes or prints the given shell command.
95 my $command = shift;
96
97 if ($DEBUG) {
98 print "$command\n";
99 } else {
100 system "$command";
101
102 if ($?) {
103 print_error("ERROR: $command");
104 }
105 }
106 }
107
108 sub print_error {
109 my $message = shift;
110
111 print STDERR "$message\n";
112 }
113
114 sub print_rule {
115 my $hash = shift;
116
117 print "\nRULE:";
118
119 my $i = 0;
120 foreach (@$hash) {
121 printf(" %2d: %s", $i++, $_);
122 }
123 print "\n";
124 }
125
126 sub flush {
127 run("$IPTABLES -F $CHAIN_INPUT");
128 run("$IPTABLES -F $CHAIN_FORWARD");
129 run("$IPTABLES -F $CHAIN_OUTPUT");
130 run("$IPTABLES -t nat -F $CHAIN_NAT_SOURCE");
131 run("$IPTABLES -t nat -F $CHAIN_NAT_DESTINATION");
132 run("$IPTABLES -t mangle -F $CHAIN_MANGLE_NAT_DESTINATION_FIX");
133 }
134
135 sub preparerules {
136 if (! -z "${General::swroot}/firewall/config"){
137 &buildrules(\%configfwdfw);
138 }
139 if (! -z "${General::swroot}/firewall/input"){
140 &buildrules(\%configinputfw);
141 }
142 if (! -z "${General::swroot}/firewall/outgoing"){
143 &buildrules(\%configoutgoingfw);
144 }
145 }
146
147 sub buildrules {
148 my $hash = shift;
149
150 foreach my $key (sort {$a <=> $b} keys %$hash) {
151 # Skip disabled rules.
152 next unless ($$hash{$key}[2] eq 'ON');
153
154 if ($DEBUG) {
155 print_rule($$hash{$key});
156 }
157
158 # Check if the target is valid.
159 my $target = $$hash{$key}[0];
160 if (!$target ~~ @VALID_TARGETS) {
161 print_error("Invalid target '$target' for rule $key");
162 next;
163 }
164
165 # Check if the chain is valid.
166 my $chain = $$hash{$key}[1];
167 if (!$chain ~~ @VALID_CHAINS) {
168 print_error("Invalid chain '$chain' in rule $key");
169 next;
170 }
171
172 # Collect all sources.
173 my @sources = &fwlib::get_addresses($hash, $key, "src");
174
175 # Collect all destinations.
176 my @destinations = &fwlib::get_addresses($hash, $key, "tgt");
177
178 # True if the destination is the firewall itself.
179 my $destination_is_firewall = ($$hash{$key}[5] eq "ipfire");
180
181 # Check if logging should be enabled.
182 my $LOG = ($$hash{$key}[17] eq 'ON');
183
184 # Check if NAT is enabled and initialize variables, that we use for that.
185 my $NAT = ($$hash{$key}[28] eq 'ON');
186 my $NAT_MODE;
187 if ($NAT) {
188 $NAT_MODE = uc($$hash{$key}[31]);
189 }
190
191 # Set up time constraints.
192 my @time_options = ();
193 if ($$hash{$key}[18] eq 'ON') {
194 push(@time_options, ("-m", "time"));
195
196 # Select all days of the week this match is active.
197 my @weekdays = ();
198 if ($$hash{$key}[19] ne '') {
199 push (@weekdays, "Mon");
200 }
201 if ($$hash{$key}[20] ne '') {
202 push (@weekdays, "Tue");
203 }
204 if ($$hash{$key}[21] ne '') {
205 push (@weekdays, "Wed");
206 }
207 if ($$hash{$key}[22] ne '') {
208 push (@weekdays, "Thu");
209 }
210 if ($$hash{$key}[23] ne '') {
211 push (@weekdays, "Fri");
212 }
213 if ($$hash{$key}[24] ne '') {
214 push (@weekdays, "Sat");
215 }
216 if ($$hash{$key}[25] ne '') {
217 push (@weekdays, "Sun");
218 }
219 if (@weekdays) {
220 push(@time_options, ("--weekdays", join(",", @weekdays)));
221 }
222
223 # Convert start time.
224 my $time_start = &format_time($$hash{$key}[26]);
225 if ($time_start) {
226 push(@time_options, ("--timestart", $time_start));
227 }
228
229 # Convert end time.
230 my $time_stop = &format_time($$hash{$key}[27]);
231 if ($time_stop) {
232 push(@time_options, ("--timestop", $time_stop));
233 }
234 }
235
236 # Check which protocols are used in this rule and so that we can
237 # later group rules by protocols.
238 my @protocols = &get_protocols($hash, $key);
239 if (!@protocols) {
240 print_error("Invalid protocol configuration for rule $key");
241 next;
242 }
243
244 foreach my $protocol (@protocols) {
245 # Check if the given protocol is supported.
246 if (($protocol ne "all") && (!$protocol ~~ @PROTOCOLS)) {
247 print_error("Protocol $protocol is not supported (rule $key)");
248 next;
249 }
250
251 # Prepare protocol options (like ICMP types, ports, etc...).
252 my @protocol_options = &get_protocol_options($hash, $key, $protocol, 0);
253
254 # Check if this protocol knows ports.
255 my $protocol_has_ports = ($protocol ~~ @PROTOCOLS_WITH_PORTS);
256
257 foreach my $src (@sources) {
258 # Skip invalid source.
259 next unless ($src);
260
261 # Sanitize source.
262 my $source = $src;
263 if ($source ~~ @ANY_ADDRESSES) {
264 $source = "";
265 }
266
267 foreach my $dst (@destinations) {
268 # Skip invalid rules.
269 next if (!$dst || ($dst eq "none"));
270
271 # Sanitize destination.
272 my $destination = $dst;
273 if ($destination ~~ @ANY_ADDRESSES) {
274 $destination = "";
275 }
276
277 # Array with iptables arguments.
278 my @options = ();
279
280 # Append protocol.
281 if ($protocol ne "all") {
282 push(@options, @protocol_options);
283 }
284
285 # Prepare source options.
286 my @source_options = ();
287 if ($source =~ /mac/) {
288 push(@source_options, $source);
289 } elsif ($source) {
290 push(@source_options, ("-s", $source));
291 }
292
293 # Prepare destination options.
294 my @destination_options = ();
295 if ($destination) {
296 push(@destination_options, ("-d", $destination));
297 }
298
299 # Add time constraint options.
300 push(@options, @time_options);
301
302 my $firewall_is_in_source_subnet = 0;
303 if ($source) {
304 $firewall_is_in_source_subnet = &firewall_is_in_subnet($source);
305 }
306
307 # Process NAT rules.
308 if ($NAT) {
309 my $nat_address = &fwlib::get_nat_address($$hash{$key}[29], $source);
310
311 # Skip NAT rules if the NAT address is unknown
312 # (i.e. no internet connection has been established, yet).
313 next unless ($nat_address);
314
315 # Destination NAT
316 if ($NAT_MODE eq "DNAT") {
317 # Make port-forwardings useable from the internal networks.
318 my @internal_addresses = &fwlib::get_internal_firewall_ip_addresses(1);
319 unless ($nat_address ~~ @internal_addresses) {
320 &add_dnat_mangle_rules($nat_address, @options);
321 }
322
323 my @nat_options = ();
324 if ($protocol ne "all") {
325 my @nat_protocol_options = &get_protocol_options($hash, $key, $protocol, 1);
326 push(@nat_options, @nat_protocol_options);
327 }
328 push(@nat_options, @source_options);
329 push(@nat_options, ("-d", $nat_address));
330 push(@nat_options, @time_options);
331
332 my $dnat_port;
333 if ($protocol_has_ports) {
334 $dnat_port = &get_dnat_target_port($hash, $key);
335 }
336
337 my @nat_action_options = ();
338
339 # Use iptables REDIRECT
340 my $use_redirect = ($destination_is_firewall && !$destination && $protocol_has_ports && $dnat_port);
341 if ($use_redirect) {
342 push(@nat_action_options, ("-j", "REDIRECT", "--to-ports", $dnat_port));
343
344 # Use iptables DNAT
345 } else {
346 if ($destination_is_firewall && !$destination) {
347 $destination = &fwlib::get_external_address();
348 }
349 next unless ($destination);
350
351 my ($dnat_address, $dnat_mask) = split("/", $destination);
352 @destination_options = ("-d", $dnat_address);
353
354 if ($protocol_has_ports) {
355 my $dnat_port = &get_dnat_target_port($hash, $key);
356
357 if ($dnat_port) {
358 $dnat_address .= ":$dnat_port";
359 }
360 }
361
362 push(@nat_action_options, ("-j", "DNAT", "--to-destination", $dnat_address));
363 }
364
365 if ($LOG) {
366 run("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @log_limit_options -j LOG --log-prefix 'DNAT '");
367 }
368 run("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @nat_action_options");
369
370 # Source NAT
371 } elsif ($NAT_MODE eq "SNAT") {
372 my @nat_options = @options;
373
374 push(@nat_options, @source_options);
375 push(@nat_options, @destination_options);
376
377 if ($LOG) {
378 run("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options @log_limit_options -j LOG --log-prefix 'SNAT '");
379 }
380 run("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options -j SNAT --to-source $nat_address");
381 }
382 }
383
384 push(@options, @source_options);
385
386 if ($firewall_is_in_source_subnet && ($fwdfwsettings{"POLICY"} eq "MODE1") && ($chain eq $CHAIN_FORWARD)) {
387 if ($LOG && !$NAT) {
388 run("$IPTABLES -A $CHAIN_INPUT @options @log_limit_options -j LOG --log-prefix '$CHAIN_INPUT '");
389 }
390 run("$IPTABLES -A $CHAIN_INPUT @options -j $target");
391 }
392
393 push(@options, @destination_options);
394
395 # Insert firewall rule.
396 if ($LOG && !$NAT) {
397 run("$IPTABLES -A $chain @options @log_limit_options -j LOG --log-prefix '$chain '");
398 }
399 run("$IPTABLES -A $chain @options -j $target");
400 }
401 }
402 }
403 }
404 }
405
406 # Formats the given timestamp into the iptables format which is "hh:mm" UTC.
407 sub format_time {
408 my $val = shift;
409
410 # Convert the given time into minutes.
411 my $minutes = &time_convert_to_minutes($val);
412
413 # Move the timestamp into UTC.
414 $minutes += &time_utc_offset();
415
416 # Make sure $minutes is between 00:00 and 23:59.
417 if ($minutes < 0) {
418 $minutes += 1440;
419 }
420
421 if ($minutes > 1440) {
422 $minutes -= 1440;
423 }
424
425 # Format as hh:mm.
426 return sprintf("%02d:%02d", $minutes / 60, $minutes % 60);
427 }
428
429 # Calculates the offsets in minutes from the local timezone to UTC.
430 sub time_utc_offset {
431 my @localtime = localtime(time);
432 my @gmtime = gmtime(time);
433
434 return ($gmtime[2] * 60 + $gmtime[1] % 60) - ($localtime[2] * 60 + $localtime[1] % 60);
435 }
436
437 # Takes a timestamp like "14:00" and converts it into minutes since midnight.
438 sub time_convert_to_minutes {
439 my ($hrs, $min) = split(":", shift);
440
441 return ($hrs * 60) + $min;
442 }
443
444 sub p2pblock {
445 my $P2PSTRING = "";
446 my $DO;
447 open( FILE, "< $p2pfile" ) or die "Unable to read $p2pfile";
448 @p2ps = <FILE>;
449 close FILE;
450 my $CMD = "-m ipp2p";
451 foreach my $p2pentry (sort @p2ps) {
452 my @p2pline = split( /\;/, $p2pentry );
453 if ( $fwdfwsettings{'POLICY'} eq 'MODE1' ) {
454 $DO = "ACCEPT";
455 if ("$p2pline[2]" eq "on") {
456 $P2PSTRING = "$P2PSTRING --$p2pline[1]";
457 }
458 }else {
459 $DO = "RETURN";
460 if ("$p2pline[2]" eq "off") {
461 $P2PSTRING = "$P2PSTRING --$p2pline[1]";
462 }
463 }
464 }
465
466 if($P2PSTRING) {
467 run("$IPTABLES -A FORWARDFW $CMD $P2PSTRING -j $DO");
468 }
469 }
470
471 sub get_protocols {
472 my $hash = shift;
473 my $key = shift;
474
475 my $uses_source_ports = ($$hash{$key}[7] eq "ON");
476 my $uses_services = ($$hash{$key}[11] eq "ON");
477
478 my @protocols = ();
479
480 # Rules which don't have source ports or services (like ICMP, ESP, ...).
481 if (!$uses_source_ports && !$uses_services) {
482 push(@protocols, $$hash{$key}[8]);
483
484 # Rules which either use ports or services.
485 } elsif ($uses_source_ports || $uses_services) {
486 # Check if service group or service
487 if ($$hash{$key}[14] eq 'cust_srv') {
488 push(@protocols, &fwlib::get_srv_prot($$hash{$key}[15]));
489
490 } elsif($$hash{$key}[14] eq 'cust_srvgrp'){
491 my $protos = &fwlib::get_srvgrp_prot($$hash{$key}[15]);
492 push(@protocols, split(",", $protos));
493
494 } else {
495 # Fetch the protocol for this rule.
496 my $protocol = lc($$hash{$key}[8]);
497
498 # Fetch source and destination ports for this rule.
499 my $source_ports = $$hash{$key}[10];
500 my $destination_ports = $$hash{$key}[15];
501
502 # Check if ports are set for protocols which do not support ports.
503 if (!($protocol ~~ @PROTOCOLS_WITH_PORTS) && ($source_ports || $destination_ports)) {
504 print_error("$protocol does not support ports");
505 return ();
506 }
507
508 push(@protocols, $protocol);
509 }
510 }
511
512 # Remove all empty elements
513 @protocols = map { $_ ? $_ : () } @protocols;
514
515 # If no protocol has been defined, we assume "all".
516 if (!@protocols) {
517 push(@protocols, "all");
518 }
519
520 # Make all protocol names lowercase.
521 @protocols = map { lc } @protocols;
522
523 return @protocols;
524 }
525
526 sub get_protocol_options {
527 my $hash = shift;
528 my $key = shift;
529 my $protocol = shift;
530 my $nat_options_wanted = shift;
531 my @options = ();
532
533 # Nothing to do if no protocol is specified.
534 if ($protocol eq "all") {
535 return @options;
536 } else {
537 push(@options, ("-p", $protocol));
538 }
539
540 # Process source ports.
541 my $use_src_ports = ($$hash{$key}[7] eq "ON");
542 my $src_ports = $$hash{$key}[10];
543
544 if ($use_src_ports && $src_ports) {
545 push(@options, &format_ports($src_ports, "src"));
546 }
547
548 # Process destination ports.
549 my $use_dst_ports = ($$hash{$key}[11] eq "ON");
550 my $use_dnat = (($$hash{$key}[28] eq "ON") && ($$hash{$key}[31] eq "dnat"));
551
552 if ($use_dst_ports) {
553 my $dst_ports_mode = $$hash{$key}[14];
554 my $dst_ports = $$hash{$key}[15];
555
556 if (($dst_ports_mode eq "TGT_PORT") && $dst_ports) {
557 if ($nat_options_wanted && $use_dnat && $$hash{$key}[30]) {
558 $dst_ports = $$hash{$key}[30];
559 }
560 push(@options, &format_ports($dst_ports, "dst"));
561
562 } elsif ($dst_ports_mode eq "cust_srv") {
563 if ($protocol eq "ICMP") {
564 push(@options, ("--icmp-type", &fwlib::get_srv_port($dst_ports, 3, "ICMP")));
565 } else {
566 $dst_ports = &fwlib::get_srv_port($dst_ports, 1, uc($protocol));
567 push(@options, &format_ports($dst_ports, "dst"));
568 }
569
570 } elsif ($dst_ports_mode eq "cust_srvgrp") {
571 push(@options, &fwlib::get_srvgrp_port($dst_ports, uc($protocol)));
572 }
573 }
574
575 # Check if a single ICMP type is selected.
576 if (!$use_src_ports && !$use_dst_ports && $protocol eq "icmp") {
577 my $icmp_type = $$hash{$key}[9];
578
579 if (($icmp_type ne "All ICMP-Types") && $icmp_type) {
580 push(@options, ("--icmp-type", $icmp_type));
581 }
582 }
583
584 return @options;
585 }
586
587 sub format_ports {
588 my $ports = shift;
589 my $type = shift;
590
591 my $arg;
592 if ($type eq "src") {
593 $arg = "--sport";
594 } elsif ($type eq "dst") {
595 $arg = "--dport";
596 }
597
598 my @options = ();
599
600 if ($ports =~ /\|/) {
601 $ports =~ s/\|/,/g;
602 push(@options, ("-m", "multiport"));
603 }
604
605 if ($ports) {
606 push(@options, ($arg, $ports));
607 }
608
609 return @options;
610 }
611
612 sub get_dnat_target_port {
613 my $hash = shift;
614 my $key = shift;
615
616 if ($$hash{$key}[14] eq "TGT_PORT") {
617 my $port = $$hash{$key}[15];
618 my $external_port = $$hash{$key}[30];
619
620 if ($external_port && ($port ne $external_port)) {
621 return $$hash{$key}[15];
622 }
623 }
624 }
625
626 sub add_dnat_mangle_rules {
627 my $nat_address = shift;
628 my @options = @_;
629
630 my $mark = 0;
631 foreach my $zone ("GREEN", "BLUE", "ORANGE") {
632 $mark++;
633
634 # Skip rule if not all required information exists.
635 next unless (exists $defaultNetworks{$zone . "_NETADDRESS"});
636 next unless (exists $defaultNetworks{$zone . "_NETMASK"});
637
638 my @mangle_options = @options;
639
640 my $netaddress = $defaultNetworks{$zone . "_NETADDRESS"};
641 $netaddress .= "/" . $defaultNetworks{$zone . "_NETMASK"};
642
643 push(@mangle_options, ("-s", $netaddress, "-d", $nat_address));
644 push(@mangle_options, ("-j", "MARK", "--set-mark", $mark));
645
646 run("$IPTABLES -t mangle -A $CHAIN_MANGLE_NAT_DESTINATION_FIX @mangle_options");
647 }
648 }
649
650 sub make_log_limit_options {
651 my @options = ("-m", "limit");
652
653 # Maybe we should get this from the configuration.
654 my $limit = 10;
655
656 # We limit log messages to $limit messages per minute.
657 push(@options, ("--limit", "$limit/min"));
658
659 # And we allow bursts of 2x $limit.
660 push(@options, ("--limit-burst", $limit * 2));
661
662 return @options;
663 }
664
665 sub firewall_is_in_subnet {
666 my $subnet = shift;
667
668 # ORANGE is missing here, because nothing may ever access
669 # the firewall from this network.
670 my $address = &fwlib::get_internal_firewall_ip_address($subnet, 0);
671
672 if ($address) {
673 return 1;
674 }
675
676 return 0;
677 }
678