#!/bin/perl
#
# /secure/monitor_logins.pl
#
# History :
#       <1> V1.1 Jan.16'96 (S.Boran)
#       <2> 30.jan.2002 S.Boran: move config to central file /secure/secure.conf
#       <3> 13.Jun.2003 SB send output to syslog or email? "-syslog" option
#
#################################

$debug = '';             # '1' for debug, '' for no debug info
$rsh = 'ssh';            # Secure shell available

# --- security precautions ---
$ENV{'PATH'} = '/bin:/usr/ucb:/opt/OBSDssh/bin:/usr/local/bin:/opt/openssh/bin';
$ENV{'SHELL'} = '/bin/sh';
$ENV{'IFS'} = '';
umask(077);                             # -rw-------

require "ctime.pl";
$tmpfile="/tmp/log.$$";
chop($os=`uname -r`);

# --- Who should mail be sent to? most places use 'root' -------
#$user = 'root';
#@check_logins=('server1','server2','server3', 'server4');

## Central config file ##   <2>
my $ConfFile = "/secure/secure.conf";
my $tool     = "monitor_logins";
chop(my $host = `uname -n`);

open(CONF, $ConfFile) or die "$ConfFile: $!\n";
while (<CONF>) {
    next if /^\s*#|^\s*$/; # skip comments
    #print "Configuration line: $_" if $debug;
    chomp;
    if (/^$host:$tool:(.+):(.+)/) {
        @check_logins = split(/ /, $1);
        $user = $2;
        print "$ConfFile - Hosts=\@hosts Notify=$notify \n" if $debug;
    }
}
close(CONF);
##

# send output to syslog or email?
if ( scalar(@ARGV) > 0 ) { # we have arguments
  if ($ARGV[0]="-syslog") { $syslog=1 };
}

$os=`uname -s`; chop($os);
if ("$os" eq "SunOS") {
    $mail='/usr/bin/mailx';
} elsif ("$os" eq "HP-UX") {
    $mail='/usr/bin/mailx';
} elsif ("$os" eq "Linux") {
    $mail='/usr/bin/mailx';
} elsif ("$os" eq "OpenBSD") {
    $mail='/usr/bin/mailx';
} else {
    $mail='/usr/bin/mailx';
}

chop ($day = &ctime(time));
$day =~ s/^\w+ (\w+ +\d+) .*/\1/;       # get "Oct 15"
print "*$day*\n" if $debug;

##----- the meat ----

foreach $target (@check_logins) {
  print "Checking $target..\n" if $debug;
  system "$rsh -n $target /secure/logins_today.pl   >> $tmpfile 2>&1";
  if ( -s $tmpfile ) {
     system "echo ========= $target ===========      >> $tmpfile 2>&1";
  }
}

## check local system too
system "/secure/logins_today.pl                         >> $tmpfile 2>&1";

if ( -s $tmpfile ) {
  print "Logins found during the night\n" if $debug;

  if ($syslog) {
    #system "cat $tmpfile| logger -t '$0'";
    system "cat $tmpfile| logger -t monitor_logins";

  } else {
    open(TMP, ">>$tmpfile")
      || die "can't open $tmpfile: $!\n";
      print TMP "\n\n==> This email was created by $host:$0\n";
      print TMP " For $host, @check_logins\n\n";
    close(TMP);
    system "$mail -s '$host clients: Unexpected logins $day' $user < $tmpfile";
  }

}

unlink $tmpfile;
##---------------------------------------

