Friday, 28 June 2019

Determine if SSL certificate is self signed using Python

I am trying to determine if an SSL certificate is self signed or not. Currently I have the following code which compares the issuer CN and the subject CN and if they are the same, marks the result as self signed.

with open(cert_file, "r") as f: 
    x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, f.read())

result = {
    'subject': dict(x509.get_subject().get_components()),
    'issuer': dict(x509.get_issuer().get_components()),
    'serialNumber': x509.get_serial_number(),
    'version': x509.get_version(),
    'notBefore': datetime.strptime(x509.get_notBefore(), '%Y%m%d%H%M%SZ'),
    'notAfter': datetime.strptime(x509.get_notAfter(), '%Y%m%d%H%M%SZ'),
}

extensions = (x509.get_extension(i) for i in range(x509.get_extension_count()))
extension_data = {e.get_short_name(): str(e) for e in extensions}
result.update(extension_data)

if result['issuer']['CN'] == result['subject']['CN']:
    result.update({'self-signed': True})
else:
    result.update({'self-signed': False})

This comparison is very simplistic, but works in a lot of cases. I'm not trying to verify SSL certs or reimplement OpenSSL. How can I make this better and be roughly 95% sure if a certificate is self signed or not?

My one requirement is that I would like to do this in Python and not call other processes or use shell commands.



from Determine if SSL certificate is self signed using Python

No comments:

Post a Comment