I have a piece of code that will return the validity dates for the last certificate listed in a tls.handshake.type == 11 packet. I want to pull all the certificates within the packet and check the validity dates for them all. Here is the code snippet I currently have. I am using pyshark.
def get_certificate_expiry_tls(pcap_file,destination=""):
capture = pyshark.FileCapture(pcap_file, display_filter='tls.handshake.type == 11')
found = False
for packet in capture:
dest_ip = ip_version(packet)
if (destination !="" and dest_ip == destination) or destination == "":
cert_hex = packet.tls.handshake_certificate
certificate_bytes = bytes.fromhex(cert_hex.replace(":", "").replace(" ", ""))
certificate = x509.load_der_x509_certificate(certificate_bytes, default_backend())
# Extract certificate details
issuer = certificate.issuer
cert_sn = certificate.serial_number
not_before = datetime.strptime(str(certificate.not_valid_before), "%Y-%m-%d %H:%M:%S")
not_after = datetime.strptime(str(certificate.not_valid_after), "%Y-%m-%d %H:%M:%S")
days_left = (not_after - datetime.now()).days
too_early = False
too_late = False
if not_before > datetime.now():
too_early = True
if datetime.now() > not_after:
too_late = True
print(f'Certificate Validity for destination {dest_ip}')
print(f'Issuer: {issuer}')
print(f'Serial Number: {cert_sn}')
if too_early:
print(f'>>>Not Before: {not_before}<<<')
else:
print(f' Not Before: {not_before}')
if too_late:
print(f'>>>Not After: {not_after}<<<')
else:
print(f' Not After: {not_after}')
print(f' Days Left: {days_left} days')
print('---')
found = True
if not found:
print(f'No certificate found on destination {destination}')
capture.close()
return()
Output looks like this for the certificate found for example:
Certificate Validity for destination 40.126.24.146
Issuer: <Name(C=US,O=DigiCert Inc,CN=DigiCert SHA2 Secure Server CA)>
Serial Number: 3287290595213795316696678255992371503
Not Before: 2023-04-05 00:00:00
Not After: 2024-04-05 23:59:59
Days Left: 303 days
---
This packet contains two certificates but I can only display the one.
Wireshark output of packet
I want to display both certificates in the output with their validity date ranges. The purpose of this code is to quickly identify a certificate that has expired.