Skip to content

Instantly share code, notes, and snippets.

@thomd
Last active September 6, 2023 11:59
Show Gist options
  • Save thomd/da7377c87b2298dc151e72a1e43e9ac5 to your computer and use it in GitHub Desktop.
Save thomd/da7377c87b2298dc151e72a1e43e9ac5 to your computer and use it in GitHub Desktop.
Shell script for checking if a ssl-certificate expires within some next days. To be triggered by a cron job or a pipeline.
#
# Notify on an upcoming expiration of a SSL ceritficate
#
# SETUP
#
# Create an Variable Group 'SSL-Cert-Check' within the Pipeline Library with the variables
# SSL_HOSTNAME
# SSL_THRESHOLD_DAYS
# TEAMS_WEBHOOK_URL
#
# TEST
#
# Test with hostname 'expired.badssl.com'
#
trigger: none
pr: none
schedules:
- cron: "0 6 * * *"
displayName: Every Day at 08:00 CET
branches:
include:
- master
always: true
pool:
vmImage: ubuntu-latest
variables:
- group: SSL-Cert-Check
steps:
- checkout: none
- script: |
expiry_date=$(echo -n Q | openssl s_client -connect "$(SSL_HOSTNAME)":443 2>/dev/null | openssl x509 -noout -dates | awk -F '=' '/notAfter/ {print $2}')
echo "##vso[task.setvariable variable=expiry_date]$expiry_date"
expiry=$(date -d "$expiry_date" +%s)
now=$(date +%s)
days=$(((expiry - now) / 24 / 60 / 60))
echo "##vso[task.setvariable variable=days]$days"
if [ "$days" -le "$SSL_THRESHOLD_DAYS" ]; then
exit 1
fi
displayName: 'SSL Expiration Check'
- script: |
echo "SSL certificate for $(SSL_HOSTNAME) expires at $(expiry_date)"
curl \
-d '{"@type":"MessageCard","@context":"http://schema.org/extensions","themeColor":"ff0000","summary":"Summary","sections":[{"text":"SSL certificate for **$(SSL_HOSTNAME)** expires in **$(days) days** at **$(expiry_date)**","markdown":true}]}' \
-H 'Content-Type: application/json' \
$(TEAMS_WEBHOOK_URL)
displayName: 'Expiration Notification'
condition: failed()
#!/usr/bin/env sh
host="example.com"
expiry_date=$(echo -n Q | openssl s_client -connect "$host":443 2>/dev/null | openssl x509 -noout -dates | awk -F '=' '/notAfter/ {print $2}') # returns e.g. "Sep 19 23:59:59 2022 GMT"
expiry=$(date -j -f "%b %d %H:%M:%S %Y %Z" "$expiry_date" +"%s") # for OSX
expiry=$(date -d "$expiry_date" +%s) # for Ubuntu
now=$(date +%s)
threshold_days=30
threshold=$((threshold_days * 24 * 60 * 60))
if [ "$((expiry - threshold))" -le "$now" ]; then
echo "SSL certificate for $host expires at $expiry_date"
# trigger a notification ...
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment