1
0
Fork 0
promscripts/x509/expiry/metrics

78 lines
2.6 KiB
Bash
Executable File

#!/bin/bash
# Retrieve X.509 certificate expiry information for a given host and port
#
# Copyright (C) 2021 Mike Gerwitz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# This will produce `x509_expire_seconds`, `x509_expire_success`, and
#`x509_expire_scrape_duration_seconds`.
#
# WARNING: This script assumes trusted input and does not perform escaping
# of label values.
set -uo pipefail
cd "$(dirname "$0")"
main()
{
local host="${1?Missing domain}"
local -i port="${2?Missing port}"
local -ri start=$( date +%s%3N )
local expire_date expire_ts=0 ok=0
expire_date=$( openssl s_client -showcerts \
-connect "$host":"$port" \
2>/dev/null \
</dev/null \
| openssl x509 -noout -dates \
| grep ^notAfter \
| cut -d= -f2 )
ok=$(( PIPESTATUS[0] == 0 ))
(( ok == 1 )) && expire_ts=$( date --date="$expire_date" +%s )
local -i expire_in=$(( expire_ts - EPOCHSECONDS ))
local -ri end=$( date +%s%3N )
local -ri duration_s=$(( ( end - start ) / 1000 ))
local -ri duration_ms=$(( ( end - start ) % 1000 ))
# Note that this does not perform any escaping; it assumes trusted input.
local labels=$( printf 'domain="%s", port="%d"' "$host" "$port" )
if [[ "$ok" == 1 ]]; then
echo -n '# HELP x509_expire_seconds '
echo 'Number of seconds until X.509 certificate reaches its "not after" date.'
echo '# TYPE x509_expire_seconds gauge'
printf 'x509_expire_seconds{%s} %d\n' "$labels" "$expire_in"
fi
echo -n '# HELP x509_expire_success '
echo 'Whether the certificate was successfully retrieved and parsed.'
echo '# TYPE x509_expire_success gauge'
printf 'x509_expire_success{%s} %d\n' "$labels" "$ok"
echo -n '# HELP x509_expire_scrape_duration_seconds '
echo 'Number of seconds spent retrieving and parsing certificate expiry data.'
echo '# TYPE x509_expire_scrape_duration_seconds gauge'
printf 'x509_expire_scrape_duration_seconds{%s} %0.3f\n' \
"$labels" \
"$duration_s.$duration_ms"
}
main "$@"