Cross-platform listing all Root CA certificates in python

1k views Asked by At

I'm looking for a cross-platform way to list all Root CA certificates installed on the running computer.

I've tried using ssl.enum_certificates("root") but it is only supported on Windows

Retrieve certificates from Windows’ system cert store. store_name may be one of CA, ROOT or MY. Windows may provide additional cert stores, too. Availability: Windows | Python 3.4+

1

There are 1 answers

2
Jossef Harush Kadouri On

Almost cross-platform - I've wrote the following function to list installed root CA certs in Linux and Windows. See this for MacOS

Example:

import os
import ssl
from cryptography.hazmat.backends import default_backend
from cryptography import x509
import platform


def get_root_ca_certs(linux_certs_dir_path='/etc/ssl/certs'):
    system = platform.system().lower()
    backend = default_backend()

    if system == 'windows':
        items = ssl.enum_certificates("root")
        for cert_bytes, encoding, is_trusted in items:
            if encoding == "x509_asn":
                cert = x509.load_der_x509_certificate(cert_bytes, backend)
                yield cert

    elif system == 'linux':
        certs_file_names = os.listdir(linux_certs_dir_path)
        backend = default_backend()
        for cert_file_name in certs_file_names:
            cert_file_path = os.path.join(linux_certs_dir_path, cert_file_name)
            if not os.path.isfile(cert_file_path):
                continue

            with open(cert_file_path, 'rb') as f:
                cert_pem = f.read()
                cert = x509.load_pem_x509_certificate(cert_pem, backend)
                yield cert
    else:
        raise NotImplemented(f'missing implementation for this operating system="{system}"')


def main():
    root_ca_certs = get_root_ca_certs()
    root_ca_certs = list(root_ca_certs)  # you can load it into a list if you are planning multiple iterations

    for root_ca_cert in root_ca_certs:
        print(root_ca_cert.subject)


if __name__ == '__main__':
    main()

Output:

...
<Name(C=PL,O=Unizeto Sp. z o.o.,CN=Certum CA)>
<Name(C=US,ST=Washington,L=Redmond,O=Microsoft Corporation,CN=Microsoft ECC TS Root Certificate Authority 2018)>
<Name(C=US,ST=Arizona,L=Scottsdale,O=GoDaddy.com\, Inc.,CN=Go Daddy Root Certificate Authority - G2)>
<Name(C=RO,O=certSIGN,OU=certSIGN ROOT CA)>
<Name(C=US,O=DigiCert Inc,OU=www.digicert.com,CN=DigiCert High Assurance EV Root CA)>
<Name(OU=Copyright (c) 1997 Microsoft Corp.,OU=Microsoft Corporation,CN=Microsoft Root Authority)>