TExcelTAD
Home › Programming for Security: Python, Bash, PowerShell & C Tools › Project: TLS Certificate Inspector

Project: TLS Certificate Inspector

Expired certificates take down more services than attackers do, and badly issued ones (wrong host name, a self-signed test certificate in production, a weak key, a missing intermediate) are a staple of audit reports. A certificate inspector reads a certificate and answers the questions an operator or auditor asks: who is it for, who issued it, when does it expire, does it match this host name, is the key strong enough, does it chain to the CA we trust? This project builds one with Python's cryptography library, first on certificates the example generates itself, then on the lab PKI in the sandbox together with openssl. How X.509 and TLS work is the subject of Applied Cryptography; here we read the fields.

Definitions

  • X.509 certificate (RFC 5280): a public key plus a subject (who), an issuer (who vouches), a validity period (notBefore, notAfter), a serial number and extensions, all signed by the issuer.
  • Subject Alternative Name (SAN): the host names (and addresses) the certificate is valid for. Browsers ignore the subject's CN and use only the SAN; the CA/Browser Forum Baseline Requirements make the SAN mandatory for public certificates.
  • Basic Constraints: CA:TRUE lets a certificate sign other certificates; a server certificate must have CA:FALSE.
  • Chain: leaf → intermediate(s) → root. Each certificate's signature is checked with the public key of the next; the root is trusted because it is in the trust store.
  • Fingerprint: a hash (SHA-256) of the whole certificate, used to pin or identify it.

Version 1: inspect certificates made in the example

The example creates a small lab CA and three leaf certificates with fixed dates: a good one, an expired one, and one signed by an unknown CA. Key generation is random, so the example prints only properties that don't depend on the key bytes. The inspection clock is fixed at 2026-01-15 so the verdicts are stable; a real tool uses the current time.

python · try it yourself
import datetime as dt
from cryptography import x509
from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec

UTC = dt.timezone.utc
NOW = dt.datetime(2026, 1, 15, tzinfo=UTC)        # fixed inspection time for this example

def name(cn):
    return x509.Name([x509.NameAttribute(NameOID.ORGANIZATION_NAME, "ExcelTAD Lab"),
                      x509.NameAttribute(NameOID.COMMON_NAME, cn)])

def make(subject, issuer, issuer_key, start, end, sans=None, ca=False):
    key = ec.generate_private_key(ec.SECP256R1())
    b = (x509.CertificateBuilder().subject_name(name(subject)).issuer_name(name(issuer))
         .public_key(key.public_key()).serial_number(0x2001 + len(subject))
         .not_valid_before(start).not_valid_after(end)
         .add_extension(x509.BasicConstraints(ca=ca, path_length=0 if ca else None), critical=True))
    if sans:
        b = b.add_extension(x509.SubjectAlternativeName([x509.DNSName(s) for s in sans]), critical=False)
        b = b.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)
    return b.sign(issuer_key or key, hashes.SHA256()), key

d = lambda y, m, day: dt.datetime(y, m, day, tzinfo=UTC)
ca, ca_key = make("Lab Root CA", "Lab Root CA", None, d(2026, 1, 1), d(2036, 1, 1), ca=True)
rogue, rogue_key = make("Unknown CA", "Unknown CA", None, d(2026, 1, 1), d(2036, 1, 1), ca=True)
good, _ = make("lab.test", "Lab Root CA", ca_key, d(2026, 1, 1), d(2026, 3, 1), ["lab.test", "www.lab.test"])
old, _ = make("old.lab.test", "Lab Root CA", ca_key, d(2024, 1, 1), d(2025, 1, 1), ["old.lab.test"])
other, _ = make("lab.test", "Unknown CA", rogue_key, d(2026, 1, 1), d(2027, 1, 1), ["lab.test"])

def inspect(cert, host, trusted, warn_days=30):
    issues = []
    left = (cert.not_valid_after_utc - NOW).days
    if NOW < cert.not_valid_before_utc:
        issues.append("not yet valid")
    if left < 0:
        issues.append(f"EXPIRED {-left} days ago")
    elif left < warn_days:
        issues.append(f"expires in {left} days")
    try:
        sans = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value.get_values_for_type(x509.DNSName)
    except x509.ExtensionNotFound:
        sans = []
    if host not in sans and not any(s.startswith("*.") and host.split(".", 1)[-1] == s[2:] for s in sans):
        issues.append(f"host {host!r} not in SAN {sans}")
    if cert.extensions.get_extension_for_class(x509.BasicConstraints).value.ca:
        issues.append("CA certificate used as server certificate")
    try:
        cert.verify_directly_issued_by(trusted)
    except Exception as e:
        issues.append(f"not issued by trusted CA ({type(e).__name__})")
    key = cert.public_key()
    print(f"{cert.subject.rfc4514_string():<32} issuer={cert.issuer.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value:<12}"
          f" {cert.not_valid_after_utc:%Y-%m-%d} key={type(key).__name__.lstrip('_')}-{key.key_size}"
          f" sig={cert.signature_hash_algorithm.name}")
    print("   ", "OK" if not issues else "; ".join(issues))

