#!/usr/bin/python3

# Michele Baldessari - Leitner Technologies - 2011
# 23.08.2011

import datetime
import getopt
import os
import pprint
import subprocess
import sys
import tempfile
import urllib.request, urllib.parse, urllib.error

def check_crl(url, warn, crit):
    tmpcrl = tempfile.mktemp("crl")
    urllib.request.urlretrieve(url, tmpcrl)
    ret = subprocess.check_output(["/usr/bin/openssl", "crl", "-inform", "DER", "-noout", "-nextupdate", "-in", tmpcrl])
    nextupdate = ret.strip().decode('utf-8').split("=")
    os.remove(tmpcrl)
    eol = datetime.datetime.strptime(nextupdate[1],"%b %d %H:%M:%S %Y GMT")
    today = datetime.datetime.now()
    delta = eol - today
    days = delta.days
    if days > crit and days <= warn:
        msg = "WARNING CRL Expires in %s days (on %s)" % (days, eol)
        exitcode = 1
    elif days < crit:
        msg = "CRITICAL CRL Expires in %s days (on %s)" % (days, eol)
        exitcode = 2
    else:
        msg = "OK CRL Expires in %s days (on %s)" % (days, eol)
        exitcode = 0
	
    print (msg)
    sys.exit(exitcode)

def usage():
    print ("check_crl.py -h|--help -v|--verbose -u|--url=<url> -w|--warning=<days> -c|--critical=<days>")

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hu:w:c:", ["help", "url=", "warning=", "critical="])
    except getopt.GetoptError as err:
        usage()
        sys.exit(2)
    url = None
    warning = None
    critical = None
    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-u", "--url"):
            url = a
        elif o in ("-w", "--warning"):
            warning = a
        elif o in ("-c", "--critical"):
            critical = a
        else:
            assert False, "unhandled option"

    if url != None and warning != None and critical != None:
        check_crl(url, int(warning), int(critical))
    else:
        usage()
        sys.exit(2)  


if __name__ == "__main__":
    main()


