Python OpenSSL.SSL.WantReadError() Examples

The following are 30 code examples of OpenSSL.SSL.WantReadError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module OpenSSL.SSL , or try the search function .
Example #1
Source File: tls.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _checkHandshakeStatus(self):
        """
        Ask OpenSSL to proceed with a handshake in progress.

        Initially, this just sends the ClientHello; after some bytes have been
        stuffed in to the C{Connection} object by C{dataReceived}, it will then
        respond to any C{Certificate} or C{KeyExchange} messages.
        """
        # The connection might already be aborted (eg. by a callback during
        # connection setup), so don't even bother trying to handshake in that
        # case.
        if self._aborted:
            return
        try:
            self._tlsConnection.do_handshake()
        except WantReadError:
            self._flushSendBIO()
        except Error:
            self._tlsShutdownFinished(Failure())
        else:
            self._handshakeDone = True
            if IHandshakeListener.providedBy(self.wrappedProtocol):
                self.wrappedProtocol.handshakeCompleted() 
Example #2
Source File: tds.py    From Slackor with GNU General Public License v3.0 6 votes vote down vote up
def socketRecv(self, packetSize):
        data = self.socket.recv(packetSize)
        if self.tlsSocket is not None:
            dd = ''
            self.tlsSocket.bio_write(data)
            while True:
                try:
                    dd += self.tlsSocket.read(packetSize)
                except SSL.WantReadError:
                    data2 = self.socket.recv(packetSize - len(data) )
                    self.tlsSocket.bio_write(data2)
                    pass
                else:
                    data = dd
                    break
        return data 
Example #3
Source File: mssql.py    From Slackor with GNU General Public License v3.0 6 votes vote down vote up
def socketRecv(self, packetSize):
        data = self.socksSocket.recv(packetSize)
        if self.tlsSocket is not None:
            dd = b''
            self.tlsSocket.bio_write(data)
            while True:
                try:
                    dd += self.tlsSocket.read(packetSize)
                except SSL.WantReadError:
                    data2 = self.socksSocket.recv(packetSize - len(data) )
                    self.tlsSocket.bio_write(data2)
                    pass
                else:
                    data = dd
                    break
        return data 
Example #4
Source File: mssql.py    From Exchange2domain with MIT License 6 votes vote down vote up
def socketRecv(self, packetSize):
        data = self.socksSocket.recv(packetSize)
        if self.tlsSocket is not None:
            dd = ''
            self.tlsSocket.bio_write(data)
            while True:
                try:
                    dd += self.tlsSocket.read(packetSize)
                except SSL.WantReadError:
                    data2 = self.socket.recv(packetSize - len(data) )
                    self.tlsSocket.bio_write(data2)
                    pass
                else:
                    data = dd
                    break
        return data 
Example #5
Source File: tcp.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def writeSomeData(self, data):
        try:
            return Connection.writeSomeData(self, data)
        except SSL.WantWriteError:
            return 0
        except SSL.WantReadError:
            self.writeBlockedOnRead = 1
            Connection.stopWriting(self)
            Connection.startReading(self)
            return 0
        except SSL.ZeroReturnError:
            return main.CONNECTION_LOST
        except SSL.SysCallError, e:
            if e[0] == -1 and data == "":
                # errors when writing empty strings are expected
                # and can be ignored
                return 0
            else:
                return main.CONNECTION_LOST 
Example #6
Source File: tls.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _checkHandshakeStatus(self):
        """
        Ask OpenSSL to proceed with a handshake in progress.

        Initially, this just sends the ClientHello; after some bytes have been
        stuffed in to the C{Connection} object by C{dataReceived}, it will then
        respond to any C{Certificate} or C{KeyExchange} messages.
        """
        # The connection might already be aborted (eg. by a callback during
        # connection setup), so don't even bother trying to handshake in that
        # case.
        if self._aborted:
            return
        try:
            self._tlsConnection.do_handshake()
        except WantReadError:
            self._flushSendBIO()
        except Error:
            self._tlsShutdownFinished(Failure())
        else:
            self._handshakeDone = True
            if IHandshakeListener.providedBy(self.wrappedProtocol):
                self.wrappedProtocol.handshakeCompleted() 
