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