#!/bin/sh -p
#
# (C) Copyright 2005-2008 Hewlett-Packard Development Company, L.P. 
#

function Usage
{
   echo "
usage: $0 [-hvr] [-k type] {-f hostfile|hostname}
  -h -- display this message.
  -v -- verbose.
  -r -- configure user authentication amongst all hosts. 
  -k type -- type of keys rsa or dsa, the default is rsa.
  -f hostfile -- specifies a file containing a list of 
       remote hosts (one host per line). If the remote host
       is in a different domain than the local host, the
       full domain name must be specified. 
  hostname -- specifies a remote host.
"
  exit $FAILURE
}

# Internal wrapper for printing various types of messages.
function printme 
{
   case $1 in
      V)
          $verbose && printf "Verbose: $2\n" 
          ;;
      E)
          printf "Error: $2\n" 
          ;;
      F)
          printf "Failure: $2\n" 
          ;;
      S)
          printf "Success: $2\n" 
          ;;
      M)
          printf "$2\n" 
          ;;
      D)
          $debug && printf "Debug: $2\n" 
          ;;
   esac 
}

# Gets the default domain name.
typeset default_domain_cache
function GetDefaultDomain
{
   typeset fn="GetDefaultDomain"
   typeset domain

   printme D "Function: in $fn"

   # Determine the local domain using nslookup on the local host
   [[ -z "$default_domain_cache" ]] && {
      domain=$( echo -e $lhost |\
                LANG=C /usr/bin/nslookup 2>&1 |\
                /usr/bin/awk '/Name:/ {print $2}')
      domain=${domain#*.}
      default_domain_cache=$domain
      [[ "$domain" = "" ]] && {
         printme V "Unable to determine the local DNS domain using nslookup"
      }
   }

   # Determine the local domain using resolv.conf
   [[ -z "$default_domain_cache" && -r /etc/resolv.conf ]] && {
      domain=$( $catpath /etc/resolv.conf |\
      grep "^domain[[:space:]]" |\
      tail -n 1 |\
      awk '{print $2}')
      default_domain_cache=$domain
      [[ "$domain" = "" ]] && {
         printme V "Unable to determine the local DNS domain using resolv.conf"
      }
   }

   # Set the global DNS domain variable.
   [[ -n "$domain" ]] && {
       default_domain=$default_domain_cache
       printme V "The default DNS domain is $default_domain"
   }

   # Just say we could not determine the domain, but no hard failure
   [[ "$default_domain" = "" ]] && {
       printme M "Unable to determine the local DNS domain"
   }

   printme D "Function: out $fn"
}

# Converts a host to a fully qualified one.
function GetFQHost
{
   typeset fn="GetFQHost"
   typeset inhost=$1
   typeset host
   typeset domain

   printme D "Function: in $fn"

   host=${inhost%%.*}
   domain=${inhost#*.}

   # If domain and host are the same, there was no domain on the host.
   [[ $domain = $host ]] && {
     GetDefaultDomain
     domain=$default_domain
   }

   # If we now have a domain, append it to host.
   [[ -n "$domain" ]] && host=$host.$domain

   # Set the output variable using the global.
   fqdnhost=$host
   printme D "Function: out $fn"
}

# This quietly tests access.
function TestAccess
{
   typeset fn="TestAccess"
   typeset first_hop
   typeset first_hop1
   typeset cmd
   typeset stat
   typeset local=$1
   typeset owner=$2
   typeset other=$3
   typeset localname=${local%%.*}
   typeset ownername=${owner%%.*}
   typeset othername=${other%%.*}

   printme D "Function: in $fn"

   if [[ $localname != $ownername ]] ; then
      first_hop="$sshstrictno $batchyes $owner "
      first_hop1="$sshstrictno $batchyes $ownername "
   fi

   # Add the shortname hostname to the known_hosts file.
   cmd="$first_hop1$sshstrictno $batchyes $othername hostname"
   eval $cmd > /dev/null
   [[ $? -ne $SUCCESS ]] && {
       printme V "Unable to add the host shortname ($othername) to known_hosts"
   }

   cmd="$first_hop$sshstrictno $batchyes $other hostname"
   printme V "TestAccess start."
   eval $cmd > /dev/null
   stat=$?
   printme V "TestAccess status (0 is good): $stat"
   printme V "TestAccess ended."

   printme D "Function: out $fn"

   return $stat
}

# Tests reachability using ping.
# This is a ping routine that we may use in the future.
function TestReachability
{
   typeset fn="TestReachability"
   typeset rhost=$1

   printme D "Function: in $fn"

   if [[ $lhost != $rhost ]] ; then
      $pingpath $rhost -n 1 -m 1 > /dev/null
      [[ $? -ne $SUCCESS ]] && {
         printme V  "$rhost is unreachable" 
         return $FAILURE
      }
   fi

   printme D "Function: out $fn"

   return $SUCCESS
}

# Gets a temporary name to store the public key of a given host.
function GetNewPubName
{
   typeset fn="GetNewPubName"
   typeset host=$1
   typeset pubf

   printme D "Function: in $fn"

   DefineFilenames "" pubf
   pubf=$gpubkeyfile
   # Set the output variable.
   gnnname="${pubf%.*}_$host.pub"

   printme V "GetNewPubName $gnnname"
   printme D "Function: out $fn"
}

# Pass in the names of variables to be defined, e.g.
# Define Filenames prv pub auth files.
function DefineFilenames
{
   typeset fn="DefineFilenames"
   typeset dfprv=$1
   typeset dfpub=$2
   typeset dfauth=$3

   printme D "Function: in $fn"

   # Define the private filename.
   [[ -n "$dfprv" ]] && {
      gprivkeyfile=$gdfbase
      printme V "Private key file name is $gprivkeyfile"
   }

   # Define the public filename.
   [[ -n "$dfpub" ]] && {
      gpubkeyfile=$gdfbase.pub
      printme V "Public key file name is $gpubkeyfile"
   }

   # Define the authorized_keys file.
   [[ -n "$dfauth" ]] && {
      gauthkeyfile=$gdfauthbase
      printme V "Authorize file name is $gauthkeyfile"
   }
   
   printme D "Function: out $fn"
}

# Remove temporary files.
function CleanupTempKeyFiles  
{
   typeset fn="CleanupTempKeyFiles"
   typeset inhost=$1
   typeset newf

   printme D "Function: in $fn"

   GetNewPubName $inhost
   newf=$gnnname 

   # Remove keys stored in temporary files.
   if [[ $inhost != $lhost ]] ; then 
      [ -f $HOME/$newf ] && rm -f $HOME/$newf
   fi 

   printme D "Function: out $fn"

   return $SUCCESS
}

# Generate key pair and sets up access to local host. 
function SetupLocalKeys 
{
   typeset fn="SetupLocalKeys"
   typeset content

   printme D "Function: in $fn"

   DefineFilenames prvf pubf authf
   prvf=$gprivkeyfile
   pubf=$gpubkeyfile
   authf=$gauthkeyfile

   # Generate keys on local if needed.
   printme V "Base key file is $HOME/$prvf" 
   [[ ! -f $HOME/$prvf ]] && {
      $sshkeygenpath $quiet -P "" -f $HOME/$prvf -t $gkeytype
      [[ $? -ne $SUCCESS ]] && {
         printme E "Unable to generate key pair on local host"
         return $FAILURE
      }
   }

   # Add the local public key to the auth file.
   if [[ ! -f $HOME/$authf ]] ; then 
      $cppath -p $HOME/$pubf $HOME/$authf
   else
      content=$($catpath $HOME/$pubf)
      grep -q "$content" $HOME/$authf
      [[ $? -ne $SUCCESS ]] && {
         $catpath $HOME/$pubf >> $HOME/$authf 
      }
   fi

   printme D "Function: out $fn"

   return $SUCCESS
}

# Push the local public key to the remote host to setup access for local. 
function PushMyKey
{
   typeset fn="PushMyKey"
   typeset other=$1
   typeset content
   typeset logit
   typeset pubf
   typeset authf
   typeset stat

   printme D "Function: in $fn"

   # Get the name of the pubfile (short form).
   DefineFilenames "" pubf authf
   pubf=$gpubkeyfile
   authf=$gauthkeyfile

   # We must have access to the remote system. If not we must always ask.
   printme M "If asked, enter password and/or add fingerprint for $luser@$other"

   # Make the directory and append local key to other's authorization file.
   # Write to syslog if we add an entry to the auth file.
   #
   logit="$loggerpath -i -t $0 \"added an entry to \$HOME/$authf for $lhost\""
   content=$($catpath $HOME/$pubf)
   echo $content | $sshpath $sshctout $other "sh -c '[ ! -r \$HOME/$authf ] && (mkdir -pm 0700 \$HOME/.ssh && touch \$HOME/$authf); grep -q \"$content\" \$HOME/$authf || ($catpath >> \$HOME/$authf && $logit); chmod 700 \$HOME/$authf'"
   [[ $? -ne $SUCCESS ]] && {
      printme V "Unable to setup $other" 
      return $FAILURE
   }

   # Check access, we might not have it.  
   if ! TestAccess $lhost $lhost $other ; then 
      printme V "TestAccess failed for host $other"
      return $FAILURE
   fi

   printme D "Function: out $fn"

   return $SUCCESS
}

# Push everyone's public key to all hosts. 
function PushPublicKey
{
   typeset fn="PushPublicKey"
   typeset owner=$1
   typeset other=$2
   typeset content
   typeset logit
   typeset pubf
   typeset authf
   typeset newf

   printme D "Function: in $fn"

   DefineFilenames "" pubf authf
   pubf=$gpubkeyfile
   authf=$gauthkeyfile
   GetNewPubName $owner
   newf=$gnnname

   # We do not need to setup this combination, already done by SetupLocalKeys. 
   [[ $lhost = $other ]] && return $SUCCESS
   [[ $owner = $lhost ]] && return $SUCCESS

   # Syslog entry.
   logit="$loggerpath -i -t $0 \"added an entry to \$HOME/$authf for $owner\""

   content=$($catpath $HOME/$newf) 
   echo $content | $sshstrictyes $other "grep -q \"$content\" \$HOME/$authf || ($catpath >> \$HOME/$authf && $logit)"
   [[ $? -ne $SUCCESS ]] && {
      printme V "Unable to push $owner's key to $other"
      return $FAILURE
   }

   printme D "Function: out $fn"

   return $SUCCESS
}

# The key is to be distributed from owner to all systems in hostlist.
function PushPublicKeys
{
   typeset fn="PushPublicKeys"
   typeset owner=$1
   typeset other
   typeset hostlist

   printme D "Function: in $fn"

   shift
   hostlist="$*"

   # Assume we can ssh to owner from here.
   # From there, copy the public file to each of the
   # other hosts.
   for other in $hostlist
   do
      if ! PushPublicKey $owner $other ; then 
         printme V "Unable to exchange keys between $owner and $other"
      fi
   done

   printme D "Function: out $fn"

   return $SUCCESS 
}

# Add key to the authorized_keys on "other".
# Generate keys (if needed) on the "other" node.
function ExchangePublicKeys
{
   typeset fn="ExchangePublicKeys"
   typeset local=$1
   typeset other=$2
   typeset prvf
   typeset pubf
   typeset authf
   typeset content
   typeset logit
   typeset newf
   typeset keygencmd

   printme D "Function: in $fn"
   printme V "local host: $local, other: $other"

   DefineFilenames prvf pubf authf
   prvf=$gprivkeyfile
   pubf=$gpubkeyfile
   authf=$gauthkeyfile
   keygencmd="$sshkeygenpath $quiet -P \"\" -f \$HOME/$prvf -t $gkeytype"

   # Syslog entry.
   logit="$loggerpath -i -t $0 \"added an entry to $HOME/$authf for $other\""

   # Push the local public key to the other system
   # This allows us to access the other node
   if ! PushMyKey $other ; then 
      printme V "Unable to push key to $other"
      return $FAILURE
   fi
   printme V "Base key file is $HOME/$prvf" 
   # Now set up the other node, if needed.
   $sshstrictno $other "sh -c '[ -f \$HOME/$prvf ] || $keygencmd'"
   [[ $? -ne $SUCCESS ]] && {
      printme V "Unable to generate key pair on $other"
      return $FAILURE
   }

   # Create a local copy of the other's public key
   GetNewPubName $other 
   newf=$gnnname
   $sshstrictyes $other "$catpath \$HOME/$pubf" > $HOME/$newf
   [[ $? -ne $SUCCESS ]] && {
      printme V "Unable to pull the $other's key"
      return $FAILURE
   }

   # Add the other's public key to the local authorized_keys. And add and an 
   # entry to syslog.
   content=$($catpath $HOME/$newf) 
   grep -q "$content" $HOME/$authf || ($catpath $HOME/$newf >> $HOME/$authf && $logit) 
   [[ $? -ne $SUCCESS ]] && {
      printme V "Unable add the $other's key to $local"
      return $FAILURE
   }

   printme D "Function: out $fn"
   return $SUCCESS
}

# Do a comprehensive test of all nodes.
# Each node should be able to talk to every other node.
function TestThem
{
   typeset fn="TestThem"
   typeset i
   typeset j

   printme D "Function: in $fn"

   for i in $everyhost
   do
      for j in $everyhost
      do
         TestAccess $lhost $i $j
         if [[ $? -eq $SUCCESS ]] ; then
            printme S "$i -> $j"
         else
            printme F "$i -> $j"
         fi
      done
   done

   printme D "Function: out $fn"
}

#
# Main
#
function Main
{
   # Local variables.
   typeset line
   typeset tmpother
   typeset everyhost
   typeset hostfile
   typeset hostlist
   typeset goodlist
   typeset hostlist_tmp
   typeset test_only=false
   typeset localhostonly=false
   typeset -i host_count=0

   # Global variables.
   typeset lhost
   typeset other
   typeset round_robin=false
   typeset verbose=false
   typeset debug=false
   typeset luser
   typeset default_domain
   typeset fqdnhost
   typeset gprivkeyfile
   typeset gpubkeyfile
   typeset gauthkeyfile
   typeset gnnname

   # General use commands
   # (some command paths are not the same on hpux and linux). 
   typeset catpath="cat"
   typeset cppath="cp"
   typeset pingpath="ping"
   typeset loggerpath="logger"
   typeset sshpath="ssh"
   typeset sshkeygenpath="ssh-keygen"

   # General status.
   typeset -i SUCCESS=0
   typeset -i FAILURE=1

   # ssh client options
   typeset quiet="-q"
   typeset batchyes=" -o BatchMode=yes"

   # Create ssh variables to simplify usage.
   typeset sshstrictyes
   typeset sshstrictno
   typeset sshctout="-o ConnectTimeout=1"
  
   # Key specific; default key type is rsa.
   typeset gkeytype=rsa
   typeset gdfbase=.ssh/id_rsa
   typeset gdfauthbase=.ssh/authorized_keys2


   # Run through the menu options
   while getopts "f:k:dhrtv" OPT; do
      case $OPT in
         f)
            hostfile=$OPTARG
            [[ -r $hostfile ]] || {
               printme E "Unable to read file $hostfile"
               exit $FAILURE
            }
            ;;
         k)
            gkeytype=$OPTARG
            # This tool supports both rsa and dsa key types.
            case $gkeytype in
               rsa)
                  # Already set as the default.
                  continue
                  ;;
               dsa)
                  gdfbase=.ssh/id_dsa
                  gdfauthbase=.ssh/authorized_keys
                  ;;
               *)
                  printme E "bad key type"
                  Usage
                  exit $FAILURE
                  ;;
               esac 
            ;;
         r)
            round_robin=true
            ;;
         # The testing and debug options are hidden features.
         t)
            test_only=true
            ;;
         d)
            debug=true
            ;;
         v)
            verbose=true
            quiet=
            ;;
         h)
            Usage
            ;;
         *)
            printme E "invalid option: $OPTARG"
            exit $FAILURE
            ;;
      esac
   done
   shift $(($OPTIND - 1))

   printme D "Function: in Main"

   # Get the 1st argument and use it for the single host.
   other=$1
   [[ -z "$hostfile" && -z "$other" ]] && {
      Usage 
   }

   # Get local user.
   luser=$(whoami)
   [[ $luser = "" ]] && {
      printme E "Unable to read local user"
      exit $FAILURE
   } 

   # Check OS type. Need to setup specific HP-UX paths.
   [ "`uname`" = "HP-UX" ] && {
      pingpath="/usr/sbin/ping"
      sshpath="/opt/ssh/bin/ssh"
      sshkeygenpath="/opt/ssh/bin/ssh-keygen"
   }

   # Setup the ssh command options.
   sshstrictyes="$sshpath -l $luser $quiet $sshctout -o StrictHostKeyChecking=yes"
   sshstrictno="$sshpath -l $luser $quiet $sshctout -o StrictHostKeyChecking=no"

   # Get the fully-qualified name of the host we're running on.
   lhost=$(hostname)
   GetFQHost $lhost lhost 
   lhost=$fqdnhost

   # Prepare hostlist:
   # Strip out the commented lines or add the single host to the list.
   if [[ -n "$hostfile" ]] ; then
      hostlist=$($catpath $hostfile | grep -vE "^#|^[[:space:]]*$")
      hostlist=$(for other in $hostlist; do printf "$other "  ; done)
   else
      hostlist=$other
   fi

   # Handle the case where the localhost is the only host to be setup
   for line in $hostlist; do host_count=host_count+1; done
   if (( $host_count == 1 )) ; then
      tmpother=$hostlist
      GetFQHost $tmpother tmpother
      tmpother=$fqdnhost
      [[ $tmpother = $lhost ]] && localhostonly=true
   fi

   # Get the fully qualified domain name for each element in hostlist.
   # We assume default domain.
   for other in $hostlist
   do
      GetFQHost $other other
      other=$fqdnhost
      [[ $other != $lhost ]] && {
        hostlist_tmp="$hostlist_tmp $other"
      }
   done

   hostlist=$hostlist_tmp
   everyhost="$lhost $hostlist"
   $verbose && for line in $everyhost; do printme V "$line is good host" ; done

   # Support for a hidden feature.
   if $test_only ; then
      printme M "\nTesting..."
      TestThem $everyhost
      exit $SUCCESS
   fi

   # Set up the keys on the local system. 
   if ! SetupLocalKeys ; then 
      printme E "Unable to setup local system $lhost"
      exit $FAILURE
   fi         

   if $localhostonly ; then
      $sshpath $sshctout $lhost "echo  'Success: local host ($lhost) setup'" 
      if [ $? != 0 ] ; then 
         printme F "local host ($lhost) setup"
         exit $FAILURE
      else
         # TestAccess will try to add the shortname to the known_hosts file.  
         TestAccess $lhost $lhost $lhost
         exit $SUCCESS
      fi 
   fi 

   # Exchange keys between local system and other.
   for other in $hostlist
   do
      if ! ExchangePublicKeys $lhost $other ; then
           tmp_hostlist="$tmp_hostlist $other"
      else
           goodlist="$goodlist $other"
      fi
   done

   if [[ "$tmp_hostlist" != "" ]] ; then 
      for line in $tmp_hostlist 
      do 
         printme F "Unable to exchange keys with $line"
      done
   fi

   if [[ "$goodlist" = "" ]] ; then 
      printme F "Unable to exchange keys with any remote host(s)"
      exit $FAILURE
   else
      everyhost="$lhost $goodlist"
   fi

   # Here we setup authentication with every host in all directions. 
   if $round_robin ; then
      for other in $everyhost
      do
         PushPublicKeys $other $everyhost
      done
      printme M "\nTesting..."
      TestThem $everyhost
   fi
 
   # We are done here, clean up keys stored in temp files. 
   for line in $everyhost; do CleanupTempKeyFiles $line; done

   printme D "Function: done Main"

   exit $SUCCESS
}

Main $@

