Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 34bc0eac7b
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

executable file 675 lines (513 sloc) 17.318 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
#!/usr/bin/perl
#
# Expiration date checker and handler. Supports x509 certificates, and
# anything a wrapper script can be written for. Run perldoc(1) on this
# script for additional documentation.
#
# The author disclaims all copyrights and releases this script into the
# public domain.

use strict;
use warnings;

use Config::General qw(ParseConfig);
use Date::Parse qw(str2time);
use File::Basename qw(basename);
use File::Temp qw(tempfile);
use Getopt::Std;

END {
  # Report problems when writing to stdout (perldoc perlopentut)
  unless ( close(STDOUT) ) {
    warn "error: problem closing STDOUT: $!\n";
    exit 74;
  }
}

my $basename = basename($0);

my %program_param = ( name => $basename, argv => "@ARGV", pid => $$ );

# list different modes of operation (subroutine that obtains expiration
# date and other metadata from an external command/code)
my %actions = (
  certificate => \&action_certificate,
  openssl_x509 => \&action_openssl_x509,
);
my @actions = sort keys %actions;

my %opts;
getopts 'h?l:c:f:', \%opts;

if ( exists $opts{l} ) {
  print "@actions\n";
  do_exit(0);
}

if ( exists $opts{h} or exists $opts{'?'} or not @ARGV ) {
  print_help();
  do_exit(64);
}

my %config = ParseConfig( -ConfigFile => $opts{f}, -LowerCaseNames => 1 );
if ( !defined $config{class} ) {
  remark(
    'error',
    'no classes defined in configuration',
    { file => $opts{f} }
  );
  do_exit(78);
}

my $op_mode = shift || q{};
$op_mode =~ tr/-/_/;

if ( !exists $actions{$op_mode} ) {
  remark( 'error', 'unknown mode',
    { allowed => join( q{,}, @actions ), mode => $op_mode } );
  print_help();
  do_exit(78);
}

# where in the prefs to read expire, window handlers from
my $report_handler = exists $opts{c} ? $opts{c} : 'default';
my $report_ref = $config{class}->{$report_handler};

if ( !defined $report_ref ) {
  remark(
    'error',
    'class preferences not found',
    { class => $report_handler, file => $opts{f} }
  );
  do_exit(78);
}

# lookup expiration date and other info via mode handler
my ( %time_param, %extra_param );
{
  my ( $time_ref, $extra_ref ) = $actions{$op_mode}->(@ARGV);
  if ( !defined $time_ref or !defined $time_ref->{expire_epoch} ) {
    remark( 'error', 'no expire date found' );
    do_exit(78);
  }
  @time_param{ keys %$time_ref } = values %$time_ref;
  @extra_param{ keys %$extra_ref } = values %$extra_ref;
}
$time_param{cur_epoch} = time;

my %lookup = (
  time => \%time_param,
  extra => \%extra_param,
  program => \%program_param
);

# check whether expired, or if within a window
if ( $time_param{expire_epoch} <= $time_param{cur_epoch} ) {

  # TODO fill out more parameters (humanized time? strftime, parameters
  # about the certificate, and etc.? - see what need for reporting)
  # seconds_ago => $cur_epoch - $expire_epoch,
  handle_condition( $report_ref->{expired}, \%lookup );

  die "error: expired handler did not exit script\n";
}

if ( exists $report_ref->{window} ) {
  my @windows;

  if ( ref $report_ref->{window} eq 'HASH' ) {
    my %tmp = %{ $report_ref->{window} };
    delete $report_ref->{window};
    $report_ref->{window}->[0] = \%tmp;
  } elsif ( ref $report_ref->{window} ne 'ARRAY' ) {
    remark(
      'error',
      'unexpected reference type for window',
      { ref => ref $report_ref->{window}, file => $opts{f} }
    );
    do_exit(78);
  }

  # build Windows to look at (sanity checks, duration conversion)
  # TODO include window timevalue in time_param hash
  for my $window_ref ( @{ $report_ref->{window} } ) {
    if ( !exists $window_ref->{inside} ) {
      remark( 'error', 'skipping window without date setting' );
      next;
    }
    $window_ref->{inside_sec} = duration2seconds( $window_ref->{inside} );
    push @windows, $window_ref;
  }

  for
    my $window_ref ( sort { $a->{inside_sec} <=> $b->{inside_sec} } @windows )
  {

    if ( $time_param{expire_epoch} <=
      ( $time_param{cur_epoch} + $window_ref->{inside_sec} ) ) {

      # TODO seconds_left => $expire_epoch - $cur_epoch,
      handle_condition( $window_ref, \%lookup );

      die "error: window handler did not exit script\n";
    }
  }
}

if ( exists $report_ref->{default} ) {
  # TODO seconds_left => $expire_epoch - $cur_epoch,
  handle_condition( $report_ref->{default}, \%lookup );

  die "error: default handler did not exit script\n";
} else {
  # if no default, exit, assuming an implicit default exit
  do_exit(0);
}

# Mode to parse for expiration date using 'openssl x509' (certificate)
sub action_openssl_x509 {
  my @x509_arguments = @_;

  my @command =
    ( qw{openssl x509 -noout -dates -subject -issuer}, @x509_arguments );

  my $results = get_output(@command);
  if ( !defined $results ) {
    remark( 'error', 'no output returned', { command => "@command" } );
    do_exit(70);
  }

  my ( %time_param, %cert_param );
  for my $line (@$results) {
    if ( $line =~ m/^notAfter=(.+)/ ) {
      $time_param{expire_epoch} = date_openssl2epoch($1)
        if !exists $time_param{expire_epoch};
      next;
    }
    if ( $line =~ m/^notBefore=(.+)/ ) {
      $time_param{start_epoch} = date_openssl2epoch($1)
        if !exists $time_param{start_epoch};
      next;
    }
    if ( $line =~ m/^subject\s*=\s*(.+)/ ) {
      $cert_param{subject} = $1 if !exists $cert_param{subject};
      next;
    }
    if ( $line =~ m/^issuer\s*=\s*(.+)/ ) {
      $cert_param{issuer} = $1 if !exists $cert_param{issuer};
      next;
    }
  }

  if ( !exists $time_param{expire_epoch} ) {
    return;
  }

  return \%time_param, \%cert_param;
}

# runs a command that should return a certificate to stdout that
# 'openssl x509' can then parse for information
sub action_certificate {
  my @command = @_;
  my $results = get_output(@command);
  if ( !defined $results ) {
    remark( 'error', 'no output returned', { command => "@command" } );
    do_exit(70);
  }

  my ( $tmp_fh, $filename );
  eval { ( $tmp_fh, $filename ) = tempfile(); };

  local $SIG{TERM} = sub { close $tmp_fh; unlink $filename };

  if ( $@ or !defined $tmp_fh ) {
    remark(
      'error',
      'no temporary file created',
      ( $@ ? do { chomp $@; { errstr => $@ } } : {} )
    );
    do_exit(73);
  }

  for my $line (@$results) {
    print $tmp_fh $line;
  }
  close $tmp_fh;

  return $actions{openssl_x509}->( '-in', $filename );
}

# parses handler prefs from under config, figures out what to do...
sub handle_condition {
  my $handle_ref = shift;
  my $lookup_ref = shift;

  # handlers must exit, default to 0 if unset
  if ( !exists $handle_ref->{exit_value} ) {
    $handle_ref->{exit_value} = 0;
  }

  my %handlers = (
    # runs a command, such as logger(1)
    exec => sub {
      my $cmd_str = shift;
      my $lookup_ref = shift;

      my @command = parse_tokens($cmd_str);
      for my $part (@command) {
        $part =~
          s/ (?<!\\) %{ ([^.]+) \. ([^}]+) } / $lookup_ref->{$1}->{$2} || '' /egx;
        $part =~ s/(\\.)/qq("$1")/eeg;
      }

      my $status = system @command;
      if ( $status != 0 ) {
        remark(
          'warning',
          'command failed',
          { command => "@command", errno => $? }
        );
      }

      return;
    },
    # like exec, but takes first token as standard input to the program
    # (to support sending data to things like mail(1))
    pipe => sub {
      my $cmd_str = shift;
      my $lookup_ref = shift;

      # standard input everything before first unbackwhacked |
      my ( $stdin, $cmd_tmp ) = split /\s*(?<!\\)\|\s*/, $cmd_str, 2;

      $stdin =~
        s/ (?<!\\) %{ ([^.]+) \. ([^}]+) } / $lookup_ref->{$1}->{$2} || '' /egx;
      $stdin =~ s/(\\.)/qq("$1")/eeg;

      my @command;
      for my $part ( parse_tokens($cmd_tmp) ) {
        $part =~
          s/ (?<!\\) %{ ([^.]+) \. ([^}]+) } / $lookup_ref->{$1}->{$2} || '' /egx;
        $part =~ s/(\\.)/qq("$1")/eeg;
        push @command, $part;
      }

      my $cmd_fh;
      open $cmd_fh, '|-' or exec @command or return;
      print $cmd_fh $stdin;
      close $cmd_fh;

      return;
    },
    # print to standard output
    stdout => sub {
      my $output_str = shift;
      my $lookup_ref = shift;

      $output_str =~
        s/ (?<!\\) %{ ([^.]+) \. ([^}]+) } / $lookup_ref->{$1}->{$2} || '' /egx;
      $output_str =~ s/(\\.)/qq("$1")/eeg;
      print "$output_str\n";

      return;
    }
  );

  for my $handle ( sort keys %handlers ) {
    if ( exists $handle_ref->{$handle} ) {
      if ( ref $handle_ref->{$handle} eq 'ARRAY' ) {
        for my $item ( @{ $handle_ref->{$handle} } ) {
          $handlers{$handle}->( $item, $lookup_ref );
        }
      } else {
        $handlers{$handle}->( $handle_ref->{$handle}, $lookup_ref );
      }
    }
  }

  do_exit( $handle_ref->{exit_value} );
}

