Skip to content

Instantly share code, notes, and snippets.

@AdrianAcala
Last active January 10, 2023 18:02
Show Gist options
  • Save AdrianAcala/ceb39151c294dca557834dffea3a03e5 to your computer and use it in GitHub Desktop.
Save AdrianAcala/ceb39151c294dca557834dffea3a03e5 to your computer and use it in GitHub Desktop.
Tests a certificate to see whether the certificate matches the domain name
#!/usr/bin/env python3
# Create a script that will check if the certificate matches the hostname of the server
# and if the certificate is valid
import socket
import ssl
import time
def check_dns_record(hostname, port):
"""This function checks if the provided hostname is a valid DNS record.
If the DNS record is valid, it will connect to the server and retrieve the SSL certificate.
It will then check the certificate details to see if the certificate matches the hostname.
:param hostname: The hostname to check
:param port: The port to connect to
:return: True if the certificate is valid, False otherwise
"""
# Resolve the DNS record for the hostname
try:
host = socket.gethostbyname(hostname)
print("Host: %s" % host)
except socket.gaierror:
print("Hostname could not be resolved. Exiting")
exit()
# Connect to the server and retrieve the SSL certificate
context = ssl.create_default_context()
with socket.create_connection((host, port)) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
cert = ssock.getpeercert()
print(cert)
# Check the certificate details
for key, value in cert.items():
if key == "subjectAltName":
for typ, dns in value:
if typ == "DNS" and dns == hostname:
print("Valid certificate")
return True
elif key == "subject":
for typ, dns in value[0]:
if typ == "commonName" and dns == hostname:
print("Valid certificate")
return True
else:
print("Invalid certificate")
def check_ssl_protocols(host, port):
# Get all the SSL protocols supported by the server
context = ssl.create_default_context()
with socket.create_connection((host, port)) as sock:
with context.wrap_socket(sock, server_hostname=host) as ssock:
print("SSL protocol: %s" % ssock.version())
def check_cipher_suites(host, port):
# Check the cipher suites supported by the server and ensure it is using AES or higher.
context = ssl.create_default_context()
with socket.create_connection((host, port)) as sock:
with context.wrap_socket(sock, server_hostname=host) as ssock:
if ssock.cipher() == None:
print("No cipher suite")
else:
print("Cipher suite: %s" % list(ssock.cipher()))
# Test every minute for the next 30 minutes
if __name__ == "__main__":
host = "www.google.com"
port = 443
for i in range(30):
check_dns_record(host, port)
check_ssl_protocols(host, port)
check_cipher_suites(host, port)
time.sleep(60)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment