Getting the Complete SSL Trust Chain of a Website

 

A few words about Trust chains


Trust chains are present all over the internet. Whenever a server is configured to use HTTPS, we know there is a trust chain working behind the scenes.
A trust chain is composed of multiple certificates, often three:

  • Leaf certificate
  • Intermediate certificate
  • Root certificate

Each of these certificates has a different lifetime. Leaf certificates usually last only a few months, intermediate certificates can last several years, and root certificates can remain valid for decades. 

In most situations we don't need to interact with the trust chain directly. The browser and the operating system handle that automatically. However, in some cases it becomes useful to retrieve the entire chain.

 

Installing get-certificate-chain

pip install get-certificate-chain

Official documentation:
 https://pypi.org/project/get-certificate-chain/

 

Collecting the trust chain

from get_certificate_chain.download import SSLCertificateChainDownloader
from cryptography.hazmat.primitives import serialization


host = "www.jaimedcsilva.com"


downloader = SSLCertificateChainDownloader()

cert = downloader.get_certificate(host=host, port=443)
downloader.cert_chain.append(cert)

downloader.walk_the_chain(cert, 1, max_depth=4)


for certificate in downloader.cert_chain:
    print(certificate.subject.rfc4514_string())
    print(certificate.public_bytes(serialization.Encoding.PEM).decode())
    
# Example Output

CN=****...
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----

...