Sunday, 4 March 2012

SSL pubkeys to keystore update script

From what I've been told for Jboss to use other services (SMS, Smtp) over SSL, their public keys have to be added to keystore.
So i whipped out this piece of code.

#!/bin/bash

CRDIR=/opt/https
KEYTL=/opt/java/bin/keytool
KYSTR=/opt/test.keystore
LOG=/opt/cron_cert.log
LST=(smtp.gmail.com:465  ssl.hqsms.com:443)

date >> ${LOG}
echo "--== List count : ${#LST[*]}" >> ${LOG}

if [ ! -d ${CRDIR} ];then
    echo "!!! ERROR: Cert dir missing: ${CRDIR}" | tee -a ${LOG}
    exit 1
fi

cd ${CRDIR}
rm -f ${CRDIR}/*.tmp

for item in ${LST[*]}
do
    if [ ! -f ${item} ];then echo "dummy" > ${item}
    fi
done

CERTS=(*)

if [ "${CERTS[0]}" = "*" ];then
    echo "??? WARNING : No certs in ${CRDIR}" | tee -a ${LOG}
    if [ ${#LST[*]} -eq 0 ];then
        echo "!!! ERROR : Certs list is empty" | tee -a ${LOG}
        exit 1
    fi
else
    echo "--== Count of certs in ${CRDIR} : ${#CERTS[*]}" >> ${LOG}
fi

if [ ! -f ${KYSTR} ];then
    ${KEYTL} -genkey -noprompt -dname "CN=s, OU=s, O=s, L=s, ST=s, C=s" -alias fooxyz -keystore ${KYSTR} -storepass Somepass -keypass Somepass
    ${KEYTL} -delete -alias fooxyz -keystore ${KYSTR} -storepass Somepass
fi

#------------------------------------------
for CRT in ${CERTS[*]}
do
    echo "--== CERT :: ${CRT}" >> ${LOG}
    echo "Q" | openssl s_client -connect ${CRT} 2>>${LOG} | grep -B 100 "END CERTIF" | grep -A 100 "BEGIN CERTIF" > ${CRT}.tmp
    # gnutls-cli  --print-cert  -p 443  some.ip

    if [ -s ${CRT}.tmp ];then
        diff -qs ${CRT} ${CRT}.tmp >> ${LOG}
        rtn=`echo $?`
        if [ ! ${rtn} == 0 ]; then
            echo "--== Updating ${CRT}" >> ${LOG}
            mv -f ${CRT}.tmp ${CRT}
            ${KEYTL} -delete -alias ${CRT} -keystore ${KYSTR} -keypass Somepass -storepass Somepass >> ${LOG} 2>&1
            ${KEYTL} -importcert -noprompt -alias ${CRT} -file ${CRDIR}/${CRT} -keystore ${KYSTR} -storepass Somepass >> ${LOG} 2>&1
    fi
    else
        echo "!!! ERROR : Couldn't get cert from ${CRT}" >> ${LOG}
    fi
    rm -f ${CRDIR}/*.tmp
done

Still got one problem with this script - when adding a new cert to keystore, keytool will report false error about removing old key before update.

No comments:

Post a Comment