Skip to content

Instantly share code, notes, and snippets.

@brandond
Created March 25, 2017 09:02
Show Gist options
  • Save brandond/f3d28734a40c49833176207b17a44786 to your computer and use it in GitHub Desktop.
Save brandond/f3d28734a40c49833176207b17a44786 to your computer and use it in GitHub Desktop.
Stupid simple Python SSL certificate chain scanner
#!/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))
@chrisdlangton
Copy link

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