Python twisted.internet.reactor.listenSSL() Examples

The following are 30 code examples of twisted.internet.reactor.listenSSL(). 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.reactor , or try the search function .
Example #1
Source File: test_ssl.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_openSSLBuffering(self):
        serverProto = self.serverProto = SingleLineServerProtocol()
        clientProto = self.clientProto = RecordingClientProtocol()

        server = protocol.ServerFactory()
        client = self.client = protocol.ClientFactory()

        server.protocol = lambda: serverProto
        client.protocol = lambda: clientProto

        sCTX = ssl.DefaultOpenSSLContextFactory(certPath, certPath)
        cCTX = ssl.ClientContextFactory()

        port = reactor.listenSSL(0, server, sCTX, interface='127.0.0.1')
        self.addCleanup(port.stopListening)

        clientConnector = reactor.connectSSL('127.0.0.1', port.getHost().port,
                                             client, cCTX)
        self.addCleanup(clientConnector.disconnect)

        return clientProto.deferred.addCallback(
            self.assertEqual, b"+OK <some crap>\r\n") 
Example #2
Source File: test_ssl.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_openSSLBuffering(self):
        serverProto = self.serverProto = SingleLineServerProtocol()
        clientProto = self.clientProto = RecordingClientProtocol()

        server = protocol.ServerFactory()
        client = self.client = protocol.ClientFactory()

        server.protocol = lambda: serverProto
        client.protocol = lambda: clientProto

        sCTX = ssl.DefaultOpenSSLContextFactory(certPath, certPath)
        cCTX = ssl.ClientContextFactory()

        port = reactor.listenSSL(0, server, sCTX, interface='127.0.0.1')
        self.addCleanup(port.stopListening)

        reactor.connectSSL('127.0.0.1', port.getHost().port, client, cCTX)

        return clientProto.deferred.addCallback(
            self.assertEquals, "+OK <some crap>\r\n") 
Example #3
Source File: test_webclient.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        plainRoot = static.Data('not me', 'text/plain')
        tlsRoot = static.Data('me neither', 'text/plain')

        plainSite = server.Site(plainRoot, timeout=None)
        tlsSite = server.Site(tlsRoot, timeout=None)

        from twisted import test
        self.tlsPort = reactor.listenSSL(0, tlsSite,
                                         contextFactory=ssl.DefaultOpenSSLContextFactory(
            FilePath(test.__file__).sibling('server.pem').path,
            FilePath(test.__file__).sibling('server.pem').path,
            ),
                                         interface="127.0.0.1")
        self.plainPort = reactor.listenTCP(0, plainSite, interface="127.0.0.1")

        self.plainPortno = self.plainPort.getHost().port
        self.tlsPortno = self.tlsPort.getHost().port

        plainRoot.putChild('one', util.Redirect(self.getHTTPS('two')))
        tlsRoot.putChild('two', util.Redirect(self.getHTTP('three')))
        plainRoot.putChild('three', util.Redirect(self.getHTTPS('four')))
        tlsRoot.putChild('four', static.Data('FOUND IT!', 'text/plain')) 
Example #4
Source File: test_ssl.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def testImmediateDisconnect(self):
        org = "twisted.test.test_ssl"
        self.setupServerAndClient(
            (org, org + ", client"), {},
            (org, org + ", server"), {})

        # Set up a server, connect to it with a client, which should work since our verifiers
        # allow anything, then disconnect.
        serverProtocolFactory = protocol.ServerFactory()
        serverProtocolFactory.protocol = protocol.Protocol
        self.serverPort = serverPort = reactor.listenSSL(0,
            serverProtocolFactory, self.serverCtxFactory)

        clientProtocolFactory = protocol.ClientFactory()
        clientProtocolFactory.protocol = ImmediatelyDisconnectingProtocol
        clientProtocolFactory.connectionDisconnected = defer.Deferred()
        clientConnector = reactor.connectSSL('127.0.0.1',
            serverPort.getHost().port, clientProtocolFactory, self.clientCtxFactory)

        return clientProtocolFactory.connectionDisconnected.addCallback(
            lambda ignoredResult: self.serverPort.stopListening()) 
Example #5
Source File: test_sslverify.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def loopback(self, serverCertOpts, clientCertOpts,
                 onServerLost=None, onClientLost=None, onData=None):
        if onServerLost is None:
            self.onServerLost = onServerLost = defer.Deferred()
        if onClientLost is None:
            self.onClientLost = onClientLost = defer.Deferred()
        if onData is None:
            onData = defer.Deferred()

        serverFactory = protocol.ServerFactory()
        serverFactory.protocol = DataCallbackProtocol
        serverFactory.onLost = onServerLost
        serverFactory.onData = onData

        clientFactory = protocol.ClientFactory()
        clientFactory.protocol = WritingProtocol
        clientFactory.onLost = onClientLost

        self.serverPort = reactor.listenSSL(0, serverFactory, serverCertOpts)
        self.clientConn = reactor.connectSSL('127.0.0.1',
                self.serverPort.getHost().port, clientFactory, clientCertOpts) 
Example #6
Source File: test_webclient.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def setUp(self):
        plainRoot = static.Data('not me', 'text/plain')
        tlsRoot = static.Data('me neither', 'text/plain')

        plainSite = server.Site(plainRoot, timeout=None)
        tlsSite = server.Site(tlsRoot, timeout=None)

        from twisted import test
        self.tlsPort = reactor.listenSSL(0, tlsSite,
                                         contextFactory=ssl.DefaultOpenSSLContextFactory(
            sibpath(test.__file__, 'server.pem'),
            sibpath(test.__file__, 'server.pem'),
            ),
                                         interface="127.0.0.1")
        self.plainPort = reactor.listenTCP(0, plainSite, interface="127.0.0.1")

        self.plainPortno = self.plainPort.getHost().port
        self.tlsPortno = self.tlsPort.getHost().port

        plainRoot.putChild('one', util.Redirect(self.getHTTPS('two')))
        tlsRoot.putChild('two', util.Redirect(self.getHTTP('three')))
        plainRoot.putChild('three', util.Redirect(self.getHTTPS('four')))
        tlsRoot.putChild('four', static.Data('FOUND IT!', 'text/plain')) 
Example #7
Source File: test_ssl.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def setUp(self):
        test_tcp.PortCleanerUpper.setUp(self)
        self.serverConns = []
        f = protocol.ServerFactory()
        f.protocol = protocol.Protocol
        self.listener = reactor.listenSSL(
            0, f, ssl.DefaultOpenSSLContextFactory(certPath, certPath), interface="127.0.0.1",
        )
        self.ports.append(self.listener)
        f = protocol.ClientFactory()
        f.protocol = test_tcp.ConnectionLosingProtocol

        f.protocol.master = self

        L = []
        def connector():
            p = self.listener.getHost().port
            ctx = ssl.ClientContextFactory()
            return reactor.connectSSL('127.0.0.1', p, f, ctx)
        self.connector = connector

        self.totalConnections = 0 
Example #8
Source File: test_sslverify.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def loopback(self, serverCertOpts, clientCertOpts,
                 onServerLost=None, onClientLost=None, onData=None):
        if onServerLost is None:
            self.onServerLost = onServerLost = defer.Deferred()
        if onClientLost is None:
            self.onClientLost = onClientLost = defer.Deferred()
        if onData is None:
            onData = defer.Deferred()

        serverFactory = protocol.ServerFactory()
        serverFactory.protocol = DataCallbackProtocol
        serverFactory.onLost = onServerLost
        serverFactory.onData = onData

        clientFactory = protocol.ClientFactory()
        clientFactory.protocol = WritingProtocol
        clientFactory.onLost = onClientLost

        self.serverPort = reactor.listenSSL(0, serverFactory, serverCertOpts)
        self.clientConn = reactor.connectSSL('127.0.0.1',
                self.serverPort.getHost().port, clientFactory, clientCertOpts) 
Example #9
Source File: test_ssl.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def testOpenSSLBuffering(self):
        serverProto = self.serverProto = SingleLineServerProtocol()
        clientProto = self.clientProto = RecordingClientProtocol()

        server = protocol.ServerFactory()
        client = self.client = protocol.ClientFactory()

        server.protocol = lambda: serverProto
        client.protocol = lambda: clientProto
        client.buffer = []

        sCTX = ssl.DefaultOpenSSLContextFactory(certPath, certPath)
        cCTX = ssl.ClientContextFactory()

        port = self.port = reactor.listenSSL(0, server, sCTX, interface='127.0.0.1')
        reactor.connectSSL('127.0.0.1', port.getHost().port, client, cCTX)

        i = 0
        while i < 5000 and not client.buffer:
            i += 1
            reactor.iterate()

        self.assertEquals(client.buffer, ["+OK <some crap>\r\n"]) 
