Created
March 25, 2017 09:02
-
-
Save brandond/f3d28734a40c49833176207b17a44786 to your computer and use it in GitHub Desktop.
Stupid simple Python SSL certificate chain scanner
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from __future__ import print_function | |
import sys | |
import socket | |
import requests | |
import datetime | |
from OpenSSL import SSL, crypto | |
def make_context(): | |
context = SSL.Context(method=SSL.TLSv1_METHOD) | |
for bundle in [requests.certs.where(), '/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem']: | |
context.load_verify_locations(cafile=bundle) | |
return context | |
def print_chain(context, hostname): | |
print('Getting certificate chain for {0}'.format(hostname)) | |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
sock = SSL.Connection(context=context, socket=sock) | |
sock.settimeout(5) | |
sock.connect((hostname, 443)) | |
sock.setblocking(1) | |
sock.do_handshake() | |
notafter = sock.get_peer_certificate().get_notAfter() | |
utcafter = datetime.datetime.strptime(notafter, "%Y%m%d%H%M%SZ") | |
utcnow = datetime.datetime.utcnow() | |
print(' 0 e: {0} [{1}]'.format(utcafter - utcnow, notafter)) | |
for (idx, cert) in enumerate(sock.get_peer_cert_chain()): | |
print(' {0} s:{1}'.format(idx, cert.get_subject())) | |
print(' {0} i:{1}'.format(' ', cert.get_issuer())) | |
sock.shutdown() | |
sock.close() | |
context = make_context() | |
for hostname in sys.stdin: | |
if hostname: | |
hostname = hostname.strip('.').strip() | |
try: | |
hostname.index('.') | |
print_chain(context, hostname) | |
except Exception as e: | |
print(' f:{0}'.format(e)) | |
try: | |
hostname = 'www.'+hostname | |
print_chain(context, hostname) | |
except: | |
print(' f:{0}'.format(e)) |
notafter
should be decoded:
notafter = sock.get_peer_certificate().get_notAfter().decode('ascii')
In Python 2 str
and bytes
are equivalent, but in Python 3 datetime.strptime
expects str
raising a f:strptime() argument 1 must be str, not bytes
error otherwise.
you should iterate more protocol methods to negotiate a connection:
for method in [SSL.TLSv1_2_METHOD, SSL.TLSv1_1_METHOD, SSL.TLSv1_METHOD, SSL.SSLv23_METHOD]:
context = SSL.Context(method=method)
just make sure you catch the exceptions in the loop to ensure it continues until a successful connection, and break once one finishes.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usually, hostname should be also specified: