def host_matches_cert(host, x509): """ Verify that the the x509 certificate we have received from 'host' correctly identifies the server we are connecting to, ie that the certificate's Common Name or a Subject Alternative Name matches 'host'. """ common_name = x509.get_subject().commonName # First see if we can match the CN if common_name == host: return True # Support single wildcard matching if common_name.startswith('*.') and host.find('.') > 0: if common_name[2:] == host.split('.', 1)[1]: return True # Also try Subject Alternative Names for a match san_list = None for i in xrange(x509.get_extension_count()): ext = x509.get_extension(i) if ext.get_short_name() == 'subjectAltName': san_list = str(ext) for san in ''.join(san_list.split()).split(','): if san == "DNS:%s" % host: return True # Server certificate does not match host msg = ('Host "%s" does not match x509 certificate contents: ' 'CommonName "%s"' % (host, common_name)) if san_list is not None: msg = msg + ', subjectAltName "%s"' % san_list raise exc.SSLCertificateError(msg)
def verify_callback(self, connection, x509, errnum, depth, preverify_ok): if x509.has_expired(): msg = "SSL Certificate expired on '%s'" % x509.get_notAfter() raise exc.SSLCertificateError(msg) if depth == 0 and preverify_ok: # We verify that the host matches against the last # certificate in the chain return self.host_matches_cert(self.host, x509) else: # Pass through OpenSSL's default result return preverify_ok
def do_verify_callback(connection, x509, errnum, depth, preverify_ok, host=None): """Verify the server's SSL certificate. This is a standalone function rather than a method to avoid issues around closing sockets if a reference is held on a VerifiedHTTPSConnection by the callback function. """ if x509.has_expired(): msg = "SSL Certificate expired on '%s'" % x509.get_notAfter() raise exc.SSLCertificateError(msg) if depth == 0 and preverify_ok: # We verify that the host matches against the last # certificate in the chain return host_matches_cert(host, x509) else: # Pass through OpenSSL's default result return preverify_ok