I am working with SSH certificates. I would like to do an automatic renew of them shortly before they expire. Not quite sure yet how the renewal will work, but I already found out how I can check the number of remaining days the certificate is valid:
# Store the expiry date in a variable
cert_expiry_date=$(ssh-keygen -L -f ~/.ssh/id_ed25519-cert.pub | grep "Valid:" | cut -d " " -f 13)
# Store the expiry date as seconds since the epoch
cert_expiry_seconds=$(date +%s -d $cert_expiry_date)
# Store the time "now" as seconds since the epoch
now=$(date +%s)
# Compute the number of days between "now" and "cert expiry"
# Note: No spaces for the division! Otherwise, bash fails.
let validity=($cert_expiry_seconds - $now)/86400
For an example:
chris@computer:~$ ssh-keygen -L -f ~/.ssh/id_ed25519-cert.pub
Type: ssh-ed25519-cert-v01@openssh.com user certificate
...
Valid: from 2024-03-23T17:34:00 to 2024-04-27T18:35:12
...
- The first line of the script collects only this
Valid:
line and extracts the last date in it. - The next line converts this extracted date into seconds since the epoch.
- Next, I also collect the seconds since the epoch for “now”.
- Finally, I subtract those both timestamps and do a division by $86400 = 24 \cdot 60 \cdot 60$. That way, I get the number of days this certificate is still valid.
At the time of writing, we have April 10th, 2024. The certificate is valid until April 27th, 2024, so we get $17$ days of remaining validity.
My idea now is something like the following:
if [ $validity -lt 4 ]; then
# renew the certificate
fi