#!/usr/bin/perl
###############################################################################
## @file basefirewallconfig
# @brief This script configures firewall rules
# @details
# @param
# @author Vlad Ivanov
# @author Pavel Sergeev
# @date   October 2008
# @version 1.00 - Initial version
# @version 1.01 - POD section was added; the usage is displayed by the
#  common function - print_pod_usage() now.
# @version 1.05 - "redirectport", "localredirectport" options support is added.
#  firewall_restart called with the states hash.
# @version 1.06 - Two colons were removed before shared functions and variables.
# @version 1.07 - Modified under the perlcheck warnings cleanup activity.
# @version 1.08 - The iptables configuration file integrity was protected with SEM_FIREWALL
# @version 1.09 - Now firewall_restart is called with 'force' parameter
# @note
###############################################################################

=pod

=head1 NAME

B<basefirewallconfig> - tool for the firewall configuration.

=head1 SYNOPSIS

B<basefirewallconfig> [B<help>]|[B<start>]|[B<restart>]|[B<stop>]|[B<show>|[B<showall>]

B<basefirewallconfig> B<add> | [B<-proto> I<protocol>] | [B<-port> I<dest_port>] | [B<-srcport> I<src_port>] | [B<-icmptype> I<icmp_type>] | [B<-if> I<interface>] | [B<-host> I<host>] | [B<-eth> I<eth_interface>] | [B<-dscp> I<dscp_value>] | [B<-redirectport> I<redirect_port>] | [B<-localredirectport> I<local_redirect_port>] 

B<basefirewallconfig> B<del> I<rule_number>

=head1 DESCRIPTION

B<basefirewallconfig> is used to configure the firewall rules and manage
the firewall itself (stop, start or restart it).

This command is able to add one iptables firewall rule at a time, list the 
existing rules (provided by configure.xml files or added by this command)
and delete one iptables firewall rule, added by this command, at a time.

=head1 OPTIONS

=over 4

=item B<help>

Print this help message and exit.

=item B<start>

Start the firewall.

=item B<restart>

Restart the firewall.

=item B<stop>

Stop the firewall.
This action may cause a security exposure, so user confirmation is required.
Also, this action will be logged and alarmed (via SEC0110 snmp message).
Alarm will be cleared by SEC0109 snmp message as soos as the firewall is started again.

=item B<show>

Show the iptables firewall rules added by this command.

=item B<showall>

Show all iptables firewall rules.

=item B<add> I<add_options>

Add one firewall rule.

=item I<Add options are:>

=over 4

=item B<-proto>

The protocol of the rule to check.

=item B<-port>

The destination port.

=item B<-srcport>

The source port.

=item B<-icmptype>

This allows specification of the ICMP type.

=item B<-if>

Name of an interface via which a packet was received.

=item B<-host>

Source hostname specification.

=item B<-eth>

Number of the ethernet interface via which a packet was received.

=item B<-dscp>

DSCP field within the TOS field in the IP header.

=item B<-redirectport>

This option is used to rewrite the destination port of a packet.

=item B<-localredirectport>

This option is used to rewrite the destination port of outgoing packets

=back

=item B<del> I<rule_number>

Delete one firewall rule [I<use "basefirewallconfig show" to get rule_number>]

=back

NOTE that all modified rules are permanent. They will survive the reboot.

=head1 EXAMPLES

=over 4

=item B<$ basefirewallconfig showall>

    You have to have the root privilege to execute this command.
    Password for root:
    Table: filter
    Chain INPUT (policy DROP)
    target     prot opt source               destination
    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state ESTABLISHED
    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:80
    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:443
    ACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0           udp dpt:1719
    ....

=item B<$ basefirewallconfig stop>

    You have to have the root privilege to execute this command.
    Password for root:
    Flushing firewall rules:                                   [  OK  ]
    Setting chains to policy ACCEPT: filter mangle             [  OK  ]
    Unloading iptables modules:                                [  OK  ]

=item B<$ basefirewallconfig> I<start>|I<restart>

    You have to have the root privilege to execute this command.
    Password for root:
    Updating iptables rules:                    [  OK  ]

=item B<$ basefirewallconfig add -proto "tcp" -port "27777" -srcport "12777" -if "eth1">

    You have to have the root privilege to execute this command.
    Password for root:
    Firewall rule was added successfully.
    Updating iptables rules:                    [  OK  ]

=item B<$ basefirewallconfig add -proto tcp -port 513 -redirectport 5513>

    You have to have the root privilege to execute this command.
    Password for root:
    Firewall rule was added successfully.
    Updating iptables rules:                    [  OK  ]

=item B<$ basefirewallconfig add -proto tcp -port 513 -localredirectport 5513>

    You have to have the root privilege to execute this command.
    Password for root:
    Firewall rule was added successfully.
    Updating iptables rules:

=item B<$ basefirewallconfig show>

    You have to have the root privilege to execute this command.
    Password for root:
    Firewall is started.
    Base Firewall rules:
    1: proto=tcp port=27777 srcport=12777 if=eth1 priority=low
    2: proto=tcp port=513 redirectport=5513 priority=low
    3: proto=tcp port=513 localredirectport=5513 priority=low

=item B<$ basefirewallconfig del 1>

    You have to have the root privilege to execute this command.
    Password for root:
    Firewall rule number 1 was deleted successfully.
    Updating iptables rules:                    [  OK  ]

=back

=head1 CAVEATS

B<basefirewallconfig> Can be run only under securityadmin account.
It cannot change rules, set in the application configuration files I<configure.xml>. 
For all user-defined rules "priority" option is set to "low". 
basefirewallconfig invoking can take some time since it is getting applications state.

=cut

use lib "/opt/nortel/base/lib";

use warnings;
use strict;
use Getopt::Long;

use common_variables;
use common_functions;
use base_firewall;
use baselog;
use base_apps_service;

use install_common;
use CommonInstallUtils;

#Hash to hold the iptable rule in
my %data = (
            'proto'             => undef,
            'port'              => undef,
            'redirectport'      => undef,
            'localredirectport' => undef,
            'srcport'           => undef,
            'icmptype'          => undef,
            'if'                => undef,
            'host'              => undef,
            'eth'               => undef,
            'dscp'              => undef,
            'priority'          => "low",
            'on'                => "on",
            'appl'              => "usercfg"
           );

my $usercfg = "$SYSCONFIG_ROOT/$IPTABLES_USERCFG";
my $rules   = undef;

sub main();
sub read_cfg();
sub save_cfg();
sub show();
sub add_rule();
sub delete_rule($);

exit(main());

sub main()
{
   my $interactive = (scalar(@ARGV) == 0) ? $TRUE : $FALSE;

   #For now this tool does not support interactive operation
   if ($interactive)
   {
      print_pod_usage("Insufficient number of arguments");
      return $ERROR;
   }

   signals_ignore();

   #Check all casual options
   unless ($interactive)
   {
      if ($ARGV[0] =~ /help$/)
      {
         print_pod_usage();
         return $OK;
      }
      elsif ($ARGV[0] =~ /^(re)?start$/)
      {
         my $appserv = new base_apps_service({$APPL_TYPE => 'all'});
         if (defined $appserv)
         {
            return $appserv->{'firewall'}->firewall_restart($appserv->get_app_states(), undef, $TRUE);
         }
         else
         {
            baselog($LOG_ERROR, "Can not create base_apps_service object");
            return $ERROR;
         }
      } ## end elsif ($ARGV[0] =~ /^(re)?start$/...
      elsif ($ARGV[0] eq "stop")
      {
         if (getYNResponse("This action will bring the system in less secure state.\nDo you want to proceed?", 'Y'))
         {
            return firewall_stop();
         }
         return $OK;
      }
      elsif ($ARGV[0] eq "showall")
      {
         return firewall_status();
      }
      elsif ($ARGV[0] eq "show")
      {
         return show();
      }
      elsif ($ARGV[0] eq "add")
      {
         if (scalar(@ARGV) == 1)
         {
            print_pod_usage("Insufficient number of arguments");
            return $ERROR;
         }
         my $res = GetOptions(\%data, 'proto=s', 'port=s', 'srcport=s', 'icmptype=s', 'if=s', 'host=s', 'eth=s', 'dscp=s', 'redirectport=s', 'localredirectport=s');
         if (!$res)
         {
            print_pod_usage();
            return $ERROR;
         }
         else
         {
            return add_rule();
         }
      } ## end elsif ($ARGV[0] eq "add")
      elsif ($ARGV[0] eq "del")
      {
         unless (defined($ARGV[1]) && $ARGV[1] =~ /^\d+$/)
         {
            print_pod_usage("Incorrect rule number");
            return $ERROR;
         }
         return delete_rule($ARGV[1]);
      } ## end elsif ($ARGV[0] eq "del")
      else
      {
         print_pod_usage("Unsupported argument '$ARGV[0]'");
         return $ERROR;
      }
   } ## end unless ($interactive)

   return $OK;
} ## end sub main()

###------------------------------------------------------------------
# Description:
#  - Print iptables rules added by basefirewallconfig only.
#  INPUT:  NONE
#  OUTPUT: $OK - when configuration file has been read and displayed
#          $ERROR - otherwise
###------------------------------------------------------------------
sub show()
{
   unless (read_cfg())
   {
      print "Could not read the configuration file\n";
      return $ERROR;
   }
   if (get_status())
   {
      print "Firewall is started.\n";
   }
   else
   {
      print "Firewall is stopped.\n";
   }

   my ($rule, $count);
   my @order = ('proto', 'port', 'redirectport', 'localredirectport', 'srcport', 'icmptype', 'if', 'host', 'eth', 'dscp', 'priority');

   unless (defined($rules) and scalar(@$rules) != 0)
   {
      print "No rules defined\n";
      return $OK;
   }

   print "Base Firewall rules:\n";
   $count = 1;
   foreach $rule (@{$rules})
   {
      print " $count: ";
      foreach (@order)
      {
         print "$_=$rule->{$_} " if (defined($rule->{$_}) && $rule->{$_} ne "");
      }
      print "\n";
      $count++;
   } ## end foreach $rule (@{$rules})

   return $OK;
} ## end sub show()

###------------------------------------------------------------------
# Description:
#  - Add iptables rule.
#
#  INPUT:  NONE
#
#  OUTPUT: $OK    - the rule has been deleted successfully
#          $ERROR - an error occurred
###------------------------------------------------------------------
sub add_rule()
{
   my %rule;

   my $semmgr = take_firewall_semaphore();
   return $ERROR unless (defined $semmgr);

   unless (read_cfg())
   {
      baselog($LOG_ERROR, "Could not read the configuration file\n", $TRUE);
   }

   #Getting rid of undef attributes
   foreach (keys(%data))
   {
      $rule{$_} = $data{$_} if (defined($data{$_}) && $data{$_} ne "");
   }
   unless (check_rule(\%rule))
   {
      baselog($LOG_ERROR, "Wrong rule\n", $TRUE);
      print_pod_usage();
      release_firewall_semaphore($semmgr);
      return $ERROR;
   } ## end unless (check_rule(\%rule)...
   push @{$rules}, \%rule;
   unless (save_cfg())
   {
      baselog($LOG_ERROR, "Could not save the configuration file\n", $TRUE);
   }
   release_firewall_semaphore($semmgr);

   print "Firewall rule was added successfully.\n";
   if (get_status())
   {
      my $appserv = new base_apps_service({$APPL_TYPE => 'all'});
      if (defined $appserv)
      {
         $appserv->{'firewall'}->firewall_restart($appserv->get_app_states());
      }
      else
      {
         baselog($LOG_ERROR, "Can not create base_apps_service object");
      }
   } ## end if (get_status())
   else
   {
      print "Firewall is stopped. The rules will be applied after the firewall restart.\n";
   }

   return $OK;
} ## end sub add_rule()

###------------------------------------------------------------------
# Description:
#  - Delete iptables rule added by basefirewallconfig by its number.
#
#  INPUT:  $_[1]  - the number of the rule to delete
#
#  OUTPUT: $OK    - the rule has been deleted successfully
#          $ERROR - an error occurred
###------------------------------------------------------------------
sub delete_rule($)
{
   my $number = shift @_;

   my $semmgr = take_firewall_semaphore();
   return $ERROR unless (defined $semmgr);

   unless (read_cfg())
   {
      baselog($LOG_ERROR, "Could not read the configuration file\n", $TRUE);
   }

   unless (defined($rules) and scalar(@$rules) != 0)
   {
      print "No rules defined\n";
      release_firewall_semaphore($semmgr);
      return $ERROR;
   } ## end unless (defined($rules) and...

   unless (exists $rules->[$number - 1])
   {
      print "There is no rule number $number\n";
      release_firewall_semaphore($semmgr);
      return $ERROR;
   } ## end unless (exists $rules->[$number...

   delete $rules->[$number - 1];

   unless (save_cfg())
   {
      baselog($LOG_ERROR, "Could not save the configuration file\n", $TRUE);
   }
   release_firewall_semaphore($semmgr);

   print "Firewall rule number $number was deleted successfully.\n";
   if (get_status())
   {
      my $appserv = new base_apps_service({$APPL_TYPE => 'all'});
      if (defined $appserv)
      {
         $appserv->{'firewall'}->firewall_restart($appserv->get_app_states());
      }
      else
      {
         baselog($LOG_ERROR, "Can not create base_apps_service object");
      }
   } ## end if (get_status())
   else
   {
      print "Firewall is stopped. The rules will be applied after the firewall restart.\n";
   }
   return $OK;
} ## end sub delete_rule($)

#####################################################################
# This subroutine reads basefirewall configuration file and place
# all iptables rules read into the variable $rules
#
# INPUT  : NONE
#
# OUTPUT : $TRUE  - no errors during reading configuration data
#          $FALSE - an error occurred
#####################################################################
sub read_cfg()
{
   $rules = undef;

   if (-e $usercfg)
   {
      $rules = get_iptables($SYSCONFIG_ROOT, $IPTABLES_USERCFG);
      unless ($rules)
      {
         baselog($LOG_ERROR, "Could not read the $usercfg file.\n");
      }
   } ## end if (-e $usercfg)
   else
   {
      baselog($LOG_DEBUG, "File $usercfg does not exist.");
   }
   return $TRUE;
} ## end sub read_cfg()

#####################################################################
# This subroutine reads basefirewall configuration file and place
# all iptables rules read into the variable $rules
#
# INPUT  : NONE
# OUTPUT : $TRUE  - no errors during saving configuration data
#          $FALSE - an error occurred
#####################################################################
sub save_cfg()
{
   my $retval = save_iptables($rules, $SYSCONFIG_ROOT, $IPTABLES_USERCFG);
   unless ($retval)
   {
      baselog($LOG_ERROR, "Could not save the $usercfg file.\n");
   }
   return $TRUE;
} ## end sub save_cfg()

__END__
