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