Example #10
Source File: test_ssl.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def testImmediateDisconnect(self):
        org = "twisted.test.test_ssl"
        self.setupServerAndClient(
            (org, org + ", client"), {},
            (org, org + ", server"), {})

        # Set up a server, connect to it with a client, which should work since our verifiers
        # allow anything, then disconnect.
        serverProtocolFactory = protocol.ServerFactory()
        serverProtocolFactory.protocol = protocol.Protocol
        self.serverPort = serverPort = reactor.listenSSL(0,
            serverProtocolFactory, self.serverCtxFactory)

        clientProtocolFactory = protocol.ClientFactory()
        clientProtocolFactory.protocol = ImmediatelyDisconnectingProtocol
        clientProtocolFactory.connectionDisconnected = defer.Deferred()
        reactor.connectSSL('127.0.0.1',
            serverPort.getHost().port, clientProtocolFactory, self.clientCtxFactory)

        return clientProtocolFactory.connectionDisconnected.addCallback(
            lambda ignoredResult: self.serverPort.stopListening()) 
Example #11
Source File: test_webclient.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def setUp(self):
        plainRoot = Data(b'not me', 'text/plain')
        tlsRoot = Data(b'me neither', 'text/plain')

        plainSite = server.Site(plainRoot, timeout=None)
        tlsSite = server.Site(tlsRoot, timeout=None)

        self.tlsPort = reactor.listenSSL(
            0, tlsSite,
            contextFactory=ssl.DefaultOpenSSLContextFactory(
                serverPEMPath, serverPEMPath),
            interface="127.0.0.1")
        self.plainPort = reactor.listenTCP(0, plainSite, interface="127.0.0.1")

        self.plainPortno = self.plainPort.getHost().port
        self.tlsPortno = self.tlsPort.getHost().port

        plainRoot.putChild(b'one', Redirect(self.getHTTPS('two')))
        tlsRoot.putChild(b'two', Redirect(self.getHTTP('three')))
        plainRoot.putChild(b'three', Redirect(self.getHTTPS('four')))
        tlsRoot.putChild(b'four', Data(b'FOUND IT!', 'text/plain')) 
Example #12
Source File: test_sslverify.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def loopback(self, serverCertOpts, clientCertOpts,
                 onServerLost=None, onClientLost=None, onData=None):
        if onServerLost is None:
            self.onServerLost = onServerLost = defer.Deferred()
        if onClientLost is None:
            self.onClientLost = onClientLost = defer.Deferred()
        if onData is None:
            onData = defer.Deferred()

        serverFactory = protocol.ServerFactory()
        serverFactory.protocol = DataCallbackProtocol
        serverFactory.onLost = onServerLost
        serverFactory.onData = onData

        clientFactory = protocol.ClientFactory()
        clientFactory.protocol = WritingProtocol
        clientFactory.onLost = onClientLost

        self.serverPort = reactor.listenSSL(0, serverFactory, serverCertOpts)
        self.clientConn = reactor.connectSSL('127.0.0.1',
                self.serverPort.getHost().port, clientFactory, clientCertOpts) 
Example #13
Source File: reverseproxy.py    From PowerHub with MIT License 6 votes vote down vote up
def run_proxy():
    proxy = DynamicProxy()
    site = Site(proxy)
    reactor.listenTCP(args.LPORT, site, interface=args.LHOST)

    if not args.SSL_KEY or not args.SSL_CERT:
        args.SSL_CERT, args.SSL_KEY = get_self_signed_cert(args.URI_HOST)
    with open(args.SSL_CERT, "br") as f:
        cert = f.read()
    cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
    global FINGERPRINT
    FINGERPRINT = cert.digest("sha1").decode()
    reactor.listenSSL(args.SSL_PORT,
                      site,
                      ssl.DefaultOpenSSLContextFactory(
                          args.SSL_KEY.encode(),
                          args.SSL_CERT.encode(),
                      ),
                      interface=args.LHOST,
                      )
    reactor.run() 
