Created
April 16, 2012 19:21
-
-
Save michaelhelmick/2400886 to your computer and use it in GitHub Desktop.
Update SSL certs
This file contains hidden or 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
import os.path | |
import ssl | |
import sys | |
import urlparse | |
import urllib | |
def check_ssl(hostname, port=443): | |
'''Check that an SSL certificate is valid | |
Uses the Mozilla CA file cached by the cURL project | |
''' | |
cafile_local = 'cacert.pem' | |
cafile_remote = 'http://curl.haxx.se/ca/cacert.pem' | |
if not os.path.isfile(cafile_local): | |
print >> sys.stderr, "Downloading %s from %s" % ( | |
cafile_local, cafile_remote) | |
urllib.urlretrieve(cafile_remote, cafile_local) | |
print >> sys.stderr, "Validating SSL cert at %s:%d" % ( | |
hostname, port) | |
try: | |
ssl.get_server_certificate((hostname, port), | |
ca_certs=cafile_local) | |
except ssl.SSLError: | |
print >> sys.stderr, "SSL cert at %s:%d is invalid!" % ( | |
hostname, port) | |
raise | |
class CheckedSSLUrlOpener(urllib.FancyURLopener): | |
'''A URL opener that checks that SSL certificates are valid | |
On SSL error, it will raise ssl. | |
''' | |
def open(self, fullurl, data=None): | |
urlbits = urlparse.urlparse(fullurl) | |
if urlbits.scheme == 'https': | |
if ':' in urlbits.netloc: | |
hostname, port = urlbits.netloc.split(':') | |
else: | |
hostname = urlbits.netloc | |
if urlbits.port is None: | |
port = 443 | |
else: | |
port = urlbits.port | |
check_ssl(hostname, port) | |
return urllib.FancyURLopener.open(self, fullurl, data) | |
# Plain usage - can probably do once per day | |
check_ssl('graph.facebook.com') | |
check_ssl('www.facebook.com') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment