2015-10-04 23:02:04 +02:00
|
|
|
# -*- coding: utf8 -*-
|
2020-03-04 19:33:23 +01:00
|
|
|
"""
|
2015-10-04 23:02:04 +02:00
|
|
|
Manage X.509 certificate life cycle
|
|
|
|
===================================
|
|
|
|
|
|
|
|
This state is useful for managing X.509 certificates' life cycles.
|
|
|
|
|
2020-03-04 19:33:23 +01:00
|
|
|
Copyright (c) 2014-2020 Jan Dittberner <jan@dittberner.info>
|
|
|
|
"""
|
2015-10-04 23:02:04 +02:00
|
|
|
|
2016-09-24 21:51:02 +02:00
|
|
|
from cryptography import x509
|
|
|
|
from cryptography.hazmat.backends import default_backend
|
2015-10-04 23:02:04 +02:00
|
|
|
from datetime import datetime
|
|
|
|
import os
|
|
|
|
|
|
|
|
|
|
|
|
def _error(ret, err_msg):
|
2020-03-04 19:33:23 +01:00
|
|
|
ret["result"] = False
|
|
|
|
ret["comment"] = err_msg
|
2015-10-04 23:02:04 +02:00
|
|
|
return ret
|
|
|
|
|
|
|
|
|
|
|
|
def valid_certificate(
|
2020-03-04 19:33:23 +01:00
|
|
|
name, mindays=14, keyfile=None, checkchain=False, trustedcerts=None
|
|
|
|
):
|
|
|
|
"""
|
2015-10-04 23:02:04 +02:00
|
|
|
Checks whether the given certificate file is valid.
|
|
|
|
|
|
|
|
name
|
|
|
|
The name of the certificate file to check
|
|
|
|
mindays
|
|
|
|
Mark the certificate as invalid if it is valid for less then this many
|
|
|
|
days
|
2020-03-04 19:33:23 +01:00
|
|
|
"""
|
|
|
|
ret = {"name": name, "changes": {}, "result": None, "comment": ""}
|
2015-10-04 23:02:04 +02:00
|
|
|
if not os.path.isfile(name):
|
2020-03-04 19:33:23 +01:00
|
|
|
return _error(ret, "certificate file {0} does not exist".format(name))
|
|
|
|
with open(name, "rb") as pemfile:
|
2016-09-24 21:51:02 +02:00
|
|
|
try:
|
2020-03-04 19:33:23 +01:00
|
|
|
cert = x509.load_pem_x509_certificate(pemfile.read(), default_backend())
|
2016-09-24 21:51:02 +02:00
|
|
|
except Exception as e:
|
2020-03-04 19:33:23 +01:00
|
|
|
return _error(ret, "error loading certificate {0}: {1}".format(name, e))
|
2016-09-24 21:51:02 +02:00
|
|
|
notafter = cert.not_valid_after
|
|
|
|
delta = notafter - datetime.utcnow()
|
2015-10-04 23:02:04 +02:00
|
|
|
if delta.days < mindays:
|
|
|
|
return _error(
|
|
|
|
ret,
|
2020-03-04 19:33:23 +01:00
|
|
|
"certificate {0} is only valid for {1} more day(s)".format(
|
|
|
|
name, delta.days
|
|
|
|
),
|
|
|
|
)
|
2015-10-04 23:02:04 +02:00
|
|
|
# TODO: check keyfile match
|
|
|
|
# TODO: check trust chain
|
2020-03-04 19:33:23 +01:00
|
|
|
ret["comment"] = "certificate {0} is ok and still valid for {1} days".format(
|
|
|
|
name, delta.days
|
|
|
|
)
|
|
|
|
ret["result"] = True
|
2015-10-04 23:02:04 +02:00
|
|
|
return ret
|