Example #14
Source File: test_ssl.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def testImmediateDisconnect(self):
        org = "twisted.test.test_ssl"
        self.setupServerAndClient(
            (org, org + ", client"), {},
            (org, org + ", server"), {})

        # Set up a server, connect to it with a client, which should work since our verifiers
        # allow anything, then disconnect.
        serverProtocolFactory = protocol.ServerFactory()
        serverProtocolFactory.protocol = protocol.Protocol
        self.serverPort = serverPort = reactor.listenSSL(0,
            serverProtocolFactory, self.serverCtxFactory)

        clientProtocolFactory = protocol.ClientFactory()
        clientProtocolFactory.protocol = ImmediatelyDisconnectingProtocol
        clientProtocolFactory.connectionDisconnected = defer.Deferred()
        reactor.connectSSL('127.0.0.1',
            serverPort.getHost().port, clientProtocolFactory, self.clientCtxFactory)

        return clientProtocolFactory.connectionDisconnected.addCallback(
            lambda ignoredResult: self.serverPort.stopListening()) 
Example #15
Source File: test_ssl.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_openSSLBuffering(self):
        serverProto = self.serverProto = SingleLineServerProtocol()
        clientProto = self.clientProto = RecordingClientProtocol()

        server = protocol.ServerFactory()
        client = self.client = protocol.ClientFactory()

        server.protocol = lambda: serverProto
        client.protocol = lambda: clientProto

        sCTX = ssl.DefaultOpenSSLContextFactory(certPath, certPath)
        cCTX = ssl.ClientContextFactory()

        port = reactor.listenSSL(0, server, sCTX, interface='127.0.0.1')
        self.addCleanup(port.stopListening)

        clientConnector = reactor.connectSSL('127.0.0.1', port.getHost().port,
                                             client, cCTX)
        self.addCleanup(clientConnector.disconnect)

        return clientProto.deferred.addCallback(
            self.assertEqual, b"+OK <some crap>\r\n") 
Example #16
Source File: test_webclient.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def setUp(self):
        plainRoot = Data(b'not me', 'text/plain')
        tlsRoot = Data(b'me neither', 'text/plain')

        plainSite = server.Site(plainRoot, timeout=None)
        tlsSite = server.Site(tlsRoot, timeout=None)

        self.tlsPort = reactor.listenSSL(
            0, tlsSite,
            contextFactory=ssl.DefaultOpenSSLContextFactory(
                serverPEMPath, serverPEMPath),
            interface="127.0.0.1")
        self.plainPort = reactor.listenTCP(0, plainSite, interface="127.0.0.1")

        self.plainPortno = self.plainPort.getHost().port
        self.tlsPortno = self.tlsPort.getHost().port

        plainRoot.putChild(b'one', Redirect(self.getHTTPS('two')))
        tlsRoot.putChild(b'two', Redirect(self.getHTTP('three')))
        plainRoot.putChild(b'three', Redirect(self.getHTTPS('four')))
        tlsRoot.putChild(b'four', Data(b'FOUND IT!', 'text/plain')) 
Example #17
Source File: server_connection.py    From calvin-base with Apache License 2.0 6 votes vote down vote up
def reactor_listen(node_name, factory, host, port):
    listener = None

    control_interface_security = _conf.get("security", "control_interface_security")
    if control_interface_security == "tls":
        _log.debug("ServerProtocolFactory with TLS enabled chosen")
        try:
            # TODO: figure out how to set more than one root cert in twisted truststore
            runtime_cred = runtime_credentials.RuntimeCredentials(node_name)
            server_credentials_data = runtime_cred.get_credentials()
            server_credentials = ssl.PrivateCertificate.loadPEM(server_credentials_data)
        except Exception as err:
            _log.error("Failed to fetch server credentials, err={}".format(err))
            raise
        try:
            listener = reactor.listenSSL(port, factory, server_credentials.options(), interface=host)
        except Exception as err:
            _log.error("Server failed listenSSL, err={}".format(err))
    else:
        listener = reactor.listenTCP(port, factory, interface=host)
        # WORKAROUND This is here due to an obscure error in twisted trying to write to a listening port
        # on some architectures/OSes. The default is to raise a RuntimeError.
        listener.doWrite = lambda: None

    return listener 
Example #18
Source File: irecv.py    From pywbem with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __init__(self, callback,
            http_port=5988, https_port=5989,
            ssl_key=None, ssl_cert=None):
        self.callback = callback
        self.http_port = http_port
        self.https_port = https_port
        self.ssl_key = ssl_key
        self.ssl_cert = ssl_cert

        site = server.Site(self)

        if self.http_port and self.http_port > 0:
            reactor.listenTCP(self.http_port, site)
        if self.https_port and self.https_port > 0:
            reactor.listenSSL(self.https_port, site,
                    self.ServerContextFactory(cert=ssl_cert, key=ssl_key)) 
Example #19
Source File: test_internet.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testSSL(self, ssl=ssl):
            pem = util.sibpath(__file__, 'server.pem')
            p = reactor.listenSSL(0, protocol.ServerFactory(), ssl.DefaultOpenSSLContextFactory(pem, pem))
            portNo = p.getHost().port
            self.assertNotEqual(str(p).find(str(portNo)), -1,
                                "%d not found in %s" % (portNo, p))
            return p.stopListening() 
Example #20
Source File: test_ssl.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testFailedVerify(self):
        org = "twisted.test.test_ssl"
        self.setupServerAndClient(
            (org, org + ", client"), {},
            (org, org + ", server"), {})

        def verify(*a):
            return False
        self.clientCtxFactory.getContext().set_verify(SSL.VERIFY_PEER, verify)

        serverConnLost = defer.Deferred()
        serverProtocol = protocol.Protocol()
        serverProtocol.connectionLost = serverConnLost.callback
        serverProtocolFactory = protocol.ServerFactory()
        serverProtocolFactory.protocol = lambda: serverProtocol
        self.serverPort = serverPort = reactor.listenSSL(0,
            serverProtocolFactory, self.serverCtxFactory)

        clientConnLost = defer.Deferred()
        clientProtocol = protocol.Protocol()
        clientProtocol.connectionLost = clientConnLost.callback
        clientProtocolFactory = protocol.ClientFactory()
        clientProtocolFactory.protocol = lambda: clientProtocol
        clientConnector = reactor.connectSSL('127.0.0.1',
            serverPort.getHost().port, clientProtocolFactory, self.clientCtxFactory)

        dl = defer.DeferredList([serverConnLost, clientConnLost], consumeErrors=True)
        return dl.addCallback(self._cbLostConns) 
Example #21
Source File: test_transport.py    From landscape-client with GNU General Public License v2.0 5 votes vote down vote up
def test_ssl_verification_negative(self):
        """
        If the SSL server provides a key which is not verified by the
        specified public key, then the client should immediately end
        the connection without uploading any message data.
        """
        self.log_helper.ignore_errors(PyCurlError)
        r = DataCollectingResource()
        context_factory = DefaultOpenSSLContextFactory(
            BADPRIVKEY, BADPUBKEY)
        port = reactor.listenSSL(0, server.Site(r), context_factory,
                                 interface="127.0.0.1")
        self.ports.append(port)
        transport = HTTPTransport(None, "https://localhost:%d/"
                                  % (port.getHost().port,), pubkey=PUBKEY)

        result = deferToThread(transport.exchange, "HI", computer_id="34",
                               message_api="X.Y")

        def got_result(ignored):
            self.assertIs(r.request, None)
            self.assertIs(r.content, None)
            self.assertTrue("server certificate verification failed"
                            in self.logfile.getvalue())
        result.addErrback(got_result)
        return result 
Example #22
Source File: daemon_protocol.py    From joinmarket-clientserver with GNU General Public License v3.0 5 votes vote down vote up
def start_daemon(host, port, factory, usessl=False, sslkey=None, sslcert=None):
    if usessl:
        assert sslkey
        assert sslcert
        reactor.listenSSL(
            port, factory, ssl.DefaultOpenSSLContextFactory(sslkey, sslcert),
            interface=host)
    else:
        reactor.listenTCP(port, factory, interface=host) 
Example #23
Source File: app.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def listenSSL(self, port, factory, ctxFactory, backlog=50, interface=''):
        """
        Connects a given protocol factory to the given numeric TCP/IP port.
        The connection is a SSL one, using contexts created by the context
        factory.
        """
        self.sslPorts.append((port, factory, ctxFactory, backlog, interface))
        if self.running:
            from twisted.internet import reactor
            return reactor.listenSSL(port, factory, ctxFactory, backlog, interface) 
Example #24
Source File: test_webclient.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def _listen(self, site):
        from twisted import test
        return reactor.listenSSL(0, site,
                                 contextFactory=ssl.DefaultOpenSSLContextFactory(
            sibpath(test.__file__, 'server.pem'),
            sibpath(test.__file__, 'server.pem'),
            ),
                                 interface="127.0.0.1") 
Example #25
Source File: application.py    From pixelated-user-agent with GNU Affero General Public License v3.0 5 votes vote down vote up
def start_site(config, resource):
    log.info('Starting the API on port %s' % config.port)

    if config.manhole:
        log.info('Starting the manhole on port 8008')

        multiService = manhole_tap.makeService(dict(namespace=globals(),
                                                    telnetPort='8008',
                                                    sshPort='8009',
                                                    sshKeyDir='sshKeyDir',
                                                    sshKeyName='id_rsa',
                                                    sshKeySize=4096,
                                                    passwd='passwd'))
        telnetService, sshService = multiService.services
        telnetFactory = telnetService.factory
        sshFactory = sshService.factory

        reactor.listenTCP(8008, telnetFactory, interface='localhost')
        reactor.listenTCP(8009, sshFactory, interface='localhost')

    site = PixelatedSite(resource)
    site.displayTracebacks = False
    if config.sslkey and config.sslcert:
        reactor.listenSSL(config.port, site, _ssl_options(config.sslkey, config.sslcert),
                          interface=config.host)
    else:
        reactor.listenTCP(config.port, site, interface=config.host) 
Example #26
Source File: test_internet.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testSSL(self, ssl=ssl):
            pem = util.sibpath(__file__, 'server.pem')
            p = reactor.listenSSL(0, protocol.ServerFactory(), ssl.DefaultOpenSSLContextFactory(pem, pem))
            portNo = p.getHost().port
            self.assertNotEqual(str(p).find(str(portNo)), -1,
                                "%d not found in %s" % (portNo, p))
            return p.stopListening() 
Example #27
Source File: twisted_transport.py    From calvin-base with Apache License 2.0 5 votes vote down vote up
def start(self):
        callbacks = {'connected': [CalvinCB(self._connected)]}
        tcp_f = TCPServerFactory(callbacks)
        runtime_to_runtime_security = _conf.get("security","runtime_to_runtime_security")
        trusted_ca_certs = []
        if runtime_to_runtime_security=="tls":
            _log.debug("TwistedCalvinServer with TLS chosen")
            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(ssl.Certificate.loadPEM(ca_cert))
                server_credentials_data = self._runtime_credentials.get_credentials()
                server_credentials = ssl.PrivateCertificate.loadPEM(server_credentials_data)
            except Exception as err:
                _log.exception("Server failed to load credentials, err={}".format(err))
            try:
                self._tcp_server = reactor.listenSSL(self._port, tcp_f, server_credentials.options(*trusted_ca_certs), interface=self._iface)
            except Exception as err:
                _log.exception("Server failed listenSSL, err={}".format(err))
        else:
            _log.debug("TwistedCalvinServer without TLS chosen")
            try:
                self._tcp_server = reactor.listenTCP(self._port, tcp_f, interface=self._iface)
            except error.CannotListenError:
                _log.exception("Could not listen on port %s:%s", self._iface, self._port)
                raise
            except Exception as exc:
                _log.exception("Failed when trying listening on port %s:%s", self._iface, self._port)
                raise
        self._port = self._tcp_server.getHost().port
        self._callback_execute('server_started', self._port)
        return self._port 
Example #28
Source File: test_webclient.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _listen(self, site):
        from twisted import test
        return reactor.listenSSL(0, site,
                                 contextFactory=ssl.DefaultOpenSSLContextFactory(
            FilePath(test.__file__).sibling('server.pem').path,
            FilePath(test.__file__).sibling('server.pem').path,
            ),
                                 interface="127.0.0.1") 
Example #29
Source File: test_webclient.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _listen(self, site):
        return reactor.listenSSL(
            0, site,
            contextFactory=ssl.DefaultOpenSSLContextFactory(
                serverPEMPath, serverPEMPath),
            interface="127.0.0.1") 
Example #30
Source File: test_ssl.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def createServer(self, address, portNumber, factory):
        """
        Create an SSL server with a certificate using L{IReactorSSL.listenSSL}.
        """
        cert = ssl.PrivateCertificate.loadPEM(FilePath(certPath).getContent())
        contextFactory = cert.options()
        return reactor.listenSSL(
            portNumber, factory, contextFactory, interface=address)