for cert, host in [(good, "www.lab.test"), (good, "mail.lab.test"), (old, "old.lab.test"), (other, "lab.test"), (ca, "lab.test")]:
    inspect(cert, host, ca)
CN=lab.test,O=ExcelTAD Lab       issuer=Lab Root CA  2026-03-01 key=ECPublicKey-256 sig=sha256
    OK
CN=lab.test,O=ExcelTAD Lab       issuer=Lab Root CA  2026-03-01 key=ECPublicKey-256 sig=sha256
    host 'mail.lab.test' not in SAN ['lab.test', 'www.lab.test']
CN=old.lab.test,O=ExcelTAD Lab   issuer=Lab Root CA  2025-01-01 key=ECPublicKey-256 sig=sha256
    EXPIRED 379 days ago
CN=lab.test,O=ExcelTAD Lab       issuer=Unknown CA   2027-01-01 key=ECPublicKey-256 sig=sha256
    not issued by trusted CA (ValueError)
CN=Lab Root CA,O=ExcelTAD Lab    issuer=Lab Root CA  2036-01-01 key=ECPublicKey-256 sig=sha256
    host 'lab.test' not in SAN []; CA certificate used as server certificate

Each line is a typical audit finding. The good certificate passes for www.lab.test (45 days left, above the 30-day warning) and fails for mail.lab.test, which isn't in its SAN. The old one expired a year ago. The certificate from the unknown CA has the right name and dates but fails the check against the trusted CA, which is exactly how a man-in-the-middle certificate looks. Here the issuer name already differs (ValueError); a forgery that copies the issuer name fails on the signature instead. Presenting the CA certificate itself as a server certificate is flagged too.

Version 2: the lab PKI, with Python and OpenSSL

The sandbox image has a lab PKI in $SAMPLES/pki (RSA 2048 keys made from a fixed seed: lab-only, never for real use). The inspector below is the same logic for the image's cryptography 41, which names the validity fields not_valid_before/not_valid_after without the _utc suffix. openssl gives the reference view; -attime fixes the verification time, so the result does not depend on the day the session is run.

bash · try it yourself
cd "$SAMPLES/pki"
cat > /tmp/certinspect.py <<'PY'
import datetime as dt, sys
from cryptography import x509
from cryptography.hazmat.primitives import hashes
NOW = dt.datetime(2026, 1, 15)
for path in sys.argv[1:]:
    c = x509.load_pem_x509_certificate(open(path, "rb").read())
    sans = c.extensions.get_extension_for_class(x509.SubjectAlternativeName).value.get_values_for_type(x509.DNSName)
    left = (c.not_valid_after - NOW).days
    state = "EXPIRED" if left < 0 else f"{left} days left"
    print(f"{path:<22} serial=0x{c.serial_number:x} san={sans} until={c.not_valid_after:%Y-%m-%d} ({state})"
          f" rsa={c.public_key().key_size} sha256={c.fingerprint(hashes.SHA256()).hex()[:16]}")
PY
python3 /tmp/certinspect.py lab.test.crt expired.lab.test.crt
echo "== openssl view"
openssl x509 -in lab.test.crt -noout -subject -issuer -dates -serial -ext subjectAltName,basicConstraints
echo "== chain verification at 2026-01-15"
openssl verify -attime 1768435200 -CAfile ca.crt lab.test.crt 2>&1
openssl verify -attime 1768435200 -CAfile ca.crt expired.lab.test.crt 2>&1 | tail -n 2
openssl verify -attime 1768435200 -CAfile lab.test.crt lab.test.crt 2>&1 | tail -n 2
lab.test.crt           serial=0x1002 san=['lab.test', 'www.lab.test'] until=2028-01-01 (716 days left) rsa=2048 sha256=e2c62753ce101eab
expired.lab.test.crt   serial=0x1003 san=['expired.lab.test'] until=2021-01-01 (EXPIRED) rsa=2048 sha256=6fec108240972460
== openssl view
subject=C = XX, O = ExcelTAD Lab, OU = Web, CN = lab.test
issuer=C = XX, O = ExcelTAD Lab, CN = ExcelTAD Lab Root CA
notBefore=Jan  1 00:00:00 2026 GMT
notAfter=Jan  1 00:00:00 2028 GMT
serial=1002
X509v3 Basic Constraints: critical
    CA:FALSE
