Python twisted.internet.ssl.optionsForClientTLS() Examples

The following are 18 code examples of twisted.internet.ssl.optionsForClientTLS(). 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 twisted.internet.ssl , or try the search function .
Example #1
Source File: test_agent.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def integrationTest(self, hostName, expectedAddress, addressType):
        """
        Wrap L{AgentTestsMixin.integrationTest} with TLS.
        """
        authority, server = certificatesForAuthorityAndServer(hostName
                                                              .decode('ascii'))
        def tlsify(serverFactory):
            return TLSMemoryBIOFactory(server.options(), False, serverFactory)
        def tlsagent(reactor):
            from twisted.web.iweb import IPolicyForHTTPS
            from zope.interface import implementer
            @implementer(IPolicyForHTTPS)
            class Policy(object):
                def creatorForNetloc(self, hostname, port):
                    return optionsForClientTLS(hostname.decode("ascii"),
                                               trustRoot=authority)
            return client.Agent(reactor, contextFactory=Policy())
        (super(AgentHTTPSTests, self)
         .integrationTest(hostName, expectedAddress, addressType,
                          serverWrapper=tlsify,
                          createAgent=tlsagent,
                          scheme=b'https')) 
Example #2
Source File: test_agent.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def integrationTest(self, hostName, expectedAddress, addressType):
        """
        Wrap L{AgentTestsMixin.integrationTest} with TLS.
        """
        certHostName = hostName.strip(b'[]')
        authority, server = certificatesForAuthorityAndServer(certHostName
                                                              .decode('ascii'))
        def tlsify(serverFactory):
            return TLSMemoryBIOFactory(server.options(), False, serverFactory)
        def tlsagent(reactor):
            from twisted.web.iweb import IPolicyForHTTPS
            from zope.interface import implementer
            @implementer(IPolicyForHTTPS)
            class Policy(object):
                def creatorForNetloc(self, hostname, port):
                    return optionsForClientTLS(hostname.decode("ascii"),
                                               trustRoot=authority)
            return client.Agent(reactor, contextFactory=Policy())
        (super(AgentHTTPSTests, self)
         .integrationTest(hostName, expectedAddress, addressType,
                          serverWrapper=tlsify,
                          createAgent=tlsagent,
                          scheme=b'https')) 
Example #3
Source File: test_sslverify.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_trustRootCertificateAuthorityTrustsConnection(self):
        """
        L{trustRootFromCertificates} called with certificate A will cause
        L{optionsForClientTLS} to accept client connections to a server with
        certificate B where B is signed by A.
        """
        caCert, serverCert = certificatesForAuthorityAndServer()

        trust = sslverify.trustRootFromCertificates([caCert])

        # Since we've listed the CA's certificate as a trusted cert, a
        # connection to the server certificate it signed should succeed.
        sProto, cProto, sWrap, cWrap, pump = loopbackTLSConnectionInMemory(
            trustRoot=trust,
            privateKey=serverCert.privateKey.original,
            serverCertificate=serverCert.original,
        )
        self.assertEqual(cWrap.data, b'greetings!')
        self.assertIsNone(cWrap.lostReason) 
Example #4
Source File: test_sslverify.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_extraKeywords(self):
        """
        When passed a keyword parameter other than C{extraCertificateOptions},
        L{sslverify.optionsForClientTLS} raises an exception just like a
        normal Python function would.
        """
        error = self.assertRaises(
            TypeError,
            sslverify.optionsForClientTLS,
            hostname=u'alpha', someRandomThing=u'beta',
        )
        self.assertEqual(
            str(error),
            "optionsForClientTLS() got an unexpected keyword argument "
            "'someRandomThing'"
        ) 
Example #5
Source File: test_sslverify.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_trustRootSelfSignedServerCertificate(self):
        """
        L{trustRootFromCertificates} called with a single self-signed
        certificate will cause L{optionsForClientTLS} to accept client
        connections to a server with that certificate.
        """
        key, cert = makeCertificate(O=b"Server Test Certificate", CN=b"server")
        selfSigned = sslverify.PrivateCertificate.fromCertificateAndKeyPair(
            sslverify.Certificate(cert),
            sslverify.KeyPair(key),
        )

        trust = sslverify.trustRootFromCertificates([selfSigned])

        # Since we trust this exact certificate, connections to this server
        # should succeed.
        sProto, cProto, sWrap, cWrap, pump = loopbackTLSConnectionInMemory(
            trustRoot=trust,
            privateKey=selfSigned.privateKey.original,
            serverCertificate=selfSigned.original,
        )
        self.assertEqual(cWrap.data, b'greetings!')
        self.assertIsNone(cWrap.lostReason) 
Example #6
Source File: test_sslverify.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_clientPresentsBadCertificate(self):
        """
        When the server verifies and the client presents an invalid certificate
        for that verification by passing it to
        L{sslverify.optionsForClientTLS}, the connection cannot be established
        with an SSL error.
        """
        cProto, sProto, cWrapped, sWrapped, pump = self.serviceIdentitySetup(
            u"valid.example.com",
            u"valid.example.com",
            validCertificate=True,
            serverVerifies=True,
            validClientCertificate=False,
            clientPresentsCertificate=True,
        )

        self.assertEqual(cWrapped.data,
                         b'')

        cErr = cWrapped.lostReason.value
        sErr = sWrapped.lostReason.value

        self.assertIsInstance(cErr, SSL.Error)
        self.assertIsInstance(sErr, SSL.Error) 
Example #7
Source File: test_sslverify.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_clientPresentsCertificate(self):
        """
        When the server verifies and the client presents a valid certificate
        for that verification by passing it to
        L{sslverify.optionsForClientTLS}, communication proceeds.
        """
        cProto, sProto, cWrapped, sWrapped, pump = self.serviceIdentitySetup(
            u"valid.example.com",
            u"valid.example.com",
            validCertificate=True,
            serverVerifies=True,
            clientPresentsCertificate=True,
        )

        self.assertEqual(cWrapped.data,
                         b'greetings!')

        cErr = cWrapped.lostReason
        sErr = sWrapped.lostReason
        self.assertIsNone(cErr)
        self.assertIsNone(sErr) 
Example #8
Source File: test_sslverify.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_butIfTheyDidItWouldWork(self):
        """
        L{ssl.optionsForClientTLS} should be using L{ssl.platformTrust} by
        default, so if we fake that out then it should trust ourselves again.
        """
        cProto, sProto, cWrapped, sWrapped, pump = self.serviceIdentitySetup(
            u"valid.example.com",
            u"valid.example.com",
            useDefaultTrust=True,
            fakePlatformTrust=True,
        )
        self.assertEqual(cWrapped.data,
                         b'greetings!')

        cErr = cWrapped.lostReason
        sErr = sWrapped.lostReason
        self.assertIsNone(cErr)
        self.assertIsNone(sErr) 
Example #9
Source File: test_sslverify.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_IPv6AddressHostname(self):
        """
        If you pass an IPv6 address to L{sslverify.optionsForClientTLS}
        L{_hostnameIsDnsName} will be False
        """
        options = sslverify.optionsForClientTLS(u'::1')
        self.assertFalse(options._hostnameIsDnsName) 
Example #10
Source File: httpsclient.py    From sydent with Apache License 2.0 5 votes vote down vote up
def creatorForNetloc(self, hostname, port):
        return optionsForClientTLS(hostname.decode("ascii"),
                                   trustRoot=self.sydent.sslComponents.trustRoot,
                                   clientCertificate=self.sydent.sslComponents.myPrivateCertificate) 
Example #11
Source File: test_sslverify.py    From learn_python3_spider with MIT License 5 votes vote down vote up
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') 
Example #12
Source File: kraken_wsclient_py.py    From kraken-wsclient-py with MIT License 5 votes vote down vote up
def add_connection(self, id_, url):
        """
        Convenience function to connect and store the resulting
        connector.
        """
        if not url.startswith("wss://"):
            raise ValueError("expected wss:// URL prefix")

        hostname = url[6:]

        factory = self.factories[id_]
        options = ssl.optionsForClientTLS(hostname=hostname) # for TLS SNI
        self._conns[id_] = connectWS(factory, options) 
Example #13
Source File: test_sslverify.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_IPv4AddressHostname(self):
        """
        If you pass an IPv4 address to L{sslverify.optionsForClientTLS}
        L{_hostnameIsDnsName} will be False
        """
        options = sslverify.optionsForClientTLS(u'127.0.0.1')
        self.assertFalse(options._hostnameIsDnsName) 
Example #14
Source File: test_sslverify.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_bytesFailFast(self):
        """
        If you pass L{bytes} as the hostname to
        L{sslverify.optionsForClientTLS} it immediately raises a L{TypeError}.
        """
        error = self.assertRaises(
            TypeError,
            sslverify.optionsForClientTLS, b'not-actually-a-hostname.com'
        )
        expectedText = (
            "optionsForClientTLS requires text for host names, not " +
            bytes.__name__
        )
        self.assertEqual(str(error), expectedText) 
Example #15
Source File: xmlstream.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def onProceed(self, obj):
        """
        Proceed with TLS negotiation and reset the XML stream.
        """

        self.xmlstream.removeObserver('/failure', self.onFailure)
        if self._configurationForTLS:
            ctx = self._configurationForTLS
        else:
            ctx = ssl.optionsForClientTLS(self.xmlstream.otherEntity.host)
        self.xmlstream.transport.startTLS(ctx)
        self.xmlstream.reset()
        self.xmlstream.sendHeader()
        self._deferred.callback(Reset) 
Example #16
Source File: xmlstream.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def __init__(self, xs, required=True, configurationForTLS=None):
        """
        @param configurationForTLS: An object which creates appropriately
            configured TLS connections. This is passed to C{startTLS} on the
            transport and is preferably created using
            L{twisted.internet.ssl.optionsForClientTLS}.  If C{None}, the
            default is to verify the server certificate against the trust roots
            as provided by the platform. See
            L{twisted.internet._sslverify.platformTrust}.
        @type configurationForTLS: L{IOpenSSLClientConnectionCreator} or
            C{None}
        """
        super(TLSInitiatingInitializer, self).__init__(
                xs, required=required)
        self._configurationForTLS = configurationForTLS 
Example #17
Source File: _validation.py    From flocker with Apache License 2.0 5 votes vote down vote up
def creatorForNetloc(self, hostname, port):
        return optionsForClientTLS(
            u"control-service",
            trustRoot=self.ca_certificate,
            clientCertificate=self.client_credential.private_certificate()) 
Example #18
Source File: twisted_transport.py    From calvin-base with Apache License 2.0 4 votes vote down vote up
def join(self):
        from twisted.internet._sslverify import OpenSSLCertificateAuthorities
        from OpenSSL import crypto
        if self._proto:
            raise Exception("Already connected")

        # Own callbacks
        callbacks = {'connected': [CalvinCB(self._connected)],
                     'disconnected': [CalvinCB(self._disconnected)],
                     'connection_failed': [CalvinCB(self._connection_failed)],
                     'data': [CalvinCB(self._data)],
                     'set_proto': [CalvinCB(self._set_proto)]}

        self._factory = TCPClientFactory(callbacks) # addr="%s:%s" % (self._host_ip, self._host_port))
        runtime_to_runtime_security = _conf.get("security","runtime_to_runtime_security")
        if runtime_to_runtime_security=="tls":
            _log.debug("TwistedCalvinTransport with TLS chosen")
            trusted_ca_certs = []
            try:
                self._runtime_credentials = runtime_credentials.RuntimeCredentials(self._node_name)
                ca_cert_list_str = certificate.get_truststore_as_list_of_strings(certificate.TRUSTSTORE_TRANSPORT)
                for ca_cert in ca_cert_list_str:
                    trusted_ca_certs.append(crypto.load_certificate(crypto.FILETYPE_PEM, ca_cert))
                ca_certs = OpenSSLCertificateAuthorities(trusted_ca_certs)
                client_credentials_data =self._runtime_credentials.get_credentials()
                client_credentials = ssl.PrivateCertificate.loadPEM(client_credentials_data)
            except Exception as err:
                _log.error("TwistedCalvinTransport: Failed to load client credentials, err={}".format(err))
                raise
            try:
                options = ssl.optionsForClientTLS(self._server_node_name,
                                                   trustRoot=ca_certs,
                                                   clientCertificate=client_credentials)
            except Exception as err:
                _log.error("TwistedCalvinTransport: Failed to create optionsForClientTLS "
                                "\n\terr={}"
                                "\n\tself._server_node_name={}".format(err,
                                                                      self._server_node_name))
                raise
            try:
                endpoint = endpoints.SSL4ClientEndpoint(reactor,
                                                        self._host_ip,
                                                        int(self._host_port),
                                                        options)
            except:
                _log.error("TwistedCalvinTransport: Client failed connectSSL")
                raise
            try:
                endpoint.connect(self._factory)
            except Exception as e:
                _log.error("TwistedCalvinTransport: Failed endpoint.connect, e={}".format(e))
                raise
        else:
            reactor.connectTCP(self._host_ip, int(self._host_port), self._factory)