Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting an expiry date from a keytool certificate

Tags:

bash

keytool

I am working on a fairly simple script to pull the expiry date from a keytool cert and compare this with todays date and then send a mail if that date is less than 30 days. However where I am getting stuck is how to extract the expiry date using bash, I am running:

keytool -list -v -keystore /usr/java/jdk1.8.0_301-amd64/jre/lib/security/cacerts -storepass <PWD> | grep "until:"

Which will output all the certs stored with multiple lines as follows:

Valid from: Tue May 26 01:00:00 IST 2015 until: Sun Jan 17 00:00:00 GMT 2038

The plan is to take the expiry (until) date from the line and convert that to epoch seconds and days to help calculate in the script.

Please can you suggest the best way for me to proceed.

like image 374
Burnt Frets Avatar asked Sep 13 '25 19:09

Burnt Frets


1 Answers

Not sure what you mean by "days" in

... and convert that to epoch seconds and days

but to covert it to epoch seconds, you can first remove everything until "until: ":

UNTIL=$(keytool ... | grep 'until:' | sed 's/^.*until: //')

and then use date:

date -d "${UNTIL}" +%s

EDIT

Ok, for multiple entries in the keystore you can adapt the following snippet. Here we read alias and "until" date, so that we can identify with which certificate we work at each iteration. You can modify it to read other fields.

KEYSTORE=/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts
KEYSTORE_PW=changeit
while read -r ALIAS; do
    # ALIAS is in the form: "Alias name: <REST>". We want <REST>.
    ALIAS=$(echo ${ALIAS} | cut -d' ' -f3)

    # read the next line
    read -r UNTIL

    # UNTIL is in the form: "Valid from: ... until: <REST>". We want <REST>
    UNTIL=$(echo ${UNTIL} | sed 's/^.*until: //')

    # convert to epoch
    EPOCH=$(date -d "${UNTIL}" +%s)

    # do something with it
    echo "${ALIAS}  -->  ${EPOCH}"
done < <(keytool -list -v -keystore "${KEYSTORE}" -storepass "${KEYSTORE_PW}" | grep -E '^Alias name:|^Valid from:')

And the output is:

debian:ac_raiz_fnmt-rcm.pem  -->  1893456000
debian:accvraiz1.pem  -->  1924940257
debian:actalis_authentication_root_ca.pem  -->  1916306522
debian:addtrust_external_root.pem  -->  1590835718
like image 98
danadam Avatar answered Sep 15 '25 10:09

danadam