0

I'm trying to get the list of CA certificates (and associated metadata (subject,issuer,notBefore,notAfter,etc) when the SSL connection is established.

I currently have this code:

import ssl
import socket

__ctx = ssl.create_default_context()

with __ctx.wrap_socket(socket.socket(), server_hostname=__hostname) as s:
    s.connect((__hostname, __port))
    __certificate = s.getpeercert()

I've tried:

    __certChain = __ctx.get_ca_certs()

But it seems to only show the Root Certificate Authority and not all the Certificate Authorities in the chain.

For example, connecting to apple.com shows the following information:

{
    "subject":
    [
        [
            [
                "countryName",
                "US"
            ]
        ],
        [
            [
                "organizationName",
                "DigiCert Inc"
            ]
        ],
        [
            [
                "organizationalUnitName",
                "www.digicert.com"
            ]
        ],
        [
            [
                "commonName",
                "DigiCert Global Root G3"
            ]
        ]
    ],
    "issuer":
    [
        [
            [
                "countryName",
                "US"
            ]
        ],
        [
            [
                "organizationName",
                "DigiCert Inc"
            ]
        ],
        [
            [
                "organizationalUnitName",
                "www.digicert.com"
            ]
        ],
        [
            [
                "commonName",
                "DigiCert Global Root G3"
            ]
        ]
    ],
    "version": 3,
    "serialNumber": "055556BCF25EA43535C3A40FD5AB4572",
    "notBefore": "Aug  1 12:00:00 2013 GMT",
    "notAfter": "Jan 15 12:00:00 2038 GMT"
}

Is there a function in the ssl/(other module) that would be able to get the list of Certificate Authorities in the chain for that connection (without having to establish a new connection)?

Any guidance is greatly appreciated!

Thanks!

  • The cert chain for a connection is (only) in the `SSLSocket` object, which doesn't appear to have a way to return any but the leaf cert. The `SSLContext` contains, and `.get_ca_certs` returns, the 'truststore' -- which is the root CAs used to _validate_ the various cert chains used on any number of connections that share the context. Your system apparently has a 'capath' type truststore, which is loaded only when used, unlike a 'cafile' truststore; if you use your `__ctx` to connect to a few dozen hosts you should see `get_ca_certs` accumulate the root certs used by _all_ of them. – dave_thompson_085 Oct 31 '22 at 05:45
  • *"But it seems to only show the Root Certificate Authority and not all the Certificate Authorities in the chain."* - looks to me like you want to get the certificate chain for the current TLS session and not only the leaf certificate - this is what `get_peer_cert_chain` does. – Steffen Ullrich Oct 31 '22 at 06:07

0 Answers0