Python OpenSSL.SSL.Error() Examples
The following are 30
code examples of OpenSSL.SSL.Error().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
OpenSSL.SSL
, or try the search function
.
Example #1
Source File: ssl.py From Exchange2domain with MIT License | 6 votes |
def wrapClientConnection(self, cert='/tmp/impacket.crt'): # Create a context, we don't really care about the SSL/TLS # versions used since it is only intended for local use and thus # doesn't have to be super-secure ctx = SSL.Context(SSL.SSLv23_METHOD) try: ctx.use_privatekey_file(cert) ctx.use_certificate_file(cert) except SSL.Error: LOG.info('SSL requested - generating self-signed certificate in /tmp/impacket.crt') generateImpacketCert(cert) ctx.use_privatekey_file(cert) ctx.use_certificate_file(cert) sslSocket = SSL.Connection(ctx, self.socksSocket) sslSocket.set_accept_state() # Now set this property back to the SSL socket instead of the regular one self.socksSocket = sslSocket
Example #2
Source File: test_sslverify.py From learn_python3_spider with MIT License | 6 votes |
def test_surpriseFromInfoCallback(self): """ pyOpenSSL isn't always so great about reporting errors. If one occurs in the verification info callback, it should be logged and the connection should be shut down (if possible, anyway; the app_data could be clobbered but there's no point testing for that). """ cProto, sProto, cWrapped, sWrapped, pump = self.serviceIdentitySetup( u"correct-host.example.com", u"correct-host.example.com", buggyInfoCallback=True, ) self.assertEqual(cWrapped.data, b'') self.assertEqual(sWrapped.data, b'') cErr = cWrapped.lostReason.value sErr = sWrapped.lostReason.value self.assertIsInstance(cErr, ZeroDivisionError) self.assertIsInstance(sErr, (ConnectionClosed, SSL.Error)) errors = self.flushLoggedErrors(ZeroDivisionError) self.assertTrue(errors)
Example #3
Source File: test_sslverify.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def test_validHostnameInvalidCertificate(self): """ When an invalid certificate containing a perfectly valid hostname is received, the connection is aborted with an OpenSSL error. """ cProto, sProto, pump = self.serviceIdentitySetup( u"valid.example.com", u"valid.example.com", validCertificate=False, ) self.assertEqual(cProto.wrappedProtocol.data, b'') self.assertEqual(sProto.wrappedProtocol.data, b'') cErr = cProto.wrappedProtocol.lostReason.value sErr = sProto.wrappedProtocol.lostReason.value self.assertIsInstance(cErr, SSL.Error) self.assertIsInstance(sErr, SSL.Error)
Example #4
Source File: test_ssl.py From learn_python3_spider with MIT License | 6 votes |
def _cbLostConns(self, results): (sSuccess, sResult), (cSuccess, cResult) = results self.assertFalse(sSuccess) self.assertFalse(cSuccess) acceptableErrors = [SSL.Error] # Rather than getting a verification failure on Windows, we are getting # a connection failure. Without something like sslverify proxying # in-between we can't fix up the platform's errors, so let's just # specifically say it is only OK in this one case to keep the tests # passing. Normally we'd like to be as strict as possible here, so # we're not going to allow this to report errors incorrectly on any # other platforms. if platform.isWindows(): from twisted.internet.error import ConnectionLost acceptableErrors.append(ConnectionLost) sResult.trap(*acceptableErrors) cResult.trap(*acceptableErrors) return self.serverPort.stopListening()
Example #5
Source File: test_ssl.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def _cbLostConns(self, results): (sSuccess, sResult), (cSuccess, cResult) = results self.assertFalse(sSuccess) self.assertFalse(cSuccess) acceptableErrors = [SSL.Error] # Rather than getting a verification failure on Windows, we are getting # a connection failure. Without something like sslverify proxying # in-between we can't fix up the platform's errors, so let's just # specifically say it is only OK in this one case to keep the tests # passing. Normally we'd like to be as strict as possible here, so # we're not going to allow this to report errors incorrectly on any # other platforms. if platform.isWindows(): from twisted.internet.error import ConnectionLost acceptableErrors.append(ConnectionLost) sResult.trap(*acceptableErrors) cResult.trap(*acceptableErrors) return self.serverPort.stopListening()
Example #6
Source File: test_sslverify.py From learn_python3_spider with MIT License | 6 votes |
def test_doesNotSwallowOtherSSLErrors(self): """ Only no cipher matches get swallowed, every other SSL error gets propagated. """ def raiser(_): # Unfortunately, there seems to be no way to trigger a real SSL # error artificially. raise SSL.Error([['', '', '']]) ctx = FakeContext(SSL.SSLv23_METHOD) ctx.set_cipher_list = raiser self.patch(sslverify.SSL, 'Context', lambda _: ctx) self.assertRaises( SSL.Error, sslverify._expandCipherString, u'ALL', SSL.SSLv23_METHOD, 0 )
Example #7
Source File: test_ssl.py From learn_python3_spider with MIT License | 6 votes |
def getHandleErrorCodeMatcher(self): """ Return a L{hamcrest.core.matcher.Matcher} for the argument L{OpenSSL.SSL.Error} will be constructed with for this case. This is basically just a random OpenSSL implementation detail. It would be better if this test worked in a way which did not require this. """ # We expect an error about how we tried to write to a shutdown # connection. This is terribly implementation-specific. return hamcrest.contains( hamcrest.contains( hamcrest.equal_to('SSL routines'), hamcrest.any_of( hamcrest.equal_to('SSL_write'), hamcrest.equal_to('ssl_write_internal'), ), hamcrest.equal_to('protocol is shutdown'), ), )
Example #8
Source File: test_sslverify.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def test_realCAsBetterNotSignOurBogusTestCerts(self): """ If we use the default trust from the platform, our dinky certificate should I{really} fail. """ cProto, sProto, pump = self.serviceIdentitySetup( u"valid.example.com", u"valid.example.com", validCertificate=False, useDefaultTrust=True, ) self.assertEqual(cProto.wrappedProtocol.data, b'') self.assertEqual(sProto.wrappedProtocol.data, b'') cErr = cProto.wrappedProtocol.lostReason.value sErr = sProto.wrappedProtocol.lostReason.value self.assertIsInstance(cErr, SSL.Error) self.assertIsInstance(sErr, SSL.Error)
Example #9
Source File: tls.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def _shutdownTLS(self): """ Initiate, or reply to, the shutdown handshake of the TLS layer. """ try: shutdownSuccess = self._tlsConnection.shutdown() except Error: # Mid-handshake, a call to shutdown() can result in a # WantWantReadError, or rather an SSL_ERR_WANT_READ; but pyOpenSSL # doesn't allow us to get at the error. See: # https://github.com/pyca/pyopenssl/issues/91 shutdownSuccess = False self._flushSendBIO() if shutdownSuccess: # Both sides have shutdown, so we can start closing lower-level # transport. This will also happen if we haven't started # negotiation at all yet, in which case shutdown succeeds # immediately. self.transport.loseConnection()
Example #10
Source File: tls.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def _checkHandshakeStatus(self): """ Ask OpenSSL to proceed with a handshake in progress. Initially, this just sends the ClientHello; after some bytes have been stuffed in to the C{Connection} object by C{dataReceived}, it will then respond to any C{Certificate} or C{KeyExchange} messages. """ # The connection might already be aborted (eg. by a callback during # connection setup), so don't even bother trying to handshake in that # case. if self._aborted: return try: self._tlsConnection.do_handshake() except WantReadError: self._flushSendBIO() except Error: self._tlsShutdownFinished(Failure()) else: self._handshakeDone = True if IHandshakeListener.providedBy(self.wrappedProtocol): self.wrappedProtocol.handshakeCompleted()
Example #11
Source File: test_sslverify.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def test_surpriseFromInfoCallback(self): """ pyOpenSSL isn't always so great about reporting errors. If one occurs in the verification info callback, it should be logged and the connection should be shut down (if possible, anyway; the app_data could be clobbered but there's no point testing for that). """ cProto, sProto, pump = self.serviceIdentitySetup( u"correct-host.example.com", u"correct-host.example.com", buggyInfoCallback=True, ) self.assertEqual(cProto.wrappedProtocol.data, b'') self.assertEqual(sProto.wrappedProtocol.data, b'') cErr = cProto.wrappedProtocol.lostReason.value sErr = sProto.wrappedProtocol.lostReason.value self.assertIsInstance(cErr, ZeroDivisionError) self.assertIsInstance(sErr, (ConnectionClosed, SSL.Error)) errors = self.flushLoggedErrors(ZeroDivisionError) self.assertTrue(errors)
Example #12
Source File: tls.py From learn_python3_spider with MIT License | 6 votes |
def _shutdownTLS(self): """ Initiate, or reply to, the shutdown handshake of the TLS layer. """ try: shutdownSuccess = self._tlsConnection.shutdown() except Error: # Mid-handshake, a call to shutdown() can result in a # WantWantReadError, or rather an SSL_ERR_WANT_READ; but pyOpenSSL # doesn't allow us to get at the error. See: # https://github.com/pyca/pyopenssl/issues/91 shutdownSuccess = False self._flushSendBIO() if shutdownSuccess: # Both sides have shutdown, so we can start closing lower-level # transport. This will also happen if we haven't started # negotiation at all yet, in which case shutdown succeeds # immediately. self.transport.loseConnection()
Example #13
Source File: serving.py From planespotter with MIT License | 6 votes |
def log_request(self, code='-', size='-'): msg = self.requestline code = str(code) if termcolor: color = termcolor.colored if code[0] == '1': # 1xx - Informational msg = color(msg, attrs=['bold']) elif code[0] == '2': # 2xx - Success msg = color(msg, color='white') elif code == '304': # 304 - Resource Not Modified msg = color(msg, color='cyan') elif code[0] == '3': # 3xx - Redirection msg = color(msg, color='green') elif code == '404': # 404 - Resource Not Found msg = color(msg, color='yellow') elif code[0] == '4': # 4xx - Client Error msg = color(msg, color='red', attrs=['bold']) else: # 5xx, or any other response msg = color(msg, color='magenta', attrs=['bold']) self.log('info', '"%s" %s %s', msg, code, size)
Example #14
Source File: tls.py From learn_python3_spider with MIT License | 6 votes |
def _checkHandshakeStatus(self): """ Ask OpenSSL to proceed with a handshake in progress. Initially, this just sends the ClientHello; after some bytes have been stuffed in to the C{Connection} object by C{dataReceived}, it will then respond to any C{Certificate} or C{KeyExchange} messages. """ # The connection might already be aborted (eg. by a callback during # connection setup), so don't even bother trying to handshake in that # case. if self._aborted: return try: self._tlsConnection.do_handshake() except WantReadError: self._flushSendBIO() except Error: self._tlsShutdownFinished(Failure()) else: self._handshakeDone = True if IHandshakeListener.providedBy(self.wrappedProtocol): self.wrappedProtocol.handshakeCompleted()
Example #15
Source File: serving.py From pyRevit with GNU General Public License v3.0 | 6 votes |
def log_request(self, code='-', size='-'): msg = self.requestline code = str(code) if termcolor: color = termcolor.colored if code[0] == '1': # 1xx - Informational msg = color(msg, attrs=['bold']) if code[0] == '2': # 2xx - Success msg = color(msg, color='white') elif code == '304': # 304 - Resource Not Modified msg = color(msg, color='cyan') elif code[0] == '3': # 3xx - Redirection msg = color(msg, color='green') elif code == '404': # 404 - Resource Not Found msg = color(msg, color='yellow') elif code[0] == '4': # 4xx - Client Error msg = color(msg, color='red', attrs=['bold']) else: # 5xx, or any other response msg = color(msg, color='magenta', attrs=['bold']) self.log('info', '"%s" %s %s', msg, code, size)
Example #16
Source File: test_sslverify.py From learn_python3_spider with MIT License | 6 votes |
def test_realCAsBetterNotSignOurBogusTestCerts(self): """ If we use the default trust from the platform, our dinky certificate should I{really} fail. """ cProto, sProto, cWrapped, sWrapped, pump = self.serviceIdentitySetup( u"valid.example.com", u"valid.example.com", validCertificate=False, useDefaultTrust=True, ) self.assertEqual(cWrapped.data, b'') self.assertEqual(sWrapped.data, b'') cErr = cWrapped.lostReason.value sErr = sWrapped.lostReason.value self.assertIsInstance(cErr, SSL.Error) self.assertIsInstance(sErr, SSL.Error)
Example #17
Source File: serving.py From RSSNewsGAE with Apache License 2.0 | 6 votes |
def log_request(self, code='-', size='-'): msg = self.requestline code = str(code) if termcolor: color = termcolor.colored if code[0] == '1': # 1xx - Informational msg = color(msg, attrs=['bold']) if code[0] == '2': # 2xx - Success msg = color(msg, color='white') elif code == '304': # 304 - Resource Not Modified msg = color(msg, color='cyan') elif code[0] == '3': # 3xx - Redirection msg = color(msg, color='green') elif code == '404': # 404 - Resource Not Found msg = color(msg, color='yellow') elif code[0] == '4': # 4xx - Client Error msg = color(msg, color='red', attrs=['bold']) else: # 5xx, or any other response msg = color(msg, color='magenta', attrs=['bold']) self.log('info', '"%s" %s %s', msg, code, size)
Example #18
Source File: test_sslverify.py From learn_python3_spider with MIT License | 6 votes |
def test_validHostnameInvalidCertificate(self): """ When an invalid certificate containing a perfectly valid hostname is received, the connection is aborted with an OpenSSL error. """ cProto, sProto, cWrapped, sWrapped, pump = self.serviceIdentitySetup( u"valid.example.com", u"valid.example.com", validCertificate=False, ) self.assertEqual(cWrapped.data, b'') self.assertEqual(sWrapped.data, b'') cErr = cWrapped.lostReason.value sErr = sWrapped.lostReason.value self.assertIsInstance(cErr, SSL.Error) self.assertIsInstance(sErr, SSL.Error)
Example #19
Source File: ssl.py From Slackor with GNU General Public License v3.0 | 6 votes |
def wrapClientConnection(self, cert='/tmp/impacket.crt'): # Create a context, we don't really care about the SSL/TLS # versions used since it is only intended for local use and thus # doesn't have to be super-secure ctx = SSL.Context(SSL.SSLv23_METHOD) try: ctx.use_privatekey_file(cert) ctx.use_certificate_file(cert) except SSL.Error: LOG.info('SSL requested - generating self-signed certificate in /tmp/impacket.crt') generateImpacketCert(cert) ctx.use_privatekey_file(cert) ctx.use_certificate_file(cert) sslSocket = SSL.Connection(ctx, self.socksSocket) sslSocket.set_accept_state() # Now set this property back to the SSL socket instead of the regular one self.socksSocket = sslSocket
Example #20
Source File: serving.py From PhonePi_SampleServer with MIT License | 6 votes |
def log_request(self, code='-', size='-'): msg = self.requestline code = str(code) if termcolor: color = termcolor.colored if code[0] == '1': # 1xx - Informational msg = color(msg, attrs=['bold']) if code[0] == '2': # 2xx - Success msg = color(msg, color='white') elif code == '304': # 304 - Resource Not Modified msg = color(msg, color='cyan') elif code[0] == '3': # 3xx - Redirection msg = color(msg, color='green') elif code == '404': # 404 - Resource Not Found msg = color(msg, color='yellow') elif code[0] == '4': # 4xx - Client Error msg = color(msg, color='red', attrs=['bold']) else: # 5xx, or any other response msg = color(msg, color='magenta', attrs=['bold']) self.log('info', '"%s" %s %s', msg, code, size)
Example #21
Source File: serving.py From lambda-packs with MIT License | 6 votes |
def log_request(self, code='-', size='-'): msg = self.requestline code = str(code) if termcolor: color = termcolor.colored if code[0] == '1': # 1xx - Informational msg = color(msg, attrs=['bold']) elif code[0] == '2': # 2xx - Success msg = color(msg, color='white') elif code == '304': # 304 - Resource Not Modified msg = color(msg, color='cyan') elif code[0] == '3': # 3xx - Redirection msg = color(msg, color='green') elif code == '404': # 404 - Resource Not Found msg = color(msg, color='yellow') elif code[0] == '4': # 4xx - Client Error msg = color(msg, color='red', attrs=['bold']) else: # 5xx, or any other response msg = color(msg, color='magenta', attrs=['bold']) self.log('info', '"%s" %s %s', msg, code, size)
Example #22
Source File: test_sslverify.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def test_doesNotSwallowOtherSSLErrors(self): """ Only no cipher matches get swallowed, every other SSL error gets propagated. """ def raiser(_): # Unfortunately, there seems to be no way to trigger a real SSL # error artificially. raise SSL.Error([['', '', '']]) ctx = FakeContext(SSL.SSLv23_METHOD) ctx.set_cipher_list = raiser self.patch(sslverify.SSL, 'Context', lambda _: ctx) self.assertRaises( SSL.Error, sslverify._expandCipherString, u'ALL', SSL.SSLv23_METHOD, 0 )
Example #23
Source File: _sslverify.py From learn_python3_spider with MIT License | 5 votes |
def _expandCipherString(cipherString, method, options): """ Expand C{cipherString} according to C{method} and C{options} to a list of explicit ciphers that are supported by the current platform. @param cipherString: An OpenSSL cipher string to expand. @type cipherString: L{unicode} @param method: An OpenSSL method like C{SSL.TLSv1_METHOD} used for determining the effective ciphers. @param options: OpenSSL options like C{SSL.OP_NO_SSLv3} ORed together. @type options: L{int} @return: The effective list of explicit ciphers that results from the arguments on the current platform. @rtype: L{list} of L{ICipher} """ ctx = SSL.Context(method) ctx.set_options(options) try: ctx.set_cipher_list(cipherString.encode('ascii')) except SSL.Error as e: # OpenSSL 1.1.1 turns an invalid cipher list into TLS 1.3 # ciphers, so pyOpenSSL >= 19.0.0 raises an artificial Error # that lacks a corresponding OpenSSL error if the cipher list # consists only of these after a call to set_cipher_list. if not e.args[0]: return [] if e.args[0][0][2] == 'no cipher match': return [] else: raise conn = SSL.Connection(ctx, None) ciphers = conn.get_cipher_list() if isinstance(ciphers[0], unicode): return [OpenSSLCipher(cipher) for cipher in ciphers] else: return [OpenSSLCipher(cipher.decode('ascii')) for cipher in ciphers]
Example #24
Source File: tls.py From learn_python3_spider with MIT License | 5 votes |
def _write(self, bytes): """ Process the given application bytes and send any resulting TLS traffic which arrives in the send BIO. This may be called by C{dataReceived} with bytes that were buffered before C{loseConnection} was called, which is why this function doesn't check for disconnection but accepts the bytes regardless. """ if self._lostTLSConnection: return # A TLS payload is 16kB max bufferSize = 2 ** 14 # How far into the input we've gotten so far alreadySent = 0 while alreadySent < len(bytes): toSend = bytes[alreadySent:alreadySent + bufferSize] try: sent = self._tlsConnection.send(toSend) except WantReadError: self._bufferedWrite(bytes[alreadySent:]) break except Error: # Pretend TLS connection disconnected, which will trigger # disconnect of underlying transport. The error will be passed # to the application protocol's connectionLost method. The # other SSL implementation doesn't, but losing helpful # debugging information is a bad idea. self._tlsShutdownFinished(Failure()) break else: # We've successfully handed off the bytes to the OpenSSL # Connection object. alreadySent += sent # See if OpenSSL wants to hand any bytes off to the underlying # transport as a result. self._flushSendBIO()
Example #25
Source File: test_ssl.py From learn_python3_spider with MIT License | 5 votes |
def test_missingPrivateKeyFile(self): """ Instantiating L{ssl.DefaultOpenSSLContextFactory} with a private key filename which does not identify an existing file results in the initializer raising L{OpenSSL.SSL.Error}. """ self.assertRaises( SSL.Error, ssl.DefaultOpenSSLContextFactory, self.mktemp(), certPath)
Example #26
Source File: test_sslverify.py From learn_python3_spider with MIT License | 5 votes |
def test_refusedAnonymousClientConnection(self): """ Check that anonymous connections are refused when certificates are required on the server. """ onServerLost = defer.Deferred() onClientLost = defer.Deferred() self.loopback(sslverify.OpenSSLCertificateOptions(privateKey=self.sKey, certificate=self.sCert, verify=True, caCerts=[self.sCert], requireCertificate=True), sslverify.OpenSSLCertificateOptions( requireCertificate=False), onServerLost=onServerLost, onClientLost=onClientLost) d = defer.DeferredList([onClientLost, onServerLost], consumeErrors=True) def afterLost(result): ((cSuccess, cResult), (sSuccess, sResult)) = result self.assertFalse(cSuccess) self.assertFalse(sSuccess) # Win32 fails to report the SSL Error, and report a connection lost # instead: there is a race condition so that's not totally # surprising (see ticket #2877 in the tracker) self.assertIsInstance(cResult.value, (SSL.Error, ConnectionLost)) self.assertIsInstance(sResult.value, SSL.Error) return d.addCallback(afterLost)
Example #27
Source File: _sslverify.py From learn_python3_spider with MIT License | 5 votes |
def _tolerateErrors(wrapped): """ Wrap up an C{info_callback} for pyOpenSSL so that if something goes wrong the error is immediately logged and the connection is dropped if possible. This wrapper exists because some versions of pyOpenSSL don't handle errors from callbacks at I{all}, and those which do write tracebacks directly to stderr rather than to a supplied logging system. This reports unexpected errors to the Twisted logging system. Also, this terminates the connection immediately if possible because if you've got bugs in your verification logic it's much safer to just give up. @param wrapped: A valid C{info_callback} for pyOpenSSL. @type wrapped: L{callable} @return: A valid C{info_callback} for pyOpenSSL that handles any errors in C{wrapped}. @rtype: L{callable} """ def infoCallback(connection, where, ret): try: return wrapped(connection, where, ret) except: f = Failure() log.err(f, "Error during info_callback") connection.get_app_data().failVerification(f) return infoCallback
Example #28
Source File: endpoints.py From learn_python3_spider with MIT License | 5 votes |
def _loadCAsFromDir(directoryPath): """ Load certificate-authority certificate objects in a given directory. @param directoryPath: a L{unicode} or L{bytes} pointing at a directory to load .pem files from, or L{None}. @return: an L{IOpenSSLTrustRoot} provider. """ caCerts = {} for child in directoryPath.children(): if not child.asTextMode().basename().split(u'.')[-1].lower() == u'pem': continue try: data = child.getContent() except IOError: # Permission denied, corrupt disk, we don't care. continue try: theCert = Certificate.loadPEM(data) except SSLError: # Duplicate certificate, invalid certificate, etc. We don't care. pass else: caCerts[theCert.digest()] = theCert return trustRootFromCertificates(caCerts.values())
Example #29
Source File: test_tcp.py From learn_python3_spider with MIT License | 5 votes |
def runAbortTest(self, clientClass, serverClass, clientConnectionLostReason=None): """ A test runner utility function, which hooks up a matched pair of client and server protocols. We then run the reactor until both sides have disconnected, and then verify that the right exception resulted. """ clientExpectedExceptions = (ConnectionAborted, ConnectionLost) serverExpectedExceptions = (ConnectionLost, ConnectionDone) # In TLS tests we may get SSL.Error instead of ConnectionLost, # since we're trashing the TLS protocol layer. if useSSL: clientExpectedExceptions = clientExpectedExceptions + (SSL.Error,) serverExpectedExceptions = serverExpectedExceptions + (SSL.Error,) client = clientClass() server = serverClass() client.otherProtocol = server server.otherProtocol = client reactor = runProtocolsWithReactor(self, server, client, self.endpoints) # Make sure everything was shutdown correctly: self.assertEqual(reactor.removeAll(), []) self.assertEqual(reactor.getDelayedCalls(), []) if clientConnectionLostReason is not None: self.assertIsInstance( client.disconnectReason.value, (clientConnectionLostReason,) + clientExpectedExceptions) else: self.assertIsInstance(client.disconnectReason.value, clientExpectedExceptions) self.assertIsInstance(server.disconnectReason.value, serverExpectedExceptions)
Example #30
Source File: test_sslverify.py From learn_python3_spider with MIT License | 5 votes |
def test_trustRootFromCertificatesUntrusted(self): """ L{trustRootFromCertificates} called with certificate A will cause L{optionsForClientTLS} to disallow any connections to a server with certificate B where B is not signed by A. """ key, cert = makeCertificate(O=b"Server Test Certificate", CN=b"server") serverCert = sslverify.PrivateCertificate.fromCertificateAndKeyPair( sslverify.Certificate(cert), sslverify.KeyPair(key), ) untrustedCert = sslverify.Certificate( makeCertificate(O=b"CA Test Certificate", CN=b"unknown CA")[1] ) trust = sslverify.trustRootFromCertificates([untrustedCert]) # Since we only trust 'untrustedCert' which has not signed our # server's cert, we should reject this connection sProto, cProto, sWrap, cWrap, pump = loopbackTLSConnectionInMemory( trustRoot=trust, privateKey=serverCert.privateKey.original, serverCertificate=serverCert.original, ) # This connection should fail, so no data was received. self.assertEqual(cWrap.data, b'') # It was an L{SSL.Error}. self.assertEqual(cWrap.lostReason.type, SSL.Error) # Some combination of OpenSSL and PyOpenSSL is bad at reporting errors. err = cWrap.lostReason.value self.assertEqual(err.args[0][0][2], 'tlsv1 alert unknown ca')