Verify an SSL Certificate for a server

Introduction

In general, you need 3 different files for an SSL Certificate : a private key for the server (.key or .pem), a certificate (.cer or .crt) given to the client for SSL-encryption, and the trust chain (.chain or .txt) that gives you a list of certificates, each signed by another, untill a root certificate you have installed on your computer.

The script I give you here is able to verify that all those 3 files are valid :

  • The private key matches the certificate ;
  • The trust chain is valid.

How it works

To verify your domain example.com, you need of course the 3 files mentioned above :

  • example.com.key : the private key
  • example.com.cer : the certificate
  • example.com.chain.txt : the trust chain

The script will verify that the private key and certificate have the same signature (with openssl -modulus parameter), and verify the certificate chain with  openssl verify.

The script

  1. #!/bin/sh
  2.  
  3. DOMAIN="$1"
  4.  
  5. if [ -z "$DOMAIN" ]; then
  6.   echo "Usage : "$(basename "$0")" domain" >&2
  7.   echo "  Will check if \$domain.key, \$domain.cer and \$domain.chain.txt are correct" >&2
  8.   exit 1
  9. fi
  10.  
  11. # Check key and certificate modulus
  12. KEY_MOD=$(openssl rsa  -noout -modulus -in ${DOMAIN}.key | openssl md5)
  13. CER_MOD=$(openssl x509 -noout -modulus -in ${DOMAIN}.cer | openssl md5)
  14.  
  15. if [ "${KEY_MOD}" != "${CER_MOD}" ]; then
  16.   echo "Error : key does not match certificate" >&2
  17.   exit 2
  18. fi
  19.  
  20. # Check certificate consistency
  21. openssl verify -CApath /etc/ssl/certs -CAfile ${DOMAIN}.chain.txt ${DOMAIN}.cer | grep -q "^${DOMAIN}.cer: OK$"
  22. if [ $? -ne 0 ]; then
  23.   openssl verify -CApath /etc/ssl/certs -CAfile ${DOMAIN}.chain.txt ${DOMAIN}.cer >&2
  24.   echo "Error while verifying certificate chain" >&2
  25.   exit 3
  26. fi
  27.  
  28. echo "Success"
  29. exit 0
  30.  

Download the script

This entry was posted in Web technologies. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>