Skip to content

Instantly share code, notes, and snippets.

@evnchn
Created March 23, 2025 23:42
Show Gist options
  • Select an option

  • Save evnchn/b2ea50e5d4174af290a343a2f0cb51f2 to your computer and use it in GitHub Desktop.

Select an option

Save evnchn/b2ea50e5d4174af290a343a2f0cb51f2 to your computer and use it in GitHub Desktop.
import os
import ssl
import sys
from datetime import UTC, datetime
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
# Define log file path
LOG_FILE = "C:/Temp/windows_cert_check.log"
# Clear existing log file
if os.path.exists(LOG_FILE):
os.remove(LOG_FILE)
def log_message(message):
"""Write message to console and log file."""
sys.stdout.reconfigure(encoding="utf-8") # Ensure the console uses UTF-8
print(message)
with open(LOG_FILE, "a", encoding="utf-8") as log:
log.write(message + "\n")
def get_windows_certificates(store_name):
"""Retrieve certificates from Windows certificate store."""
certs = []
store = ssl.enum_certificates(store_name)
for cert in store:
try:
# Extract certificate data
cert_bytes, encoding, trust = cert
cert_obj = x509.load_der_x509_certificate(cert_bytes, default_backend())
# Extract details
subject = cert_obj.subject.rfc4514_string()
issuer = cert_obj.issuer.rfc4514_string()
valid_from = cert_obj.not_valid_before_utc
valid_until = cert_obj.not_valid_after_utc
certs.append(
{
"subject": subject,
"issuer": issuer,
"valid_from": valid_from,
"valid_until": valid_until,
"bytes": cert_bytes,
"object": cert_obj,
}
)
except Exception as e:
log_message(f"ERROR: Failed to load certificate from {store_name}: {str(e)}")
return certs
def check_certificate(cert):
"""Check certificate validity and structure."""
subject = cert["subject"]
issuer = cert["issuer"]
valid_from = cert["valid_from"]
valid_until = cert["valid_until"]
try:
# Ensure certificate is not expired
now = datetime.now(UTC)
if now < valid_from:
log_message(f"WARNING: Certificate {subject} is NOT YET VALID! (Valid from: {valid_from})")
elif now > valid_until:
log_message(f"WARNING: Certificate {subject} is EXPIRED! (Valid until: {valid_until})")
else:
log_message(f"VALID: Certificate {str(subject)}, Issuer: {str(issuer)}")
# Try serializing and reloading certificate (check for corruption)
cert_bytes = cert["object"].public_bytes(serialization.Encoding.PEM)
x509.load_pem_x509_certificate(cert_bytes, default_backend())
except Exception as e:
log_message(f"BAD CERTIFICATE: {subject}, Issuer: {str(issuer)} - ERROR: {str(e)}")
# Main execution
log_message("Checking Windows Certificate Store...\n")
for store in ["ROOT", "CA"]:
log_message(f"Checking store: {store}")
certificates = get_windows_certificates(store)
for cert in certificates:
check_certificate(cert)
log_message("\nScan complete. See log file for details: " + LOG_FILE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment