Search code examples
pythonhttpsurllib3

Retrieve server certificate in urllib3


In python's urllib3, can one retrieve the server certificate after making a successful HTTPS request? If so, how?


Solution

  • There doesn't seem to be a direct way that I can find. It seems that urllib3 uses the standard python ssl.SSLSocket under the hood. This has several methods that might be useful, see the details in the link, but the one that seems to provide what you want is getpeercert().

    Here is a small example to illustrate:

    from cryptography.x509 import load_der_x509_certificate
    from urllib3.connection import HTTPSConnection
    
    https_conn = HTTPSConnection("example.com", server_hostname="example.com")
    https_conn.connect()
    ssl_sock = https_conn.sock
    cert1 = ssl_sock.getpeercert(binary_form=False)
    # cert1 is a dict with many useful fields. Might be all you need
    print(cert1)
    cert2 = ssl_sock.getpeercert(binary_form=True)
    # cert2 is the full DER encoded certificate, which you can supply to
    # other libraries to do more advanced stuff
    x509_cert = load_der_x509_certificate(cert2)
    print(x509_cert.serial_number)
    

    Note that this just makes the connection, nothing useful has been done yet.