Package ndg :: Package httpsclient :: Module ssl_context_util
[hide private]

Source Code for Module ndg.httpsclient.ssl_context_util

 1  """ndg_httpsclient SSL Context utilities module containing convenience routines 
 2  for setting SSL context configuration. 
 3   
 4  """ 
 5  __author__ = "P J Kershaw (STFC)" 
 6  __date__ = "09/12/11" 
 7  __copyright__ = "(C) 2012 Science and Technology Facilities Council" 
 8  __license__ = "BSD - see LICENSE file in top-level directory" 
 9  __contact__ = "Philip.Kershaw@stfc.ac.uk" 
10  __revision__ = '$Id$' 
11  import urlparse 
12   
13  from OpenSSL import SSL 
14   
15  from ndg.httpsclient.ssl_peer_verification import ServerSSLCertVerification 
16   
17   
18 -class SSlContextConfig(object):
19 """ 20 Holds configuration options for creating a SSL context. This is used as a 21 template to create the contexts with specific verification callbacks. 22 """
23 - def __init__(self, key_file=None, cert_file=None, pem_file=None, ca_dir=None, 24 verify_peer=False):
25 self.key_file = key_file 26 self.cert_file = cert_file 27 self.pem_file = pem_file 28 self.ca_dir = ca_dir 29 self.verify_peer = verify_peer
30 31
32 -def make_ssl_context_from_config(ssl_config=False, url=None):
33 return make_ssl_context(ssl_config.key_file, ssl_config.cert_file, 34 ssl_config.pem_file, ssl_config.ca_dir, 35 ssl_config.verify_peer, url)
36 37
38 -def make_ssl_context(key_file=None, cert_file=None, pem_file=None, ca_dir=None, 39 verify_peer=False, url=None, method=SSL.SSLv23_METHOD):
40 """ 41 Creates SSL context containing certificate and key file locations. 42 """ 43 ssl_context = SSL.Context(method) 44 45 # Key file defaults to certificate file if present. 46 if cert_file: 47 ssl_context.use_certificate_file(cert_file) 48 if key_file: 49 ssl_context.use_privatekey_file(key_file) 50 else: 51 if cert_file: 52 ssl_context.use_privatekey_file(cert_file) 53 54 if pem_file or ca_dir: 55 ssl_context.load_verify_locations(pem_file, ca_dir) 56 57 def _callback(conn, x509, errnum, errdepth, preverify_ok): 58 """Default certification verification callback. 59 Performs no checks and returns the status passed in. 60 """ 61 return preverify_ok
62 63 verify_callback = _callback 64 65 if verify_peer: 66 ssl_context.set_verify_depth(9) 67 if url: 68 set_peer_verification_for_url_hostname(ssl_context, url) 69 else: 70 ssl_context.set_verify(SSL.VERIFY_PEER, verify_callback) 71 else: 72 ssl_context.set_verify(SSL.VERIFY_NONE, verify_callback) 73 return ssl_context 74 75
76 -def set_peer_verification_for_url_hostname(ssl_context, url, 77 if_verify_enabled=False):
78 '''Convenience routine to set peer verification callback based on 79 ServerSSLCertVerification class''' 80 if not if_verify_enabled or (ssl_context.get_verify_mode() & SSL.VERIFY_PEER): 81 urlObj = urlparse.urlparse(url) 82 hostname = urlObj.hostname 83 verify_callback = ServerSSLCertVerification(hostname=hostname) 84 ssl_context.set_verify(SSL.VERIFY_PEER, verify_callback)
85