Python OpenSSL.SSL.Connection() Examples

The following are 30 code examples of OpenSSL.SSL.Connection(). 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 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 #2
Source File: tcp.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def __init__(self, sock, protocol, client, server, sessionno, reactor):
        """
        Server(sock, protocol, client, server, sessionno)

        Initialize it with a socket, a protocol, a descriptor for my peer (a
        tuple of host, port describing the other end of the connection), an
        instance of Port, and a session number.
        """
        Connection.__init__(self, sock, protocol, reactor)
        self.server = server
        self.client = client
        self.sessionno = sessionno
        self.hostname = client[0]
        self.logstr = "%s,%s,%s" % (self.protocol.__class__.__name__,
                                    sessionno,
                                    self.hostname)
        self.repstr = "<%s #%s on %s>" % (self.protocol.__class__.__name__,
                                          self.sessionno,
                                          self.server._realPortNumber)
        self.startReading()
        self.connected = 1 
Example #3
Source File: _sslverify.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def simpleVerifyHostname(connection, hostname):
    """
    Check only the common name in the certificate presented by the peer and
    only for an exact match.

    This is to provide I{something} in the way of hostname verification to
    users who haven't installed C{service_identity}. This check is overly
    strict, relies on a deprecated TLS feature (you're supposed to ignore the
    commonName if the subjectAlternativeName extensions are present, I
    believe), and lots of valid certificates will fail.

    @param connection: the OpenSSL connection to verify.
    @type connection: L{OpenSSL.SSL.Connection}

    @param hostname: The hostname expected by the user.
    @type hostname: L{unicode}

    @raise twisted.internet.ssl.VerificationError: if the common name and
        hostname don't match.
    """
    commonName = connection.get_peer_certificate().get_subject().commonName
    if commonName != hostname:
        raise SimpleVerificationError(repr(commonName) + "!=" +
                                      repr(hostname)) 
Example #4
Source File: tcp.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def startTLS(self, ctx, extra):
            assert not self.TLS
            if self.dataBuffer or self._tempDataBuffer:
                # pre-TLS bytes are still being written.  Starting TLS now
                # will do the wrong thing.  Instead, mark that we're trying
                # to go into the TLS state.
                self._tlsWaiting = _TLSDelayed([], ctx, extra)
                return False

            self.stopReading()
            self.stopWriting()
            self._startTLS()
            self.socket = SSL.Connection(ctx.getContext(), self.socket)
            self.fileno = self.socket.fileno
            self.startReading()
            return True 
Example #5
Source File: handlers.py    From oss-ftp with MIT License 6 votes vote down vote up
def ftp_PROT(self, line):
            """Setup un/secure data channel."""
            arg = line.upper()
            if not isinstance(self.socket, SSL.Connection):
                self.respond(
                    "503 PROT not allowed on insecure control connection.")
            elif not self._pbsz:
                self.respond(
                    "503 You must issue the PBSZ command prior to PROT.")
            elif arg == 'C':
                self.respond('200 Protection set to Clear')
                self._prot = False
            elif arg == 'P':
                self.respond('200 Protection set to Private')
                self._prot = True
            elif arg in ('S', 'E'):
                self.respond('521 PROT %s unsupported (use C or P).' % arg)
            else:
                self.respond("502 Unrecognized PROT type (use C or P).") 
Example #6
Source File: tcp.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def doWrite(self):
        # Retry disconnecting
        if self.disconnected:
            # This case is triggered when "disconnected" is set to True by a
            # call to _postLoseConnection from FileDescriptor.doWrite (to which
            # we upcall at the end of this overridden version of that API).  It
            # means that while, as far as any protocol connected to this
            # transport is concerned, the connection no longer exists, the
            # connection *does* actually still exist.  Instead of closing the
            # connection in the overridden _postLoseConnection, we probably
            # tried (and failed) to send a TLS close alert.  The TCP connection
            # is still up and we're waiting for the socket to become writeable
            # enough for the TLS close alert to actually be sendable.  Only
            # then will the connection actually be torn down. -exarkun
            return self._postLoseConnection()
        if self._writeDisconnected:
            return self._closeWriteConnection()

        if self.readBlockedOnWrite:
            self.readBlockedOnWrite = 0
            self._resetReadWrite()
        return Connection.doWrite(self) 
Example #7
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 #8
Source File: handlers.py    From oss-ftp with MIT License 6 votes vote down vote up
def ftp_PROT(self, line):
            """Setup un/secure data channel."""
            arg = line.upper()
            if not isinstance(self.socket, SSL.Connection):
                self.respond(
                    "503 PROT not allowed on insecure control connection.")
            elif not self._pbsz:
                self.respond(
                    "503 You must issue the PBSZ command prior to PROT.")
            elif arg == 'C':
                self.respond('200 Protection set to Clear')
                self._prot = False
            elif arg == 'P':
                self.respond('200 Protection set to Private')
                self._prot = True
            elif arg in ('S', 'E'):
                self.respond('521 PROT %s unsupported (use C or P).' % arg)
            else:
                self.respond("502 Unrecognized PROT type (use C or P).") 
Example #9
Source File: ssl.py    From Slackor with GNU General Public License v3.0 6 votes vote down vote up
def wrapClientConnection(self, cert='/tmp/impacket.crt'):
        # Create a context, we don't really care about the SSL/TLS
        # versions used since it is only intended for local use and thus
        # doesn't have to be super-secure
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        try:
            ctx.use_privatekey_file(cert)
            ctx.use_certificate_file(cert)
        except SSL.Error:
            LOG.info('SSL requested - generating self-signed certificate in /tmp/impacket.crt')
            generateImpacketCert(cert)
            ctx.use_privatekey_file(cert)
            ctx.use_certificate_file(cert)

        sslSocket = SSL.Connection(ctx, self.socksSocket)
        sslSocket.set_accept_state()

        # Now set this property back to the SSL socket instead of the regular one
        self.socksSocket = sslSocket 
Example #10
Source File: _sslverify.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def clientConnectionForTLS(self, tlsProtocol):
        """
        Create a TLS connection for a client.

        @note: This will call C{set_app_data} on its connection.  If you're
            delegating to this implementation of this method, don't ever call
            C{set_app_data} or C{set_info_callback} on the returned connection,
            or you'll break the implementation of various features of this
            class.

        @param tlsProtocol: the TLS protocol initiating the connection.
        @type tlsProtocol: L{twisted.protocols.tls.TLSMemoryBIOProtocol}

        @return: the configured client connection.
        @rtype: L{OpenSSL.SSL.Connection}
        """
        context = self._ctx
        connection = SSL.Connection(context, None)
        connection.set_app_data(tlsProtocol)
        return connection 
Example #11
Source File: _sslverify.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _identityVerifyingInfoCallback(self, connection, where, ret):
        """
        U{info_callback
        <http://pythonhosted.org/pyOpenSSL/api/ssl.html#OpenSSL.SSL.Context.set_info_callback>
        } for pyOpenSSL that verifies the hostname in the presented certificate
        matches the one passed to this L{ClientTLSOptions}.

        @param connection: the connection which is handshaking.
        @type connection: L{OpenSSL.SSL.Connection}

        @param where: flags indicating progress through a TLS handshake.
        @type where: L{int}

        @param ret: ignored
        @type ret: ignored
        """
        if where & SSL.SSL_CB_HANDSHAKE_START:
            connection.set_tlsext_host_name(self._hostnameBytes)
        elif where & SSL.SSL_CB_HANDSHAKE_DONE:
            try:
                verifyHostname(connection, self._hostnameASCII)
            except VerificationError:
                f = Failure()
                transport = connection.get_app_data()
                transport.failVerification(f) 
Example #12
Source File: crashpoc.py    From CVE-2019-0708 with GNU General Public License v3.0 6 votes vote down vote up
def send_init_packets(host):
	tpkt = TPKT()
	tpdu = TPDU()
	rdp_neg = RDP_NEG_REQ()
	rdp_neg['Type'] = 1
	rdp_neg['requestedProtocols'] = 1
	tpdu['VariablePart'] = rdp_neg.getData()
	tpdu['Code'] = 0xe0
	tpkt['TPDU'] = tpdu.getData()
	s = socket.socket()
	s.connect((host, 3389))
	s.sendall(tpkt.getData())
	s.recv(8192)
	ctx = SSL.Context(SSL.TLSv1_METHOD)
	tls = SSL.Connection(ctx,s)
	tls.set_connect_state()
	tls.do_handshake()
	return tls

# This can be fixed length now buttfuckit 
Example #13
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 #14
Source File: tls.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _unbufferPendingWrites(self):
        """
        Un-buffer all waiting writes in L{TLSMemoryBIOProtocol._appSendBuffer}.
        """
        pendingWrites, self._appSendBuffer = self._appSendBuffer, []
        for eachWrite in pendingWrites:
            self._write(eachWrite)

        if self._appSendBuffer:
            # If OpenSSL ran out of buffer space in the Connection on our way
            # through the loop earlier and re-buffered any of our outgoing
            # writes, then we're done; don't consider any future work.
            return

        if self._producer is not None:
            # If we have a registered producer, let it know that we have some
            # more buffer space.
            self._producer.resumeProducing()
            return

        if self.disconnecting:
            # Finally, if we have no further buffered data, no producer wants
            # to send us more data in the future, and the application told us
            # to end the stream, initiate a TLS shutdown.
            self._shutdownTLS() 