X509v3 Subject Alternative Name:
    DNS:lab.test, DNS:www.lab.test
== chain verification at 2026-01-15
lab.test.crt: OK
error 10 at 0 depth lookup: certificate has expired
error expired.lab.test.crt: verification failed
error 20 at 0 depth lookup: unable to get local issuer certificate
error lab.test.crt: verification failed

The Python and OpenSSL views agree on serial, SAN and dates. openssl verify accepts the lab certificate against the lab CA, rejects the expired one with error 10, and rejects the leaf when it is offered as its own trust anchor (error 20, "unable to get local issuer certificate"): a leaf can't vouch for itself.

How certificate problems are detected

  • Inventory and expiry monitoring: run the inspector over every certificate file and every TLS endpoint you operate (in your own network: openssl s_client -connect host:443 -servername host feeds it), and alert at 30 and 7 days. Certificate lifetimes are shrinking (under CA/Browser Forum ballot SC-081 the maximum for public TLS certificates fell from 398 to 200 days on 15 March 2026, falls to 100 days in March 2027 and to 47 days in March 2029), so manual renewal no longer works.
  • Certificate Transparency logs list every publicly trusted certificate issued for your domains; monitoring them reveals certificates you didn't request.
  • Configuration scanners (testssl.sh, sslyze, in a lab or on your own hosts) check chains, protocol versions and ciphers.

How they are fixed or prevented

  1. Automate issuance and renewal with ACME (Let's Encrypt, an internal ACME CA) and treat expiry as a monitored metric.
  2. Serve the full chain (leaf plus intermediates) and test with a client that has only the root.
  3. Put every name in the SAN, avoid broad wildcards, and never deploy self-signed or test certificates outside the lab.
  4. Strong keys and signatures: RSA 2048 bits or more, or ECDSA P-256; SHA-256 signatures; no SHA-1.
  5. Clients must verify: verify=False in requests, -k in curl and custom trust managers that accept everything turn TLS into decoration.

Pitfalls

  • A script called inspect.py (or ssl.py, json.py) shadows the standard module of that name: the first draft of this session's script was named inspect.py, and cryptography's own import inspect loaded it instead. Name tools distinctively and run them with python3 -I where the directory is not trusted.
  • Naive datetimes: cryptography 42 and later deprecate not_valid_after in favour of not_valid_after_utc; comparing a naive and an aware datetime raises TypeError.
  • Checking the CN: modern clients ignore it; check the SAN.
  • verify_directly_issued_by checks one link only. Full path validation (name constraints, key usage, revocation) needs a real verifier such as cryptography's x509.verification module or OpenSSL.
  • Private keys next to certificates in a world-readable directory, or committed to a repository: inspect permissions too.

Practice

1. Add a check that warns when the validity period is longer than 398 days. Which of the example's certificates would it flag?

Compute (c.not_valid_after_utc - c.not_valid_before_utc).days > 398. Only the two CA certificates (10 years) are flagged; other has 365 days. Public TLS leaf certificates were limited to 398 days from September 2020 until 15 March 2026, when ballot SC-081 lowered the limit to 200 days (100 from March 2027, 47 from March 2029); with 200 the check would also flag other and old (366 days). CA certificates are not subject to these limits, so apply the check to leaf certificates only.

2. How would you inspect the certificate of a lab web server at 10.10.0.10:443?

From inside the lab, openssl s_client -connect 10.10.0.10:443 -servername lab.test -showcerts </dev/null prints the chain; save the PEM blocks and run the inspector on them. In Python, ssl.get_server_certificate(("10.10.0.10", 443)) returns the leaf in PEM. Only for hosts you operate or are authorised to test.

3. Why does the session pass -attime to openssl verify?

Without it OpenSSL uses the current time, so the result for lab.test.crt would change from OK to "expired" after 1 January 2028. Fixing the time makes the check reproducible; in monitoring you want the real time.

Test yourself

Which field do modern browsers use to match a certificate to a host name?

  1. Subject CN
  2. Subject Alternative Name
  3. Issuer
  4. Serial number

The certificate from the unknown CA has the right name and dates. What check fails?

  1. Expiry
  2. Host name
  3. Issuance by the trusted CA (issuer and signature)
  4. Key size

What does openssl verify error 10 mean?

  1. Unknown issuer
  2. Certificate has expired
  3. Self-signed certificate
  4. Hostname mismatch

Which Basic Constraints value must a server (leaf) certificate have?

  1. CA:TRUE
  2. CA:FALSE
  3. pathlen:0
  4. No constraint