#!/bin/sh
#############################################
# get-cert.sh for Linux
#
# Joe Klemencic 5/12/2005
#
# This script will try to get an x509 cert from
# the FNAL KCA and convert it into a pkcs12 file
# then attempt to auto-import it into Mozilla &
# FireFox if possible
#
#############################################

#############################################
#
# Check to see if we have the required utilities
# If not, you can set change the following 
# to represent the paths of your utilities
#############################################

#############################################
#
# Formatting, quiet/help flags and better path
# handling submitted by Chris Green 09/07/2005
#
#############################################


RUNPATH=`dirname $0 2>/dev/null || echo "."`
# ... or ...
#RUNPATH=<insert-favorite-path-here>

usage() {
    cat <<EOF
usage: `basename $0` [-hiq]

Incorrect flag. Use the -i flag to try to auto-import into Mozilla and
FireFox or run without any flags to only get a KCA certificate and
convert into a PKCS12 file. Use -q to suppress most informational output.
EOF
}

# Check to see if we have kx509 utility
KX509PROG=`which kx509 2>/dev/null` > /dev/null 2>&1
if [ $? -ne 0 ]; then
        echo kx509 is required to run this script. Please install kx509 from the FNAL Kerberos utilities
        echo and ensure it is in your path or modify this script to point to the location kx509 is installed at
        exit 1
fi

# Check to see if we have kx509 utility
KXLISTPROG=`which kxlist 2>/dev/null` > /dev/null 2>&1
if [ $? -ne 0 ]; then
        echo kxlist is required to run this script. Please install kxlist from the FNAL Kerberos utilities
        echo and ensure it is in your path or modify this script to point to the location kxlist is installed at
        exit 1
fi

# Check to see if openssl is installed
SSLPROG=`which openssl 2>/dev/null` > /dev/null 2>&1
if [ $? -ne 0 ]; then
        echo openssl is required to run this script. Please install openssl
        echo and ensure it is in your path or modify this script to point to the location openssl is installed at
        exit 1
fi

while getopts :hiq OPT; do
    case $OPT in
	i)
	      ai=1
	      ;;
	q)
	      quiet=1
	      ;;
        h)
	      usage
	      exit 1
	      ;;
	*)
	      usage
	      exit 2
    esac
done
shift `expr $OPTIND - 1`

if [ -n "$ai" -a -z "$quiet" ]
then
        echo Option selected to obtain KCA certificates and attempt to auto-import into Mozilla and FireFox
fi

if [ $# -ne 0 ]
then
	usage
        exit 1
fi

##########################################
#
# Get a certificate and import
#
##########################################

# Obtain a cert from a Kerberos ticket
"$KX509PROG"

# Error - no valid krb cache
if [ $? -ne 0 ]; then
        echo You do not have a valid Kerberos ticket
        echo Please obtain a valid Kerberos ticket then re-run get-cert.sh
        exit 1
fi

if [ -z "$ai" -a -z "$quiet" ]
then
        echo No \'-i\' parameter given to auto-import into Mozilla and FireFox. 
        echo I will obtain a certificate and convert into a PKCS12 file,
        echo then try to copy it to your .globus directory
fi

# Stuff it into an x509 file in /tmp/x509up_u<UID>
"$KXLISTPROG" -p > /dev/null 2>&1

# Convert the certificate from x509 to pkcs12
"$SSLPROG" pkcs12 -export -passout pass:"" -in /tmp/x509up_u$UID -out /tmp/x509up_u$UID.p12 -name "Fermilab KCA" > /dev/null 2>&1

# Change the permissions on the pkcs12 file
chmod 600 /tmp/x509up_u$UID.p12

# Create the pub/priv certs in .globus if it exists
# Contributed by Keith Chadwick 07/2005
if [ -d $HOME/.globus ]
then
        echo
        echo Please enter a password to protect your exported certificates for Globus use \(you will need to retype this password when you import your certificate into Globus applications\)
        read -s gpass
        if [ "$gpass" == "" ]; then
                echo You must input a password to protect your exported Globus certificates
        exit
        fi

        $SSLPROG pkcs12 -in /tmp/x509up_u$UID.p12 -passin pass:"" -passout pass:"" -clcerts -nokeys -out $HOME/.globus/usercert-kca.pem 
        $SSLPROG pkcs12 -in /tmp/x509up_u$UID.p12 -passin pass:"" -passout pass:"" -nocerts -out $HOME/.globus/userkey-kca.pem 
        chmod 600 $HOME/.globus/usercert-kca.pem
        chmod 600 $HOME/.globus/userkey-kca.pem
        echo
        echo Your certificates have been copied to your $HOME/.globus directory.
        echo Certificate: $HOME/.globus/usercert-kca.pem
        echo Key: $HOME/.globus/userkey-kca.pem
fi

if [ -n "$ai" ]
then
 # Prompt user to close all Browser windows before proceeding

 if [ -z "$quiet" ]; then
  echo
  echo Please close all browser windows \(FireFox, Mozilla\) before proceeding.
  echo If prompted to enter a NEW password, this is because you have not
  echo yet initialized your Mozilla/Firefox certificate store.
  echo You can either simply press the RETURN key at that prompt
  echo \(which may allow others to open your certificate store\)
  echo or set a password to secure the certificate store
  echo \(please remember the password you enter or else you
  echo  will no longer be able to open the certificate store\)
  echo
  echo If you are prompted to enter your password, please enter
  echo the password you assigned to secure your certificate store.
  echo If you have multiple Mozilla and Firefox installations,
  echo you will be prompted for a password for each browser instance.
  echo
  echo Press RETURN to continue
 else
  echo "Close all browser windows. Press enter to acknowledge."
 fi
 read

 # Is Mozilla/Firefox installed in users home dir?
 if [ -d "$HOME/.mozilla" ]; then
        TMP=/tmp/get-cert.sh.$$
        trap "rm \"$TMP\"* 2>/dev/null" 0
        CERTUTIL=`which certutil 2>/dev/null` > /dev/null 2>&1
        if [ -z "$CERTUTIL" ]; then
          CERTUTIL="$RUNPATH/certutil"
        fi
        PK12UTIL=`which pk12util 2>/dev/null` >/dev/null 2>&1
        if [ -z "$PK12UTIL" ]; then
          PK12UTIL="$RUNPATH/pk12util"
        fi
        printf "\n\n\n" > $TMP
        # Find all Mozilla/Firefox cert stores
        find "$HOME/.mozilla" -name cert8.db | while read cert;
        do
                i=${cert%/*}
 
                # See if an existing Fermilab KCA cert is present
                "$CERTUTIL" -L -n "Fermilab KCA" -d "$i" > /dev/null 2>&1
                # Found existing Fermilab KCA certificate
                if [ $? -eq 0 ] ; then
                        # Delete existing Fermilab KCA certificate
                        echo Found existing certificate. Deleting...
                        "$CERTUTIL" -D -n "Fermilab KCA" -d "$i"
                fi
 
                # Import the new Fermilab KCA cert into the found Mozilla/FireFox certificate stores
                "$PK12UTIL" -i /tmp/x509up_u$UID.p12 -d "$i" -w "$TMP"
                if [ $? -eq 0 ]; then
		    echo Imported certificate to $i
		else
		    echo Failed to import certificate to $i
                fi
         done
 fi
 if [ -z "$quiet" ]; then
   echo
   echo Fermilab KCA certificate imported into browsers
  fi
fi

if [ -z "$quiet" ]; then
  echo
  echo If you need to manually import the certificate into other
  echo applications such as Nessus, your can find the converted certificates at:
  echo x509 format: /tmp/x509up_u$UID
  echo PKCS12 format: /tmp/x509up_u$UID.p12
  echo
else
  echo "Credentials in /tmp/x509up_u$UID (x509) and /tmp/x509up_u$UID.p12 (PKCS12)"
fi
