Python twisted.internet.interfaces.ISSLTransport() Examples

The following are 28 code examples of twisted.internet.interfaces.ISSLTransport(). 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.interfaces , or try the search function .
Example #1
Source File: iosim.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def bufferReceived(self, buf):
        if isinstance(buf, TLSNegotiation):
            assert self.tls is not None # By the time you're receiving a
                                        # negotiation, you have to have called
                                        # startTLS already.
            if self.tls.sent:
                self.tls.pretendToVerify(buf, self)
                self.tls = None # We're done with the handshake if we've gotten
                                # this far... although maybe it failed...?
                # TLS started!  Unbuffer...
                b, self.tlsbuf = self.tlsbuf, None
                self.writeSequence(b)
                directlyProvides(self, interfaces.ISSLTransport)
            else:
                # We haven't sent our own TLS negotiation: time to do that!
                self.tls.readyToSend = True
        else:
            self.protocol.dataReceived(buf) 
Example #2
Source File: imap4.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def __cbLoginCaps(self, capabilities, username, password):
        # If the server advertises STARTTLS, we might want to try to switch to TLS
        tryTLS = 'STARTTLS' in capabilities

        # If our transport supports switching to TLS, we might want to try to switch to TLS.
        tlsableTransport = interfaces.ITLSTransport(self.transport, None) is not None

        # If our transport is not already using TLS, we might want to try to switch to TLS.
        nontlsTransport = interfaces.ISSLTransport(self.transport, None) is None

        if not self.startedTLS and tryTLS and tlsableTransport and nontlsTransport:
            d = self.startTLS()

            d.addCallbacks(
                self.__cbLoginTLS,
                self.__ebLoginTLS,
                callbackArgs=(username, password),
                )
            return d
        else:
            if nontlsTransport:
                log.msg("Server has no TLS support. logging in over cleartext!")
            args = ' '.join((_quote(username), _quote(password)))
            return self.sendCommand(Command('LOGIN', args)) 
Example #3
Source File: pop3client.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def _login(self, caps, username, password):
        if self.serverChallenge is not None:
            return self._apop(username, password, self.serverChallenge)

        tryTLS = 'STLS' in caps

        #If our transport supports switching to TLS, we might want to try to switch to TLS.
        tlsableTransport = interfaces.ITLSTransport(self.transport, None) is not None

        # If our transport is not already using TLS, we might want to try to switch to TLS.
        nontlsTransport = interfaces.ISSLTransport(self.transport, None) is None

        if not self.startedTLS and tryTLS and tlsableTransport and nontlsTransport:
            d = self.startTLS()

            d.addCallback(self._loginTLS, username, password)
            return d

        elif self.startedTLS or self.allowInsecureLogin:
            return self._plaintext(username, password)
        else:
            return defer.fail(InsecureAuthenticationDisallowed()) 
Example #4
Source File: iosim.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def bufferReceived(self, buf):
        if isinstance(buf, TLSNegotiation):
            assert self.tls is not None # By the time you're receiving a
                                        # negotiation, you have to have called
                                        # startTLS already.
            if self.tls.sent:
                self.tls.pretendToVerify(buf, self)
                self.tls = None # we're done with the handshake if we've gotten
                                # this far... although maybe it failed...?
                # TLS started!  Unbuffer...
                b, self.tlsbuf = self.tlsbuf, None
                self.writeSequence(b)
                directlyProvides(self, interfaces.ISSLTransport)
            else:
                # We haven't sent our own TLS negotiation: time to do that!
                self.tls.readyToSend = True
        else:
            self.protocol.dataReceived(buf) 
Example #5
Source File: test_pop3client.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def testSSLTransportConsideredSecure(self):
        """
        If a server doesn't offer APOP but the transport is secured using
        SSL or TLS, a plaintext login should be allowed, not rejected with
        an InsecureAuthenticationDisallowed exception.
        """
        p, t = setUp(greet=False)
        directlyProvides(t, interfaces.ISSLTransport)
        p.dataReceived("+OK Howdy\r\n")
        d = p.login("username", "password")
        self.assertEquals(t.value(), "USER username\r\n")
        t.clear()
        p.dataReceived("+OK\r\n")
        self.assertEquals(t.value(), "PASS password\r\n")
        p.dataReceived("+OK\r\n")
        return d 
Example #6
Source File: pop3client.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def _login(self, caps, username, password):
        if self.serverChallenge is not None:
            return self._apop(username, password, self.serverChallenge)

        tryTLS = 'STLS' in caps

        #If our transport supports switching to TLS, we might want to try to switch to TLS.
        tlsableTransport = interfaces.ITLSTransport(self.transport, None) is not None

        # If our transport is not already using TLS, we might want to try to switch to TLS.
        nontlsTransport = interfaces.ISSLTransport(self.transport, None) is None

        if not self.startedTLS and tryTLS and tlsableTransport and nontlsTransport:
            d = self.startTLS()

            d.addCallback(self._loginTLS, username, password)
            return d

        elif self.startedTLS or not nontlsTransport or self.allowInsecureLogin:
            return self._plaintext(username, password)
        else:
            return defer.fail(InsecureAuthenticationDisallowed()) 
Example #7
Source File: http.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def isSecure(self):
        """
        Return True if this request is using a secure transport.

        Normally this method returns True if this request's HTTPChannel
        instance is using a transport that implements ISSLTransport.

        This will also return True if setHost() has been called
        with ssl=True.

        @returns: True if this request is secure
        @rtype: C{bool}
        """
        if self._forceSSL:
            return True
        transport = getattr(getattr(self, 'channel', None), 'transport', None)
        if interfaces.ISSLTransport(transport, None) is not None:
            return True
        return False 
Example #8
Source File: metafd.py    From ccs-calendarserver with Apache License 2.0 6 votes vote down vote up
def createTransport(self, skt, peer, data, protocol):
        """
        Create a TCP transport, from a socket object passed by the parent.
        """
        self._connectionCount += 1
        transport = Server(skt, protocol, peer, JustEnoughLikeAPort,
                           self._connectionCount, reactor)
        if data == 'SSL':
            if self.usingSocketFile:
                # Mark the transport as "secure", enough for getHostInfo() to
                # think so
                transport.getPeerCertificate = lambda _: None
                directlyProvides(transport, ISSLTransport)
            else:
                transport.startTLS(self.contextFactory)
        transport.startReading()
        return transport 
Example #9
Source File: test_smtp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_requireTLSAndHELOFallbackSucceedsIfOverTLS(self):
        """
        If TLS is provided at the transport level, we can honour the HELO
        fallback if we're set to require TLS.
        """
        transport = StringTransport()
        directlyProvides(transport, interfaces.ISSLTransport)
        self.clientProtocol.requireAuthentication = False
        self.clientProtocol.requireTransportSecurity = True
        self.clientProtocol.heloFallback = True
        self.clientProtocol.makeConnection(transport)

        self.clientProtocol.dataReceived(b"220 localhost\r\n")
        transport.clear()
        self.clientProtocol.dataReceived(b"500 not an esmtp server\r\n")
        self.assertEqual(b"HELO testuser\r\n", transport.value()) 
Example #10
Source File: test_pop3client.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def testSSLTransportConsideredSecure(self):
        """
        If a server doesn't offer APOP but the transport is secured using
        SSL or TLS, a plaintext login should be allowed, not rejected with
        an InsecureAuthenticationDisallowed exception.
        """
        p, t = setUp(greet=False)
        directlyProvides(t, interfaces.ISSLTransport)
        p.dataReceived(b"+OK Howdy\r\n")
        d = p.login(b"username", b"password")
        self.assertEqual(t.value(), b"USER username\r\n")
        t.clear()
        p.dataReceived(b"+OK\r\n")
        self.assertEqual(t.value(), b"PASS password\r\n")
        p.dataReceived(b"+OK\r\n")
        return d 
Example #11
Source File: http.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def isSecure(self):
        """
        Return L{True} if this request is using a secure transport.

        Normally this method returns L{True} if this request's L{HTTPChannel}
        instance is using a transport that implements
        L{interfaces.ISSLTransport}.

        This will also return L{True} if L{Request.setHost} has been called
        with C{ssl=True}.

        @returns: L{True} if this request is secure
        @rtype: C{bool}
        """
        if self._forceSSL:
            return True
        channel = getattr(self, 'channel', None)
        if channel is None:
            return False
        return channel.isSecure() 
Example #12
Source File: http.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def isSecure(self):
        """
        Return L{True} if this request is using a secure transport.

        Normally this method returns L{True} if this request's L{HTTPChannel}
        instance is using a transport that implements
        L{interfaces.ISSLTransport}.

        This will also return L{True} if L{Request.setHost} has been called
        with C{ssl=True}.

        @returns: L{True} if this request is secure
        @rtype: C{bool}
        """
        if self._forceSSL:
            return True
        channel = getattr(self, 'channel', None)
        if channel is None:
            return False
        return channel.isSecure() 
Example #13
Source File: iosim.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def bufferReceived(self, buf):
        if isinstance(buf, TLSNegotiation):
            assert self.tls is not None # By the time you're receiving a
                                        # negotiation, you have to have called
                                        # startTLS already.
            if self.tls.sent:
                self.tls.pretendToVerify(buf, self)
                self.tls = None # We're done with the handshake if we've gotten
                                # this far... although maybe it failed...?
                # TLS started!  Unbuffer...
                b, self.tlsbuf = self.tlsbuf, None
                self.writeSequence(b)
                directlyProvides(self, interfaces.ISSLTransport)
            else:
                # We haven't sent our own TLS negotiation: time to do that!
                self.tls.readyToSend = True
        else:
            self.protocol.dataReceived(buf) 
Example #14
Source File: test_smtp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_requireTLSAndHELOFallbackSucceedsIfOverTLS(self):
        """
        If TLS is provided at the transport level, we can honour the HELO
        fallback if we're set to require TLS.
        """
        transport = StringTransport()
        directlyProvides(transport, interfaces.ISSLTransport)
        self.clientProtocol.requireAuthentication = False
        self.clientProtocol.requireTransportSecurity = True
        self.clientProtocol.heloFallback = True
        self.clientProtocol.makeConnection(transport)

        self.clientProtocol.dataReceived(b"220 localhost\r\n")
        transport.clear()
        self.clientProtocol.dataReceived(b"500 not an esmtp server\r\n")
        self.assertEqual(b"HELO testuser\r\n", transport.value()) 
Example #15
Source File: imap4.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def __cbLoginCaps(self, capabilities, username, password):
        # If the server advertises STARTTLS, we might want to try to switch to TLS
        tryTLS = 'STARTTLS' in capabilities

        # If our transport supports switching to TLS, we might want to try to switch to TLS.
        tlsableTransport = interfaces.ITLSTransport(self.transport, None) is not None

        # If our transport is not already using TLS, we might want to try to switch to TLS.
        nontlsTransport = interfaces.ISSLTransport(self.transport, None) is None

        if not self.startedTLS and tryTLS and tlsableTransport and nontlsTransport:
            d = self.startTLS()

            d.addCallbacks(
                self.__cbLoginTLS,
                self.__ebLoginTLS,
                callbackArgs=(username, password),
                )
            return d
        else:
            if nontlsTransport:
                log.msg("Server has no TLS support. logging in over cleartext!")
            args = b' '.join((_quote(username), _quote(password)))
            return self.sendCommand(Command(b'LOGIN', args)) 
Example #16
Source File: tcp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _getTLSClass(klass, _existing={}):
    if klass not in _existing:
        class TLSConnection(_TLSMixin, klass):
            implements(interfaces.ISSLTransport)
        _existing[klass] = TLSConnection
    return _existing[klass] 
Example #17
Source File: imap4.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def capabilities(self):
        cap = {'AUTH': self.challengers.keys()}
        if self.ctx and self.canStartTLS:
            if not self.startedTLS and interfaces.ISSLTransport(self.transport, None) is None:
                cap['LOGINDISABLED'] = None
                cap['STARTTLS'] = None
        cap['NAMESPACE'] = None
        cap['IDLE'] = None
        return cap 
Example #18
Source File: http.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def isSecure(self):
        """
        Return L{True} if this channel is using a secure transport.

        Normally this method returns L{True} if this instance is using a
        transport that implements L{interfaces.ISSLTransport}.

        @returns: L{True} if this request is secure
        @rtype: C{bool}
        """
        if interfaces.ISSLTransport(self.transport, None) is not None:
            return True
        return False 
Example #19
Source File: http.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def isSecure(self):
        if self._forceSSL:
            return True
        transport = getattr(getattr(self, 'channel', None), 'transport', None)
        if interfaces.ISSLTransport(transport, None) is not None:
            return True
        return False 
Example #20
Source File: imap4.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def capabilities(self):
        cap = {b'AUTH': list(self.challengers.keys())}
        if self.ctx and self.canStartTLS:
            if not self.startedTLS and interfaces.ISSLTransport(self.transport, None) is None:
                cap[b'LOGINDISABLED'] = None
                cap[b'STARTTLS'] = None
        cap[b'NAMESPACE'] = None
        cap[b'IDLE'] = None
        return cap 
Example #21
Source File: imap4.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def capabilities(self):
        cap = {'AUTH': self.challengers.keys()}
        if self.ctx and self.canStartTLS:
            if not self.startedTLS and interfaces.ISSLTransport(self.transport, None) is None:
                cap['LOGINDISABLED'] = None
                cap['STARTTLS'] = None
        cap['NAMESPACE'] = None
        cap['IDLE'] = None
        return cap 
Example #22
Source File: http.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def isSecure(self):
        """
        Return L{True} if this channel is using a secure transport.

        Normally this method returns L{True} if this instance is using a
        transport that implements L{interfaces.ISSLTransport}.

        @returns: L{True} if this request is secure
        @rtype: C{bool}
        """
        if interfaces.ISSLTransport(self.transport, None) is not None:
            return True
        return False 
Example #23
Source File: tcp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def startTLS(self, contextFactory, normal=True):
            """
            @see: L{ITLSTransport.startTLS}
            """
            # Figure out which direction the SSL goes in.  If normal is True,
            # we'll go in the direction indicated by the subclass.  Otherwise,
            # we'll go the other way (client = not normal ^ _tlsClientDefault,
            # in other words).
            if normal:
                client = self._tlsClientDefault
            else:
                client = not self._tlsClientDefault

            tlsFactory = TLSMemoryBIOFactory(contextFactory, client, None)
            tlsProtocol = TLSMemoryBIOProtocol(tlsFactory, self.protocol, False)
            self.protocol = tlsProtocol

            self.getHandle = tlsProtocol.getHandle
            self.getPeerCertificate = tlsProtocol.getPeerCertificate

            # Mark the transport as secure.
            directlyProvides(self, interfaces.ISSLTransport)

            # Remember we did this so that write and writeSequence can send the
            # data to the right place.
            self._tls = True

            # Hook it up
            self.protocol.makeConnection(_BypassTLS(self)) 
Example #24
Source File: test_smtp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _requireTransportSecurityOverSSLTest(self, capabilities):
        """
        Verify that when L{smtp.ESMTPClient} connects to a server over a
        transport providing L{ISSLTransport}, C{requireTransportSecurity} is
        C{True}, and it is presented with the given capabilities, it will try
        to send its mail and not first attempt to negotiate TLS using the
        I{STARTTLS} protocol action.

        @param capabilities: Bytes to include in the test server's capability
            response.  These must be formatted exactly as required by the
            protocol, including a line which ends the capability response.
        @type param: L{bytes}

        @raise: C{self.failureException} if the behavior of
            C{self.clientProtocol} is not as described.
        """
        transport = StringTransport()
        directlyProvides(transport, interfaces.ISSLTransport)
        self.clientProtocol.makeConnection(transport)

        # Get the handshake out of the way
        self.clientProtocol.dataReceived(self.SERVER_GREETING)
        transport.clear()

        # Tell the client about the server's capabilities
        self.clientProtocol.dataReceived(self.EHLO_RESPONSE + capabilities)

        # The client should now try to send a message - without first trying to
        # negotiate TLS, since the transport is already secure.
        self.assertEqual(
            b"MAIL FROM:<test@example.org>\r\n",
            transport.value()) 
Example #25
Source File: http.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def connectionMade(self):
        self._secure = interfaces.ISSLTransport(self.transport, None) is not None
        address = self.transport.getHost()
        self._host = _cachedGetHostByAddr(address.host)
        self.setTimeout(self.inputTimeOut)
        self.factory.addConnectedChannel(self) 
Example #26
Source File: server.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def capabilities(self):
        cap = {'AUTH': self.challengers.keys()}
        if self.ctx and self.canStartTLS:
            t = self.transport
            ti = interfaces.ISSLTransport
            if not self.startedTLS and ti(t, None) is None:
                cap['LOGINDISABLED'] = None
                cap['STARTTLS'] = None
        cap['NAMESPACE'] = None
        cap['IDLE'] = None
        # patched ############
        cap['LITERAL+'] = None
        ######################
        return cap 
Example #27
Source File: pop3client.py    From Safejumper-for-Desktop with GNU General Public License v2.0 4 votes vote down vote up
def _login(self, caps, username, password):
        """
        Continue the process of logging in to the server.

        This callback function runs after the server capabilities are received.

        If the server provided a challenge in the greeting, proceed with an
        APOP login.  Otherwise, if the server and the transport support
        encrypted communication, try to switch to TLS and then complete
        the login process with the L{_loginTLS} callback function.  Otherwise,
        if insecure authentication is allowed, do a plaintext login.
        Otherwise, fail with an L{InsecureAuthenticationDisallowed} error.

        @type caps: L{dict} mapping L{bytes} to L{list} of L{bytes} and/or
            L{bytes} to L{None}
        @param caps: The server capabilities.

        @type username: L{bytes}
        @param username: The username with which to log in.

        @type password: L{bytes}
        @param password: The password with which to log in.

        @rtype: L{Deferred <defer.Deferred>} which successfully fires with
            L{bytes}
        @return: A deferred which fires when the login process is complete.
            On a successful login, it returns the server's response minus the
            status indicator.
        """
        if self.serverChallenge is not None:
            return self._apop(username, password, self.serverChallenge)

        tryTLS = 'STLS' in caps

        # If our transport supports switching to TLS, we might want to
        # try to switch to TLS.
        tlsableTransport = interfaces.ITLSTransport(self.transport, None) is not None

        # If our transport is not already using TLS, we might want to
        # try to switch to TLS.
        nontlsTransport = interfaces.ISSLTransport(self.transport, None) is None

        if not self.startedTLS and tryTLS and tlsableTransport and nontlsTransport:
            d = self.startTLS()

            d.addCallback(self._loginTLS, username, password)
            return d

        elif self.startedTLS or not nontlsTransport or self.allowInsecureLogin:
            return self._plaintext(username, password)
        else:
            return defer.fail(InsecureAuthenticationDisallowed()) 
Example #28
Source File: pop3client.py    From learn_python3_spider with MIT License 4 votes vote down vote up
def _login(self, caps, username, password):
        """
        Continue the process of logging in to the server.

        This callback function runs after the server capabilities are received.

        If the server provided a challenge in the greeting, proceed with an
        APOP login.  Otherwise, if the server and the transport support
        encrypted communication, try to switch to TLS and then complete
        the login process with the L{_loginTLS} callback function.  Otherwise,
        if insecure authentication is allowed, do a plaintext login.
        Otherwise, fail with an L{InsecureAuthenticationDisallowed} error.

        @type caps: L{dict} mapping L{bytes} to L{list} of L{bytes} and/or
            L{bytes} to L{None}
        @param caps: The server capabilities.

        @type username: L{bytes}
        @param username: The username with which to log in.

        @type password: L{bytes}
        @param password: The password with which to log in.

        @rtype: L{Deferred <defer.Deferred>} which successfully fires with
            L{bytes}
        @return: A deferred which fires when the login process is complete.
            On a successful login, it returns the server's response minus the
            status indicator.
        """
        if self.serverChallenge is not None:
            return self._apop(username, password, self.serverChallenge)

        tryTLS = b'STLS' in caps

        # If our transport supports switching to TLS, we might want to
        # try to switch to TLS.
        tlsableTransport = interfaces.ITLSTransport(self.transport, None) is not None

        # If our transport is not already using TLS, we might want to
        # try to switch to TLS.
        nontlsTransport = interfaces.ISSLTransport(self.transport, None) is None

        if not self.startedTLS and tryTLS and tlsableTransport and nontlsTransport:
            d = self.startTLS()

            d.addCallback(self._loginTLS, username, password)
            return d

        elif self.startedTLS or not nontlsTransport or self.allowInsecureLogin:
            return self._plaintext(username, password)
        else:
            return defer.fail(InsecureAuthenticationDisallowed())