# converts a string into a list of tokens
sub parse_tokens {
  my $string = shift;
  my @tokens;

UBLE: {
    # non-quoted strings, backslashed quotes and whitespace allowed
    push( @tokens, $1 ), redo UBLE if $string =~ m/ \G ( [^"'\s]+ ) \s* /cgx;

    # double-quoted strings, backslashed quotes allowed
    push( @tokens, $1 ), redo UBLE
      if $string =~ m/ \G " ((?: \\.|[^\\"] )+) " \s* /cgx;

    push( @tokens, $1 ), redo UBLE
      if $string =~ m/ \G ' ((?: \\.|[^\\'] )+) ' \s* /cgx;

    last UBLE if $string =~ / \G $ /gcx;

    remark( 'error', 'unparseable token in string', { data => $string } );
    do_exit(78);
  }

  return @tokens;
}

sub date_openssl2epoch {
  my $date = shift;

  my $time = str2time($date);
  return $time;
}

# takes command to run (and optional leading hashref with parameters),
# returns filehandle (or undef on error) with STDOUT of program
sub get_output {
  my $param = {};
  if ( @_ and ref $_[0] eq 'HASH' ) {
    $param = { %$param, %{ $_[0] } };
    shift @_;
  }

  my @command = @_;
  return unless @command;

  #remark( 'debug', 'command run', { command => "@command" } );

  my $timeout = $param->{timeout} || 60;

  my @results;

  eval {
    local $SIG{ALRM} = sub { die "alarm\n" };

    alarm $timeout;

    my $output_fh;
    open $output_fh, '-|' or exec @command or die "exec error\n";
    @results = <$output_fh>;
    close $output_fh;

    alarm 0;
  };
  if ($@) {
    my $error_str =
        $@ eq "alarm\n" ? 'command timed out'
      : $@ eq "exec error\n" ? undef
      : 'unexpected command error';

    if ( defined $error_str ) {
      chomp $@;
      remark( 'error', $error_str, { command => "@command", errno => $@ } );
    }
  }

  return @results ? \@results : undef;
}

sub duration2seconds {
  my $tmpdur = shift;
  my $seconds;

  # how to convert short human durations into seconds
  my %factor = (
    y => 31536000,
    w => 604800,
    d => 86400,
    h => 3600,
    m => 60,
    s => 1,
  );

  # assume raw seconds for plain number
  if ( $tmpdur =~ m/^\d+$/ ) {
    $seconds = $tmpdur * 60;

  } elsif ( $tmpdur =~ m/^[ywdhms\d\s]+$/ ) {

    # match "2m 5s" style input and convert to seconds
    while ( $tmpdur =~ m/(\d+)\s*([ywdhms])/g ) {
      $seconds += $1 * $factor{$2};
    }
  } else {
    remark( 'error', 'unknown characters in duration', { data => $tmpdur } );
    do_exit(78);
  }

  unless ( defined $seconds and $seconds =~ m/^\d+$/ ) {
    remark( 'error', 'unable to parse duration', { data => $tmpdur } );
    do_exit(78);
  }

  return $seconds;
}

# Wrapper for exit values, in case need to alter them under particular
# monitoring systems. Script uses 100+ for various error conditions.
sub do_exit {
  my $exit_value = shift;

  exit $exit_value;
}

sub remark {
  my $priority = shift;
  my $message = shift;
  my $attributes = shift;

  chomp $message;

  my $attr_str;
  if ($attributes) {
    $attr_str = join ', ',
      map { $attributes->{$_} ||= q{}; "$_=$attributes->{$_}" }
      sort keys %$attributes;
  }

  print STDERR "$priority: $message"
    . ( $attr_str ? ": $attr_str" : q{} ) . "\n";
  return 1;
}

sub print_help {
  print <<"END_USAGE";
Usage: $basename -f prefs [options] mode [arguments]

Expiration date handler.

Options:
-h/-? Display this message.
-f pp Read preferences file from pp.
-c cc Specify custom class to read from preferences file.
-l List supported modes and exit.

Run perldoc(1) on this script for additional documentation.

END_USAGE
  return;
}