Example #15
Source File: tls.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def serverConnectionForTLS(self, protocol):
        """
        Construct an OpenSSL server connection from the wrapped old-style
        context factory.

        @note: Since old-style context factories don't distinguish between
            clients and servers, this is exactly the same as
            L{_ContextFactoryToConnectionFactory.clientConnectionForTLS}.

        @param protocol: The protocol initiating a TLS connection.
        @type protocol: L{TLSMemoryBIOProtocol}

        @return: a connection
        @rtype: L{OpenSSL.SSL.Connection}
        """
        return self._connectionForTLS(protocol) 
Example #16
Source File: tls.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def clientConnectionForTLS(self, protocol):
        """
        Construct an OpenSSL server connection from the wrapped old-style
        context factory.

        @note: Since old-style context factories don't distinguish between
            clients and servers, this is exactly the same as
            L{_ContextFactoryToConnectionFactory.serverConnectionForTLS}.

        @param protocol: The protocol initiating a TLS connection.
        @type protocol: L{TLSMemoryBIOProtocol}

        @return: a connection
        @rtype: L{OpenSSL.SSL.Connection}
        """
        return self._connectionForTLS(protocol) 
Example #17
Source File: tls.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _applyProtocolNegotiation(self, connection):
        """
        Applies ALPN/NPN protocol neogitation to the connection, if the factory
        supports it.

        @param connection: The OpenSSL connection object to have ALPN/NPN added
            to it.
        @type connection: L{OpenSSL.SSL.Connection}

        @return: Nothing
        @rtype: L{None}
        """
        if IProtocolNegotiationFactory.providedBy(self.wrappedFactory):
            protocols = self.wrappedFactory.acceptableProtocols()
            context = connection.get_context()
            _setAcceptableProtocols(context, protocols)

        return 
Example #18
Source File: tls.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _createConnection(self, tlsProtocol):
        """
        Create an OpenSSL connection and set it up good.

        @param tlsProtocol: The protocol which is establishing the connection.
        @type tlsProtocol: L{TLSMemoryBIOProtocol}

        @return: an OpenSSL connection object for C{tlsProtocol} to use
        @rtype: L{OpenSSL.SSL.Connection}
        """
        connectionCreator = self._connectionCreator
        if self._creatorInterface is IOpenSSLClientConnectionCreator:
            connection = connectionCreator.clientConnectionForTLS(tlsProtocol)
            self._applyProtocolNegotiation(connection)
            connection.set_connect_state()
        else:
            connection = connectionCreator.serverConnectionForTLS(tlsProtocol)
            self._applyProtocolNegotiation(connection)
            connection.set_accept_state()
        return connection 
Example #19
Source File: ssl.py    From Exchange2domain with MIT License 6 votes vote down vote up
def wrapClientConnection(self, cert='/tmp/impacket.crt'):
        # Create a context, we don't really care about the SSL/TLS
        # versions used since it is only intended for local use and thus
        # doesn't have to be super-secure
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        try:
            ctx.use_privatekey_file(cert)
            ctx.use_certificate_file(cert)
        except SSL.Error:
            LOG.info('SSL requested - generating self-signed certificate in /tmp/impacket.crt')
            generateImpacketCert(cert)
            ctx.use_privatekey_file(cert)
            ctx.use_certificate_file(cert)

        sslSocket = SSL.Connection(ctx, self.socksSocket)
        sslSocket.set_accept_state()

        # Now set this property back to the SSL socket instead of the regular one
        self.socksSocket = sslSocket 
Example #20
Source File: tls.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _createConnection(self, tlsProtocol):
        """
        Create an OpenSSL connection and set it up good.

        @param tlsProtocol: The protocol which is establishing the connection.
        @type tlsProtocol: L{TLSMemoryBIOProtocol}

        @return: an OpenSSL connection object for C{tlsProtocol} to use
        @rtype: L{OpenSSL.SSL.Connection}
        """
        connectionCreator = self._connectionCreator
        if self._creatorInterface is IOpenSSLClientConnectionCreator:
            connection = connectionCreator.clientConnectionForTLS(tlsProtocol)
            self._applyProtocolNegotiation(connection)
            connection.set_connect_state()
        else:
            connection = connectionCreator.serverConnectionForTLS(tlsProtocol)
            self._applyProtocolNegotiation(connection)
            connection.set_accept_state()
        return connection 
Example #21
Source File: tls.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _applyProtocolNegotiation(self, connection):
        """
        Applies ALPN/NPN protocol neogitation to the connection, if the factory
        supports it.

        @param connection: The OpenSSL connection object to have ALPN/NPN added
            to it.
        @type connection: L{OpenSSL.SSL.Connection}

        @return: Nothing
        @rtype: L{None}
        """
        if IProtocolNegotiationFactory.providedBy(self.wrappedFactory):
            protocols = self.wrappedFactory.acceptableProtocols()
            context = connection.get_context()
            _setAcceptableProtocols(context, protocols)

        return 
Example #22
Source File: _sslverify.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def simpleVerifyHostname(connection, hostname):
    """
    Check only the common name in the certificate presented by the peer and
    only for an exact match.

    This is to provide I{something} in the way of hostname verification to
    users who haven't installed C{service_identity}. This check is overly
    strict, relies on a deprecated TLS feature (you're supposed to ignore the
    commonName if the subjectAlternativeName extensions are present, I
    believe), and lots of valid certificates will fail.

    @param connection: the OpenSSL connection to verify.
    @type connection: L{OpenSSL.SSL.Connection}

    @param hostname: The hostname expected by the user.
    @type hostname: L{unicode}

    @raise twisted.internet.ssl.VerificationError: if the common name and
        hostname don't match.
    """
    commonName = connection.get_peer_certificate().get_subject().commonName
    if commonName != hostname:
        raise SimpleVerificationError(repr(commonName) + "!=" +
                                      repr(hostname)) 
Example #23
Source File: tls.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def clientConnectionForTLS(self, protocol):
        """
        Construct an OpenSSL server connection from the wrapped old-style
        context factory.

        @note: Since old-style context factories don't distinguish between
            clients and servers, this is exactly the same as
            L{_ContextFactoryToConnectionFactory.serverConnectionForTLS}.

        @param protocol: The protocol initiating a TLS connection.
        @type protocol: L{TLSMemoryBIOProtocol}

        @return: a connection
        @rtype: L{OpenSSL.SSL.Connection}
        """
        return self._connectionForTLS(protocol) 
Example #24
Source File: _sslverify.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def clientConnectionForTLS(self, tlsProtocol):
        """
        Create a TLS connection for a client.

        @note: This will call C{set_app_data} on its connection.  If you're
            delegating to this implementation of this method, don't ever call
            C{set_app_data} or C{set_info_callback} on the returned connection,
            or you'll break the implementation of various features of this
            class.

        @param tlsProtocol: the TLS protocol initiating the connection.
        @type tlsProtocol: L{twisted.protocols.tls.TLSMemoryBIOProtocol}

        @return: the configured client connection.
        @rtype: L{OpenSSL.SSL.Connection}
        """
        context = self._ctx
        connection = SSL.Connection(context, None)
        connection.set_app_data(tlsProtocol)
        return connection 
Example #25
Source File: tls.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def serverConnectionForTLS(self, protocol):
        """
        Construct an OpenSSL server connection from the wrapped old-style
        context factory.

        @note: Since old-style context factories don't distinguish between
            clients and servers, this is exactly the same as
            L{_ContextFactoryToConnectionFactory.clientConnectionForTLS}.

        @param protocol: The protocol initiating a TLS connection.
        @type protocol: L{TLSMemoryBIOProtocol}

        @return: a connection
        @rtype: L{OpenSSL.SSL.Connection}
        """
        return self._connectionForTLS(protocol) 
Example #26
Source File: tls.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _unbufferPendingWrites(self):
        """
        Un-buffer all waiting writes in L{TLSMemoryBIOProtocol._appSendBuffer}.
        """
        pendingWrites, self._appSendBuffer = self._appSendBuffer, []
        for eachWrite in pendingWrites:
            self._write(eachWrite)

        if self._appSendBuffer:
            # If OpenSSL ran out of buffer space in the Connection on our way
            # through the loop earlier and re-buffered any of our outgoing
            # writes, then we're done; don't consider any future work.
            return

        if self._producer is not None:
            # If we have a registered producer, let it know that we have some
            # more buffer space.
            self._producer.resumeProducing()
            return

        if self.disconnecting:
            # Finally, if we have no further buffered data, no producer wants
            # to send us more data in the future, and the application told us
            # to end the stream, initiate a TLS shutdown.
            self._shutdownTLS() 
Example #27
Source File: tls.py    From learn_python3_spider with MIT License 6 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.
        """
        self._tlsConnection = self.factory._createConnection(self)
        self._appSendBuffer = []

        # Add interfaces provided by the transport we are wrapping:
        for interface in providedBy(transport):
            directlyProvides(self, interface)

        # 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.
        self._checkHandshakeStatus() 
Example #28
Source File: tls.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 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.
        """
        self._tlsConnection = self.factory._createConnection(self)
        self._appSendBuffer = []

        # Add interfaces provided by the transport we are wrapping:
        for interface in providedBy(transport):
            directlyProvides(self, interface)

        # 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.
        self._checkHandshakeStatus() 
Example #29
Source File: tcp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def startReading(self):
        self._userWantRead = True
        if not self.readBlockedOnWrite:
            return Connection.startReading(self) 
Example #30
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