Python twisted.internet.ssl.ClientContextFactory() Examples

The following are 30 code examples of twisted.internet.ssl.ClientContextFactory(). 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_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 #2
Source File: pop3client.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _getContextFactory(self):
        """
        Get a context factory with which to negotiate TLS.

        @rtype: L{None} or
            L{ClientContextFactory <twisted.internet.ssl.ClientContextFactory>}
        @return: A context factory or L{None} if TLS is not supported on the
            client.
        """
        try:
            from twisted.internet import ssl
        except ImportError:
            return None
        else:
            context = ssl.ClientContextFactory()
            context.method = ssl.SSL.TLSv1_METHOD
            return context 
Example #3
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 #4
Source File: mail.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _sendmail(self, to_addrs, msg):
        # Import twisted.mail here because it is not available in python3
        from twisted.mail.smtp import ESMTPSenderFactory
        msg = BytesIO(msg)
        d = defer.Deferred()
        factory = ESMTPSenderFactory(self.smtpuser, self.smtppass, self.mailfrom, \
            to_addrs, msg, d, heloFallback=True, requireAuthentication=False, \
            requireTransportSecurity=self.smtptls)
        factory.noisy = False

        if self.smtpssl:
            reactor.connectSSL(self.smtphost, self.smtpport, factory, ssl.ClientContextFactory())
        else:
            reactor.connectTCP(self.smtphost, self.smtpport, factory)

        return d 
Example #5
Source File: pop3client.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _getContextFactory(self):
        """
        Get a context factory with which to negotiate TLS.

        @rtype: L{None} or
            L{ClientContextFactory <twisted.internet.ssl.ClientContextFactory>}
        @return: A context factory or L{None} if TLS is not supported on the
            client.
        """
        try:
            from twisted.internet import ssl
        except ImportError:
            return None
        else:
            context = ssl.ClientContextFactory()
            context.method = ssl.SSL.TLSv1_METHOD
            return context 
Example #6
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 #7
Source File: test_tls.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_getHandle(self):
        """
        L{TLSMemoryBIOProtocol.getHandle} returns the L{OpenSSL.SSL.Connection}
        instance it uses to actually implement TLS.

        This may seem odd.  In fact, it is.  The L{OpenSSL.SSL.Connection} is
        not actually the "system handle" here, nor even an object the reactor
        knows about directly.  However, L{twisted.internet.ssl.Certificate}'s
        C{peerFromTransport} and C{hostFromTransport} methods depend on being
        able to get an L{OpenSSL.SSL.Connection} object in order to work
        properly.  Implementing L{ISystemHandle.getHandle} like this is the
        easiest way for those APIs to be made to work.  If they are changed,
        then it may make sense to get rid of this implementation of
        L{ISystemHandle} and return the underlying socket instead.
        """
        factory = ClientFactory()
        contextFactory = ClientContextFactory()
        wrapperFactory = TLSMemoryBIOFactory(contextFactory, True, factory)
        proto = TLSMemoryBIOProtocol(wrapperFactory, Protocol())
        transport = StringTransport()
        proto.makeConnection(transport)
        self.assertIsInstance(proto.getHandle(), ConnectionType) 
Example #8
Source File: test_tls.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_makeConnection(self):
        """
        When L{TLSMemoryBIOProtocol} is connected to a transport, it connects
        the protocol it wraps to a transport.
        """
        clientProtocol = Protocol()
        clientFactory = ClientFactory()
        clientFactory.protocol = lambda: clientProtocol

        contextFactory = ClientContextFactory()
        wrapperFactory = TLSMemoryBIOFactory(
            contextFactory, True, clientFactory)
        sslProtocol = wrapperFactory.buildProtocol(None)

        transport = StringTransport()
        sslProtocol.makeConnection(transport)

        self.assertNotIdentical(clientProtocol.transport, None)
        self.assertNotIdentical(clientProtocol.transport, transport) 
Example #9
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 #10
Source File: twisted_brpc.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def callRemote(self, method, *args, **kwargs):
        if pipeline_debug: print 'callRemote to %s : %s' % (self.host, method)
        args = (args, kwargs)
        query = Query(self.path, self.host, method, self.user,
                      self.password, *args)
        self.factory.addQuery(query)

        if pipeline_debug: print 'factory started: %s' % self.factory.started
        if not self.factory.started:
            self.factory.started = True
            def connect(host):
                if self.secure:
                    if pipeline_debug: print 'connecting to %s' % str((host, self.port or 443))
                    from twisted.internet import ssl
                    reactor.connectSSL(host, self.port or 443,
                                       self.factory, ssl.ClientContextFactory(),
                                       timeout=60)
                else:
                    if pipeline_debug: print 'connecting to %s' % str((host, self.port or 80))
                    reactor.connectTCP(host, self.port or 80, self.factory,
                                       timeout=60)
            df = reactor.resolve(self.host)
            df.addCallback(connect)
            df.addErrback(query.deferred.errback)
        return query.deferred 
Example #11
Source File: HTTPDownloader.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def downloadPageFactory(url, file, progressCallback=None,
                        agent="BitTorrent client",
                        bindAddress=None,
                        contextFactory=None):
    """Download a web page to a file.

    @param file: path to file on filesystem, or file-like object.
    """
    scheme, host, port, path = client._parse(url)
    factory = ProgressHTTPDownloader(url, file,
                                     progressCallback=progressCallback,
                                     agent=agent,
                                     supportPartial=0)
    if scheme == 'https':
        from twisted.internet import ssl
        if contextFactory is None:
            contextFactory = ssl.ClientContextFactory()
        reactor.connectSSL(host, port, factory, contextFactory,
                           bindAddress=bindAddress)
    else:
        reactor.connectTCP(host, port, factory,
                           bindAddress=bindAddress)
    return factory 
Example #12
Source File: twisted_ebrpc.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def callRemote(self, method, *args, **kwargs):
        if pipeline_debug: print 'callRemote to %s : %s' % (self.host, method)
        args = (args, kwargs)
        query = Query(self.path, self.host, method, self.user,
                      self.password, *args)
        self.factory.addQuery(query)

        if pipeline_debug: print 'factory started: %s' % self.factory.started
        if not self.factory.started:
            self.factory.started = True
            def connect(host):
                if self.secure:
                    if pipeline_debug: print 'connecting to %s' % str((host, self.port or 443))
                    from twisted.internet import ssl
                    reactor.connectSSL(host, self.port or 443,
                                       self.factory, ssl.ClientContextFactory(),
                                       timeout=60)
                else:
                    if pipeline_debug: print 'connecting to %s' % str((host, self.port or 80))
                    reactor.connectTCP(host, self.port or 80, self.factory,
                                       timeout=60)
            df = reactor.resolve(self.host)
            df.addCallback(connect)
            df.addErrback(query.deferred.errback)
        return query.deferred 
Example #13
Source File: client.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def getPage(url, contextFactory=None, *args, **kwargs):
    """Download a web page as a string.

    Download a page. Return a deferred, which will callback with a
    page (as a string) or errback with a description of the error.

    See HTTPClientFactory to see what extra args can be passed.
    """
    scheme, host, port, path = _parse(url)
    factory = HTTPClientFactory(url, *args, **kwargs)
    if scheme == 'https':
        from twisted.internet import ssl
        if contextFactory is None:
            contextFactory = ssl.ClientContextFactory()
        reactor.connectSSL(host, port, factory, contextFactory)
    else:
        reactor.connectTCP(host, port, factory)
    return factory.deferred 
Example #14
Source File: client.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def downloadPage(url, file, contextFactory=None, *args, **kwargs):
    """Download a web page to a file.

    @param file: path to file on filesystem, or file-like object.
    
    See HTTPDownloader to see what extra args can be passed.
    """
    scheme, host, port, path = _parse(url)
    factory = HTTPDownloader(url, file, *args, **kwargs)
    if scheme == 'https':
        from twisted.internet import ssl
        if contextFactory is None:
            contextFactory = ssl.ClientContextFactory()
        reactor.connectSSL(host, port, factory, contextFactory)
    else:
        reactor.connectTCP(host, port, factory)
    return factory.deferred 
Example #15
Source File: xmlstream.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def startTLS(self):
        def proceed(obj):
            print "proceed"
            ctx = ssl.ClientContextFactory()
            ctx.method = SSL.TLSv1_METHOD   # We only do TLS, no SSL
            self.transport.startTLS(ctx)
            self.reset()
            self.tlsEstablished = 1
            self.sendHeader()

        def failure(obj):
            self.factory.stopTrying()
            self.dispatch(obj, TLS_FAILED_EVENT)

        self.addOnetimeObserver("/proceed", proceed)
        self.addOnetimeObserver("/failure", failure)
        self.send("<starttls xmlns='%s'/>" % NS_XMPP_TLS) 
Example #16
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 #17
Source File: twisted_ebrpc.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def callRemote(self, method, *args, **kwargs):
        if pipeline_debug: print 'callRemote to %s : %s' % (self.host, method)
        args = (args, kwargs)
        query = Query(self.path, self.host, method, self.user,
                      self.password, *args)
        self.factory.addQuery(query)

        if pipeline_debug: print 'factory started: %s' % self.factory.started
        if not self.factory.started:
            self.factory.started = True
            def connect(host):
                if self.secure:
                    if pipeline_debug: print 'connecting to %s' % str((host, self.port or 443))
                    from twisted.internet import ssl
                    reactor.connectSSL(host, self.port or 443,
                                       self.factory, ssl.ClientContextFactory(),
                                       timeout=60)
                else:
                    if pipeline_debug: print 'connecting to %s' % str((host, self.port or 80))
                    reactor.connectTCP(host, self.port or 80, self.factory,
                                       timeout=60)
            df = reactor.resolve(self.host)
            df.addCallback(connect)
            df.addErrback(query.deferred.errback)
        return query.deferred 
Example #18
Source File: mail.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _sendmail(self, to_addrs, msg):
        # Import twisted.mail here because it is not available in python3
        from twisted.mail.smtp import ESMTPSenderFactory
        msg = BytesIO(msg)
        d = defer.Deferred()
        factory = ESMTPSenderFactory(self.smtpuser, self.smtppass, self.mailfrom, \
            to_addrs, msg, d, heloFallback=True, requireAuthentication=False, \
            requireTransportSecurity=self.smtptls)
        factory.noisy = False

        if self.smtpssl:
            reactor.connectSSL(self.smtphost, self.smtpport, factory, ssl.ClientContextFactory())
        else:
            reactor.connectTCP(self.smtphost, self.smtpport, factory)

        return d 
Example #19
Source File: xmlrpc.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def callRemote(self, method, *args):
        """
        Call remote XML-RPC C{method} with given arguments.

        @return: a L{defer.Deferred} that will fire with the method response,
            or a failure if the method failed. Generally, the failure type will
            be L{Fault}, but you can also have an C{IndexError} on some buggy
            servers giving empty responses.

            If the deferred is cancelled before the request completes, the
            connection is closed and the deferred will fire with a
            L{defer.CancelledError}.
        """
        def cancel(d):
            factory.deferred = None
            connector.disconnect()
        factory = self.queryFactory(
            self.path, self.host, method, self.user,
            self.password, self.allowNone, args, cancel, self.useDateTime)
        if self.secure:
            from twisted.internet import ssl
            connector = reactor.connectSSL(self.host, self.port or 443,
                                           factory, ssl.ClientContextFactory())
        else:
            connector = reactor.connectTCP(self.host, self.port or 80, factory)
        return factory.deferred 
Example #20
Source File: test_tls.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def client(self, reactor, serverAddress):
        """
        Construct a TCP client endpoint wrapped to immediately start TLS.
        """
        return StartTLSClientEndpoint(
            TCP4ClientEndpoint(
                reactor, '127.0.0.1', serverAddress.port),
            ClientContextFactory()) 
Example #21
Source File: test_tls.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def client(self, reactor, serverAddress):
        """
        Create an SSL client endpoint which will connect localhost on
        the port given by C{serverAddress}.

        @type serverAddress: L{IPv4Address}
        """
        return SSL4ClientEndpoint(
            reactor, '127.0.0.1', serverAddress.port,
            ClientContextFactory()) 
Example #22
Source File: test_webclient.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testFactoryInfo(self):
        url = self.getURL('file')
        scheme, host, port, path = client._parse(url)
        factory = client.HTTPClientFactory(url)
        reactor.connectSSL(host, port, factory, ssl.ClientContextFactory())
        # The base class defines _cbFactoryInfo correctly for this
        return factory.deferred.addCallback(self._cbFactoryInfo, factory) 
Example #23
Source File: pop3testserver.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def getContext(self):
        try:
            from twisted.internet import ssl
        except ImportError:
           self.ctx = None
        else:
            self.ctx = ssl.ClientContextFactory()
            self.ctx.method = ssl.SSL.TLSv1_METHOD 
Example #24
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_tlsAfterStartTLS(self):
        """
        The C{TLS} attribute of a L{Connection} instance is C{True} after
        L{Connection.startTLS} is called.
        """
        skt = FakeSocket(b"")
        protocol = FakeProtocol()
        conn = Connection(skt, protocol, reactor=_FakeFDSetReactor())
        conn._tlsClientDefault = True
        conn.startTLS(ClientContextFactory(), True)
        self.assertTrue(conn.TLS) 
Example #25
Source File: test_ssl.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.contextFactory = ssl.ClientContextFactory()
        self.contextFactory._contextFactory = FakeContext
        self.context = self.contextFactory.getContext() 
Example #26
Source File: test_ssl.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_method(self):
        """
        L{ssl.ClientContextFactory.getContext} returns a context which can use
        SSLv3 or TLSv1 but not SSLv2.
        """
        self.assertEqual(self.context._method, SSL.SSLv23_METHOD)
        self.assertTrue(self.context._options & SSL.OP_NO_SSLv2)
        self.assertFalse(self.context._options & SSL.OP_NO_SSLv3)
        self.assertFalse(self.context._options & SSL.OP_NO_TLSv1) 
Example #27
Source File: test_webclient.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def testFactoryInfo(self):
        url = self.getURL('file')
        uri = client.URI.fromBytes(url)
        factory = client.HTTPClientFactory(url)
        reactor.connectSSL(nativeString(uri.host), uri.port, factory,
                           ssl.ClientContextFactory())
        # The base class defines _cbFactoryInfo correctly for this
        return factory.deferred.addCallback(self._cbFactoryInfo, factory) 
Example #28
Source File: xmlrpc.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def callRemote(self, method, *args):
        """
        Call remote XML-RPC C{method} with given arguments.

        @return: a L{defer.Deferred} that will fire with the method response,
            or a failure if the method failed. Generally, the failure type will
            be L{Fault}, but you can also have an C{IndexError} on some buggy
            servers giving empty responses.

            If the deferred is cancelled before the request completes, the
            connection is closed and the deferred will fire with a
            L{defer.CancelledError}.
        """
        def cancel(d):
            factory.deferred = None
            connector.disconnect()
        factory = self.queryFactory(
            self.path, self.host, method, self.user,
            self.password, self.allowNone, args, cancel, self.useDateTime)

        if self.secure:
            from twisted.internet import ssl
            connector = self._reactor.connectSSL(
                nativeString(self.host), self.port or 443,
                factory, ssl.ClientContextFactory(),
                timeout=self.connectTimeout)
        else:
            connector = self._reactor.connectTCP(
                nativeString(self.host), self.port or 80, factory,
                timeout=self.connectTimeout)
        return factory.deferred 
Example #29
Source File: HTTPDownloader.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def getPageFactory(url,
                   agent="BitTorrent client",
                   bindAddress=None,
                   contextFactory=None,
                   proxy=None,
                   timeout=120):
    """Download a web page as a string.

    Download a page. Return a deferred, which will callback with a
    page (as a string) or errback with a description of the error.

    See HTTPClientFactory to see what extra args can be passed.
    """
    scheme, host, port, path = client._parse(url)
    if proxy:
        host, port = proxy.split(':')
        port = int(port)
    factory = HTTPProxyUnGzipClientFactory(url, agent=agent, proxy=proxy)
    if scheme == 'https':
        from twisted.internet import ssl
        if contextFactory is None:
            contextFactory = ssl.ClientContextFactory()
        reactor.connectSSL(host, port, factory, contextFactory,
                           bindAddress=bindAddress,
                           timeout=timeout)
    else:
        reactor.connectTCP(host, port, factory,
                           bindAddress=bindAddress,
                           timeout=timeout)
    return factory 
Example #30
Source File: pop3client.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _getContextFactory(self):
        try:
            from twisted.internet import ssl
        except ImportError:
            return None
        else:
            context = ssl.ClientContextFactory()
            context.method = ssl.SSL.TLSv1_METHOD
            return context