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 # Reload firewall rules.
95 # Load P2P block rules.
98 # Load GeoIP block rules.
101 # Reload firewall policy.
102 run
("/usr/sbin/firewall-policy");
106 # Executes or prints the given shell command.
115 print_error
("ERROR: $command");
123 print STDERR
"$message\n";
133 printf(" %2d: %s", $i++, $_);
141 return scalar @
$hash;
145 run
("$IPTABLES -F $CHAIN_INPUT");
146 run
("$IPTABLES -F $CHAIN_FORWARD");
147 run
("$IPTABLES -F $CHAIN_OUTPUT");
148 run
("$IPTABLES -t nat -F $CHAIN_NAT_SOURCE");
149 run
("$IPTABLES -t nat -F $CHAIN_NAT_DESTINATION");
150 run
("$IPTABLES -t mangle -F $CHAIN_MANGLE_NAT_DESTINATION_FIX");
154 if (! -z
"${General::swroot}/firewall/input"){
155 &buildrules
(\
%configinputfw);
157 if (! -z
"${General::swroot}/firewall/outgoing"){
158 &buildrules
(\
%configoutgoingfw);
160 if (! -z
"${General::swroot}/firewall/config"){
161 &buildrules
(\
%configfwdfw);
168 # Search for targets that need to be specially handled when adding
169 # forwarding rules. Additional rules will automatically get inserted
170 # into the INPUT/OUTPUT chains for these targets.
171 my @special_input_targets = ();
172 if (!$POLICY_FORWARD_ALLOWED) {
173 push(@special_input_targets, "ACCEPT");
176 if ($POLICY_INPUT_ACTION eq "DROP") {
177 push(@special_input_targets, "REJECT");
178 } elsif ($POLICY_INPUT_ACTION eq "REJECT") {
179 push(@special_input_targets, "DROP");
182 my @special_output_targets = ();
183 if ($POLICY_OUTPUT_ALLOWED) {
184 push(@special_output_targets, ("DROP", "REJECT"));
186 push(@special_output_targets, "ACCEPT");
188 if ($POLICY_OUTPUT_ACTION eq "DROP") {
189 push(@special_output_targets, "REJECT");
190 } elsif ($POLICY_OUTPUT_ACTION eq "REJECT") {
191 push(@special_output_targets, "DROP");
195 foreach my $key (sort {$a <=> $b} keys %$hash) {
196 # Skip disabled rules.
197 next unless ($$hash{$key}[2] eq 'ON');
199 # Count number of elements in this line
200 my $elements = &count_elements
($$hash{$key});
203 print_rule
($$hash{$key});
206 # Check if the target is valid.
207 my $target = $$hash{$key}[0];
208 if (!$target ~~ @VALID_TARGETS) {
209 print_error
("Invalid target '$target' for rule $key");
213 # Check if the chain is valid.
214 my $chain = $$hash{$key}[1];
215 if (!$chain ~~ @VALID_CHAINS) {
216 print_error
("Invalid chain '$chain' in rule $key");
220 # Collect all sources.
221 my @sources = &fwlib
::get_addresses
($hash, $key, "src");
223 # Collect all destinations.
224 my @destinations = &fwlib
::get_addresses
($hash, $key, "tgt");
226 # True if the destination is the firewall itself.
227 my $destination_is_firewall = ($$hash{$key}[5] eq "ipfire");
229 # Check if logging should be enabled.
230 my $LOG = ($$hash{$key}[17] eq 'ON');
232 # Check if NAT is enabled and initialize variables, that we use for that.
233 my $NAT = ($$hash{$key}[28] eq 'ON');
236 $NAT_MODE = uc($$hash{$key}[31]);
239 # Set up time constraints.
240 my @time_options = ();
241 if ($$hash{$key}[18] eq 'ON') {
242 push(@time_options, ("-m", "time"));
244 # Select all days of the week this match is active.
246 if ($$hash{$key}[19] ne '') {
247 push (@weekdays, "Mon");
249 if ($$hash{$key}[20] ne '') {
250 push (@weekdays, "Tue");
252 if ($$hash{$key}[21] ne '') {
253 push (@weekdays, "Wed");
255 if ($$hash{$key}[22] ne '') {
256 push (@weekdays, "Thu");
258 if ($$hash{$key}[23] ne '') {
259 push (@weekdays, "Fri");
261 if ($$hash{$key}[24] ne '') {
262 push (@weekdays, "Sat");
264 if ($$hash{$key}[25] ne '') {
265 push (@weekdays, "Sun");
268 push(@time_options, ("--weekdays", join(",", @weekdays)));
271 # Convert start time.
272 my $time_start = &format_time
($$hash{$key}[26]);
274 push(@time_options, ("--timestart", $time_start));
278 my $time_stop = &format_time
($$hash{$key}[27]);
280 push(@time_options, ("--timestop", $time_stop));
284 # Concurrent connection limit
285 my @ratelimit_options = ();
287 if (($elements gt 34) && ($$hash{$key}[32] eq 'ON')) {
288 my $conn_limit = $$hash{$key}[33];
290 if ($conn_limit ge 1) {
291 push(@ratelimit_options, ("-m", "connlimit"));
293 # Use the the entire source IP address
294 push(@ratelimit_options, "--connlimit-saddr");
295 push(@ratelimit_options, ("--connlimit-mask", "32"));
298 push(@ratelimit_options, ("--connlimit-upto", $conn_limit));
303 if (($elements gt 37) && ($$hash{$key}[34] eq 'ON')) {
304 my $rate_limit = "$$hash{$key}[35]/$$hash{$key}[36]";
307 push(@ratelimit_options, ("-m", "limit"));
308 push(@ratelimit_options, ("--limit", $rate_limit));
312 # Check which protocols are used in this rule and so that we can
313 # later group rules by protocols.
314 my @protocols = &get_protocols
($hash, $key);
316 print_error
("Invalid protocol configuration for rule $key");
320 foreach my $protocol (@protocols) {
321 # Check if the given protocol is supported.
322 if (($protocol ne "all") && (!$protocol ~~ @PROTOCOLS)) {
323 print_error
("Protocol $protocol is not supported (rule $key)");
327 # Prepare protocol options (like ICMP types, ports, etc...).
328 my @protocol_options = &get_protocol_options
($hash, $key, $protocol, 0);
330 # Check if this protocol knows ports.
331 my $protocol_has_ports = ($protocol ~~ @PROTOCOLS_WITH_PORTS);
333 foreach my $src (@sources) {
334 # Skip invalid source.
335 next unless (defined $src);
339 my $source = @
$src[0];
340 if ($source ~~ @ANY_ADDRESSES) {
344 my $source_intf = @
$src[1];
346 foreach my $dst (@destinations) {
347 # Skip invalid rules.
348 next unless (defined $dst);
349 next if (!$dst || ($dst eq "none"));
351 # Sanitize destination.
352 my $destination = @
$dst[0];
353 if ($destination ~~ @ANY_ADDRESSES) {
357 my $destination_intf = @
$dst[1];
359 # Array with iptables arguments.
363 if ($protocol ne "all") {
364 push(@options, @protocol_options);
367 # Prepare source options.
368 my @source_options = ();
369 if ($source =~ /mac/) {
370 push(@source_options, $source);
372 push(@source_options, ("-s", $source));
376 push(@source_options, ("-i", $source_intf));
379 # Prepare destination options.
380 my @destination_options = ();
382 push(@destination_options, ("-d", $destination));
385 if ($destination_intf) {
386 push(@destination_options, ("-o", $destination_intf));
389 # Add time constraint options.
390 push(@options, @time_options);
392 # Add ratelimiting option
393 push(@options, @ratelimit_options);
395 my $firewall_is_in_source_subnet = 1;
397 $firewall_is_in_source_subnet = &firewall_is_in_subnet
($source);
400 my $firewall_is_in_destination_subnet = 1;
402 $firewall_is_in_destination_subnet = &firewall_is_in_subnet
($destination);
407 my $nat_address = &fwlib
::get_nat_address
($$hash{$key}[29], $source);
409 # Skip NAT rules if the NAT address is unknown
410 # (i.e. no internet connection has been established, yet).
411 next unless ($nat_address);
414 if ($NAT_MODE eq "DNAT") {
415 my @nat_options = ();
416 if ($protocol ne "all") {
417 my @nat_protocol_options = &get_protocol_options
($hash, $key, $protocol, 1);
418 push(@nat_options, @nat_protocol_options);
420 push(@nat_options, @time_options);
422 # Make port-forwardings useable from the internal networks.
423 my @internal_addresses = &fwlib
::get_internal_firewall_ip_addresses
(1);
424 unless ($nat_address ~~ @internal_addresses) {
425 &add_dnat_mangle_rules
($nat_address, $source_intf, @nat_options);
428 push(@nat_options, @source_options);
429 push(@nat_options, ("-d", $nat_address));
432 if ($protocol_has_ports) {
433 $dnat_port = &get_dnat_target_port
($hash, $key);
436 my @nat_action_options = ();
438 # Use iptables REDIRECT
439 my $use_redirect = ($destination_is_firewall && !$destination && $protocol_has_ports && $dnat_port);
441 push(@nat_action_options, ("-j", "REDIRECT", "--to-ports", $dnat_port));
445 if ($destination_is_firewall && !$destination) {
446 $destination = &fwlib
::get_external_address
();
448 next unless ($destination);
450 my ($dnat_address, $dnat_mask) = split("/", $destination);
451 @destination_options = ("-d", $dnat_address);
453 if ($protocol_has_ports) {
454 my $dnat_port = &get_dnat_target_port
($hash, $key);
457 $dnat_address .= ":$dnat_port";
461 push(@nat_action_options, ("-j", "DNAT", "--to-destination", $dnat_address));
465 run
("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @log_limit_options -j LOG --log-prefix 'DNAT '");
467 run
("$IPTABLES -t nat -A $CHAIN_NAT_DESTINATION @nat_options @nat_action_options");
470 } elsif ($NAT_MODE eq "SNAT") {
471 my @nat_options = @options;
473 push(@nat_options, @source_options);
474 push(@nat_options, @destination_options);
477 run
("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options @log_limit_options -j LOG --log-prefix 'SNAT '");
479 run
("$IPTABLES -t nat -A $CHAIN_NAT_SOURCE @nat_options -j SNAT --to-source $nat_address");
483 push(@options, @source_options);
484 push(@options, @destination_options);
486 # Insert firewall rule.
488 run
("$IPTABLES -A $chain @options @log_limit_options -j LOG --log-prefix '$chain '");
490 run
("$IPTABLES -A $chain @options -j $target");
492 # Handle forwarding rules and add corresponding rules for firewall access.
493 if ($chain eq $CHAIN_FORWARD) {
494 # If the firewall is part of the destination subnet and access to the destination network
495 # is granted/forbidden for any network that the firewall itself is part of, we grant/forbid access
496 # for the firewall, too.
497 if ($firewall_is_in_destination_subnet && ($target ~~ @special_input_targets)) {
499 run
("$IPTABLES -A $CHAIN_INPUT @options @log_limit_options -j LOG --log-prefix '$CHAIN_INPUT '");
501 run
("$IPTABLES -A $CHAIN_INPUT @options -j $target");
505 if ($firewall_is_in_source_subnet && ($target ~~ @special_output_targets)) {
507 run
("$IPTABLES -A $CHAIN_OUTPUT @options @log_limit_options -j LOG --log-prefix '$CHAIN_OUTPUT '");
509 run
("$IPTABLES -A $CHAIN_OUTPUT @options -j $target");
516 #Reload firewall.local if present
517 if ( -f
'/etc/sysconfig/firewall.local'){
518 run
("/etc/sysconfig/firewall.local reload");
522 # Formats the given timestamp into the iptables format which is "hh:mm" UTC.
526 # Convert the given time into minutes.
527 my $minutes = &time_convert_to_minutes
($val);
529 # Move the timestamp into UTC.
530 $minutes += &time_utc_offset
();
532 # Make sure $minutes is between 00:00 and 23:59.
537 if ($minutes > 1440) {
542 return sprintf("%02d:%02d", $minutes / 60, $minutes % 60);
545 # Calculates the offsets in minutes from the local timezone to UTC.
546 sub time_utc_offset
{
547 my @localtime = localtime(time);
548 my @gmtime = gmtime(time);
550 return ($gmtime[2] * 60 + $gmtime[1] % 60) - ($localtime[2] * 60 + $localtime[1] % 60);
553 # Takes a timestamp like "14:00" and converts it into minutes since midnight.
554 sub time_convert_to_minutes
{
555 my ($hrs, $min) = split(":", shift);
557 return ($hrs * 60) + $min;
561 open(FILE
, "<$p2pfile") or die "Unable to read $p2pfile";
563 foreach my $p2pentry (<FILE
>) {
564 my @p2pline = split(/\;/, $p2pentry);
565 next unless ($p2pline[2] eq "off");
567 push(@protocols, "--$p2pline[1]");
571 run
("$IPTABLES -F P2PBLOCK");
573 run
("$IPTABLES -A P2PBLOCK -m ipp2p @protocols -j DROP");
578 my %geoipsettings = ();
580 # Check if the geoip settings file exists
581 if (-e
"$geoipfile") {
583 &General
::readhash
("$geoipfile", \
%geoipsettings);
585 # Exit submodule, go on processing the remaining script
589 # If geoip blocking is not enabled, we are finished here.
590 if ($geoipsettings{'GEOIPBLOCK_ENABLED'} ne "on") {
591 # Exit submodule. Process remaining script.
595 # Get supported locations.
596 my @locations = &fwlib
::get_geoip_locations
();
598 # Create iptables chain.
599 run
("$IPTABLES -F GEOIPBLOCK");
601 # Loop through all supported geoip locations and
602 # create iptables rules, if blocking this country
604 foreach my $location (@locations) {
605 if($geoipsettings{$location} eq "on") {
606 run
("$IPTABLES -A GEOIPBLOCK -m geoip --src-cc $location -j DROP");
615 my $uses_source_ports = ($$hash{$key}[7] eq "ON");
616 my $uses_services = ($$hash{$key}[11] eq "ON");
620 # Rules which don't have source ports or services (like ICMP, ESP, ...).
621 if (!$uses_source_ports && !$uses_services) {
622 push(@protocols, $$hash{$key}[8]);
624 # Rules which either use ports or services.
625 } elsif ($uses_source_ports || $uses_services) {
626 # Check if service group or service
627 if ($$hash{$key}[14] eq 'cust_srv') {
628 push(@protocols, &fwlib
::get_srv_prot
($$hash{$key}[15]));
630 } elsif($$hash{$key}[14] eq 'cust_srvgrp'){
631 my $protos = &fwlib
::get_srvgrp_prot
($$hash{$key}[15]);
632 push(@protocols, split(",", $protos));
635 # Fetch the protocol for this rule.
636 my $protocol = lc($$hash{$key}[8]);
638 # Fetch source and destination ports for this rule.
639 my $source_ports = $$hash{$key}[10];
640 my $destination_ports = $$hash{$key}[15];
642 # Check if ports are set for protocols which do not support ports.
643 if (!($protocol ~~ @PROTOCOLS_WITH_PORTS) && ($source_ports || $destination_ports)) {
644 print_error
("$protocol does not support ports");
648 push(@protocols, $protocol);
652 # Remove all empty elements
653 @protocols = map { $_ ?
$_ : () } @protocols;
655 # If no protocol has been defined, we assume "all".
657 push(@protocols, "all");
660 # Make all protocol names lowercase.
661 @protocols = map { lc } @protocols;
666 sub get_protocol_options
{
669 my $protocol = shift;
670 my $nat_options_wanted = shift;
673 # Nothing to do if no protocol is specified.
674 if ($protocol eq "all") {
677 push(@options, ("-p", $protocol));
680 if ($protocol ~~ @PROTOCOLS_WITH_PORTS) {
681 # Process source ports.
682 my $use_src_ports = ($$hash{$key}[7] eq "ON");
683 my $src_ports = $$hash{$key}[10];
685 if ($use_src_ports && $src_ports) {
686 push(@options, &format_ports
($src_ports, "src"));
689 # Process destination ports.
690 my $use_dst_ports = ($$hash{$key}[11] eq "ON");
691 my $use_dnat = (($$hash{$key}[28] eq "ON") && ($$hash{$key}[31] eq "dnat"));
693 if ($use_dst_ports) {
694 my $dst_ports_mode = $$hash{$key}[14];
695 my $dst_ports = $$hash{$key}[15];
697 if (($dst_ports_mode eq "TGT_PORT") && $dst_ports) {
698 if ($nat_options_wanted && $use_dnat && $$hash{$key}[30]) {
699 $dst_ports = $$hash{$key}[30];
701 push(@options, &format_ports
($dst_ports, "dst"));
703 } elsif ($dst_ports_mode eq "cust_srv") {
704 if ($protocol eq "ICMP") {
705 push(@options, ("--icmp-type", &fwlib
::get_srv_port
($dst_ports, 3, "ICMP")));
707 $dst_ports = &fwlib
::get_srv_port
($dst_ports, 1, uc($protocol));
708 push(@options, &format_ports
($dst_ports, "dst"));
711 } elsif ($dst_ports_mode eq "cust_srvgrp") {
712 push(@options, &fwlib
::get_srvgrp_port
($dst_ports, uc($protocol)));
717 # Check if a single ICMP type is selected.
718 if ($protocol eq "icmp") {
719 my $icmp_type = $$hash{$key}[9];
721 if (($icmp_type ne "All ICMP-Types") && $icmp_type) {
722 push(@options, ("--icmp-type", $icmp_type));
734 if ($type eq "src") {
736 } elsif ($type eq "dst") {
742 if ($ports =~ /\|/) {
744 push(@options, ("-m", "multiport"));
748 push(@options, ($arg, $ports));
754 sub get_dnat_target_port
{
758 if ($$hash{$key}[14] eq "TGT_PORT") {
759 my $port = $$hash{$key}[15];
760 my $external_port = $$hash{$key}[30];
762 if ($external_port && ($port ne $external_port)) {
763 return $$hash{$key}[15];
768 sub add_dnat_mangle_rules
{
769 my $nat_address = shift;
770 my $interface = shift;
774 foreach my $zone ("GREEN", "BLUE", "ORANGE") {
777 # Skip rule if not all required information exists.
778 next unless (exists $defaultNetworks{$zone . "_NETADDRESS"});
779 next unless (exists $defaultNetworks{$zone . "_NETMASK"});
781 next if ($interface && $interface ne $defaultNetworks{$zone . "_DEV"});
783 my @mangle_options = @options;
785 my $netaddress = $defaultNetworks{$zone . "_NETADDRESS"};
786 $netaddress .= "/" . $defaultNetworks{$zone . "_NETMASK"};
788 push(@mangle_options, ("-s", $netaddress, "-d", $nat_address));
789 push(@mangle_options, ("-j", "MARK", "--set-mark", $mark));
791 run
("$IPTABLES -t mangle -A $CHAIN_MANGLE_NAT_DESTINATION_FIX @mangle_options");
795 sub make_log_limit_options
{
796 my @options = ("-m", "limit");
798 # Maybe we should get this from the configuration.
801 # We limit log messages to $limit messages per minute.
802 push(@options, ("--limit", "$limit/min"));
804 # And we allow bursts of 2x $limit.
805 push(@options, ("--limit-burst", $limit * 2));
810 sub firewall_is_in_subnet
{
813 # ORANGE is missing here, because nothing may ever access
814 # the firewall from this network.
815 my $address = &fwlib
::get_internal_firewall_ip_address
($subnet, 0);