Skip to content

Finding Expired SSL Certificates

Article Number: 000021834

Environment

Any Kubernetes environment using TLS certificates

Situation

There can be many SSL certificates in a Kubernetes cluster. When a certificate expires and is left in the system, it can cause monitoring alerts or issues. To help find expired certificates that may be affecting your Kubernetes clusters you can use the following scripts.

Resolution

Kubernetes Secrets

You can run the following command to check your Kubernetes secrets for any expired TLS certificates.

for ns in $(kubectl get ns -o jsonpath='{.items[*].metadata.name}'); do
  for sec in $(kubectl get secrets -n $ns -o json | jq -r '.items[] | select(.type=="kubernetes.io/tls") | .metadata.name'); do
    exp=$(kubectl get secret $sec -n $ns -o jsonpath="{.data['tls\.crt']}" | base64 -d | openssl x509 -noout -enddate | cut -d= -f2)
    if [[ $(date -d "$exp" +%s) -lt $(date +%s) ]]; then
      echo "Expired certificate: $sec (namespace: $ns, expiry date: $exp)"
    fi
  done
done

If you want to check for certificates expiring within a certain period of time, for example by 30 days, you can increment the date like this: '-d +30 days'. Please note that this is wrapped in single quotes .
See the example below for reference.

for ns in $(kubectl get ns -o jsonpath='{.items[*].metadata.name}'); do
  for sec in $(kubectl get secrets -n $ns -o json | jq -r '.items[] | select(.type=="kubernetes.io/tls") | .metadata.name'); do
    exp=$(kubectl get secret $sec -n $ns -o jsonpath="{.data['tls\.crt']}" | base64 -d | openssl x509 -noout -enddate | cut -d= -f2)
    if [[ $(date -d "$exp" +%s) -lt $(date -d '+30 days' +%s) ]]; then
      echo "Expired certificate: $sec (namespace: $ns, expiry date: $exp)"
    fi
  done
done

Local Machines

You can run the following command on your nodes to check for expiring certificates located on the host machine:

sudo find / -type f -name "*.crt" -exec sh -c '
  for cert; do
    exp=$(openssl x509 -in "$cert" -noout -enddate 2>/dev/null | cut -d= -f2)
    if [ -n "$exp" ] && [ "$(date -d "$exp" +%s)" -lt "$(date +%s)" ]; then
      echo "Expired certificate: $cert (validity period: $exp)"
    fi
  done
' sh {} + 2>/dev/null

If you want to check for certificates expiring within a certain time frame, for example by 30 days, you can increment the date like this: -d +30 days. Note that single quotes ( ' ) are not needed in this case.

See the example below for reference.

sudo find / -type f -name "*.crt" -exec sh -c '
  for cert; do
    exp=$(openssl x509 -in "$cert" -noout -enddate 2>/dev/null | cut -d= -f2)
    if [ -n "$exp" ] && [ "$(date -d "$exp" +%s)" -lt "$(date -d +30 days +%s)" ]; then 
      echo "Expired certificate: $cert (validity period: $exp)"
    fi
  done
' sh {} + 2>/dev/null