From 643b0747cfb03547793049693df1fa919c48c8b6 Mon Sep 17 00:00:00 2001 From: James Hale Date: Sat, 25 Dec 2021 08:34:43 -0500 Subject: [PATCH] Check expiry in hours --- CHANGELOG.md | 3 +++ bin/check-ssl-cert.rb | 39 ++++++++++++++++++++++++++------------- 2 files changed, 29 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e3e9596..e92bac9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ This CHANGELOG follows the format listed [here](https://github.com/sensu-plugins ## [Unreleased] +### Added +- `check-ssh-cert.rb` can now calculate expiry in hours, instead of days. + ### Changed - Removed centos build from .bonsai.yml diff --git a/bin/check-ssl-cert.rb b/bin/check-ssl-cert.rb index a2b99f2..766b950 100755 --- a/bin/check-ssl-cert.rb +++ b/bin/check-ssl-cert.rb @@ -29,7 +29,7 @@ # for details. # -require 'date' +require 'time' require 'openssl' require 'sensu-plugin/check/cli' @@ -38,15 +38,15 @@ # class CheckSSLCert < Sensu::Plugin::Check::CLI option :critical, - description: 'Numbers of days left', + description: 'Time (hours or days) left', short: '-c', - long: '--critical DAYS', + long: '--critical TIME', required: true option :warning, - description: 'Numbers of days left', + description: 'Time (hours or days) left', short: '-w', - long: '--warning DAYS', + long: '--warning TIME', required: true option :pem, @@ -79,6 +79,11 @@ class CheckSSLCert < Sensu::Plugin::Check::CLI short: '-S', long: '--pass ' + option :hours, + description: 'Calculate expiry in hours, instead of days. Useful for short-lived (<24h) ACME certs', + short: '-H', + long: '--hours' + def ssl_cert_expiry `openssl s_client -servername #{config[:servername]} -connect #{config[:host]}:#{config[:port]} < /dev/null 2>&1 | openssl x509 -enddate -noout`.split('=').last end @@ -117,16 +122,24 @@ def run ssl_cert_expiry end - days_until = (Date.parse(expiry.to_s) - Date.today).to_i + time_delta = Time.parse(expiry.to_s) - Time.now + + if config[:hours] + time_delta_check = (time_delta / 3600).floor + time_check_unit = 'hours' + else + time_delta_check = (time_delta / 86_400).floor + time_check_unit = 'days' + end - if days_until < 0 # rubocop:disable Style/NumericPredicate - critical "Expired #{days_until.abs} days ago" - elsif days_until < config[:critical].to_i - critical "#{days_until} days left" - elsif days_until < config[:warning].to_i - warning "#{days_until} days left" + if time_delta_check < 0 # rubocop:disable Style/NumericPredicate + critical "Expired #{time_delta_check} #{time_check_unit} ago" + elsif time_delta_check < config[:critical].to_i + critical "#{time_delta_check} #{time_check_unit} left" + elsif time_delta_check < config[:warning].to_i + warning "#{time_delta_check} #{time_check_unit} left" else - ok "#{days_until} days left" + ok "#{time_delta_check} #{time_check_unit} left" end end end