]>
git.ipfire.org Git - people/teissler/ipfire-2.x.git/blob - config/firewall/rules.pl
2 ###############################################################################
4 # IPFire.org - A linux based firewall #
5 # Copyright (C) 2013 Alexander Marx <amarx@ipfire.org> #
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. #
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. #
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/>. #
20 ###############################################################################
24 require '/var/ipfire/general-functions.pl';
25 require "${General::swroot}/lang.pl";
26 require "/usr/lib/firewall/firewall-lib.pl";
28 # Set to one to enable debugging mode.
31 my $IPTABLES = "iptables --wait";
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);
43 my @PROTOCOLS = ("tcp", "udp", "icmp", "igmp", "ah", "esp", "gre", "ipv6", "ipip");
44 my @PROTOCOLS_WITH_PORTS = ("tcp", "udp");
46 my @VALID_TARGETS = ("ACCEPT", "DROP", "REJECT");
49 my %defaultNetworks=();
53 my %configoutgoingfw=();
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";
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 &General
::get_aliases
(\
%aliases);
73 my @log_limit_options = &make_log_limit_options
();
82 # Reload firewall rules.
85 # Load P2P block rules.
88 # Reload firewall policy.
89 run
("/usr/sbin/firewall-policy");
93 # Executes or prints the given shell command.
102 print_error
("ERROR: $command");
110 print STDERR
"$message\n";
120 printf(" %2d: %s", $i++, $_);
126 run
("$IPTABLES -F $CHAIN_INPUT");
127 run
("$IPTABLES -F $CHAIN_FORWARD");
128 run
("$IPTABLES -F $CHAIN_OUTPUT");
129 run
("$IPTABLES -t nat -F $CHAIN_NAT_SOURCE");
130 run
("$IPTABLES -t nat -F $CHAIN_NAT_DESTINATION");
131 run
("$IPTABLES -t mangle -F $CHAIN_MANGLE_NAT_DESTINATION_FIX");
135 if (! -z
"${General::swroot}/firewall/config"){
136 &buildrules
(\
%configfwdfw);
138 if (! -z
"${General::swroot}/firewall/input"){
139 &buildrules
(\
%configinputfw);
141 if (! -z
"${General::swroot}/firewall/outgoing"){
142 &buildrules
(\
%configoutgoingfw);
149 foreach my $key (sort {$a <=> $b} keys %$hash) {
150 # Skip disabled rules.
151 next unless ($$hash{$key}[2] eq 'ON');
154 print_rule
($$hash{$key});
157 # Check if the target is valid.
158 my $target = $$hash{$key}[0];
159 if (!$target ~~ @VALID_TARGETS) {
160 print_error
("Invalid target '$target' for rule $key");
164 # Check if the chain is valid.
165 my $chain = $$hash{$key}[1];
166 if (!$chain ~~ @VALID_CHAINS) {
167 print_error
("Invalid chain '$chain' in rule $key");
171 # Collect all sources.
172 my @sources = &get_addresses
($hash, $key, "src");
174 # Collect all destinations.
175 my @destinations = &get_addresses
($hash, $key, "tgt");
177 # Check if logging should be enabled.
178 my $LOG = ($$hash{$key}[17] eq 'ON');
180 # Check if NAT is enabled and initialize variables, that we use for that.
181 my $NAT = ($$hash{$key}[28] eq 'ON');
184 $NAT_MODE = uc($$hash{$key}[31]);
187 # Set up time constraints.
188 my @time_options = ();
189 if ($$hash{$key}[18] eq 'ON') {
190 push(@time_options, ("-m", "time"));
192 # Select all days of the week this match is active.
194 if ($$hash{$key}[19] ne '') {
195 push (@weekdays, "Mon");
197 if ($$hash{$key}[20] ne '') {
198 push (@weekdays, "Tue");
200 if ($$hash{$key}[21] ne '') {
201 push (@weekdays, "Wed");
203 if ($$hash{$key}[22] ne '') {
204 push (@weekdays, "Thu");
206 if ($$hash{$key}[23] ne '') {
207 push (@weekdays, "Fri");
209 if ($$hash{$key}[24] ne '') {
210 push (@weekdays, "Sat");
212 if ($$hash{$key}[25] ne '') {
213 push (@weekdays, "Sun");
216 push(@time_options, ("--weekdays", join(",", @weekdays)));
219 # Convert start time.
220 my $time_start = &format_time
($$hash{$key}[26]);
222 push(@time_options, ("--timestart", $time_start));
226 my $time_stop = &format_time
($$hash{$key}[27]);
228 push(@time_options, ("--timestop", $time_stop));
232 # Check which protocols are used in this rule and so that we can
233 # later group rules by protocols.
234 my @protocols = &get_protocols
($hash, $key);
236 print_error
("Invalid protocol configuration for rule $key");
240 foreach my $protocol (@protocols) {
241 # Check if the given protocol is supported.
242 if (($protocol ne "all") && (!$protocol ~~ @PROTOCOLS)) {
243 print_error
("Protocol $protocol is not supported (rule $key)");
247 # Prepare protocol options (like ICMP types, ports, etc...).
248 my @protocol_options = &get_protocol_options
($hash, $key, $protocol);
250 # Check if this protocol knows ports.
251 my $protocol_has_ports = ($protocol ~~ @PROTOCOLS_WITH_PORTS);
253 foreach my $source (@sources) {
254 foreach my $destination (@destinations) {
255 # Skip invalid rules.
256 next if (!$source || !$destination || ($destination eq "none"));
258 # Array with iptables arguments.
262 if ($protocol ne "all") {
263 push(@options, ("-p", $protocol));
264 push(@options, @protocol_options);
267 # Prepare source options.
268 my @source_options = ();
269 if ($source =~ /mac/) {
270 push(@source_options, $source);
272 push(@source_options, ("-s", $source));
275 # Prepare destination options.
276 my @destination_options = ("-d", $destination);
278 # Add time constraint options.
279 push(@options, @time_options);
283 my $nat_address = &get_nat_address
($$hash{$key}[29]);
285 # Skip NAT rules if the NAT address is unknown
286 # (i.e. no internet connection has been established, yet).
287 next unless ($nat_address);
290 if ($NAT_MODE eq "DNAT") {
291 # Make port-forwardings useable from the internal networks.
292 &add_dnat_mangle_rules
($nat_address, @options);
294 my @nat_options = @options;
295 push(@nat_options, @source_options);
296 push(@nat_options, ("-d", $nat_address));
298 my ($dnat_address, $dnat_mask) = split("/", $destination);
299 @destination_options = ("-d", $dnat_address);
301 if ($protocol_has_ports) {
302 my $dnat_port = &get_dnat_target_port
($hash, $key);
305 $dnat_address .= ":$dnat_port";
310 run
("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @log_limit_options -j LOG --log-prefix 'DNAT '");
312 run
("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options -j DNAT --to-destination $dnat_address");
315 } elsif ($NAT_MODE eq "SNAT") {
316 my @nat_options = @options;
318 push(@nat_options, @source_options);
319 push(@nat_options, @destination_options);
322 run
("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options @log_limit_options -j LOG --log-prefix 'SNAT '");
324 run
("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options -j SNAT --to-source $nat_address");
328 push(@options, @source_options);
329 push(@options, @destination_options);
331 # Insert firewall rule.
333 run
("$IPTABLES -A $chain @options @log_limit_options -j LOG --log-prefix '$chain '");
335 run
("$IPTABLES -A $chain @options -j $target");
342 sub get_external_interface
() {
343 open(IFACE
, "/var/ipfire/red/iface") or return "";
350 sub get_external_address
() {
351 open(ADDR
, "/var/ipfire/red/local-ipaddress") or return "";
352 my $address = <ADDR
>;
361 foreach my $alias (sort keys %aliases) {
363 return $aliases{$alias};
368 sub get_nat_address
{
371 # Any static address of any zone.
372 if ($zone eq "RED" || $zone eq "GREEN" || $zone eq "ORANGE" || $zone eq "BLUE") {
373 return $defaultNetworks{$zone . "_ADDRESS"};
375 } elsif ($zone eq "Default IP") {
376 return &get_external_address
();
379 return &get_alias
($zone);
382 print_error
("Could not find NAT address");
385 # Formats the given timestamp into the iptables format which is "hh:mm" UTC.
389 # Convert the given time into minutes.
390 my $minutes = &time_convert_to_minutes
($val);
392 # Move the timestamp into UTC.
393 $minutes += &time_utc_offset
();
395 # Make sure $minutes is between 00:00 and 23:59.
400 if ($minutes > 1440) {
405 return sprintf("%02d:%02d", $minutes / 60, $minutes % 60);
408 # Calculates the offsets in minutes from the local timezone to UTC.
409 sub time_utc_offset
{
410 my @localtime = localtime(time);
411 my @gmtime = gmtime(time);
413 return ($gmtime[2] * 60 + $gmtime[1] % 60) - ($localtime[2] * 60 + $localtime[1] % 60);
416 # Takes a timestamp like "14:00" and converts it into minutes since midnight.
417 sub time_convert_to_minutes
{
418 my ($hrs, $min) = split(":", shift);
420 return ($hrs * 60) + $min;
426 open( FILE
, "< $p2pfile" ) or die "Unable to read $p2pfile";
429 my $CMD = "-m ipp2p";
430 foreach my $p2pentry (sort @p2ps) {
431 my @p2pline = split( /\;/, $p2pentry );
432 if ( $fwdfwsettings{'POLICY'} eq 'MODE1' ) {
434 if ("$p2pline[2]" eq "on") {
435 $P2PSTRING = "$P2PSTRING --$p2pline[1]";
439 if ("$p2pline[2]" eq "off") {
440 $P2PSTRING = "$P2PSTRING --$p2pline[1]";
446 run
("$IPTABLES -A FORWARDFW $CMD $P2PSTRING -j $DO");
460 if ($type eq "src") {
461 $addr_type = $$hash{$key}[3];
462 $value = $$hash{$key}[4];
464 } elsif ($type eq "tgt") {
465 $addr_type = $$hash{$key}[5];
466 $value = $$hash{$key}[6];
469 if ($addr_type ~~ ["cust_grp_src", "cust_grp_tgt"]) {
470 foreach my $grp (sort {$a <=> $b} keys %customgrp) {
471 if ($customgrp{$grp}[0] eq $value) {
472 my @address = &get_address
($customgrp{$grp}[3], $customgrp{$grp}[2], $type);
475 push(@addresses, @address);
480 my @address = &get_address
($addr_type, $value, $type);
483 push(@addresses, @address);
497 # If the user manually typed an address, we just check if it is a MAC
498 # address. Otherwise, we assume that it is an IP address.
499 if ($key ~~ ["src_addr", "tgt_addr"]) {
500 if (&General
::validmac
($value)) {
501 push(@ret, "-m mac --mac-source $value");
506 # If a default network interface (GREEN, BLUE, etc.) is selected, we
507 # try to get the corresponding address of the network.
508 } elsif ($key ~~ ["std_net_src", "std_net_tgt", "Standard Network"]) {
509 my $external_interface = &get_external_interface
();
511 my $network_address = &fwlib
::get_std_net_ip
($value, $external_interface);
512 if ($network_address) {
513 push(@ret, $network_address);
517 } elsif ($key ~~ ["cust_net_src", "cust_net_tgt", "Custom Network"]) {
518 my $network_address = &fwlib
::get_net_ip
($value);
519 if ($network_address) {
520 push(@ret, $network_address);
524 } elsif ($key ~~ ["cust_host_src", "cust_host_tgt", "Custom Host"]) {
525 my $host_address = &fwlib
::get_host_ip
($value, $type);
527 push(@ret, $host_address);
531 } elsif ($key ~~ ["ovpn_net_src", "ovpn_net_tgt", "OpenVPN static network"]) {
532 my $network_address = &fwlib
::get_ovpn_net_ip
($value, 1);
533 if ($network_address) {
534 push(@ret, $network_address);
538 } elsif ($key ~~ ["ovpn_host_src", "ovpn_host_tgt", "OpenVPN static host"]) {
539 my $host_address = &fwlib
::get_ovpn_host_ip
($value, 33);
541 push(@ret, $host_address);
545 } elsif ($key ~~ ["ovpn_n2n_src", "ovpn_n2n_tgt", "OpenVPN N-2-N"]) {
546 my $network_address = &fwlib
::get_ovpn_n2n_ip
($value, 11);
547 if ($network_address) {
548 push(@ret, $network_address);
552 } elsif ($key ~~ ["ipsec_net_src", "ipsec_net_tgt", "IpSec Network"]) {
553 my $network_address = &fwlib
::get_ipsec_net_ip
($value, 11);
554 if ($network_address) {
555 push(@ret, $network_address);
558 # The firewall's own IP addresses.
559 } elsif ($key ~~ ["ipfire", "ipfire_src"]) {
561 if ($value eq "ALL") {
565 } elsif ($value eq "GREEN") {
566 push(@ret, $defaultNetworks{"GREEN_ADDRESS"});
569 } elsif ($value eq "BLUE") {
570 push(@ret, $defaultNetworks{"BLUE_ADDRESS"});
573 } elsif ($value eq "ORANGE") {
574 push(@ret, $defaultNetworks{"ORANGE_ADDRESS"});
577 } elsif ($value ~~ ["RED", "RED1"]) {
578 my $address = &get_external_address
();
580 push(@ret, $address);
585 my %alias = &get_alias
($value);
587 push(@ret, $alias{"IPT"});
591 # If nothing was selected, we assume "any".
603 my $uses_source_ports = ($$hash{$key}[7] eq "ON");
604 my $uses_services = ($$hash{$key}[11] eq "ON");
608 # Rules which don't have source ports or services (like ICMP, ESP, ...).
609 if (!$uses_source_ports && !$uses_services) {
610 push(@protocols, $$hash{$key}[8]);
612 # Rules which either use ports or services.
613 } elsif ($uses_source_ports || $uses_services) {
614 # Check if service group or service
615 if ($$hash{$key}[14] eq 'cust_srv') {
616 push(@protocols, &fwlib
::get_srv_prot
($$hash{$key}[15]));
618 } elsif($$hash{$key}[14] eq 'cust_srvgrp'){
619 my $protos = &fwlib
::get_srvgrp_prot
($$hash{$key}[15]);
620 push(@protocols, split(",", $protos));
623 # Fetch the protocol for this rule.
624 my $protocol = lc($$hash{$key}[8]);
626 # Fetch source and destination ports for this rule.
627 my $source_ports = $$hash{$key}[10];
628 my $destination_ports = $$hash{$key}[15];
630 # Check if ports are set for protocols which do not support ports.
631 if (!($protocol ~~ @PROTOCOLS_WITH_PORTS) && ($source_ports || $destination_ports)) {
632 print_error
("$protocol does not support ports");
636 push(@protocols, $protocol);
640 # Remove all empty elements
641 @protocols = map { $_ ?
$_ : () } @protocols;
643 # If no protocol has been defined, we assume "all".
645 push(@protocols, "all");
648 # Make all protocol names lowercase.
649 @protocols = map { lc } @protocols;
654 sub get_protocol_options
{
657 my $protocol = shift;
660 # Process source ports.
661 my $use_src_ports = ($$hash{$key}[7] eq "ON");
662 my $src_ports = $$hash{$key}[10];
664 if ($use_src_ports && $src_ports) {
665 push(@options, &format_ports
($src_ports, "src"));
668 # Process destination ports.
669 my $use_dst_ports = ($$hash{$key}[11] eq "ON");
670 my $use_dnat = (($$hash{$key}[28] eq "ON") && ($$hash{$key}[31] eq "dnat"));
672 if ($use_dst_ports) {
673 my $dst_ports_mode = $$hash{$key}[14];
674 my $dst_ports = $$hash{$key}[15];
676 if (($dst_ports_mode eq "TGT_PORT") && $dst_ports) {
677 if ($use_dnat && $$hash{$key}[30]) {
678 $dst_ports = $$hash{$key}[30];
680 push(@options, &format_ports
($dst_ports, "dst"));
682 } elsif ($dst_ports_mode eq "cust_srv") {
683 if ($protocol eq "ICMP") {
684 push(@options, ("--icmp-type", &fwlib
::get_srv_port
($dst_ports, 3, "ICMP")));
686 $dst_ports = &fwlib
::get_srv_port
($dst_ports, 1, uc($protocol));
687 push(@options, &format_ports
($dst_ports, "dst"));
690 } elsif ($dst_ports_mode eq "cust_srvgrp") {
691 push(@options, &fwlib
::get_srvgrp_port
($dst_ports, uc($protocol)));
695 # Check if a single ICMP type is selected.
696 if (!$use_src_ports && !$use_dst_ports && $protocol eq "icmp") {
697 my $icmp_type = $$hash{$key}[9];
699 if (($icmp_type ne "All ICMP-Types") && $icmp_type) {
700 push(@options, ("--icmp-type", $icmp_type));
712 if ($type eq "src") {
714 } elsif ($type eq "dst") {
720 if ($ports =~ /\|/) {
722 push(@options, ("-m", "multiport"));
726 push(@options, ($arg, $ports));
732 sub get_dnat_target_port
{
736 if ($$hash{$key}[14] eq "TGT_PORT") {
737 my $port = $$hash{$key}[15];
738 my $external_port = $$hash{$key}[30];
740 if ($external_port && ($port ne $external_port)) {
741 return $$hash{$key}[15];
746 sub add_dnat_mangle_rules
{
747 my $nat_address = shift;
751 foreach my $zone ("GREEN", "BLUE", "ORANGE") {
754 # Skip rule if not all required information exists.
755 next unless (exists $defaultNetworks{$zone . "_NETADDRESS"});
756 next unless (exists $defaultNetworks{$zone . "_NETMASK"});
758 my @mangle_options = @options;
760 my $netaddress = $defaultNetworks{$zone . "_NETADDRESS"};
761 $netaddress .= "/" . $defaultNetworks{$zone . "_NETMASK"};
763 push(@mangle_options, ("-s", $netaddress, "-d", $nat_address));
764 push(@mangle_options, ("-j", "MARK", "--set-mark", $mark));
766 run
("$IPTABLES -t mangle -A $CHAIN_MANGLE_NAT_DESTINATION_FIX @mangle_options");
770 sub make_log_limit_options
{
771 my @options = ("-m", "limit");
773 # Maybe we should get this from the configuration.
776 # We limit log messages to $limit messages per minute.
777 push(@options, ("--limit", "$limit/min"));
779 # And we allow bursts of 2x $limit.
780 push(@options, ("--limit-burst", $limit * 2));