Analyzing TLS Certificates of Websites Using Python

  ·   3 min read

In today’s world, cybersecurity is paramount, and understanding the state of TLS (Transport Layer Security) certificates is essential for ensuring secure communications over the internet. As a DevOps engineer, you might find yourself needing to audit websites to verify their TLS configurations. Fortunately, Python provides a suite of libraries that make this task straightforward.

In this article, we will create a Python script that accepts a domain name as a command-line argument, analyzes its TLS certificate, and provides detailed information such as:

  • Certificate validity periods (start and end dates)
  • Security cipher suites
  • Subject Alternative Names (SANs) — the domains the certificate is valid for

Let’s dive into the implementation.

Prerequisites

Before we start writing our script, ensure you have the following:

  1. Python installed on your machine (version 3.6 or later).
  2. The ssl and socket libraries, which are built into Python.
  3. The third-party cryptography library. You can install it via pip:
pip install cryptography

The Python Script

Below is the complete script that performs the operations mentioned:

import ssl
import socket
import sys
from datetime import datetime
from cryptography.x509 import load_pem_x509_certificate
from cryptography.hazmat.backends import default_backend

def get_tls_cert(domain):
    port = 443  # default HTTPS port
    context = ssl.create_default_context()

    with socket.create_connection((domain, port)) as conn:
        with context.wrap_socket(conn, server_hostname=domain) as sock:
            cert = sock.getpeercert(True)
            return cert

def parse_cert(cert):
    certificate = load_pem_x509_certificate(cert, default_backend())
    return certificate

def print_cert_info(certificate):
    subject = certificate.subject
    issuer = certificate.issuer
    version = certificate.version
    not_before = certificate.not_valid_before
    not_after = certificate.not_valid_after
    san_list = certificate.extensions.get_extension_for_class(cryptography.x509.SubjectAlternativeName).value

    print(f"Subject: {subject}")
    print(f"Issuer: {issuer}")
    print(f"Version: {version.name}")
    print(f"Validity Period: {not_before} to {not_after}")
    print(f"Subject Alternative Names: {[d for d in san_list]}")

def main(domain):
    try:
        cert = get_tls_cert(domain)
        certificate = parse_cert(cert)
        print_cert_info(certificate)

    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python analyze_tls_cert.py <domain>")
        sys.exit(1)

    domain = sys.argv[1]
    main(domain)

How the Script Works

  1. Getting the TLS Certificate:

    • The get_tls_cert function establishes a socket connection to the specified domain on port 443 (the default for HTTPS).
    • It uses SSL to wrap the socket and retrieve the peer certificate in PEM format.
  2. Parsing the Certificate:

    • The parse_cert function utilizes the cryptography library to load and parse the retrieved certificate.
  3. Displaying the Certificate Information:

    • The print_cert_info function extracts and displays various properties of the certificate including the subject, issuer, validity dates, and Subject Alternative Names (SANs).
  4. Driver Functionality:

    • The main function fetches the argument from the command line, invokes the certificate retrieval, and handles exceptions.

Running the Script

To execute the script, save it as analyze_tls_cert.py and run it by providing a domain name:

python analyze_tls_cert.py example.com

This command will output the validity, subject, issuer, and other relevant details about the TLS certificate for example.com.

Conclusion

Automating TLS certificate checks is crucial for maintaining a secured and compliant web presence. The Python script provided gives you a foundational approach that you can extend as per your requirements.

Additional Resources

This foundational knowledge of interacting with TLS certificates using Python is vital for any serious DevOps engineer, particularly when automating security audits and compliance checks. Happy coding!