#!/bin/bash set -euo pipefail # ==== Variables ==== # Output warning if fewer than this number of seconds until expiry WARNSECONDS=1209600 # Two weeks # File containing a newline separated list of host:port combinations to be checked HOSTSANDPORTS="hostsandports.txt" # Number of seconds before OpenSSL should timeout when connecting to hosts TIMEOUT=10 # ==== Variables ==== # Loop through all host:port combinations while read -r HOSTANDPORT ; do # echo "DEBUG: HOSTANDPORT: $HOSTANDPORT." # Host before colon HOST=$(echo "$HOSTANDPORT" | cut -d ":" -f "1") # Port after colon, or nothing if no port given (assumes 443 later on) PORT=$(echo "$HOSTANDPORT" | cut -s -d ":" -f "2") # echo "DEBUG: HOST: $HOST." # Assume no STARTTLS (unless special ports later on) STARTTLS="" if [ "$PORT" = "" ] ; then # Assume 443 if no port specified PORT=443 elif [ "$PORT" -eq 25 ] ; then # Assume SMTP STARTTLS if port 25 STARTTLS="-starttls smtp" elif [ "$PORT" -eq 143 ] ; then # Assume IMAP STARTTLS if port 143 STARTTLS="-starttls imap" fi # echo "DEBUG: PORT: $PORT." # echo "DEBUG: STARTTLS: $STARTTLS." # Try various TLS versions against this host:port to try and get a response RETCODE=1 for PROTOCOL in -tls1_3 -tls1_2 -tls1_1 -tls1 ; do if [ "$RETCODE" -eq 0 ] ; then break fi set +e # Get the "Not After" field for the certificate expiry EXPIRYSTRING=$(echo "Q" | timeout "$TIMEOUT" openssl s_client $STARTTLS -connect "$HOST:$PORT" -servername "$HOST" "$PROTOCOL" 2> /dev/null | openssl x509 -noout -text 2> /dev/null | grep "Not After" | sed -r 's/\s*Not After : //') RETCODE="$?" set -e done # echo "DEBUG: EXPIRYSTRING: $EXPIRYSTRING." # Convert expiry into unixtime EXPIRY=$(date -d "$EXPIRYSTRING" +%s) # echo "DEBUG: EXPIRY: $EXPIRY." NOW=$(date +%s) # echo "DEBUG: NOW: $NOW." # Number of seconds left DIFFERENCE=$(("$EXPIRY" - "$NOW")) # echo "DEBUG: DIFFERENCE: $DIFFERENCE." # Warn if less than WARNSECONDS less if [ "$DIFFERENCE" -lt "$WARNSECONDS" ] ; then echo "Warning! The certificate at $HOST:$PORT expires in $DIFFERENCE seconds (~$((DIFFERENCE / 60 / 60 / 24)) days)." # else # echo "DEBUG: The certificate at $HOST:$PORT expires in $DIFFERENCE seconds (~$((DIFFERENCE / 60 / 60 / 24)) days)." fi done < "$HOSTSANDPORTS"