def _secure(s, host, ssl_context): local_port = s.getsockname()[1] # Secure the connection if an SSL context has been provided if ssl_context: log_debug("[#%04X] C: <SECURE> %s", local_port, host) try: s = ssl_context.wrap_socket( s, server_hostname=host if HAS_SNI and host else None) except SSLError as cause: s.close() error = SecurityError( "Failed to establish secure connection to {!r}".format( cause.args[1])) error.__cause__ = cause raise error else: # Check that the server provides a certificate der_encoded_server_certificate = s.getpeercert(binary_form=True) if der_encoded_server_certificate is None: s.close() raise ProtocolError( "When using a secure socket, the server should always " "provide a certificate") else: der_encoded_server_certificate = None return s, der_encoded_server_certificate
def _secure(s, host, ssl_context, **config): local_port = s.getsockname()[1] # Secure the connection if an SSL context has been provided if ssl_context and SSL_AVAILABLE: log_debug("[#%04X] C: <SECURE> %s", local_port, host) try: s = ssl_context.wrap_socket(s, server_hostname=host if HAS_SNI and host else None) except SSLError as cause: s.close() error = SecurityError("Failed to establish secure connection to {!r}".format(cause.args[1])) error.__cause__ = cause raise error else: # Check that the server provides a certificate der_encoded_server_certificate = s.getpeercert(binary_form=True) if der_encoded_server_certificate is None: s.close() raise ProtocolError("When using a secure socket, the server should always " "provide a certificate") trust = config.get("trust", TRUST_DEFAULT) if trust == TRUST_ON_FIRST_USE: store = PersonalCertificateStore() if not store.match_or_trust(host, der_encoded_server_certificate): s.close() raise ProtocolError("Server certificate does not match known certificate " "for %r; check details in file %r" % (host, KNOWN_HOSTS)) else: der_encoded_server_certificate = None return s, der_encoded_server_certificate