2

I would like to get the days until a cert expires. Extracting the dates is easy with openssl

> cat cert | openssl x509 -noout -enddate
notAfter=Jun  8 17:07:09 2021 GMT

Unfortunately parsing the date Jun 8 17:07:09 2021 GMT and finding the days until today is not so straight forward. The goal would be to have

> cat cert | openssl x509 -noout -enddate | ...some commands...
15

Meaning 15 days until the cert expires.

I am aware of the openssl -checkend option, but that is just a boolean and I want the number of days.

tcurdt
  • 14,518
  • 10
  • 57
  • 72

2 Answers2

10

You may use this one liner shell script:

expiryDays=$(( ($(date -d "$(openssl x509 -in cert -enddate -noout | cut -d= -f2)" '+%s') - $(date '+%s')) / 86400 ))

Here is the breakup:

  • openssl ... command to print expiry date in notAfter=... format
  • cut -d= -f2 to get text after =
  • date -d '+%s': to get EPOCH seconds value for expiry date
  • date '+%s': to get EPOCH seconds value for today's date
  • (epochExpiry - epochToday) / 86400: to get difference of 2 EPOCH date-time stamps in number of days
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • This looks almost perfect. Unfortunately `date -d "Jun 8 17:07:09 2021 GMT" +%s` seems to only work on linux. On macOS -d sets the kernel's value for daylight saving time. – tcurdt Apr 02 '21 at 20:12
  • Yes of course but since you used `linux` tag in question this solution should work there. btw I also use mac but have gnu utilities installed using `home brew` to make it work – anubhava Apr 02 '21 at 20:15
  • 1
    Fair point. For that I should have asked for a POSIX solution. – tcurdt Apr 02 '21 at 20:21
1

A quickie perl script using the Date::Parse module (Install through your OS package manager or favorite CPAN client):

#!/usr/bin/env perl
use strict;
use warnings;
use Date::Parse;
use feature qw/say/;

my $certdate = str2time($ARGV[0]);
my $now = time;
my $expiresecs = $certdate - $now;
say int(($expiresecs / (60 * 60 * 24)));

Example:

$ ./showdays "Jun  8 17:07:09 2021 GMT"
67
Shawn
  • 47,241
  • 3
  • 26
  • 60