-
Notifications
You must be signed in to change notification settings - Fork 2
/
tls_cert_plugin.py
52 lines (40 loc) · 1.53 KB
/
tls_cert_plugin.py
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
# TLS Certificate Expiration Plugin
# Returns the number of days remaining for the certificate on the give domain(s)
# Fetch latest CA certs
# sudo curl -O https://curl.haxx.se/ca/cacert.pem -o /etc/signalfx/cacert.pem
# Example configuration:
# - type: python-monitor
# scriptFilePath: "/usr/local/scripts/tls.py"
# domains: ["splunk.com", "github.com", "google.com"]
import datetime
import socket
import ssl
import logging
logger = logging.getLogger(__name__)
def ssl_expiry_datetime(hostname):
ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'
context = ssl.create_default_context(cafile='/etc/signalfx/cacert.pem')
conn = context.wrap_socket(
socket.socket(socket.AF_INET),
server_hostname=hostname,
)
# 3 second timeout
conn.settimeout(3.0)
conn.connect((hostname, 443))
ssl_info = conn.getpeercert()
# Parse the string from the certificate into a Python datetime object
return datetime.datetime.strptime(ssl_info['notAfter'], ssl_date_fmt)
def ssl_valid_time_remaining(hostname):
# Get the number of seconds left in a cert's lifetime
try:
expires = ssl_expiry_datetime(hostname)
except ssl.SSLError:
return datetime.timedelta(0)
return expires - datetime.datetime.utcnow()
def run(config, output):
domains = config.get("domains")
for domain in domains:
t = ssl_valid_time_remaining(domain)
t = t.total_seconds()
t = int(t) / 86400
output.send_gauge("days.remaining", t, {"domain": domain, "source": "tls_cert_expiration"})