Saturday, July 18, 2015

Certificates: Make a chain file

I toasted a server recently.  I like doing that.  It's like cleaning out the pipes with a bongoberry smoothie.  Chuck the old cruft overboard and reinstall just the bits I love.  But I chucked out the certificate chain as well.  I still had the certificate itself but with no onward chain mobiles won't talk to my server.  Whoops.  Not actually a problem as I had been a good little boy and kept backups of my disks religiously every day so I could simply have recovered it.  But I took this as a wee bit of a challenge.  I haven't been in the security industry for a while now.  The amount of junk google returns when you search for openssl and chain file is impressive.  So could I make myself a chain file from scratch?  Here's how.

What's a chain file?  Its a sequence of certificates that connect my personal certificate to some self-proclaimed authority.

Given my certificate, how do I find the next certificate up the chain?  Dump the certificate and you should see an extension called "Authority Information Access" with the URL of at least one more, and usually just one, upstream certificate.  Download and repeat.  You may find that the downloaded certificate is a binary blob that you need to convert but that's all.

Finally concatenate those bits into a chain file.  Yay.  man 1:0 google.

By the way, jeg elsker https://www.ssllabs.com/ssltest/analyze.html


# start with your certificate:
cert=my.crt
# we will copy the individual certificates to 001.crt, 002.crt and so on:
counter=0
# Now, for each certificate:
link="$(printf "%03d.crt" $((++counter)))" # 001.cert, 002.crt, ...
# Check that the certificate is in the human readable PEM format.
# If not it needs to be converted. Then copy into 001/2/3.crt
if openssl x509 -in "$cert" -text -noout &>/dev/null
then cp "$cert" "$link"
else openssl x509 -in "$cert" -inform DER -out "$link" -outform PEM
fi
# Make sure the certificate ends in a new line:
echo >> "$link"
# Get the next certificate up the chain:
cert="$(openssl x509 -in $link -text -noout | sed -nr '/Authority Information Access:/,/^\s*$/p' | sed -nr '/CA Issuers/{s/.*URI://g;p}')"
# Rinse and repeat until you have no more.
# Concatenate the 001.crt 002.crt etc in that order:
cat [0-9][0-9][0-9].crt > my.ca-bundle