File:  [LON-CAPA] / loncom / configuration / Firewall.pm
Revision 1.13: download - view: text, annotated - select for diffs
Sun Sep 22 15:50:35 2013 UTC (11 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_11_0_RC2, HEAD
- Additional output for unexpected states.

# The LearningOnline Network with CAPA
# Firewall configuration to allow internal LON-CAPA communication between servers   
#
# $Id: Firewall.pm,v 1.13 2013/09/22 15:50:35 raeburn Exp $
#
# The LearningOnline Network with CAPA
#
# Copyright Michigan State University Board of Trustees
#
# This file is part of the LearningOnline Network with CAPA (LON-CAPA).
#
# LON-CAPA is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# LON-CAPA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with LON-CAPA; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# /home/httpd/html/adm/gpl.txt
#
# http://www.lon-capa.org/
#
# Startup script for the LON-CAPA network processes
#

package LONCAPA::Firewall;

use strict;
use lib '/home/httpd/perl/lib';
use LONCAPA::Configuration;
use LONCAPA;

sub firewall_open_port {
    my ($iptables,$fw_chains,$lond_port,$iphost,$ports) = @_;
    return 'inactive firewall' if (!&firewall_is_active());
    return 'port number unknown' if !$lond_port;
    return 'invalid firewall chain' unless (ref($fw_chains) eq 'ARRAY');
    my (@opened,@chains,@badchains,@okchains);
    foreach my $chain (@{$fw_chains}) {
        if ($chain =~ /^([\w\-]+)$/) {
            push(@okchains,$1);
        } else {
            push(@badchains,$chain);
        }
    }
    if (!@okchains) {
        return 'None of the chain names has the expected format'."\n";
    }
    if (ref($ports) ne 'ARRAY') {
        return 'List of ports to open needed.';
    }
    foreach my $portnum (@{$ports}) {
        my $port = '';
        if ($portnum =~ /^(\d+)$/) {
            $port = $1;
        } else {
            print "Skipped non-numeric port: $portnum\n";
            next;
        }
        print "Opening firewall access on port $port.\n";
        my $result;
        if ($port eq $lond_port) {
            # For lond port, restrict the servers allowed to attempt to communicate
            # to include only source IPs in the LON-CAPA cluster.
            my (@port_error,%command_error,@lond_port_open,
                @lond_port_curropen);
            if (ref($iphost) eq 'HASH') {
                if (keys(%{$iphost}) > 0) {
                    my %curropen;
                    foreach my $fw_chain (@okchains) {
                        &firewall_close_anywhere($iptables,$fw_chain,$port);
                        my $current = &firewall_is_port_open($iptables,$fw_chain,$port,$lond_port,$iphost,\%curropen);
                    }
                    foreach my $key (keys(%{$iphost})) {
                        my $ip = '';
                        if ($key =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/) {
                            if (($1<=255) && ($2<=255) && ($3<=255) && ($4<=255)) {
                                $ip = "$1.$2.$3.$4";
                            } else {
                                print "IP address: $key does not have expected format\n";
                                next;
                            }
                        } else {
                            print "IP address: $key does not have expected format\n";
                            next;
                        }
                        if ($curropen{$ip}) {
                            push(@lond_port_curropen,$ip);
                        } else {
                            foreach my $fw_chain (@okchains) {
                                my $firewall_command =
                                    "$iptables -I $fw_chain -p tcp -s $ip -d 0/0 --dport $port -j ACCEPT";
                                system($firewall_command);
                                my $return_status = $?>>8;
                                if ($return_status == 1) {
                                    unless(grep(/^\Q$ip\E$/,@port_error)) {
                                        push (@port_error,$ip);
                                    }
                                } elsif ($return_status == 2) {
                                    push(@{$command_error{$fw_chain}},$ip);
                                } elsif ($return_status == 0) {
                                    push(@lond_port_open,$ip);
                                    last;
                                }
                            }
                        }
                    }
                } else {
                    print "no key found in $iphost hash ref\n";
                }
            } else {
                print "$iphost is not a reference to a hash\n";
            }
            if (@lond_port_curropen) {
                unless (grep(/^\Q$port\E$/,@opened)) {
                    push(@opened,$port);
                }
                print "Port already open for ".scalar(@lond_port_curropen)." IP addresses\n";
            }
            if (@lond_port_open) {
                unless (grep(/^\Q$port\E$/,@opened)) {   
                    push(@opened,$port);
                }
                print "Port opened for ".scalar(@lond_port_open)." IP addresses\n";
            }
            if (@port_error) {
                print "Error opening port for following IP addresses: ".join(', ',@port_error)."\n";
            }
            if (keys(%command_error) > 0) {
                foreach my $chain (sort(keys(%command_error))) {
                    if (ref($command_error{$chain}) eq 'ARRAY') {
                        if (@{$command_error{$chain}}) {
                            print "Bad command error opening port for following IP addresses: ".
                                  join(', ',@{$command_error{$chain}})."\n".
                                 'Command was: "'."$iptables -I $chain -p tcp -s ".'$ip'." -d 0/0 --dport $port -j ACCEPT".'", where $ip is IP address'."\n";
                        }
                    }
                }
            }
        } else {
            my (@port_errors,%command_errors);
            foreach my $fw_chain (@okchains) {
                my $firewall_command =
                    "$iptables -I $fw_chain -p tcp -d 0/0 --dport $port -j ACCEPT";
                system($firewall_command);
                my $return_status = $?>>8;
                if ($return_status == 1) {
                    push(@port_errors,$fw_chain);
                } elsif ($return_status == 2) {
                    $command_errors{$fw_chain} = $firewall_command;
                } elsif ($return_status == 0) {
                    push(@opened,$port);
                    last;
                }
            }
            unless (grep(/^\Q$port\E$/,@opened)) {
                if (@port_errors) {
                    print "Error opening port for chains: ".
                          join(', ',@port_errors).".\n";
                }
                if (keys(%command_errors)) {
                    foreach my $fw_chain (sort(keys(%command_errors))) {
                        print "Bad command error opening port for chain: $fw_chain.  Command was\n".
                          "  ".$command_errors{$fw_chain}."\n";
                    }
                }
            }
        }
    }
    foreach my $port (@{$ports}) {
        if (!grep(/^\Q$port\E$/,@opened)) {
            return 'Required port not open: '.$port."\n";
        }
    }
    return 'ok';
}

sub firewall_is_port_open {
    my ($iptables,$fw_chain,$port,$lond_port,$iphost,$curropen) = @_;
    # for lond port returns number of source IPs for which firewall port is open
    # for other ports returns 1 if the firewall port is open, 0 if not.
    #
    # check if firewall is active or installed
    return if (! &firewall_is_active());
    my $count = 0;
    if (open(PIPE,"$iptables -L $fw_chain -n |")) {
        while(<PIPE>) {
            if ($port eq $lond_port) {
                if (ref($iphost) eq 'HASH') {
                    if (/^ACCEPT\s+tcp\s+\-{2}\s+(\S+)\s+\S+\s+tcp\s+dpt\:\Q$port\E/) {
                        my $ip = $1;
                        if ($iphost->{$ip}) {
                            $count ++;
                            if (ref($curropen) eq 'HASH') {
                                $curropen->{$ip} ++;
                            }
                        }
                    }
                }
            } else {
                if (/tcp dpt\:\Q$port\E/) {
                    $count ++;
                    last;
                }
            }
        }
        close(PIPE);
    }
    return $count;
}

sub firewall_is_active {
    if (-e '/proc/net/ip_tables_names') {
        return 1;
    } else {
        return 0;
    }
}

sub firewall_close_port {
    my ($iptables,$fw_chains,$lond_port,$iphost,$ports) = @_;
    return 'inactive firewall' if (!&firewall_is_active());
    return 'port number unknown' if !$lond_port;
    return 'invalid firewall chain' unless (ref($fw_chains) eq 'ARRAY');
    my (@opened,@chains,@badchains,@okchains);
    foreach my $chain (@{$fw_chains}) {
        if ($chain =~ /^([\w\-]+)$/) {
            push(@okchains,$1);
        } else {
            push(@badchains,$chain);
        }
    }
    if (!@okchains) {
        return 'None of the chain names has the expected format'."\n";
    }
    if (ref($ports) ne 'ARRAY') {
        return 'List of ports to close needed.';
    }
    foreach my $portnum (@{$ports}) {
        my $port = '';
        if ($portnum =~ /^(\d+)$/) {
            $port = $1;
        } else {
            print "Skipped non-numeric port: $portnum\n"; 
            next;
        }
        print "Closing firewall access on port $port.\n";
        if (($port ne '') && ($port eq $lond_port)) {
            my $output;
            foreach my $fw_chain (@okchains) {
                my (@port_error,@command_error,@lond_port_close);
                my %to_close;
                if (open(PIPE, "$iptables -n -L $fw_chain |")) {
                    while (<PIPE>) {
                        chomp();
                        next unless (/dpt:\Q$port\E\s*$/);
                        if (/^ACCEPT\s+tcp\s+\-{2}\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+/) {
                            my $ip = $1;
                            my $keepopen = 0;
                            if (ref($iphost) eq 'HASH') {
                                if (exists($iphost->{$ip})) {
                                    $keepopen = 1; 
                                }
                            }
                            unless ($keepopen) {
                                $to_close{$ip} = $port;
                            }
                        }
                    }
                    close(PIPE);
                }
                if (keys(%to_close) > 0) {
                    foreach my $ip (keys(%to_close)) {
                        my $firewall_command =
                            "$iptables -D $fw_chain -p tcp -s $ip -d 0/0 --dport $port -j ACCEPT";
                        system($firewall_command);
                        my $return_status = $?>>8;
                        if ($return_status == 1) {
                            push (@port_error,$ip);
                        } elsif ($return_status == 2) {
                            push(@command_error,$ip);
                        } elsif ($return_status == 0) {
                            push(@lond_port_close,$ip);
                        }
                    }
                }
                if (@lond_port_close) {
                    $output .= "Port closed for ".scalar(@lond_port_close)." IP addresses\n";
                }
                if (@port_error) {
                    $output .= "Error closing port for following IP addresses: ".join(', ',@port_error)."\n";
                }
                if (@command_error) {
                    $output .= "Bad command error opening port for following IP addresses: ".
                          join(', ',@command_error)."\n".
                          'Command was: "'."$iptables -D $fw_chain -p tcp -s ".'$ip'." -d 0/0 --dport $port -j ACCEPT".'", where $ip is IP address'."\n";
                }
            }
            if ($output) {
                 print $output;
            } else {
                print "No IP addresses required discontinuation of access.\n";
            }
        } else {
            foreach my $fw_chain (@okchains) {
                my (@port_error,@command_error,@lond_port_close);
                my $to_close;
                if (open(PIPE, "$iptables -n -L $fw_chain |")) {
                    while (<PIPE>) {
                        chomp();
                        next unless (/dpt:\Q$port\E\s*$/);
                        $to_close = 1;
                    }
                    close(PIPE);
                }
                if ($to_close) {
                    my $firewall_command =
                        "$iptables -D $fw_chain -p tcp -d 0/0 --dport $port -j ACCEPT";
                    system($firewall_command);
                    my $return_status = $?>>8;
                    if ($return_status == 1) {
                        # Error
                        print "Error closing port for chain: $fw_chain.\n";
                    } elsif ($return_status == 2) {
                        # Bad command
                        print "Bad command error closing port.  Command was\n".
                              "  ".$firewall_command."\n";
                    } else {
                        print "Port closed for chain $fw_chain.\n";
                    }
                }
            }
        }
    }
    return;
}

sub firewall_close_anywhere {
    my ($iptables,$fw_chain,$port) = @_;
    if (open(PIPE, "$iptables --line-numbers -n -L $fw_chain |")) {
        while (<PIPE>) {
            next unless (/dpt:\Q$port\E/);
            chomp();
            if (/^(\d+)\s+ACCEPT\s+tcp\s+\-{2}\s+0\.0\.0\.0\/0\s+0\.0\.0\.0\/0/) {
                my $firewall_command = "$iptables -D $fw_chain $1";
                system($firewall_command);
                my $return_status = $?>>8;
                if ($return_status == 1) {
                    print 'Error closing port '.$port.' for source "anywhere"'."\n";
                } elsif ($return_status == 2) {
                    print 'Bad command error closing port '.$port.' for source "anywhere".  Command was'."\n".
                          ' '.$firewall_command."\n";
                } else {
                    print 'Port '.$port.' closed for source "anywhere"'."\n";
                }
            }
        }
        close(PIPE);
    }
}

sub get_lond_port {
    my $perlvarref=&LONCAPA::Configuration::read_conf();
    my $lond_port;
    if (ref($perlvarref) eq 'HASH') {
        if (defined($perlvarref->{'londPort'})) {
            $lond_port = $perlvarref->{'londPort'};
        }
    }
    if (!$lond_port) {
        print("Unable to determine lond port number from LON-CAPA configuration.\n");
    }
    return $lond_port;
}

sub get_fw_chains {
    my ($iptables) = @_;
    my $distro = &LONCAPA::distro();
    my @fw_chains;
    my $suse_config = "/etc/sysconfig/SuSEfirewall2";
    my $ubuntu_config = "/etc/ufw/ufw.conf";
    if (-e $suse_config) {
        push(@fw_chains,'input_ext');
    } else {
        my @posschains;
        if (-e $ubuntu_config) {
            @posschains = ('ufw-user-input','INPUT');
        } else {
            if ($distro =~ /^(debian|ubuntu|suse|sles)/) {
                @posschains = ('INPUT'); 
            } else {
                @posschains = ('RH-Firewall-1-INPUT','INPUT');
            }
            if (!-e '/etc/sysconfig/iptables') {
                if (!-e '/var/lib/iptables') {
                    unless ($distro =~ /^(debian|ubuntu)/) {
                        print("Unable to find iptables file containing static definitions\n");
                    }
                }
                if ($distro =~ /^(fedora|rhes|centos|scientific)/) {
                    push(@fw_chains,'RH-Firewall-1-INPUT');
                }
            }
        }
        if ($iptables eq '') {
            $iptables = &get_pathto_iptables();
        }
        my %counts;
        if (open(PIPE,"$iptables -L -n |")) {
            while(<PIPE>) {
                foreach my $chain (@posschains) {
                    if (/(\Q$chain\E)/) {
                        $counts{$1} ++;
                    }
                }
            }
            close(PIPE);
        }
        foreach my $fw_chain (@posschains) {
            if ($counts{$fw_chain}) {
                unless(grep(/^\Q$fw_chain\E$/,@fw_chains)) {
                    push(@fw_chains,$fw_chain);
                }
            }
        }
    }
    return @fw_chains;
}

sub get_pathto_iptables {
    my $iptables;
    if (-e '/sbin/iptables') {
        $iptables = '/sbin/iptables';
    } elsif (-e '/usr/sbin/iptables') {
        $iptables = '/usr/sbin/iptables';
    } else {
        print("Unable to find iptables command\n");
    }
    return $iptables;
}

1;
__END__

=pod

=head1 NAME

B<LONCAPA::Firewall> - dynamic opening/closing of firewall ports

=head1 SYNOPSIS

 use lib '/home/httpd/lib/perl/';
 use LONCAPA::Firewall;

 LONCAPA::Firewall::firewall_open_port();
 LONCAPA::Firewall::firewall_close_port();
 LONCAPA::Firewall::firewall_is_port_open();
 LONCAPA::Firewall::firewall_is_active();
 LONCAPA::Firewall::firewall_close_anywhere();

=head1 DESCRIPTION

The scripts: /etc/init.d/loncontrol, used to stop or start LON-CAPA services, 
as well as the setuid script /home/httpd/perl/lciptables, called by loncron 
for housekeeping tasks, make use of the methods provided by this module to 
open and close firewall ports (currently the default port: 5663), used
for socket-based communication between LON-CAPA servers in the cluster
of networked servers to which the server belongs. 

The following methods are available:

=over 4

=item LONCAPA::Firewall::firewall_open_port( $iptables,$fw_chains,$lond_port,$iphost,$port );

=back

=over 4

=item LONCAPA::Firewall::firewall_close_port( $iptables,$fw_chains,$lond_port,$iphost,$ports );

=back

=over 4

=item LONCAPA::Firewall::firewall_is_port_open( $iptables,$fw_chain,$port,$lond_port,$iphost,$curropen );

=back

=over 4

=item LONCAPA::Firewall::firewall_is_active();

=back

=over 4

=item LONCAPA::Firewall::firewall_close_anywhere( $iptables,$fw_chain,$port );

=back

=over 4

=item LONCAPA::Firewall::get_lond_port();

=back

=over 4

=item LONCAPA::Firewall::get_fw_chains();

=back

=over 4

=item LONCAPA::Firewall::get_pathto_iptables();


=head1 AUTHORS

This library is free software; you can redistribute it and/or
modify it under the same terms as LON-CAPA itself.

=cut


FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>