#!/usr/bin/perl
###############################################################################
## @file masterfirewallconfig
# @brief   This script configures master firewall rules
# @details
# @author  Tim Costa
# @date    August 2008
#
# @version 1.00 - Initial version
# @version 1.01 - The iptables configuration file integrity was protected with SEM_FIREWALL
# @version 1.02 - Show the criticality of rules when displaying show or showall
###############################################################################

=pod

=head1 NAME

B<masterfirewallconfig> - tool for master firewall configuration.

=head1 SYNOPSIS

B<masterfirewallconfig> [B<show>]|[B<showall>]|[B<edit> I<service> I<action (accept/reject)>]|[B<restart>]

=head1 DESCRIPTION

B<masterfirewallconfig> is used to manage firewall rules <accept/reject>

This command is able to list the existing firewall rules (as in the master_firewall_control.xml file) and change the status of each rule between "accept" and "reject"

=head1 OPTIONS

=over 4

=item B<help>

Print this help message and exit.

=item B<show>

Print out all current controlled rules on the machine.

=item B<showall>

Print all possible Nortel configured default firewall rules.

=item B<edit> I<service> I<action (accept/reject)>

Modify the "action" of the specified entry to either accept or reject

=item B<restart>

Restart the firewall and apply all configuration changes.

=back

=head1 CAVEATS

B<masterfirewallconfig> can be run only under securityadmin account.
It can only accept/reject rules, not configure them.

=cut

use lib "/opt/nortel/base/lib";
use common_variables;
use common_functions;
use install_common;

use base_firewall;
use master_firewall;
use CommonInstallUtils;
use baselog;
use XMLRef;
use strict;
use warnings;

my %actions = (
               "restart" => \&firewall_restart,
               "show"    => \&show,
               "showall" => \&showall,
               "help"    => \&print_pod_usage,
               "edit"    => \&edit
              );

## @skipline
sub main();
## @skipline
sub edit(@);
## @skipline
sub show();
## @skipline
sub showall();
## @skipline
sub display(@);
## @skipline
sub follow_ref(@);

exit(main());

###############################################################################
## @fn main()
# @brief   Main entry point
# @return  $OK    - OK
# @return  $ERROR - an error occured
# @author  Tim Costa
# @date    August 2008
###############################################################################
sub main()
{

   # Check input
   if (!scalar(@ARGV))
   {
      print_pod_usage("Insufficient number of arguments");
   }
   elsif (exists($actions{$ARGV[0]}))
   {
      return invoke_subroutine_safely($actions{$ARGV[0]});
   }
   else
   {
      print_pod_usage("Unsupported argument $ARGV[0]");
   }
   return $ERROR;
} ## end sub main()

###############################################################################
## @fn edit(@)
# @brief   Modify rule action
# @details Change the action of a rule using 'service' as a key between
#	   'accept' and 'reject'
# @param   $_[1]  - the service to change
# @param   $_[2]  - the new action
# @return  $OK    - the rule has been changed successfully
# @return  $ERROR - an error occured
# @author  Tim Costa
# @date    August 2008
###############################################################################
sub edit(@)
{
   my $search_service = $ARGV[1];
   my $new_action     = $ARGV[2];
   my $position       = undef;

   unless (defined($new_action) and ($new_action eq $ACCEPT or $new_action eq $REJECT))
   {
      print_pod_usage("Improper syntax");
      return $ERROR;
   }

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

   my $master_rules = new master_firewall;
   unless (defined($master_rules))
   {
      baselog($LOG_ERROR, "Could not create MFC object.");
      release_firewall_semaphore($semmgr);
      return $ERROR;
   } ## end unless (defined($master_rules...

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

   unless (defined($position = $master_rules->service_find($search_service)))
   {
      print "Service '$search_service' not found\n";
      release_firewall_semaphore($semmgr);
      return $ERROR;
   } ## end unless (defined($position ...

   if (defined(${@{$master_rules}}[$position]{'non_critical'}) && (${@{$master_rules}}[$position]{'non_critical'} eq $YES))
   {
      baselog($LOG_INFO, "Modifying firewall rule ${@{$master_rules}}[$position]{'service'} from ${@{$master_rules}}[$position]{'action'} to $new_action", $TRUE);
      ${@{$master_rules}}[$position]{'action'} = $new_action;
   }
   else
   {
      baselog($LOG_WARNING, "This rule is marked as critical, therefore it cannot be modified!\n", $TRUE);
      release_firewall_semaphore($semmgr);
      return $ERROR;
   } ## end else [ if (defined(${@{$master_rules...

   print "WARNING: Altering firewall rules can have critical effects on application functionality\n";
   unless (getYNResponse("Are you sure you want to continue?", 'N'))
   {
      print "Action aborted\n";
      release_firewall_semaphore($semmgr);
      return $OK;
   } ## end unless (getYNResponse("Are you sure you want to continue?"...

   unless ($master_rules->save_master_cfg())
   {
      baselog($LOG_ERROR, "Could not save the configuration file\n", $TRUE);
      release_firewall_semaphore($semmgr);
      return $ERROR;
   } ## end unless ($master_rules->save_master_cfg...
   print "Firewall rule $search_service was changed successfully.\nPlease use 'masterfirewallconfig restart' to apply all rule changes.\n";
   release_firewall_semaphore($semmgr);
   return $OK;
} ## end sub edit(@)

## @fn show()
# @brief   Print local iptables rules
# @details Cross reference iptables rules (from iptables.xml file) with the matching
#          rule in master_firewall_control.xml, and then print all properties.
#          'service' tag is used as the comparison key.
# @param   NONE
# @return  $OK - when configuration file has been read and displayed
# @return  $ERROR - otherwise
# @author  Tim Costa
# @date    August 2008
sub show()
{
   my $master_rules = new master_firewall;
   unless (defined($master_rules))
   {
      baselog($LOG_ERROR, "Could not create MFC object.");
      return $ERROR;
   }

   my $iptables_rules = $master_rules->read_iptables_cfg();
   unless (defined($iptables_rules))
   {
      baselog($LOG_ERROR, "Could not read the IPTables configuration file\n", $TRUE);
      return $ERROR;
   }

   my ($position, $rule_check) = undef;
   my ($key, $key_root, $xpath, $reffile, $refvalue);
   my @show_rules;

   unless (scalar(@$master_rules) != 0)
   {
      print "No rules defined in $MASTERCFG file!\n";
      return $ERROR;
   }
   unless (scalar(@$iptables_rules) != 0)
   {
      print "No rules defined in $IPTABLES_CFG file!\n";
      return $ERROR;
   }

   foreach my $iptables_rule (@{$iptables_rules})
   {
      if (   defined($iptables_rule->{'service'})
          && defined($position   = $master_rules->service_find("$iptables_rule->{'service'}"))
          && defined($rule_check = ${@{$master_rules}}[$position]))
      {
         foreach $key (keys %$iptables_rule)
         {

            #Check if any of the keys has a reference value
            #If so, then follow the reference to retrieve the actual value
            if (
                  $key =~ /_ref$/
               && defined($xpath = $iptables_rule->{$key})
               && defined($key_root = substr($key, 0, -4))  #Remove "_ref" from key name
               && defined($rule_check->{$key_root})  #Compare with MFC file
               && defined($reffile = $iptables_rule->{'reference'}) && defined($refvalue = follow_ref($reffile, $xpath))
               )
            {
               $rule_check->{$key_root} = $refvalue;
            } ## end if ($key =~ /_ref$/ &&...
         } ## end foreach $key (keys %$iptables_rule...
         push @show_rules, $rule_check;
      } ## end if (defined($iptables_rule...
   } ## end foreach my $iptables_rule (...
   return display($FALSE, @show_rules);
} ## end sub show()

## @fn showall()
# @brief   Print all master firewall rules
# @details Display the entire contents of the master_firewall_control.xml file
# @param   NONE
# @return  $OK - when configuration file has been read and displayed
# @return  $ERROR - otherwise
# @author  Tim Costa
# @date    August 2008
sub showall()
{
   my $rules = new master_firewall;
   unless (defined($rules))
   {
      baselog($LOG_ERROR, "Could not create MFC object.");
      return $ERROR;
   }

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

   return display($TRUE, @{$rules});
} ## end sub showall()

