Skip to content

Instantly share code, notes, and snippets.

@phelixbtc
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phelixbtc/0230e872f8c199a5057c to your computer and use it in GitHub Desktop.
Save phelixbtc/0230e872f8c199a5057c to your computer and use it in GitHub Desktop.
requests fingerprint
"""
requests based url opener with support self supplied fingerprints
"""
debug = True
try:
import requests
except ImportError:
#pass
raise
def sanitiseFingerprint(fpr):
"""
Sanitise a fingerprint (of a TLS certificate, for instance) for
comparison. This removes colons, spaces and makes the string
upper case.
"""
#fpr = fpr.translate (None, ': ')
fpr = fpr.replace (":", "")
fpr = fpr.replace (" ", "")
fpr = fpr.upper ()
return fpr
class Opener(object): # could also inherit from requests object
def __init__(self, fps_sha256={}, debug=False):
"""fps_sha256 can be a dict hosts:array of sha256 fingerprints"""
self.fps_sha256 = fps_sha256
self.debug = debug
# make local !!!
# Set ciphers and enable fingerprint verification via PyOpenSSL
requests.packages.urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST = "EDH+aRSA+AES256:EECDH+aRSA+AES256:!SSLv3"
requests.packages.urllib3.contrib.pyopenssl._verify_callback = self.verify_fingerprint
requests.packages.urllib3.contrib.pyopenssl.inject_into_urllib3()
# PyOpenSSL callback
def verify_fingerprint(self, connection, x509, errnum, errdepth, ok):
global c,x
x = x509
print "self:", type(self)
print "connection:", type(connection)
print "x509:", type(x509)
c = connection
#print dir(connection)
host = connection.get_servername()
seen_fp = sanitiseFingerprint(x509.digest("sha256"))
if self.debug:
print "Checking TLS cert", seen_fp, "for", host
# Accept a cert if verification is forced off, or if it's a non-primary CA cert (the main cert will still be verified), or if the SHA256 matches
if host in self.fps_sha256:
if self.fps_sha256[host] == "NONE":
return True
if errdepth > 0: # ???
return True
if seen_fp in self.fps_sha256[host]:
return True
def get(self, url, fps=None):
s = requests.Session()
return s.get(url)
def test_tls_config(self):
"""Returns HTML analysis from SSLLabs."""
data = self.fetch("https://www.ssllabs.com/ssltest/viewMyClient.html")
data = data.replace("ssllabs", "x")
with open("test_tls_config.html", "w") as f:
f.write(data)
if __name__ == "__main__":
import OpenSSL
print "versions:"
print "OpenSSL:", OpenSSL.__version__
print "requests:", requests.__version__
opener = Opener()
url = "https://namecoin.org"
print "url:", url
print opener.get(url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment