]>
git.ipfire.org Git - people/teissler/ipfire-2.x.git/blob - config/firewall/rules.pl
5b3383125c243986b9022be56f675bfc00f39a20
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);
42 my @ANY_ADDRESSES = ("0.0.0.0/0.0.0.0", "0.0.0.0/0", "0/0");
44 my @PROTOCOLS = ("tcp", "udp", "icmp", "igmp", "ah", "esp", "gre", "ipv6", "ipip");
45 my @PROTOCOLS_WITH_PORTS = ("tcp", "udp");
47 my @VALID_TARGETS = ("ACCEPT", "DROP", "REJECT");
50 my %defaultNetworks=();
54 my %configoutgoingfw=();
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";
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);
74 my @log_limit_options = &make_log_limit_options
();
83 # Reload firewall rules.
86 # Load P2P block rules.
89 # Reload firewall policy.
90 run
("/usr/sbin/firewall-policy");
94 # Executes or prints the given shell command.
103 print_error
("ERROR: $command");
111 print STDERR
"$message\n";
121 printf(" %2d: %s", $i++, $_);
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");
136 if (! -z
"${General::swroot}/firewall/config"){
137 &buildrules
(\
%configfwdfw);
139 if (! -z
"${General::swroot}/firewall/input"){
140 &buildrules
(\
%configinputfw);
142 if (! -z
"${General::swroot}/firewall/outgoing"){
143 &buildrules
(\
%configoutgoingfw);
150 foreach my $key (sort {$a <=> $b} keys %$hash) {
151 # Skip disabled rules.
152 next unless ($$hash{$key}[2] eq 'ON');
155 print_rule
($$hash{$key});
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");
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");
172 # Collect all sources.
173 my @sources = &get_addresses
($hash, $key, "src");
175 # Collect all destinations.
176 my @destinations = &get_addresses
($hash, $key, "tgt");
178 # Check if logging should be enabled.
179 my $LOG = ($$hash{$key}[17] eq 'ON');
181 # Check if NAT is enabled and initialize variables, that we use for that.
182 my $NAT = ($$hash{$key}[28] eq 'ON');
185 $NAT_MODE = uc($$hash{$key}[31]);
188 # Set up time constraints.
189 my @time_options = ();
190 if ($$hash{$key}[18] eq 'ON') {
191 push(@time_options, ("-m", "time"));
193 # Select all days of the week this match is active.
195 if ($$hash{$key}[19] ne '') {
196 push (@weekdays, "Mon");
198 if ($$hash{$key}[20] ne '') {
199 push (@weekdays, "Tue");
201 if ($$hash{$key}[21] ne '') {
202 push (@weekdays, "Wed");
204 if ($$hash{$key}[22] ne '') {
205 push (@weekdays, "Thu");
207 if ($$hash{$key}[23] ne '') {
208 push (@weekdays, "Fri");
210 if ($$hash{$key}[24] ne '') {
211 push (@weekdays, "Sat");
213 if ($$hash{$key}[25] ne '') {
214 push (@weekdays, "Sun");
217 push(@time_options, ("--weekdays", join(",", @weekdays)));
220 # Convert start time.
221 my $time_start = &format_time
($$hash{$key}[26]);
223 push(@time_options, ("--timestart", $time_start));
227 my $time_stop = &format_time
($$hash{$key}[27]);
229 push(@time_options, ("--timestop", $time_stop));
233 # Check which protocols are used in this rule and so that we can
234 # later group rules by protocols.
235 my @protocols = &get_protocols
($hash, $key);
237 print_error
("Invalid protocol configuration for rule $key");
241 foreach my $protocol (@protocols) {
242 # Check if the given protocol is supported.
243 if (($protocol ne "all") && (!$protocol ~~ @PROTOCOLS)) {
244 print_error
("Protocol $protocol is not supported (rule $key)");
248 # Prepare protocol options (like ICMP types, ports, etc...).
249 my @protocol_options = &get_protocol_options
($hash, $key, $protocol);
251 # Check if this protocol knows ports.
252 my $protocol_has_ports = ($protocol ~~ @PROTOCOLS_WITH_PORTS);
254 foreach my $source (@sources) {
255 foreach my $destination (@destinations) {
256 # Skip invalid rules.
257 next if (!$source || !$destination || ($destination eq "none"));
260 if ($source ~~ @ANY_ADDRESSES) {
264 # Sanitize destination.
265 if ($destination ~~ @ANY_ADDRESSES) {
269 # Array with iptables arguments.
273 if ($protocol ne "all") {
274 push(@options, ("-p", $protocol));
275 push(@options, @protocol_options);
278 # Prepare source options.
279 my @source_options = ();
280 if ($source =~ /mac/) {
281 push(@source_options, $source);
283 push(@source_options, ("-s", $source));
286 # Prepare destination options.
287 my @destination_options = ();
289 push(@destination_options, ("-d", $destination));
292 # Add time constraint options.
293 push(@options, @time_options);
295 my $firewall_is_in_source_subnet = 0;
297 $firewall_is_in_source_subnet = &firewall_is_in_subnet
($source);
302 my $nat_address = &get_nat_address
($$hash{$key}[29]);
304 # Skip NAT rules if the NAT address is unknown
305 # (i.e. no internet connection has been established, yet).
306 next unless ($nat_address);
309 if ($NAT_MODE eq "DNAT") {
310 # Make port-forwardings useable from the internal networks.
311 &add_dnat_mangle_rules
($nat_address, @options);
313 my @nat_options = @options;
314 push(@nat_options, @source_options);
315 push(@nat_options, ("-d", $nat_address));
317 my ($dnat_address, $dnat_mask) = split("/", $destination);
318 @destination_options = ("-d", $dnat_address);
320 if ($protocol_has_ports) {
321 my $dnat_port = &get_dnat_target_port
($hash, $key);
324 $dnat_address .= ":$dnat_port";
329 run
("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @log_limit_options -j LOG --log-prefix 'DNAT '");
331 run
("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options -j DNAT --to-destination $dnat_address");
334 } elsif ($NAT_MODE eq "SNAT") {
335 my @nat_options = @options;
337 push(@nat_options, @source_options);
338 push(@nat_options, @destination_options);
341 run
("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options @log_limit_options -j LOG --log-prefix 'SNAT '");
343 run
("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options -j SNAT --to-source $nat_address");
347 push(@options, @source_options);
349 if ($firewall_is_in_source_subnet && ($fwdfwsettings{"POLICY"} eq "MODE1") && ($chain eq $CHAIN_FORWARD)) {
351 run
("$IPTABLES -A $CHAIN_INPUT @options @log_limit_options -j LOG --log-prefix '$CHAIN_INPUT '");
353 run
("$IPTABLES -A $CHAIN_INPUT @options -j $target");
356 push(@options, @destination_options);
358 # Insert firewall rule.
360 run
("$IPTABLES -A $chain @options @log_limit_options -j LOG --log-prefix '$chain '");
362 run
("$IPTABLES -A $chain @options -j $target");
369 sub get_external_interface
() {
370 open(IFACE
, "/var/ipfire/red/iface") or return "";
377 sub get_external_address
() {
378 open(ADDR
, "/var/ipfire/red/local-ipaddress") or return "";
379 my $address = <ADDR
>;
388 foreach my $alias (sort keys %aliases) {
390 return $aliases{$alias};
395 sub get_nat_address
{
398 # Any static address of any zone.
399 if ($zone eq "RED" || $zone eq "GREEN" || $zone eq "ORANGE" || $zone eq "BLUE") {
400 return $defaultNetworks{$zone . "_ADDRESS"};
402 } elsif ($zone eq "Default IP") {
403 return &get_external_address
();
406 return &get_alias
($zone);
409 print_error
("Could not find NAT address");
412 # Formats the given timestamp into the iptables format which is "hh:mm" UTC.
416 # Convert the given time into minutes.
417 my $minutes = &time_convert_to_minutes
($val);
419 # Move the timestamp into UTC.
420 $minutes += &time_utc_offset
();
422 # Make sure $minutes is between 00:00 and 23:59.
427 if ($minutes > 1440) {
432 return sprintf("%02d:%02d", $minutes / 60, $minutes % 60);
435 # Calculates the offsets in minutes from the local timezone to UTC.
436 sub time_utc_offset
{
437 my @localtime = localtime(time);
438 my @gmtime = gmtime(time);
440 return ($gmtime[2] * 60 + $gmtime[1] % 60) - ($localtime[2] * 60 + $localtime[1] % 60);
443 # Takes a timestamp like "14:00" and converts it into minutes since midnight.
444 sub time_convert_to_minutes
{
445 my ($hrs, $min) = split(":", shift);
447 return ($hrs * 60) + $min;
453 open( FILE
, "< $p2pfile" ) or die "Unable to read $p2pfile";
456 my $CMD = "-m ipp2p";
457 foreach my $p2pentry (sort @p2ps) {
458 my @p2pline = split( /\;/, $p2pentry );
459 if ( $fwdfwsettings{'POLICY'} eq 'MODE1' ) {
461 if ("$p2pline[2]" eq "on") {
462 $P2PSTRING = "$P2PSTRING --$p2pline[1]";
466 if ("$p2pline[2]" eq "off") {
467 $P2PSTRING = "$P2PSTRING --$p2pline[1]";
473 run
("$IPTABLES -A FORWARDFW $CMD $P2PSTRING -j $DO");
487 if ($type eq "src") {
488 $addr_type = $$hash{$key}[3];
489 $value = $$hash{$key}[4];
491 } elsif ($type eq "tgt") {
492 $addr_type = $$hash{$key}[5];
493 $value = $$hash{$key}[6];
496 if ($addr_type ~~ ["cust_grp_src", "cust_grp_tgt"]) {
497 foreach my $grp (sort {$a <=> $b} keys %customgrp) {
498 if ($customgrp{$grp}[0] eq $value) {
499 my @address = &get_address
($customgrp{$grp}[3], $customgrp{$grp}[2], $type);
502 push(@addresses, @address);
507 my @address = &get_address
($addr_type, $value, $type);
510 push(@addresses, @address);
524 # If the user manually typed an address, we just check if it is a MAC
525 # address. Otherwise, we assume that it is an IP address.
526 if ($key ~~ ["src_addr", "tgt_addr"]) {
527 if (&General
::validmac
($value)) {
528 push(@ret, "-m mac --mac-source $value");
533 # If a default network interface (GREEN, BLUE, etc.) is selected, we
534 # try to get the corresponding address of the network.
535 } elsif ($key ~~ ["std_net_src", "std_net_tgt", "Standard Network"]) {
536 my $external_interface = &get_external_interface
();
538 my $network_address = &fwlib
::get_std_net_ip
($value, $external_interface);
539 if ($network_address) {
540 push(@ret, $network_address);
544 } elsif ($key ~~ ["cust_net_src", "cust_net_tgt", "Custom Network"]) {
545 my $network_address = &fwlib
::get_net_ip
($value);
546 if ($network_address) {
547 push(@ret, $network_address);
551 } elsif ($key ~~ ["cust_host_src", "cust_host_tgt", "Custom Host"]) {
552 my $host_address = &fwlib
::get_host_ip
($value, $type);
554 push(@ret, $host_address);
558 } elsif ($key ~~ ["ovpn_net_src", "ovpn_net_tgt", "OpenVPN static network"]) {
559 my $network_address = &fwlib
::get_ovpn_net_ip
($value, 1);
560 if ($network_address) {
561 push(@ret, $network_address);
565 } elsif ($key ~~ ["ovpn_host_src", "ovpn_host_tgt", "OpenVPN static host"]) {
566 my $host_address = &fwlib
::get_ovpn_host_ip
($value, 33);
568 push(@ret, $host_address);
572 } elsif ($key ~~ ["ovpn_n2n_src", "ovpn_n2n_tgt", "OpenVPN N-2-N"]) {
573 my $network_address = &fwlib
::get_ovpn_n2n_ip
($value, 11);
574 if ($network_address) {
575 push(@ret, $network_address);
579 } elsif ($key ~~ ["ipsec_net_src", "ipsec_net_tgt", "IpSec Network"]) {
580 my $network_address = &fwlib
::get_ipsec_net_ip
($value, 11);
581 if ($network_address) {
582 push(@ret, $network_address);
585 # The firewall's own IP addresses.
586 } elsif ($key ~~ ["ipfire", "ipfire_src"]) {
588 if ($value eq "ALL") {
592 } elsif ($value eq "GREEN") {
593 push(@ret, $defaultNetworks{"GREEN_ADDRESS"});
596 } elsif ($value eq "BLUE") {
597 push(@ret, $defaultNetworks{"BLUE_ADDRESS"});
600 } elsif ($value eq "ORANGE") {
601 push(@ret, $defaultNetworks{"ORANGE_ADDRESS"});
604 } elsif ($value ~~ ["RED", "RED1"]) {
605 my $address = &get_external_address
();
607 push(@ret, $address);
612 my %alias = &get_alias
($value);
614 push(@ret, $alias{"IPT"});
618 # If nothing was selected, we assume "any".
630 my $uses_source_ports = ($$hash{$key}[7] eq "ON");
631 my $uses_services = ($$hash{$key}[11] eq "ON");
635 # Rules which don't have source ports or services (like ICMP, ESP, ...).
636 if (!$uses_source_ports && !$uses_services) {
637 push(@protocols, $$hash{$key}[8]);
639 # Rules which either use ports or services.
640 } elsif ($uses_source_ports || $uses_services) {
641 # Check if service group or service
642 if ($$hash{$key}[14] eq 'cust_srv') {
643 push(@protocols, &fwlib
::get_srv_prot
($$hash{$key}[15]));
645 } elsif($$hash{$key}[14] eq 'cust_srvgrp'){
646 my $protos = &fwlib
::get_srvgrp_prot
($$hash{$key}[15]);
647 push(@protocols, split(",", $protos));
650 # Fetch the protocol for this rule.
651 my $protocol = lc($$hash{$key}[8]);
653 # Fetch source and destination ports for this rule.
654 my $source_ports = $$hash{$key}[10];
655 my $destination_ports = $$hash{$key}[15];
657 # Check if ports are set for protocols which do not support ports.
658 if (!($protocol ~~ @PROTOCOLS_WITH_PORTS) && ($source_ports || $destination_ports)) {
659 print_error
("$protocol does not support ports");
663 push(@protocols, $protocol);
667 # Remove all empty elements
668 @protocols = map { $_ ?
$_ : () } @protocols;
670 # If no protocol has been defined, we assume "all".
672 push(@protocols, "all");
675 # Make all protocol names lowercase.
676 @protocols = map { lc } @protocols;
681 sub get_protocol_options
{
684 my $protocol = shift;
687 # Process source ports.
688 my $use_src_ports = ($$hash{$key}[7] eq "ON");
689 my $src_ports = $$hash{$key}[10];
691 if ($use_src_ports && $src_ports) {
692 push(@options, &format_ports
($src_ports, "src"));
695 # Process destination ports.
696 my $use_dst_ports = ($$hash{$key}[11] eq "ON");
697 my $use_dnat = (($$hash{$key}[28] eq "ON") && ($$hash{$key}[31] eq "dnat"));
699 if ($use_dst_ports) {
700 my $dst_ports_mode = $$hash{$key}[14];
701 my $dst_ports = $$hash{$key}[15];
703 if (($dst_ports_mode eq "TGT_PORT") && $dst_ports) {
704 if ($use_dnat && $$hash{$key}[30]) {
705 $dst_ports = $$hash{$key}[30];
707 push(@options, &format_ports
($dst_ports, "dst"));
709 } elsif ($dst_ports_mode eq "cust_srv") {
710 if ($protocol eq "ICMP") {
711 push(@options, ("--icmp-type", &fwlib
::get_srv_port
($dst_ports, 3, "ICMP")));
713 $dst_ports = &fwlib
::get_srv_port
($dst_ports, 1, uc($protocol));
714 push(@options, &format_ports
($dst_ports, "dst"));
717 } elsif ($dst_ports_mode eq "cust_srvgrp") {
718 push(@options, &fwlib
::get_srvgrp_port
($dst_ports, uc($protocol)));
722 # Check if a single ICMP type is selected.
723 if (!$use_src_ports && !$use_dst_ports && $protocol eq "icmp") {
724 my $icmp_type = $$hash{$key}[9];
726 if (($icmp_type ne "All ICMP-Types") && $icmp_type) {
727 push(@options, ("--icmp-type", $icmp_type));
739 if ($type eq "src") {
741 } elsif ($type eq "dst") {
747 if ($ports =~ /\|/) {
749 push(@options, ("-m", "multiport"));
753 push(@options, ($arg, $ports));
759 sub get_dnat_target_port
{
763 if ($$hash{$key}[14] eq "TGT_PORT") {
764 my $port = $$hash{$key}[15];
765 my $external_port = $$hash{$key}[30];
767 if ($external_port && ($port ne $external_port)) {
768 return $$hash{$key}[15];
773 sub add_dnat_mangle_rules
{
774 my $nat_address = shift;
778 foreach my $zone ("GREEN", "BLUE", "ORANGE") {
781 # Skip rule if not all required information exists.
782 next unless (exists $defaultNetworks{$zone . "_NETADDRESS"});
783 next unless (exists $defaultNetworks{$zone . "_NETMASK"});
785 my @mangle_options = @options;
787 my $netaddress = $defaultNetworks{$zone . "_NETADDRESS"};
788 $netaddress .= "/" . $defaultNetworks{$zone . "_NETMASK"};
790 push(@mangle_options, ("-s", $netaddress, "-d", $nat_address));
791 push(@mangle_options, ("-j", "MARK", "--set-mark", $mark));
793 run
("$IPTABLES -t mangle -A $CHAIN_MANGLE_NAT_DESTINATION_FIX @mangle_options");
797 sub make_log_limit_options
{
798 my @options = ("-m", "limit");
800 # Maybe we should get this from the configuration.
803 # We limit log messages to $limit messages per minute.
804 push(@options, ("--limit", "$limit/min"));
806 # And we allow bursts of 2x $limit.
807 push(@options, ("--limit-burst", $limit * 2));
812 sub firewall_is_in_subnet
{
815 my ($net_address, $net_mask) = split("/", $subnet);
820 # ORANGE is missing here, because nothing may ever access
821 # the firewall from this network.
822 foreach my $zone ("GREEN", "BLUE") {
823 next unless (exists $defaultNetworks{$zone . "_ADDRESS"});
825 my $zone_address = $defaultNetworks{$zone . "_ADDRESS"};
827 if (&General
::IpInSubnet
($zone_address, $net_address, $net_mask)) {