Skip to content

Instantly share code, notes, and snippets.

@zielmicha
Created February 2, 2013 13:19
Show Gist options
  • Save zielmicha/4697339 to your computer and use it in GitHub Desktop.
Save zielmicha/4697339 to your computer and use it in GitHub Desktop.
Verifies certificates when connecting using HTTPS. Requires Python >=3.2. Based on http://thejosephturner.com/blog/2011/03/19/https-certificate-verification-in-python-with-urllib2/.
# Verifies certificates when connecting using HTTPS.
# Needs cacert.txt (cat /usr/share/ca-certificates/mozilla/* > cacert.txt).
import http.client
import socket
import ssl
class VerifiedHTTPSConnection(http.client.HTTPSConnection):
def connect(self):
sock = socket.create_connection((self.host, self.port), self.timeout)
if self._tunnel_host:
self.sock = sock
self._tunnel()
self.sock = ssl.wrap_socket(sock,
self.key_file,
self.cert_file,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs="cacerts.txt")
ssl.match_hostname(self.sock.getpeercert(), self.host)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment