Search code examples
pythonsslssl-certificatesni

ssl.get_server_certificate for sites with SNI (Server Name Indication)


I am trying to get the server certificate of badssl.com subdomains (ex. https://expired.badssl.com).

import ssl
ssl.get_server_certificate(('expired.badssl.com', 443))

But when examining the above generated certificate I see that the certificate has

Identity: badssl-fallback-unknown-subdomain-or-no-sni

which means SNI is failing. How can I get the server certificate of different subdomains of badssl.com? (I am using python 2.7.12)


Solution

  • Found the answer.

    import ssl
    hostname = "expired.badssl.com"
    port = 443
    conn = ssl.create_connection((hostname, port))
    context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    sock = context.wrap_socket(conn, server_hostname=hostname)
    certificate = ssl.DER_cert_to_PEM_cert(sock.getpeercert(True))