Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A Python script that uses M2Crypto to check the validity of an SSL certificate.
from M2Crypto import SSL
from M2Crypto.SSL.Checker import SSLVerificationError, NoCertificate, WrongCertificate, WrongHost
import socket, re
from datetime import datetime
import pytz
class ValidationResults:
def __init__(self):
self.connection_error = False
self.no_certificate = False
self.wrong_certificate = False
self.wrong_host = False
self.certificate_expired = False
self.expiration_date = None
self.unknown_error = False
self.inner_exception = None
def __str__(self):
return """
Connection error:\t%s
No certificate:\t\t%s
Wrong certificate:\t%s
Wrong host:\t\t%s
Certificate expired:\t%s
Expiration date:\t%s
Unknown error:\t\t%s
Inner exception:\t%s
""" % (self.connection_error,
class Validator:
numericIpMatch = re.compile('^[0-9]+(\.[0-9]+)*$')
valid_hostname = False
def __init__(self):
def __call__(self, hostname, get_cert_from, port):
val_results = ValidationResults()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
cxt = SSL.Context()
cxt.set_verify(SSL.verify_none, depth=1)
SSL.Connection.clientPostConnectionCheck = None # we'll verify things later manually!
c = SSL.Connection(cxt, sock)
c.connect((get_cert_from, port))
cert = c.get_peer_cert()
except Exception, e:
# socket connection
val_results.connection_error = True
val_results.inner_exception = e
return val_results
# NoCertificate WrongCertificate WrongHost ValueError
c = SSL.Checker.Checker(hostname)
except NoCertificate:
val_results.no_certificate = True
except WrongCertificate:
val_results.wrong_certificate = True
except WrongHost:
val_results.wrong_host = True
except Exception, e:
val_results.unknown_error = True
val_results.inner_exception = e
if cert.get_not_after().get_datetime() <=
val_results.certificate_expired = True
val_results.expiration_date = cert.get_not_after().get_datetime()
return val_results
if __name__ == '__main__':
get_cert_from = ''
hostname = ''
port = 993
v = Validator()
print v(hostname, get_cert_from, port)

This comment has been minimized.

Copy link
Owner Author

bretwalker commented Apr 19, 2013

Output for looking for a hostname of

Connection error:        False
No certificate:          False
Wrong certificate:       False
Wrong host:              False
Certificate expired:     False
Expiration date:         2013-06-07 19:43:27+00:00
Unknown error:           False
Inner exception:         None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.