Wednesday, September 14, 2011

Bash Script to Automate Import of External Cert Given Host and Port Into Java Keystore

Here's a bash script to import an external cert and import it into the local JDK's keystore, using some commands I found here:

Save this to a file called add_cert, then chmod +x add_cert and put it in your path:
#!/bin/bash

# add_cert
# Written by Gary S. Weaver 2011-09-14
# Downloads cert and imports it automatically into Java keystore.
# This is useful to run immediately after updating the JDK with a new keystore.

# References:
# http://serverfault.com/questions/129503/save-remote-ssl-certificate-via-linux-command-line
# http://www.sslshopper.com/article-most-common-java-keytool-keystore-commands.html
# http://docs.codehaus.org/display/JETTY/How+to+configure+SSL

set -e

KEYTOOL_PATHNAME=$1
KEYSTORE_PATHNAME=$2
KEYSTORE_PASSPHRASE=$3
HOST=$4
PORT=$5

if [ $# -eq 0 ]
then
  echo ""
  echo "usage: add_cert keytool_pathname keystore_pathname passphrase host [optional_port]"
  exit 1
fi

if [ ! -f "$KEYTOOL_PATHNAME" ]
then
  echo "the first argument must be a valid path to the keytool executable (e.g. '\$JAVA_HOME/bin/keytool'): '$KEYTOOL_PATHNAME'"
  echo ""
  echo "usage: add_cert keytool_pathname keystore_pathname passphrase host [optional_port]"
  exit 1
fi

if [ ! -f "$KEYSTORE_PATHNAME" ]
then
  echo "the second argument must be a valid path to the keystore (e.g. '\$JAVA_HOME/jre/lib/security/jssecacerts'): '$KEYSTORE_PATHNAME'"
  echo ""
  echo "usage: add_cert keytool_pathname keystore_pathname passphrase host [optional_port]"
  exit 1
fi

if [ -z "$KEYSTORE_PASSPHRASE" ]
then
  echo "the third argument must be a valid passphrase (e.g. 'changeit'): '$KEYSTORE_PASSPHRASE'"
  echo ""
  echo "usage: add_cert keytool_pathname keystore_pathname passphrase host [optional_port]"
  exit 1
fi

if [ -z "$HOST" ]
then
  echo "the fourth argument must be a valid hostname (e.g. www.acme.org): '$HOST'"
  echo ""
  echo "usage: add_cert keytool_pathname keystore_pathname passphrase host [optional_port]"
  exit 1
fi

if [ -z "$PORT" ]
then
  PORT=443
fi

echo "openssl s_client -connect $HOST:$PORT /tmp/$HOST.pem"
openssl s_client -connect $HOST:$PORT /tmp/$HOST.pem
echo "$KEYTOOL_PATHNAME -keystore jssecacerts -import -alias $HOST -file /tmp/$HOST.pem -trustcacerts -noprompt -storepass $KEYSTORE_PASSPHRASE"
$KEYTOOL_PATHNAME -keystore $KEYSTORE_PATHNAME -import -alias $HOST -file /tmp/$HOST.pem -trustcacerts -noprompt -storepass $KEYSTORE_PASSPHRASE

In addition, here are some helpful commands:

List all certs by alias in alphanumeric order:
$JAVA_HOME/bin/keytool -list -v -keystore $JAVA_HOME/jre/lib/security/keystore_name -storepass store_password | grep "Alias name" | sort

Remove a cert given its alias:
$JAVA_HOME/bin/keytool -delete -alias alias_name -keystore $JAVA_HOME/jre/lib/security/keystore_name -storepass store_password