Monitoring Expiry of GPG Keys

View Markdown Other Articles

Article written by a human: Mike Cardwell

I've been using a small script to monitor when my PGP master and subkeys expire for a while now. You just supply it with an email address which can be used to locate the private key in your GnuPG keyring, and the number of days before expiry you want to start being alerted. It prints out nothing unless your key is within that expiry period range. You may find it useful:

#!/usr/bin/env perl
use strict;
use warnings;
use POSIX qw( mktime );

my $today = mktime(0,0,12,(localtime())[3..5]);

my @email   = grep( !/^\d+$/, @ARGV );
my( $days ) = grep( /^\d+$/,  @ARGV );

my %done = ();
foreach my $email (@email) {
  foreach my $line (split(/\r?\n/,`gpg --list-sigs $email 2>/dev/null`)) {
    next unless $line =~ /^([sp]ub) .+ \S+\/(\S+) \S+ \[expire[ds]: (\d+)-(\d+)-(\d+)\]$/;
    my( $type, $id, $expires ) = ( $1, $2, mktime(0,0,12,$5,$4-1,$3-1900) );

    next if exists $done{$id};
    $done{$id}=1;

    my $remaining = int(($expires - $today)/86400);
    if (!defined $days || $remaining <= $days) {
      print "PGP ${type}key $id expires in $remaining days ($email)\n";
    }
  }
}

My cron job runs daily and warns me when I'm within a week of expiry:

5 5 * * *   check_gpg_expiry.pl 7 mike.cardwell@example.com

· PayPal · Patreon · Bitcoin RSS · Atom · Mastodon · Bluesky
← Read more