Example #7
Source File: tcp.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def doRead(self):
        if self.writeBlockedOnRead:
            self.writeBlockedOnRead = 0
            self._resetReadWrite()
        try:
            return Connection.doRead(self)
        except SSL.ZeroReturnError:
            return main.CONNECTION_DONE
        except SSL.WantReadError:
            return
        except SSL.WantWriteError:
            self.readBlockedOnWrite = 1
            Connection.startWriting(self)
            Connection.stopReading(self)
            return
        except SSL.SysCallError, (retval, desc):
            if ((retval == -1 and desc == 'Unexpected EOF')
                or retval > 0):
                return main.CONNECTION_LOST
            log.err()
            return main.CONNECTION_LOST 
Example #8
Source File: tcp.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def writeSomeData(self, data):
        try:
            return Connection.writeSomeData(self, data)
        except SSL.WantWriteError:
            return 0
        except SSL.WantReadError:
            self.writeBlockedOnRead = 1
            Connection.stopWriting(self)
            Connection.startReading(self)
            return 0
        except SSL.ZeroReturnError:
            return main.CONNECTION_LOST
        except SSL.SysCallError, e:
            if e[0] == -1 and data == "":
                # errors when writing empty strings are expected
                # and can be ignored
                return 0
            else:
                return main.CONNECTION_LOST 
Example #9
Source File: tds.py    From cracke-dit with MIT License 6 votes vote down vote up
def socketRecv(self, packetSize):
        data = self.socket.recv(packetSize)
        if self.tlsSocket is not None:
            dd = ''
            self.tlsSocket.bio_write(data)
            while True:
                try:
                    dd += self.tlsSocket.read(packetSize)
                except SSL.WantReadError:
                    data2 = self.socket.recv(packetSize - len(data) )
                    self.tlsSocket.bio_write(data2)
                    pass
                else:
                    data = dd
                    break
        return data 
Example #10
Source File: handlers.py    From oss-ftp with MIT License 6 votes vote down vote up
def recv(self, buffer_size):
            try:
                return super(SSLConnection, self).recv(buffer_size)
            except SSL.WantReadError:
                debug("call: recv(), err: want-read", inst=self)
                self._ssl_want_read = True
                raise RetryError
            except SSL.WantWriteError:
                debug("call: recv(), err: want-write", inst=self)
                self._ssl_want_write = True
                raise RetryError
            except SSL.ZeroReturnError as err:
                debug("call: recv() -> shutdown(), err: zero-return",
                      inst=self)
                super(SSLConnection, self).handle_close()
                return b''
            except SSL.SysCallError as err:
                debug("call: recv(), err: %r" % err, inst=self)
                errnum, errstr = err.args
                if (errnum in _ERRNOS_DISCONNECTED or
                        errstr == 'Unexpected EOF'):
                    super(SSLConnection, self).handle_close()
                    return b''
                else:
                    raise 
Example #11
Source File: mssql.py    From CVE-2019-1040 with MIT License 6 votes vote down vote up
def socketRecv(self, packetSize):
        data = self.socksSocket.recv(packetSize)
        if self.tlsSocket is not None:
            dd = b''
            self.tlsSocket.bio_write(data)
            while True:
                try:
                    dd += self.tlsSocket.read(packetSize)
                except SSL.WantReadError:
                    data2 = self.socksSocket.recv(packetSize - len(data) )
                    self.tlsSocket.bio_write(data2)
                    pass
                else:
                    data = dd
                    break
        return data 
Example #12
Source File: handlers.py    From oss-ftp with MIT License 6 votes vote down vote up
def _handle_ssl_want_rw(self):
            prev_row_pending = self._ssl_want_read or self._ssl_want_write
            try:
                yield
            except SSL.WantReadError:
                # we should never get here; it's just for extra safety
                self._ssl_want_read = True
            except SSL.WantWriteError:
                # we should never get here; it's just for extra safety
                self._ssl_want_write = True

            if self._ssl_want_read:
                self.modify_ioloop_events(
                    self._wanted_io_events | self.ioloop.READ, logdebug=True)
            elif self._ssl_want_write:
                self.modify_ioloop_events(
                    self._wanted_io_events | self.ioloop.WRITE, logdebug=True)
            else:
                if prev_row_pending:
                    self.modify_ioloop_events(self._wanted_io_events) 
Example #13
Source File: handlers.py    From oss-ftp with MIT License 6 votes vote down vote up
def recv(self, buffer_size):
            try:
                return super(SSLConnection, self).recv(buffer_size)
            except SSL.WantReadError:
                debug("call: recv(), err: want-read", inst=self)
                self._ssl_want_read = True
                raise RetryError
            except SSL.WantWriteError:
                debug("call: recv(), err: want-write", inst=self)
                self._ssl_want_write = True
                raise RetryError
            except SSL.ZeroReturnError as err:
                debug("call: recv() -> shutdown(), err: zero-return",
                      inst=self)
                super(SSLConnection, self).handle_close()
                return b''
            except SSL.SysCallError as err:
                debug("call: recv(), err: %r" % err, inst=self)
                errnum, errstr = err.args
                if (errnum in _ERRNOS_DISCONNECTED or
                        errstr == 'Unexpected EOF'):
                    super(SSLConnection, self).handle_close()
                    return b''
                else:
                    raise 
Example #14
Source File: handlers.py    From oss-ftp with MIT License 6 votes vote down vote up
def _handle_ssl_want_rw(self):
            prev_row_pending = self._ssl_want_read or self._ssl_want_write
            try:
                yield
            except SSL.WantReadError:
                # we should never get here; it's just for extra safety
                self._ssl_want_read = True
            except SSL.WantWriteError:
                # we should never get here; it's just for extra safety
                self._ssl_want_write = True

            if self._ssl_want_read:
                self.modify_ioloop_events(
                    self._wanted_io_events | self.ioloop.READ, logdebug=True)
            elif self._ssl_want_write:
                self.modify_ioloop_events(
                    self._wanted_io_events | self.ioloop.WRITE, logdebug=True)
            else:
                if prev_row_pending:
                    self.modify_ioloop_events(self._wanted_io_events) 
Example #15
Source File: tds.py    From PiBunny with MIT License 6 votes vote down vote up
def socketRecv(self, packetSize):
        data = self.socket.recv(packetSize)
        if self.tlsSocket is not None:
            dd = ''
            self.tlsSocket.bio_write(data)
            while True:
                try:
                    dd += self.tlsSocket.read(packetSize)
                except SSL.WantReadError:
                    data2 = self.socket.recv(packetSize - len(data) )
                    self.tlsSocket.bio_write(data2)
                    pass
                else:
                    data = dd
                    break
        return data 
Example #16
Source File: tds.py    From CVE-2017-7494 with GNU General Public License v3.0 6 votes vote down vote up
def socketRecv(self, packetSize):
        data = self.socket.recv(packetSize)
        if self.tlsSocket is not None:
            dd = ''
            self.tlsSocket.bio_write(data)
            while True:
                try:
                    dd += self.tlsSocket.read(packetSize)
                except SSL.WantReadError:
                    data2 = self.socket.recv(packetSize - len(data) )
                    self.tlsSocket.bio_write(data2)
                    pass
                else:
                    data = dd
                    break
        return data 
Example #17
Source File: mssqlrelayclient.py    From CVE-2019-1040 with MIT License 5 votes vote down vote up
def initConnection(self):
        self.connect()
        #This is copied from tds.py
        resp = self.preLogin()
        if resp['Encryption'] == TDS_ENCRYPT_REQ or resp['Encryption'] == TDS_ENCRYPT_OFF:
            LOG.debug("Encryption required, switching to TLS")

            # Switching to TLS now
            ctx = SSL.Context(SSL.TLSv1_METHOD)
            ctx.set_cipher_list('RC4, AES256')
            tls = SSL.Connection(ctx,None)
            tls.set_connect_state()
            while True:
                try:
                    tls.do_handshake()
                except SSL.WantReadError:
                    data = tls.bio_read(4096)
                    self.sendTDS(TDS_PRE_LOGIN, data,0)
                    tds = self.recvTDS()
                    tls.bio_write(tds['Data'])
                else:
                    break

            # SSL and TLS limitation: Secure Socket Layer (SSL) and its replacement,
            # Transport Layer Security(TLS), limit data fragments to 16k in size.
            self.packetSize = 16*1024-1
            self.tlsSocket = tls
        self.resp = resp
        return True 
