#!/bin/sh
# Documentation in perl code below.
# -*- perl -*-
# vim:set syn=perl:

# Ensure ZEUSHOME is setup to point to our installation
if [ -z "$ZEUSHOME" ]
then
    # Have a good guess, we live in $ZEUSHOME/zxtm/bin
    OLD_PWD=`pwd`
    cd `dirname $0`/../..
    ZEUSHOME=`pwd`
    export ZEUSHOME
    cd $OLD_PWD
fi

if [ ! -d "$ZEUSHOME/zxtm" ]
then
   echo "`basename $0`: FATAL: Cannot find ZXTM installation, check \$ZEUSHOME"
   exit 1
fi

# Restart ourselves in perl
exec $ZEUSHOME/perl/miniperl -wTx $0 ${1+"$@"}

#!perl -wT #"
#line 28

=head1 NAME

userauth - authenticate a user using ZXTM's UI authentication configuration.
Designed to be used for PAM authentication.

=head1 SYNOPSIS

B<userauth> [B<--help>]

In normal operation there are no command line options.  The environment
variables PAM_USER (username) and PAM_AUTHTOK (password) are the mandatory
inputs.  For more details execute perl-doc on the script.

=head1 DESCRIPTION

The userauth script is for internal use by PAM on ZXTM appliances.  It
authenticates a username and password using the ZXTM UI authentication
configuration.

Importantly, it does not take command line arguments.  Instead it handles the
PAM environment variables PAM_USER and PAM_AUTHTOK (password), it also makes
use of PAM_RHOST, PAM_SERVICE, and PAM_TTY for logging purposes.  If the user
authenticates correctly a ZXTM audit log entry is added to record the
authentication and the script exits with status 0.  If the user authentication
fails a loginfailed ZXTM audit log entry is made, and the script exits with a
non-zero status.

The optional B<--help> command line argument may be specified to get this help
information.  The script will subsequently exit with status 0.

=head1 ENVIRONMENT

=over 4

=item ZEUSHOME

If ZEUSHOME is defined the script will expect a ZXTM installation to exist at
the location it specifies.  If it is not defined /opt/zeus will be used.

=item PAM_USER

The username.

=item PAM_AUTHTOK

The password.

=item PAM_RHOST

The remote host (may be empty or not specified.)

=item PAM_SERVICE

The PAM service identifier (may be empty or not specified.)

=item PAM_TTY

The PAM tty identifier (may be empty or not specified.)

=back

=head1 AUTHOR

Zeus Technology, support@riverbed.com

=head1 COPYRIGHT

Copyright (C) 2009-2014 Zeus Technology Ltd., a 
subsidiary of Riverbed Technology, Inc. All rights reserved.

=cut

BEGIN {
   # Check and set initial environment.
   if ( not exists $ENV{ZEUSHOME} ) {
      $ENV{ZEUSHOME} = "/opt/zeus";
   }
   if ( not -d "$ENV{ZEUSHOME}/zxtm" ) {
      warn "PAM authentication script run without valid ZXTM environment.";
      exit(1);
   }
   ($ENV{"ZEUSHOME"}) = ( $ENV{"ZEUSHOME"} =~ m@^(.*)$@ ); # Untaint
   unshift @INC,  "$ENV{ZEUSHOME}/zxtmadmin/lib/perl", "$ENV{ZEUSHOME}/perl";
   $ENV{"PATH"} = ""; # Tainted and not required
}

use strict;
if (grep { /^--help$/ } @ARGV) {
   eval "use Pod::Usage ();";
   if ($@) {
      print "Pod::Usage not available, read script headers for help.\n";
      exit(0);
   }
   my ($file) = ($0 =~ m/^(.*)$/);
   Pod::Usage::pod2usage( -exitstatus => 0, -verbose => 1, -noperldoc => 1, -input => $file );
}
use Zeus::ZXTM::StorageManager;
use Zeus::ZXTM::AccessControl qw( 
   authenticateUser registerAuthenticationSuccess registerAuthenticationFailure
);
use Zeus::ZXTM::EventLog qw( logEvent ZLOG_WARN );
use Zeus::ZXTM::LogUtils qw( logAuditEvent );
use Zeus::ZXTM::ApplianceUtils qw( hasApplianceFeature isFullyLockedDown );

my $tmp_login_file = "/tmp/last_login";

# Remove any previous temporary login information
unlink( $tmp_login_file );

# Get and check PAM user and password.
my $user = $ENV{PAM_USER};
my $pass = $ENV{PAM_AUTHTOK};
if (not (defined $user and defined $pass)) {
   logEvent(
      type => ZLOG_WARN,
      tags => ['autherror'],
      msg => "PAM authentication script run without valid PAM environment.",
     );
   exit(1);
}

# Get parts to use in login type identifier.
my $logintype = $ENV{PAM_SERVICE};
if (not defined $logintype) {
   $logintype = "Unknown";
} elsif ($logintype eq 'login') {
   $logintype = "Console";
} elsif ($logintype eq 'sshd') {
   $logintype = "SSH";
}

# Do not allow root access on a LOCKED_DOWN appliance, even as an admin user.
if( hasApplianceFeature( 'LOCKED_DOWN' ) && $user eq 'root' ) {
   logAuditEvent(
      event => 'loginfail',
      logintype => $logintype,
      session => Zeus::Session::createEphemeralSession(
        user => 'root',
        ip => $ENV{PAM_RHOST}
      ),
   );
   exit(1);
}

# The 'root' user should be authenticated against the 'admin' user
# (if this is not a LOCKED_DOWN appliance)
$user = "admin" if $user eq 'root';

# Check authentication for the support user. Only perform this check before
# the system is fully locked down. After the machine is locked down
# properly the only means of access is using an SSH key.
if( hasApplianceFeature( 'LOCKED_DOWN' ) && $user eq 'zeus-system'
     && !isFullyLockedDown() ) {

   open( SHADOW, '/etc/shadow' ) or exit( -1 );
   my $crypt = undef;
   while( my $entry = <SHADOW> ) {
      if( $entry =~ /^$user:([^:]+):/ ) {
         $crypt = $1;
         last;
      }
   }
   close( SHADOW );

   # Don't audit log this login - it should only happen before the
   # machine is locked down, so the end user doesn't need to know
   # about it.
   if( $crypt && crypt( $pass, $crypt ) eq $crypt ) {
      exit 0;
   }

   exit 1;
}


# Run authentication and check permissions.
my $storage = new Zeus::ZXTM::StorageManager;
my( $userdetails, $error_type ) = authenticateUser(
   username => $user,
   password => $pass,
   ip => $ENV{PAM_RHOST},
   storage => $storage,
   type => $logintype
);

if( $userdetails && $userdetails->{group} ) {
   my $gcfg = $storage->getGroupConfig( $userdetails->{group} );
   if( $gcfg && $gcfg->checkPage( "Appliance_Console" ) eq 'full' ) {
      my $rofileok = ( $logintype eq 'Console' ) && 
         !hasApplianceFeature( 'LOCKED_DOWN' );
      logAuditEvent(
         event => 'login',
         logintype => $logintype,
         session => Zeus::Session::createEphemeralSession(
            ip => $ENV{PAM_RHOST},
            user => $user,
            group => $userdetails->{group},
            auth => $userdetails->{authname}, 
         ),
         ignorewritefail => $rofileok,
      );

      if( $userdetails->{authname} ne 'local' ) {
         # Remember the login credentials for the audit log
         # if it's a remote user...
         if( open( ENV, ">$tmp_login_file" ) ) {
            print ENV "ORIG_USER=$user\n";
            print ENV "ORIG_GROUP=$userdetails->{group}\n";
            print ENV "ORIG_AUTH=$userdetails->{authname}\n";
            close ENV;
         }
      }

      exit(0);
   }
}

if( defined $error_type && $error_type eq "passwordexpired" ) {
   logAuditEvent(
      event => 'passwordexpired',
      logintype => $logintype,
      session => Zeus::Session::createEphemeralSession(
        user => $user,
        ip => $ENV{PAM_RHOST} 
      ),
   );
}


logAuditEvent(
   event => 'loginfail',
   logintype => $logintype,
   session => Zeus::Session::createEphemeralSession(
     ip => $ENV{PAM_RHOST} 
   ),
);
      
exit(1);