__END__

=head1 NAME

check-expire - expiration date checker and handler

=head1 SYNOPSIS

Check the certificate on C<www.example.org:443>, and handle the expired
or near-expired certificate via options in the C<prefs> configuration
file:

$ check-expire -f prefs certificate check-web www.example.org:443

Where the C<check-web> wrapper outputs the certificate via:

#!/bin/sh
echo GET / HTTP/1.0 | openssl s_client -connect "$1" 2>&1

Directly accessible certificate files can be checked via:

$ check-expire -f prefs openssl-x509 -in /path/to/some.cert

=head1 DESCRIPTION

=head2 Overview

Checks expiration dates on data like x509 certificates. Uses preferences
to handle expired certificates, or configurable actions should the
expiration date be inside a particular time window. Requires wrapper
scripts to obtain the certificate or expiration date to parse.

=head2 Normal Usage

$ check-expire -f prefs mode [mode options]

See L<"OPTIONS"> for details on the command line switches supported.

=head1 OPTIONS

This script currently supports the following command line switches.
Arguments following the C<mode> will vary.

=over 4

=item B<-h>, B<-?>

Prints a brief usage note about the script.

=item B<-f> I<prefs>

Read handling preferences from the I<prefs> file. See L<"FILES"> for
configuration details.

=item B<-c> I<class>

Specify a custom handling class, otherwise set to C<default>. The class
is read from the preferences file, see L<"FILES"> for details.

=item B<-l>

List allowed modes to standard output and exit.

=back

=head1 FILES

The preferences file specifies how to handle expiration dates. See below
for an example. At minimum, a named C<class> block should be created
with the name C<default>. This block should contain rules to handle
different conditions: C<expired> will be called if the data is expired,
followed by any C<window> blocks, ordered to process the shortest
durations first. If none match, a C<default> hander is called.

The first matching handler block will exit the script, with an
C<exit_value> of zero, unless a different C<exit_value> is set.

Blocks can include C<stdout> to print output, C<exec> to run named
commands, C<pipe> to send input to a named command, and C<exit_value> to
change the exit status of C<check-expire>. Aruguments to these options
can template information about the certificate and other data (see the
example below for the syntax, and the source for available parameters).

C<exec> and C<pipe> must be commands to run, not shell statements. If
shell code is needed, write a wrapper script, and execute that.

C<window> handlers must include a single C<inside> statement followed by
a duration in sections, or a shorthand duration such as C<7d>.

The following outputs values read by SiteScope. For expired or near-
expired data, errors are raised in SiteScope via the higher return
codes. Data expiring inside a month generates an e-mail, but no
SiteScope error.

<class default>
# default handler used if nothing else matches
<default>
stdout "Return Code: 0"
</default>

# higher return code if expiring inside 7 days, e-mail warnings
<window>
inside 7d

stdout "Return Code: 1"
exit_value 1

pipe expiring soon: %{extra.subject} | /bin/mail -s "cert warning" root
</window>

# just warn via e-mail if expiring inside 30 days
<window>
inside 30d

stdout "Return Code: 0"
pipe expiring soon: %{extra.subject} | /bin/mail -s "cert warning" root
</window>

# handler for expired data (equal to or past expiration date)
<expired>
exec /usr/bin/logger expired certificate: subject=%{extra.subject}

pipe <<END_PIPE
Expired certificate:
subject=%{extra.subject}
expired=%{time.expire_epoch}
command=%{program.name} %{program.argv}
| /bin/mail -s "expired cert" root
END_PIPE

stdout "Return Code: 2"
exit_value 2
</expired>

</class>

See L<Config::General|Config::General> for details on the configuration
file format.

=head1 BUGS

=head2 Reporting Bugs

Newer versions of this script may be available from:

http://github.com/thrig/sial.org-scripts/tree/master

If the bug is in the latest version, send a report to the author.
Patches that fix problems or add new features are welcome.

=head2 Known Issues

No known issues.

=head1 TODO

Mode handler for key=value output from a program, to facilitate
interface scripts to other arbitrary systems.

More metadata in %lookup (with modifying %lookup too much once doing
tests!), for humanized dates, time durations, and other details.

Document usage under Nagios or other interfaces.

Read things to check from preferences file and loop over, instead of
needing a different command run for each thing to check?

=head1 SEE ALSO

perl(1), s_client(1), x509(1)

=head1 AUTHOR

Jeremy Mates

=head1 COPYRIGHT

The author disclaims all copyrights and releases this script into the
public domain.

=cut
Something went wrong with that request. Please try again.