Example #18
Source File: mssqlrelayclient.py    From PiBunny with MIT License 5 votes vote down vote up
def init_connection(self):
        self.connect()
        #This is copied from tds.py
        resp = self.preLogin()
        if resp['Encryption'] == TDS_ENCRYPT_REQ or resp['Encryption'] == TDS_ENCRYPT_OFF:
            logging.info("Encryption required, switching to TLS")

            # Switching to TLS now
            ctx = SSL.Context(SSL.TLSv1_METHOD)
            ctx.set_cipher_list('RC4')
            tls = SSL.Connection(ctx,None)
            tls.set_connect_state()
            while True:
                try:
                    tls.do_handshake()
                except SSL.WantReadError:
                    data = tls.bio_read(4096)
                    self.sendTDS(TDS_PRE_LOGIN, data,0)
                    tds = self.recvTDS()
                    tls.bio_write(tds['Data'])
                else:
                    break

            # SSL and TLS limitation: Secure Socket Layer (SSL) and its replacement, 
            # Transport Layer Security(TLS), limit data fragments to 16k in size.
            self.packetSize = 16*1024-1
            self.tlsSocket = tls
        self.resp = resp 
Example #19
Source File: context-info-callback.py    From pyopenssl with Apache License 2.0 5 votes vote down vote up
def go():
    port = socket()
    port.bind(('', 0))
    port.listen(1)

    called = []
    def info(conn, where, ret):
        print count.next()
        called.append(None)
    context = Context(TLSv1_METHOD)
    context.set_info_callback(info)
    context.use_certificate(
        load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
    context.use_privatekey(
        load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))

    while 1:
        client = socket()
        client.setblocking(False)
        client.connect_ex(port.getsockname())

        clientSSL = Connection(Context(TLSv1_METHOD), client)
        clientSSL.set_connect_state()

        server, ignored = port.accept()
        server.setblocking(False)

        serverSSL = Connection(context, server)
        serverSSL.set_accept_state()

        del called[:]
        while not called:
            for ssl in clientSSL, serverSSL:
                try:
                    ssl.do_handshake()
                except WantReadError:
                    pass 
Example #20
Source File: context-verify-callback.py    From pyopenssl with Apache License 2.0 5 votes vote down vote up
def go():
    port = socket()
    port.bind(('', 0))
    port.listen(1)

    called = []
    def info(*args):
        print count.next()
        called.append(None)
        return 1
    context = Context(TLSv1_METHOD)
    context.set_verify(VERIFY_PEER, info)
    context.use_certificate(
        load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
    context.use_privatekey(
        load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))

    while 1:
        client = socket()
        client.setblocking(False)
        client.connect_ex(port.getsockname())

        clientSSL = Connection(context, client)
        clientSSL.set_connect_state()

        server, ignored = port.accept()
        server.setblocking(False)

        serverSSL = Connection(context, server)
        serverSSL.set_accept_state()

        del called[:]
        while not called:
            for ssl in clientSSL, serverSSL:
                try:
                    ssl.send('foo')
                except WantReadError, e:
                    pass 
Example #21
Source File: ssl_pyopenssl.py    From bokken with GNU General Public License v2.0 5 votes vote down vote up
def _safe_call(self, is_reader, call, *args, **kwargs):
        """Wrap the given call with SSL error-trapping.
        
        is_reader: if False EOF errors will be raised. If True, EOF errors
        will return "" (to emulate normal sockets).
        """
        start = time.time()
        while True:
            try:
                return call(*args, **kwargs)
            except SSL.WantReadError:
                # Sleep and try again. This is dangerous, because it means
                # the rest of the stack has no way of differentiating
                # between a "new handshake" error and "client dropped".
                # Note this isn't an endless loop: there's a timeout below.
                time.sleep(self.ssl_retry)
            except SSL.WantWriteError:
                time.sleep(self.ssl_retry)
            except SSL.SysCallError, e:
                if is_reader and e.args == (-1, 'Unexpected EOF'):
                    return ""
                
                errnum = e.args[0]
                if is_reader and errnum in wsgiserver.socket_errors_to_ignore:
                    return ""
                raise socket.error(errnum)
            except SSL.Error, e:
                if is_reader and e.args == (-1, 'Unexpected EOF'):
                    return ""
                
                thirdarg = None
                try:
                    thirdarg = e.args[0][0][2]
                except IndexError:
                    pass
                
                if thirdarg == 'http request':
                    # The client is talking HTTP to an HTTPS server.
                    raise wsgiserver.NoSSLError()
                
                raise wsgiserver.FatalSSLAlert(*e.args) 
Example #22
Source File: ssl_pyopenssl.py    From cosa-nostra with GNU General Public License v3.0 5 votes vote down vote up
def _safe_call(self, is_reader, call, *args, **kwargs):
        """Wrap the given call with SSL error-trapping.
        
        is_reader: if False EOF errors will be raised. If True, EOF errors
        will return "" (to emulate normal sockets).
        """
        start = time.time()
        while True:
            try:
                return call(*args, **kwargs)
            except SSL.WantReadError:
                # Sleep and try again. This is dangerous, because it means
                # the rest of the stack has no way of differentiating
                # between a "new handshake" error and "client dropped".
                # Note this isn't an endless loop: there's a timeout below.
                time.sleep(self.ssl_retry)
            except SSL.WantWriteError:
                time.sleep(self.ssl_retry)
            except SSL.SysCallError, e:
                if is_reader and e.args == (-1, 'Unexpected EOF'):
                    return ""
                
                errnum = e.args[0]
                if is_reader and errnum in wsgiserver.socket_errors_to_ignore:
                    return ""
                raise socket.error(errnum)
            except SSL.Error, e:
                if is_reader and e.args == (-1, 'Unexpected EOF'):
                    return ""
                
                thirdarg = None
                try:
                    thirdarg = e.args[0][0][2]
                except IndexError:
                    pass
                
                if thirdarg == 'http request':
                    # The client is talking HTTP to an HTTPS server.
                    raise wsgiserver.NoSSLError()
                
                raise wsgiserver.FatalSSLAlert(*e.args) 
Example #23
Source File: tls.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _flushSendBIO(self):
        """
        Read any bytes out of the send BIO and write them to the underlying
        transport.
        """
        try:
            bytes = self._tlsConnection.bio_read(2 ** 15)
        except WantReadError:
            # There may be nothing in the send BIO right now.
            pass
        else:
            self.transport.write(bytes) 
Example #24
Source File: tls.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def makeConnection(self, transport):
        """
        Connect this wrapper to the given transport and initialize the
        necessary L{OpenSSL.SSL.Connection} with a memory BIO.
        """
        tlsContext = self.factory._contextFactory.getContext()
        self._tlsConnection = Connection(tlsContext, None)
        if self.factory._isClient:
            self._tlsConnection.set_connect_state()
        else:
            self._tlsConnection.set_accept_state()
        self._appSendBuffer = []

        # Intentionally skip ProtocolWrapper.makeConnection - it might call
        # wrappedProtocol.makeConnection, which we want to make conditional.
        Protocol.makeConnection(self, transport)
        self.factory.registerProtocol(self)
        if self._connectWrapped:
            # Now that the TLS layer is initialized, notify the application of
            # the connection.
            ProtocolWrapper.makeConnection(self, transport)

        # Now that we ourselves have a transport (initialized by the
        # ProtocolWrapper.makeConnection call above), kick off the TLS
        # handshake.
        try:
            self._tlsConnection.do_handshake()
        except WantReadError:
            # This is the expected case - there's no data in the connection's
            # input buffer yet, so it won't be able to complete the whole
            # handshake now.  If this is the speak-first side of the
            # connection, then some bytes will be in the send buffer now; flush
            # them.
            self._flushSendBIO() 
Example #25
Source File: tcp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def doRead(self):
        if self.disconnected:
            # See the comment in the similar check in doWrite below.
            # Additionally, in order for anything other than returning
            # CONNECTION_DONE here to make sense, it will probably be necessary
            # to implement a way to switch back to TCP from TLS (actually, if
            # we did something other than return CONNECTION_DONE, that would be
            # a big part of implementing that feature).  In other words, the
            # expectation is that doRead will be called when self.disconnected
            # is True only when the connection has been lost.  It's possible
            # that the other end could stop speaking TLS and then send us some
            # non-TLS data.  We'll end up ignoring that data and dropping the
            # connection.  There's no unit tests for this check in the cases
            # where it makes a difference.  The test suite only hits this
            # codepath when it would have otherwise hit the SSL.ZeroReturnError
            # exception handler below, which has exactly the same behavior as
            # this conditional.  Maybe that's the only case that can ever be
            # triggered, I'm not sure.  -exarkun
            return main.CONNECTION_DONE
        if self.writeBlockedOnRead:
            self.writeBlockedOnRead = 0
            self._resetReadWrite()
        try:
            return Connection.doRead(self)
        except SSL.ZeroReturnError:
            return main.CONNECTION_DONE
        except SSL.WantReadError:
            return
        except SSL.WantWriteError:
            self.readBlockedOnWrite = 1
            Connection.startWriting(self)
            Connection.stopReading(self)
            return
        except SSL.SysCallError, (retval, desc):
            if ((retval == -1 and desc == 'Unexpected EOF')
                or retval > 0):
                return main.CONNECTION_LOST
            log.err()
            return main.CONNECTION_LOST 
Example #26
Source File: ssl_pyopenssl.py    From moviegrabber with GNU General Public License v3.0 5 votes vote down vote up
def _safe_call(self, is_reader, call, *args, **kwargs):
        """Wrap the given call with SSL error-trapping.
        
        is_reader: if False EOF errors will be raised. If True, EOF errors
        will return "" (to emulate normal sockets).
        """
        start = time.time()
        while True:
            try:
                return call(*args, **kwargs)
            except SSL.WantReadError:
                # Sleep and try again. This is dangerous, because it means
                # the rest of the stack has no way of differentiating
                # between a "new handshake" error and "client dropped".
                # Note this isn't an endless loop: there's a timeout below.
                time.sleep(self.ssl_retry)
            except SSL.WantWriteError:
                time.sleep(self.ssl_retry)
            except SSL.SysCallError, e:
                if is_reader and e.args == (-1, 'Unexpected EOF'):
                    return ""
                
                errnum = e.args[0]
                if is_reader and errnum in wsgiserver.socket_errors_to_ignore:
                    return ""
                raise socket.error(errnum)
            except SSL.Error, e:
                if is_reader and e.args == (-1, 'Unexpected EOF'):
                    return ""
                
                thirdarg = None
                try:
                    thirdarg = e.args[0][0][2]
                except IndexError:
                    pass
                
                if thirdarg == 'http request':
                    # The client is talking HTTP to an HTTPS server.
                    raise wsgiserver.NoSSLError()
                
                raise wsgiserver.FatalSSLAlert(*e.args) 
Example #27
Source File: tls.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _flushReceiveBIO(self):
        """
        Try to receive any application-level bytes which are now available
        because of a previous write into the receive BIO.  This will take
        care of delivering any application-level bytes which are received to
        the protocol, as well as handling of the various exceptions which
        can come from trying to get such bytes.
        """
        # Keep trying this until an error indicates we should stop or we
        # close the connection.  Looping is necessary to make sure we
        # process all of the data which was put into the receive BIO, as
        # there is no guarantee that a single recv call will do it all.
        while not self._lostTLSConnection:
            try:
                bytes = self._tlsConnection.recv(2 ** 15)
            except WantReadError:
                # The newly received bytes might not have been enough to produce
                # any application data.
                break
            except ZeroReturnError:
                # TLS has shut down and no more TLS data will be received over
                # this connection.
                self._shutdownTLS()
                # Passing in None means the user protocol's connnectionLost
                # will get called with reason from underlying transport:
                self._tlsShutdownFinished(None)
            except Error:
                # Something went pretty wrong.  For example, this might be a
                # handshake failure during renegotiation (because there were no
                # shared ciphers, because a certificate failed to verify, etc).
                # TLS can no longer proceed.
                failure = Failure()
                self._tlsShutdownFinished(failure)
            else:
                if not self._aborted:
                    ProtocolWrapper.dataReceived(self, bytes)

        # The received bytes might have generated a response which needs to be
        # sent now.  For example, the handshake involves several round-trip
        # exchanges without ever producing application-bytes.
        self._flushSendBIO() 
Example #28
Source File: mssqlrelayclient.py    From CVE-2017-7494 with GNU General Public License v3.0 5 votes vote down vote up
def init_connection(self):
        self.connect()
        #This is copied from tds.py
        resp = self.preLogin()
        if resp['Encryption'] == TDS_ENCRYPT_REQ or resp['Encryption'] == TDS_ENCRYPT_OFF:
            logging.info("Encryption required, switching to TLS")

            # Switching to TLS now
            ctx = SSL.Context(SSL.TLSv1_METHOD)
            ctx.set_cipher_list('RC4')
            tls = SSL.Connection(ctx,None)
            tls.set_connect_state()
            while True:
                try:
                    tls.do_handshake()
                except SSL.WantReadError:
                    data = tls.bio_read(4096)
                    self.sendTDS(TDS_PRE_LOGIN, data,0)
                    tds = self.recvTDS()
                    tls.bio_write(tds['Data'])
                else:
                    break

            # SSL and TLS limitation: Secure Socket Layer (SSL) and its replacement, 
            # Transport Layer Security(TLS), limit data fragments to 16k in size.
            self.packetSize = 16*1024-1
            self.tlsSocket = tls
        self.resp = resp 
Example #29
Source File: ssl_pyopenssl.py    From SalesforceXyTools with Apache License 2.0 5 votes vote down vote up
def _safe_call(self, is_reader, call, *args, **kwargs):
        """Wrap the given call with SSL error-trapping.
        
        is_reader: if False EOF errors will be raised. If True, EOF errors
        will return "" (to emulate normal sockets).
        """
        start = time.time()
        while True:
            try:
                return call(*args, **kwargs)
            except SSL.WantReadError:
                # Sleep and try again. This is dangerous, because it means
                # the rest of the stack has no way of differentiating
                # between a "new handshake" error and "client dropped".
                # Note this isn't an endless loop: there's a timeout below.
                time.sleep(self.ssl_retry)
            except SSL.WantWriteError:
                time.sleep(self.ssl_retry)
            except SSL.SysCallError, e:
                if is_reader and e.args == (-1, 'Unexpected EOF'):
                    return ""
                
                errnum = e.args[0]
                if is_reader and errnum in wsgiserver.socket_errors_to_ignore:
                    return ""
                raise socket.error(errnum)
            except SSL.Error, e:
                if is_reader and e.args == (-1, 'Unexpected EOF'):
                    return ""
                
                thirdarg = None
                try:
                    thirdarg = e.args[0][0][2]
                except IndexError:
                    pass
                
                if thirdarg == 'http request':
                    # The client is talking HTTP to an HTTPS server.
                    raise wsgiserver.NoSSLError()
                
                raise wsgiserver.FatalSSLAlert(*e.args) 
Example #30
Source File: ssl_pyopenssl.py    From nightmare with GNU General Public License v2.0 5 votes vote down vote up
def _safe_call(self, is_reader, call, *args, **kwargs):
        """Wrap the given call with SSL error-trapping.
        
        is_reader: if False EOF errors will be raised. If True, EOF errors
        will return "" (to emulate normal sockets).
        """
        start = time.time()
        while True:
            try:
                return call(*args, **kwargs)
            except SSL.WantReadError:
                # Sleep and try again. This is dangerous, because it means
                # the rest of the stack has no way of differentiating
                # between a "new handshake" error and "client dropped".
                # Note this isn't an endless loop: there's a timeout below.
                time.sleep(self.ssl_retry)
            except SSL.WantWriteError:
                time.sleep(self.ssl_retry)
            except SSL.SysCallError, e:
                if is_reader and e.args == (-1, 'Unexpected EOF'):
                    return ""
                
                errnum = e.args[0]
                if is_reader and errnum in wsgiserver.socket_errors_to_ignore:
                    return ""
                raise socket.error(errnum)
            except SSL.Error, e:
                if is_reader and e.args == (-1, 'Unexpected EOF'):
                    return ""
                
                thirdarg = None
                try:
                    thirdarg = e.args[0][0][2]
                except IndexError:
                    pass
                
                if thirdarg == 'http request':
                    # The client is talking HTTP to an HTTPS server.
                    raise wsgiserver.NoSSLError()
                
                raise wsgiserver.FatalSSLAlert(*e.args)