## @fn print_rule(@)
# @brief   Format the print the rule to the screen
# @param   $showall - determines whether to preform a showall or show command
# @param   @_ - the rule to print
# @return  NONE
sub print_rule(@)
{
   my $showall = shift @_;

   my $rule_header = "";
   my $rule_format = "";

   if ($showall)
   {
      $rule_header = "Master Firewall rules:\n" . "Rule#  Service           Proto  Dev  DefaultPort DefaultSrcprt Dscp   ICMPtype  Dynamic  Critical";
      $rule_format = "@<<<<< @<<<<<<<<<<<<<<<< @<<<<< @<<< @<<<<<<<<<< @<<<<<<<<<<<< @<<<<< @<<<<<<<< @<<<<<<< @<<<";
   }
   else
   {
      $rule_header = "Master Firewall rules:\n" . "Rule#  Service           Proto  Dev  Port        Srcprt       Dscp   ICMPtype  Dynamic  Action  Critical";
      $rule_format = "@<<<<< @<<<<<<<<<<<<<<<< @<<<<< @<<< @<<<<<<<<<< @<<<<<<<<<<< @<<<<< @<<<<<<<< @<<<<<<< @<<<<<< @<<<";
   }

   #$FORMAT_FORMFEED = "";

   if ($~ ne 'RULE_CON')
   {
      eval "format RULE_HEADER = \n" . "$rule_header" . "\n" . ".";
      eval "format RULE_CON = \n" . "$rule_format" . "\n" . '@_' . "\n" . ".";
   }
   $^ = 'RULE_HEADER';
   $~ = 'RULE_CON';

   write;
} ## end sub print_rule(@)

## @fn display(@)
# @brief   Display all iptables rules
# @details Print each rule from the specified rules array, in the order specified
#	   in the @order array
# @param   $showall - determines whether preform a showall or show command
# @param   @rules_to_display - an array of the rule hashes to be displayed
# @return  $OK    - displayed correctly
#
# @author  Tim Costa
# @date    August 2008
sub display(@)
{
   my $showall          = shift @_;
   my @rules_to_display = @_;
   my $count            = 1;

   foreach my $rule (@rules_to_display)
   {
      my $is_critical = "Yes";
      if (defined($rule->{'non_critical'}) && ($rule->{'non_critical'} eq $YES))
      {
         $is_critical = "No";
      }

      if ($showall)
      {
         print_rule($TRUE, $count, $rule->{'service'}, $rule->{'proto'}, $rule->{'dev'}, $rule->{'port'}, $rule->{'srcport'}, $rule->{'dscp'}, $rule->{'icmptype'}, $rule->{'has_ref'}, $is_critical);
      }
      else
      {
         print_rule(
                    $FALSE,
                    $count,
                    $rule->{'service'},
                    $rule->{'proto'},
                    $rule->{'dev'},
                    $rule->{'port'},
                    $rule->{'srcport'},
                    $rule->{'dscp'},
                    $rule->{'icmptype'},
                    $rule->{'has_ref'},
                    $rule->{'action'},
                    $is_critical
                   );
      } ## end else [ if ($showall)
      $count++;
   } ## end foreach my $rule (@rules_to_display...

   return $OK;
} ## end sub display(@)

## @fn follow_ref(@)
# @brief   Follow the reference file and return the new value
# @details
# @param
#          $reffile - path to reference file
#	   $xpath - xpath to attribute
# @return
#          $refvalue - the value of the reference
#          $undef    - an error occured or reference is undefined
#
# @author  Tim Costa
# @date    August 2008
sub follow_ref(@)
{
   my ($reffile,  $xpath)  = shift @_;
   my ($refvalue, $xmlref) = undef;

   $xmlref = XMLRef::new();

   unless ($xmlref)
   {
      baselog($LOG_ERROR, "Could not read the $reffile file.\n");
      return undef;
   }

   $refvalue = $xmlref->get_referenced_value($reffile, $xpath, "n/a");
   return $refvalue;
} ## end sub follow_ref(@)

__END__
