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");
51 my %defaultNetworks=();
55 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 $geoipfile = "${General::swroot}/firewall/geoipblock";
64 my $configgrp = "${General::swroot}/fwhosts/customgroups";
65 my $netsettings = "${General::swroot}/ethernet/settings";
67 &General
::readhash
("${General::swroot}/firewall/settings", \
%fwdfwsettings);
68 &General
::readhash
("${General::swroot}/optionsfw/settings", \
%fwoptions);
69 &General
::readhash
("$netsettings", \
%defaultNetworks);
70 &General
::readhasharray
($configfwdfw, \
%configfwdfw);
71 &General
::readhasharray
($configinput, \
%configinputfw);
72 &General
::readhasharray
($configoutgoing, \
%configoutgoingfw);
73 &General
::readhasharray
($configgrp, \
%customgrp);
75 my @log_limit_options = &make_log_limit_options
();
77 my $POLICY_INPUT_ALLOWED = 0;
78 my $POLICY_FORWARD_ALLOWED = ($fwdfwsettings{"POLICY"} eq "MODE2");
79 my $POLICY_OUTPUT_ALLOWED = ($fwdfwsettings{"POLICY1"} eq "MODE2");
81 my $POLICY_INPUT_ACTION = $fwoptions{"FWPOLICY2"};
82 my $POLICY_FORWARD_ACTION = $fwoptions{"FWPOLICY"};
83 my $POLICY_OUTPUT_ACTION = $fwoptions{"FWPOLICY1"};
92 # Prepare firewall rules.
93 if (! -z
"${General::swroot}/firewall/input"){
94 &buildrules
(\
%configinputfw);
96 if (! -z
"${General::swroot}/firewall/outgoing"){
97 &buildrules
(\
%configoutgoingfw);
99 if (! -z
"${General::swroot}/firewall/config"){
100 &buildrules
(\
%configfwdfw);
103 # Load P2P block rules.
106 # Load GeoIP block rules.
109 # Reload firewall policy.
110 run
("/usr/sbin/firewall-policy");
112 #Reload firewall.local if present
113 if ( -f
'/etc/sysconfig/firewall.local'){
114 run
("/etc/sysconfig/firewall.local reload");
119 # Executes or prints the given shell command.
128 print_error
("ERROR: $command");
136 print STDERR
"$message\n";
146 printf(" %2d: %s", $i++, $_);
154 return scalar @
$hash;
158 run
("$IPTABLES -F $CHAIN_INPUT");
159 run
("$IPTABLES -F $CHAIN_FORWARD");
160 run
("$IPTABLES -F $CHAIN_OUTPUT");
161 run
("$IPTABLES -t nat -F $CHAIN_NAT_SOURCE");
162 run
("$IPTABLES -t nat -F $CHAIN_NAT_DESTINATION");
163 run
("$IPTABLES -t mangle -F $CHAIN_MANGLE_NAT_DESTINATION_FIX");
169 # Search for targets that need to be specially handled when adding
170 # forwarding rules. Additional rules will automatically get inserted
171 # into the INPUT/OUTPUT chains for these targets.
172 my @special_input_targets = ();
173 if (!$POLICY_FORWARD_ALLOWED) {
174 push(@special_input_targets, "ACCEPT");
177 if ($POLICY_INPUT_ACTION eq "DROP") {
178 push(@special_input_targets, "REJECT");
179 } elsif ($POLICY_INPUT_ACTION eq "REJECT") {
180 push(@special_input_targets, "DROP");
183 my @special_output_targets = ();
184 if ($POLICY_OUTPUT_ALLOWED) {
185 push(@special_output_targets, ("DROP", "REJECT"));
187 push(@special_output_targets, "ACCEPT");
189 if ($POLICY_OUTPUT_ACTION eq "DROP") {
190 push(@special_output_targets, "REJECT");
191 } elsif ($POLICY_OUTPUT_ACTION eq "REJECT") {
192 push(@special_output_targets, "DROP");
196 foreach my $key (sort {$a <=> $b} keys %$hash) {
197 # Skip disabled rules.
198 next unless ($$hash{$key}[2] eq 'ON');
200 # Count number of elements in this line
201 my $elements = &count_elements
($$hash{$key});
204 print_rule
($$hash{$key});
207 # Check if the target is valid.
208 my $target = $$hash{$key}[0];
209 if (!$target ~~ @VALID_TARGETS) {
210 print_error
("Invalid target '$target' for rule $key");
214 # Check if the chain is valid.
215 my $chain = $$hash{$key}[1];
216 if (!$chain ~~ @VALID_CHAINS) {
217 print_error
("Invalid chain '$chain' in rule $key");
221 # Collect all sources.
222 my @sources = &fwlib
::get_addresses
($hash, $key, "src");
224 # Collect all destinations.
225 my @destinations = &fwlib
::get_addresses
($hash, $key, "tgt");
227 # True if the destination is the firewall itself.
228 my $destination_is_firewall = ($$hash{$key}[5] eq "ipfire");
230 # Check if logging should be enabled.
231 my $LOG = ($$hash{$key}[17] eq 'ON');
233 # Check if NAT is enabled and initialize variables, that we use for that.
234 my $NAT = ($$hash{$key}[28] eq 'ON');
237 $NAT_MODE = uc($$hash{$key}[31]);
240 # Set up time constraints.
241 my @time_options = ();
242 if ($$hash{$key}[18] eq 'ON') {
243 push(@time_options, ("-m", "time"));
245 # Select all days of the week this match is active.
247 if ($$hash{$key}[19] ne '') {
248 push (@weekdays, "Mon");
250 if ($$hash{$key}[20] ne '') {
251 push (@weekdays, "Tue");
253 if ($$hash{$key}[21] ne '') {
254 push (@weekdays, "Wed");
256 if ($$hash{$key}[22] ne '') {
257 push (@weekdays, "Thu");
259 if ($$hash{$key}[23] ne '') {
260 push (@weekdays, "Fri");
262 if ($$hash{$key}[24] ne '') {
263 push (@weekdays, "Sat");
265 if ($$hash{$key}[25] ne '') {
266 push (@weekdays, "Sun");
269 push(@time_options, ("--weekdays", join(",", @weekdays)));
272 # Convert start time.
273 my $time_start = &format_time
($$hash{$key}[26]);
275 push(@time_options, ("--timestart", $time_start));
279 my $time_stop = &format_time
($$hash{$key}[27]);
281 push(@time_options, ("--timestop", $time_stop));
285 # Concurrent connection limit
286 my @ratelimit_options = ();
288 if (($elements ge 34) && ($$hash{$key}[32] eq 'ON')) {
289 my $conn_limit = $$hash{$key}[33];
291 if ($conn_limit ge 1) {
292 push(@ratelimit_options, ("-m", "connlimit"));
294 # Use the the entire source IP address
295 push(@ratelimit_options, "--connlimit-saddr");
296 push(@ratelimit_options, ("--connlimit-mask", "32"));
299 push(@ratelimit_options, ("--connlimit-upto", $conn_limit));
304 if (($elements ge 37) && ($$hash{$key}[34] eq 'ON')) {
305 my $rate_limit = "$$hash{$key}[35]/$$hash{$key}[36]";
308 push(@ratelimit_options, ("-m", "limit"));
309 push(@ratelimit_options, ("--limit", $rate_limit));
313 # Check which protocols are used in this rule and so that we can
314 # later group rules by protocols.
315 my @protocols = &get_protocols
($hash, $key);
317 print_error
("Invalid protocol configuration for rule $key");
321 foreach my $protocol (@protocols) {
322 # Check if the given protocol is supported.
323 if (($protocol ne "all") && (!$protocol ~~ @PROTOCOLS)) {
324 print_error
("Protocol $protocol is not supported (rule $key)");
328 # Prepare protocol options (like ICMP types, ports, etc...).
329 my @protocol_options = &get_protocol_options
($hash, $key, $protocol, 0);
331 # Check if this protocol knows ports.
332 my $protocol_has_ports = ($protocol ~~ @PROTOCOLS_WITH_PORTS);
334 foreach my $src (@sources) {
335 # Skip invalid source.
336 next unless (defined $src);
340 my $source = @
$src[0];
341 if ($source ~~ @ANY_ADDRESSES) {
345 my $source_intf = @
$src[1];
347 foreach my $dst (@destinations) {
348 # Skip invalid rules.
349 next unless (defined $dst);
350 next if (!$dst || ($dst eq "none"));
352 # Sanitize destination.
353 my $destination = @
$dst[0];
354 if ($destination ~~ @ANY_ADDRESSES) {
358 my $destination_intf = @
$dst[1];
360 # Array with iptables arguments.
364 if ($protocol ne "all") {
365 push(@options, @protocol_options);
368 # Prepare source options.
369 my @source_options = ();
370 if ($source =~ /mac/) {
371 push(@source_options, $source);
372 } elsif ($source =~ /-m geoip/) {
373 push(@source_options, $source);
375 push(@source_options, ("-s", $source));
378 # Prepare destination options.
379 my @destination_options = ();
380 if ($destination =~ /-m geoip/) {
381 push(@destination_options, $destination);
382 } elsif ($destination) {
383 push(@destination_options, ("-d", $destination));
386 # Add time constraint options.
387 push(@options, @time_options);
389 # Add ratelimiting option
390 push(@options, @ratelimit_options);
392 my $firewall_is_in_source_subnet = 1;
394 $firewall_is_in_source_subnet = &firewall_is_in_subnet
($source);
397 my $firewall_is_in_destination_subnet = 1;
399 $firewall_is_in_destination_subnet = &firewall_is_in_subnet
($destination);
404 my $nat_address = &fwlib
::get_nat_address
($$hash{$key}[29], $source);
406 # Skip NAT rules if the NAT address is unknown
407 # (i.e. no internet connection has been established, yet).
408 next unless ($nat_address);
411 if ($NAT_MODE eq "DNAT") {
412 my @nat_options = ();
413 if ($protocol ne "all") {
414 my @nat_protocol_options = &get_protocol_options
($hash, $key, $protocol, 1);
415 push(@nat_options, @nat_protocol_options);
417 push(@nat_options, @time_options);
419 # Make port-forwardings useable from the internal networks.
420 my @internal_addresses = &fwlib
::get_internal_firewall_ip_addresses
(1);
421 unless ($nat_address ~~ @internal_addresses) {
422 &add_dnat_mangle_rules
($nat_address, $source_intf, @nat_options);
425 push(@nat_options, @source_options);
426 push(@nat_options, ("-d", $nat_address));
429 if ($protocol_has_ports) {
430 $dnat_port = &get_dnat_target_port
($hash, $key);
433 my @nat_action_options = ();
435 # Use iptables REDIRECT
436 my $use_redirect = ($destination_is_firewall && !$destination && $protocol_has_ports && $dnat_port);
438 push(@nat_action_options, ("-j", "REDIRECT", "--to-ports", $dnat_port));
442 if ($destination_is_firewall && !$destination) {
443 $destination = &fwlib
::get_external_address
();
445 next unless ($destination);
447 my ($dnat_address, $dnat_mask) = split("/", $destination);
448 @destination_options = ("-d", $dnat_address);
450 if ($protocol_has_ports) {
451 my $dnat_port = &get_dnat_target_port
($hash, $key);
454 $dnat_address .= ":$dnat_port";
458 push(@nat_action_options, ("-j", "DNAT", "--to-destination", $dnat_address));
462 run
("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @log_limit_options -j LOG --log-prefix 'DNAT '");
464 run
("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @nat_action_options");
467 } elsif ($NAT_MODE eq "SNAT") {
468 my @nat_options = @options;
470 push(@nat_options, @source_options);
471 push(@nat_options, @destination_options);
474 run
("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options @log_limit_options -j LOG --log-prefix 'SNAT '");
476 run
("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options -j SNAT --to-source $nat_address");
480 # Add source and destination interface to the filter rules.
481 # These are supposed to help filtering forged packets that originate
482 # from BLUE with an IP address from GREEN for instance.
484 push(@source_options, ("-i", $source_intf));
487 if ($destination_intf) {
488 push(@destination_options, ("-o", $destination_intf));
491 push(@options, @source_options);
492 push(@options, @destination_options);
494 # Insert firewall rule.
496 run
("$IPTABLES -A $chain @options @log_limit_options -j LOG --log-prefix '$chain '");
498 run
("$IPTABLES -A $chain @options -j $target");
500 # Handle forwarding rules and add corresponding rules for firewall access.
501 if ($chain eq $CHAIN_FORWARD) {
502 # If the firewall is part of the destination subnet and access to the destination network
503 # is granted/forbidden for any network that the firewall itself is part of, we grant/forbid access
504 # for the firewall, too.
505 if ($firewall_is_in_destination_subnet && ($target ~~ @special_input_targets)) {
507 run
("$IPTABLES -A $CHAIN_INPUT @options @log_limit_options -j LOG --log-prefix '$CHAIN_INPUT '");
509 run
("$IPTABLES -A $CHAIN_INPUT @options -j $target");
513 if ($firewall_is_in_source_subnet && ($target ~~ @special_output_targets)) {
515 run
("$IPTABLES -A $CHAIN_OUTPUT @options @log_limit_options -j LOG --log-prefix '$CHAIN_OUTPUT '");
517 run
("$IPTABLES -A $CHAIN_OUTPUT @options -j $target");
526 # Formats the given timestamp into the iptables format which is "hh:mm" UTC.
530 # Convert the given time into minutes.
531 my $minutes = &time_convert_to_minutes
($val);
533 # Move the timestamp into UTC.
534 $minutes += &time_utc_offset
();
536 # Make sure $minutes is between 00:00 and 23:59.
541 if ($minutes > 1440) {
546 return sprintf("%02d:%02d", $minutes / 60, $minutes % 60);
549 # Calculates the offsets in minutes from the local timezone to UTC.
550 sub time_utc_offset
{
551 my @localtime = localtime(time);
552 my @gmtime = gmtime(time);
554 return ($gmtime[2] * 60 + $gmtime[1] % 60) - ($localtime[2] * 60 + $localtime[1] % 60);
557 # Takes a timestamp like "14:00" and converts it into minutes since midnight.
558 sub time_convert_to_minutes
{
559 my ($hrs, $min) = split(":", shift);
561 return ($hrs * 60) + $min;
565 open(FILE
, "<$p2pfile") or die "Unable to read $p2pfile";
567 foreach my $p2pentry (<FILE
>) {
568 my @p2pline = split(/\;/, $p2pentry);
569 next unless ($p2pline[2] eq "off");
571 push(@protocols, "--$p2pline[1]");
575 run
("$IPTABLES -F P2PBLOCK");
577 run
("$IPTABLES -A P2PBLOCK -m ipp2p @protocols -j DROP");
582 my %geoipsettings = ();
583 $geoipsettings{'GEOIPBLOCK_ENABLED'} = "off";
585 # Flush iptables chain.
586 run
("$IPTABLES -F GEOIPBLOCK");
588 # Check if the geoip settings file exists
589 if (-e
"$geoipfile") {
591 &General
::readhash
("$geoipfile", \
%geoipsettings);
594 # If geoip blocking is not enabled, we are finished here.
595 if ($geoipsettings{'GEOIPBLOCK_ENABLED'} ne "on") {
596 # Exit submodule. Process remaining script.
600 # Get supported locations.
601 my @locations = &fwlib
::get_geoip_locations
();
603 # Loop through all supported geoip locations and
604 # create iptables rules, if blocking this country
606 foreach my $location (@locations) {
607 if($geoipsettings{$location} eq "on") {
608 run
("$IPTABLES -A GEOIPBLOCK -m geoip --src-cc $location -j DROP");
617 my $uses_source_ports = ($$hash{$key}[7] eq "ON");
618 my $uses_services = ($$hash{$key}[11] eq "ON");
622 # Rules which don't have source ports or services (like ICMP, ESP, ...).
623 if (!$uses_source_ports && !$uses_services) {
624 push(@protocols, $$hash{$key}[8]);
626 # Rules which either use ports or services.
627 } elsif ($uses_source_ports || $uses_services) {
628 # Check if service group or service
629 if ($$hash{$key}[14] eq 'cust_srv') {
630 push(@protocols, &fwlib
::get_srv_prot
($$hash{$key}[15]));
632 } elsif($$hash{$key}[14] eq 'cust_srvgrp'){
633 my $protos = &fwlib
::get_srvgrp_prot
($$hash{$key}[15]);
634 push(@protocols, split(",", $protos));
637 # Fetch the protocol for this rule.
638 my $protocol = lc($$hash{$key}[8]);
640 # Fetch source and destination ports for this rule.
641 my $source_ports = $$hash{$key}[10];
642 my $destination_ports = $$hash{$key}[15];
644 # Check if ports are set for protocols which do not support ports.
645 if (!($protocol ~~ @PROTOCOLS_WITH_PORTS) && ($source_ports || $destination_ports)) {
646 print_error
("$protocol does not support ports");
650 push(@protocols, $protocol);
654 # Remove all empty elements
655 @protocols = map { $_ ?
$_ : () } @protocols;
657 # If no protocol has been defined, we assume "all".
659 push(@protocols, "all");
662 # Make all protocol names lowercase.
663 @protocols = map { lc } @protocols;
668 sub get_protocol_options
{
671 my $protocol = shift;
672 my $nat_options_wanted = shift;
675 # Nothing to do if no protocol is specified.
676 if ($protocol eq "all") {
679 push(@options, ("-p", $protocol));
682 if ($protocol ~~ @PROTOCOLS_WITH_PORTS) {
683 # Process source ports.
684 my $use_src_ports = ($$hash{$key}[7] eq "ON");
685 my $src_ports = $$hash{$key}[10];
687 if ($use_src_ports && $src_ports) {
688 push(@options, &format_ports
($src_ports, "src"));
691 # Process destination ports.
692 my $use_dst_ports = ($$hash{$key}[11] eq "ON");
693 my $use_dnat = (($$hash{$key}[28] eq "ON") && ($$hash{$key}[31] eq "dnat"));
695 if ($use_dst_ports) {
696 my $dst_ports_mode = $$hash{$key}[14];
697 my $dst_ports = $$hash{$key}[15];
699 if (($dst_ports_mode eq "TGT_PORT") && $dst_ports) {
700 if ($nat_options_wanted && $use_dnat && $$hash{$key}[30]) {
701 $dst_ports = $$hash{$key}[30];
703 push(@options, &format_ports
($dst_ports, "dst"));
705 } elsif ($dst_ports_mode eq "cust_srv") {
706 if ($protocol eq "ICMP") {
707 push(@options, ("--icmp-type", &fwlib
::get_srv_port
($dst_ports, 3, "ICMP")));
709 $dst_ports = &fwlib
::get_srv_port
($dst_ports, 1, uc($protocol));
710 push(@options, &format_ports
($dst_ports, "dst"));
713 } elsif ($dst_ports_mode eq "cust_srvgrp") {
714 push(@options, &fwlib
::get_srvgrp_port
($dst_ports, uc($protocol)));
719 # Check if a single ICMP type is selected.
720 if ($protocol eq "icmp") {
721 my $icmp_type = $$hash{$key}[9];
723 if (($icmp_type ne "All ICMP-Types") && $icmp_type) {
724 push(@options, ("--icmp-type", $icmp_type));
736 if ($type eq "src") {
738 } elsif ($type eq "dst") {
744 if ($ports =~ /\|/) {
746 push(@options, ("-m", "multiport"));
750 push(@options, ($arg, $ports));
756 sub get_dnat_target_port
{
760 if ($$hash{$key}[14] eq "TGT_PORT") {
761 my $port = $$hash{$key}[15];
762 my $external_port = $$hash{$key}[30];
764 if ($external_port && ($port ne $external_port)) {
765 return $$hash{$key}[15];
770 sub add_dnat_mangle_rules
{
771 my $nat_address = shift;
772 my $interface = shift;
776 foreach my $zone ("GREEN", "BLUE", "ORANGE") {
779 # Skip rule if not all required information exists.
780 next unless (exists $defaultNetworks{$zone . "_NETADDRESS"});
781 next unless (exists $defaultNetworks{$zone . "_NETMASK"});
783 next if ($interface && $interface ne $defaultNetworks{$zone . "_DEV"});
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 # ORANGE is missing here, because nothing may ever access
816 # the firewall from this network.
817 my $address = &fwlib
::get_internal_firewall_ip_address
($subnet, 0);