Skip to content

Instantly share code, notes, and snippets.

@kgriffs
Last active April 8, 2021 01:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kgriffs/a460b3d659f38b4e7d941468a1e665e9 to your computer and use it in GitHub Desktop.
Save kgriffs/a460b3d659f38b4e7d941468a1e665e9 to your computer and use it in GitHub Desktop.
Validate a server's certificate in Python 3 using only the standard library + certifi
import datetime
from enum import Enum
import socket
import ssl
import certifi
class CertificateStatus(Enum):
UNKNOWN = -1
CONNECTION_ERROR = 100
VALID = 200
INVALID = 500
def get_cert(host_ip, sni_name, port=443):
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.load_verify_locations(certifi.where())
status = CertificateStatus.UNKNOWN
peer_cert = None
try:
with socket.create_connection((host_ip, port), timeout=5) as sock:
with context.wrap_socket(sock, server_hostname=sni_name) as ssock:
peer_cert = ssock.getpeercert()
status = CertificateStatus.VALID
except ssl.SSLError:
status = CertificateStatus.INVALID
except Exception:
status = CertificateStatus.CONNECTION_ERROR
return status, peer_cert
def get_cert_ttl_days(cert):
exp_date = datetime.datetime.strptime(cert['notAfter'], '%b %d %H:%M:%S %Y GMT')
cur_date = datetime.datetime.utcnow()
days_to_expire = int((exp_date - cur_date).days)
return days_to_expire
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment