Example #1
0
    def test_server_with_client_proposing_SHA256_on_TLSv1_1(self):
        gen_sock = MockSocket(bytearray(0))

        gen_record_layer = RecordLayer(gen_sock)
        gen_record_layer.version = (3, 0)

        ciphers = [CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256,
                   CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256,
                   0x88, # TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
                   CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV]

        client_hello = ClientHello().create(version=(3, 2),
                                            random=bytearray(32),
                                            session_id=bytearray(0),
                                            cipher_suites=ciphers)

        for res in gen_record_layer.sendRecord(client_hello):
            if res in (0, 1):
                self.assertTrue(False, "Blocking socket")
            else:
                break

        # test proper
        sock = MockSocket(gen_sock.sent[0])

        conn = TLSConnection(sock)

        srv_private_key = parsePEMKey(srv_raw_key, private=True)
        srv_cert_chain = X509CertChain([X509().parse(srv_raw_certificate)])
        with self.assertRaises(TLSLocalAlert) as err:
            conn.handshakeServer(certChain=srv_cert_chain,
                                 privateKey=srv_private_key)

        self.assertEqual(err.exception.description,
                         AlertDescription.handshake_failure)
    def test_client_with_server_responing_with_SHA256_on_TLSv1_1(self):
        # socket to generate the faux response
        gen_sock = MockSocket(bytearray(0))

        gen_record_layer = RecordLayer(gen_sock)
        gen_record_layer.version = (3, 2)

        server_hello = ServerHello().create(
            version=(3, 2),
            random=bytearray(32),
            session_id=bytearray(0),
            cipher_suite=CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256,
            certificate_type=None,
            tackExt=None,
            next_protos_advertised=None,
        )

        for res in gen_record_layer.sendRecord(server_hello):
            if res in (0, 1):
                self.assertTrue(False, "Blocking socket")
            else:
                break

        # test proper
        sock = MockSocket(gen_sock.sent[0])

        conn = TLSConnection(sock)

        with self.assertRaises(TLSLocalAlert) as err:
            conn.handshakeClientCert()

        self.assertEqual(err.exception.description, AlertDescription.illegal_parameter)
Example #3
0
    def test_padding_extension_with_hello_over_256(self):
        sock = self.prepare_mock_socket_with_handshake_failure()

        conn = TLSConnection(sock)
        # create hostname extension
        with self.assertRaises(TLSRemoteAlert):
            # use serverName with 252 bytes
            settings = HandshakeSettings()
            settings.maxVersion = (3, 3)
            settings.keyShares = []
            conn.handshakeClientCert(
                settings=settings,
                serverName='aaaaaaaaaabbbbbbbbbbccccccccccdddddddddd.' +
                'eeeeeeeeeeffffffffffgggggggggghhhhhhhhhh.' +
                'iiiiiiiiiijjjjjjjjjjkkkkkkkkkkllllllllll.' +
                'mmmmmmmmmmnnnnnnnnnnoooooooooopppppppppp.' +
                'qqqqqqqqqqrrrrrrrrrrsssssssssstttttttttt.' +
                'uuuuuuuuuuvvvvvvvvvvwwwwwwwwwwxxxxxxxxxx.' + 'y.com')

        self.assertEqual(len(sock.sent), 1)
        # check for version and content type (handshake)
        self.assertEqual(sock.sent[0][0:3], bytearray(b'\x16' + b'\x03\x03'))
        # check for handshake message type (client_hello)
        self.assertEqual(sock.sent[0][5:6], bytearray(b'\x01'))
        self.assertEqual(sock.sent[0][5:9], bytearray(b'\x01\x00\x02\x00'))
        # 5 bytes is record layer header, 4 bytes is handshake protocol header
        self.assertEqual(len(sock.sent[0]) - 5 - 4, 512)
Example #4
0
    def test_client_with_server_responing_with_SHA256_on_TLSv1_1(self):
        # socket to generate the faux response
        gen_sock = MockSocket(bytearray(0))

        gen_record_layer = RecordLayer(gen_sock)
        gen_record_layer.version = (3, 2)

        server_hello = ServerHello().create(
            version=(3, 2),
            random=bytearray(32),
            session_id=bytearray(0),
            cipher_suite=CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256,
            certificate_type=None,
            tackExt=None,
            next_protos_advertised=None)

        for res in gen_record_layer.sendRecord(server_hello):
            if res in (0, 1):
                self.assertTrue(False, "Blocking socket")
            else:
                break

        # test proper
        sock = MockSocket(gen_sock.sent[0])

        conn = TLSConnection(sock)

        with self.assertRaises(TLSLocalAlert) as err:
            conn.handshakeClientCert()

        self.assertEqual(err.exception.description,
                         AlertDescription.illegal_parameter)
    def test_padding_extension_with_hello_over_256(self):
        sock = self.prepare_mock_socket_with_handshake_failure()

        conn = TLSConnection(sock)
        # create hostname extension
        with self.assertRaises(TLSRemoteAlert):
            # use serverName with 254 bytes
            conn.handshakeClientCert(
                serverName='aaaaaaaaaabbbbbbbbbbccccccccccdddddddddd' +
                           'eeeeeeeeeeffffffffffgggggggggghhhhhhhhhh' +
                           'iiiiiiiiiijjjjjjjjjjkkkkkkkkkkllllllllll' +
                           'mmmmmmmmmmnnnnnnnnnnoooooooooopppppppppp' +
                           'qqqqqqqqqqrrrrrrrrrrsssssssssstttttttttt' +
                           'uuuuuuuuuuvvvvvvvvvvwwwwwwwwwwxxxxxxxxxx' +
                           'yyyyyyyyyy.com')

        self.assertEqual(len(sock.sent), 1)
        # check for version and content type (handshake)
        self.assertEqual(sock.sent[0][0:3], bytearray(
            b'\x16' +
            b'\x03\x03'))
        # check for handshake message type (client_hello)
        self.assertEqual(sock.sent[0][5:6], bytearray(
            b'\x01'))
        self.assertEqual(sock.sent[0][5:9], bytearray(
            b'\x01\x00\x02\x00'))
        # 5 bytes is record layer header, 4 bytes is handshake protocol header
        self.assertEqual(len(sock.sent[0]) - 5 - 4, 512)
    def test_server_with_client_proposing_SHA256_on_TLSv1_1(self):
        gen_sock = MockSocket(bytearray(0))

        gen_record_layer = RecordLayer(gen_sock)
        gen_record_layer.version = (3, 0)

        ciphers = [
            CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256,
            CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256,
            0x88,  # TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
            CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV,
        ]

        client_hello = ClientHello().create(
            version=(3, 2), random=bytearray(32), session_id=bytearray(0), cipher_suites=ciphers
        )

        for res in gen_record_layer.sendRecord(client_hello):
            if res in (0, 1):
                self.assertTrue(False, "Blocking socket")
            else:
                break

        # test proper
        sock = MockSocket(gen_sock.sent[0])

        conn = TLSConnection(sock)

        srv_private_key = parsePEMKey(self.srv_raw_key, private=True)
        srv_cert_chain = X509CertChain([X509().parse(self.srv_raw_certificate)])
        with self.assertRaises(TLSLocalAlert) as err:
            conn.handshakeServer(certChain=srv_cert_chain, privateKey=srv_private_key)

        self.assertEqual(err.exception.description, AlertDescription.handshake_failure)
Example #7
0
 def finish_request(self, sock, client_address):
     try:
         tlsConnection = TLSConnection(sock)
         if self.handshake(tlsConnection) == True:
             self.RequestHandlerClass(tlsConnection, client_address, self)
             tlsConnection.close()
     except OSError:
         print("Connection closed before data was received")
    def test_keyingMaterialExporter_tls1_2_sha384(self):
        sock = MockSocket(bytearray(0))
        conn = TLSConnection(sock)
        conn._clientRandom = bytearray(b'012345678901234567890123456789ab')
        conn._serverRandom = bytearray(b'987654321098765432109876543210ab')
        conn._recordLayer.version = (3, 3)
        conn.session = Session()
        conn.session.cipherSuite = \
            CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384

        mat = conn.keyingMaterialExporter(bytearray(b'test'), 20)
        self.assertEqual(mat,
                bytearray(b'1\xb8X\xef\x9b\xa5\n9p\x13\xfaxXI\\$\xdf\xb5\xc7i'))
Example #9
0
    def open(self, host='', port=IMAP4_TLS_PORT):
        """Setup connection to remote server on "host:port".

        This connection will be used by the routines:
        read, readline, send, shutdown.
        """
        self.host = host
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect((host, port))
        self.sock = TLSConnection(self.sock)
        ClientHelper._handshake(self, self.sock)
        self.file = self.sock.makefile('rb')
    def test_keyingMaterialExporter_tls1_2_sha256(self):
        sock = MockSocket(bytearray(0))
        conn = TLSConnection(sock)
        conn._clientRandom = bytearray(b'012345678901234567890123456789ab')
        conn._serverRandom = bytearray(b'987654321098765432109876543210ab')
        conn._recordLayer.version = (3, 3)
        conn.session = Session()
        conn.session.cipherSuite = \
            CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256

        mat = conn.keyingMaterialExporter(bytearray(b'test'), 20)
        self.assertEqual(mat,
                bytearray(b'\xe6EQ\x93\xcb!\xe7\x87\x1e\xdd\x85' +
                          b'\xb2\x08|\xc9\xbfDh\r\x90'))
    def test_keyingMaterialExporter_tls1_1(self):
        sock = MockSocket(bytearray(0))
        conn = TLSConnection(sock)
        conn._clientRandom = bytearray(b'012345678901234567890123456789ab')
        conn._serverRandom = bytearray(b'987654321098765432109876543210ab')
        conn._recordLayer.version = (3, 2)
        conn.session = Session()
        conn.session.cipherSuite = \
            CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA

        mat = conn.keyingMaterialExporter(bytearray(b'test'), 20)
        self.assertEqual(mat,
                bytearray(b'\x1f\xf8\x18\x01:\x9f\x15a\xd5x\xaa;Y>' +
                          b'\xafG\x92AH\xa4'))
Example #12
0
    def test_keyingMaterialExporter_tls1_3_sha384(self):
        sock = MockSocket(bytearray(0))
        conn = TLSConnection(sock)
        conn._recordLayer.version = (3, 4)
        conn.session = Session()
        conn.session.cipherSuite = \
            CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
        conn.session.exporterMasterSecret = \
            bytearray(b'0123456789abcdef0123456789abcdef0123456789abcdef' +
                      b'0123456789abcdef0123456789abcdef0123456789abcdef')

        mat = conn.keyingMaterialExporter(bytearray(b'test'), 20)
        self.assertEqual(
            mat, bytearray(b';\x96;\x08U*\xbd1\x0fL5^0\xe1*I\x9e\xd3\xcb0'))
Example #13
0
 def __init__(self, factory, wrappedProtocol):
     ProtocolWrapper.__init__(self, factory, wrappedProtocol)
     AsyncStateMachine.__init__(self)
     self.fakeSocket = _FakeSocket(self)
     self.tlsConnection = TLSConnection(self.fakeSocket)
     self.tlsStarted = False
     self.connectionLostCalled = False
Example #14
0
def wrap_socket(sock,
                keyfile=None,
                certfile=None,
                server_side=False,
                cert_reqs=CERT_NONE,
                ssl_version=PROTOCOL_SSLv23,
                ca_certs=None,
                do_handshake_on_connect=True,
                suppress_ragged_eofs=True,
                ciphers=None,
                fingerprint=None):

    try:
        sock = TLSConnection(sock)

        if do_handshake_on_connect:
            checker = None if fingerprint is None else tlslite.CheckerXfw(
                x509Fingerprint=fingerprint)
            helper = ClientHelper(checker=checker)
            helper._handshake(sock)
    except:
        sock = None
        raise

    return sock
Example #15
0
    def test_keyingMaterialExporter_tls1_3_sha256(self):
        sock = MockSocket(bytearray(0))
        conn = TLSConnection(sock)
        conn._recordLayer.version = (3, 4)
        conn.session = Session()
        conn.session.cipherSuite = \
            CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
        conn.session.exporterMasterSecret = \
            bytearray(b'0123456789abcdef0123456789abcdef' +
                      b'0123456789abcdef0123456789abcdef')

        mat = conn.keyingMaterialExporter(bytearray(b'test'), 20)
        self.assertEqual(
            mat,
            bytearray(
                b'W_h\x10\x83\xc0XD\x0fw\x0e\xfc/\x92\x8f\xb3\xfd\x13\x96\xd9')
        )
Example #16
0
    def connect(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        if hasattr(sock, 'settimeout'):
            sock.settimeout(10)
        sock.connect((self.host, self.port))

        #Use a TLSConnection to emulate a socket
        self.sock = TLSConnection(sock)

        #When httplib closes this, close the socket
        self.sock.closeSocket = True
        self._handshake(self.sock)
Example #17
0
    def test_server_with_client_not_using_required_EMS(self):
        gen_sock = MockSocket(bytearray(0))

        gen_record_layer = RecordLayer(gen_sock)
        gen_record_layer.version = (3, 0)

        ciphers = [
            CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256,
            CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256,
            CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV
        ]

        client_hello = ClientHello().create(version=(3, 3),
                                            random=bytearray(32),
                                            session_id=bytearray(0),
                                            cipher_suites=ciphers)

        for res in gen_record_layer.sendRecord(client_hello):
            if res in (0, 1):
                self.assertTrue(False, "Blocking socket")
            else:
                break

        # test proper
        sock = MockSocket(gen_sock.sent[0])

        conn = TLSConnection(sock)

        hs = HandshakeSettings()
        hs.requireExtendedMasterSecret = True

        srv_private_key = parsePEMKey(srv_raw_key, private=True)
        srv_cert_chain = X509CertChain([X509().parse(srv_raw_certificate)])
        with self.assertRaises(TLSLocalAlert) as err:
            conn.handshakeServer(certChain=srv_cert_chain,
                                 privateKey=srv_private_key,
                                 settings=hs)

        self.assertEqual(err.exception.description,
                         AlertDescription.insufficient_security)
Example #18
0
    def test_client_with_server_responing_with_wrong_session_id_in_TLS1_3(
            self):
        # socket to generate the faux response
        gen_sock = MockSocket(bytearray(0))

        gen_record_layer = RecordLayer(gen_sock)
        gen_record_layer.version = (3, 3)

        srv_ext = []
        srv_ext.append(SrvSupportedVersionsExtension().create((3, 4)))
        srv_ext.append(ServerKeyShareExtension().create(KeyShareEntry().create(
            GroupName.secp256r1, bytearray(b'\x03' + b'\x01' * 32))))

        server_hello = ServerHello().create(
            version=(3, 3),
            random=bytearray(32),
            session_id=bytearray(b"test"),
            cipher_suite=CipherSuite.TLS_AES_128_GCM_SHA256,
            certificate_type=None,
            tackExt=None,
            next_protos_advertised=None,
            extensions=srv_ext)

        for res in gen_record_layer.sendRecord(server_hello):
            if res in (0, 1):
                self.assertTrue(False, "Blocking socket")
            else:
                break

        # test proper
        sock = MockSocket(gen_sock.sent[0])

        conn = TLSConnection(sock)

        with self.assertRaises(TLSLocalAlert) as err:
            conn.handshakeClientCert()

        self.assertEqual(err.exception.description,
                         AlertDescription.illegal_parameter)
Example #19
0
    def open(self, host = '', port = IMAP4_TLS_PORT):
        """Setup connection to remote server on "host:port".

        This connection will be used by the routines:
        read, readline, send, shutdown.
        """
        self.host = host
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect((host, port))
        self.sock = TLSConnection(self.sock)
        ClientHelper._handshake(self, self.sock)
        self.file = self.sock.makefile('rb')
Example #20
0
 def test_connection_no_rsa_pss(self):
     settings = HandshakeSettings()
     settings.maxVersion = (3, 3)
     # exclude pss as the keys in this module are too small for
     # the needed salt size for sha512 hash
     settings.rsaSchemes = ["pkcs1"]
     conn = TLSConnection(self.client_socket)
     conn.handshakeClientCert(serverName="localhost", settings=settings)
     self.assertIn(conn.session.cipherSuite, CipherSuite.aeadSuites)
     conn.write(bytearray(b"client hello"))
     ret = conn.read(min=len("Conn OK"))
     self.assertEqual(ret, bytearray(b"Conn OK"))
Example #21
0
    def test_keyingMaterialExporter_tls1_3(self):
        sock = MockSocket(bytearray(0))
        conn = TLSConnection(sock)
        conn._clientRandom = bytearray(b'012345678901234567890123456789ab')
        conn._serverRandom = bytearray(b'987654321098765432109876543210ab')
        conn._recordLayer.version = (3, 4)
        conn.session = Session()
        conn.session.cipherSuite = \
            CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256

        with self.assertRaises(AssertionError):
            conn.keyingMaterialExporter(bytearray(b'test'), 20)
Example #22
0
    def test_keyingMaterialExporter_invalid_label(self):
        sock = MockSocket(bytearray(0))
        conn = TLSConnection(sock)
        conn._clientRandom = bytearray(b'012345678901234567890123456789ab')
        conn._serverRandom = bytearray(b'987654321098765432109876543210ab')
        conn._recordLayer.version = (3, 1)
        conn.session = Session()
        conn.session.cipherSuite = \
            CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA

        with self.assertRaises(ValueError):
            conn.keyingMaterialExporter(bytearray(b'server finished'), 20)
    def test_server_with_client_not_using_required_EMS(self):
        gen_sock = MockSocket(bytearray(0))

        gen_record_layer = RecordLayer(gen_sock)
        gen_record_layer.version = (3, 0)

        ciphers = [CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256,
                   CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256,
                   CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV]

        client_hello = ClientHello().create(version=(3, 3),
                                            random=bytearray(32),
                                            session_id=bytearray(0),
                                            cipher_suites=ciphers)

        for res in gen_record_layer.sendRecord(client_hello):
            if res in (0, 1):
                self.assertTrue(False, "Blocking socket")
            else:
                break

        # test proper
        sock = MockSocket(gen_sock.sent[0])

        conn = TLSConnection(sock)

        hs = HandshakeSettings()
        hs.requireExtendedMasterSecret = True

        srv_private_key = parsePEMKey(srv_raw_key, private=True)
        srv_cert_chain = X509CertChain([X509().parse(srv_raw_certificate)])
        with self.assertRaises(TLSLocalAlert) as err:
            conn.handshakeServer(certChain=srv_cert_chain,
                                 privateKey=srv_private_key,
                                 settings=hs)

        self.assertEqual(err.exception.description,
                         AlertDescription.insufficient_security)
Example #24
0
    def __init__(self, sock=None):
        AsyncStateMachine.__init__(self)

        if sock:
            self.tlsConnection = TLSConnection(sock)

        #Calculate the sibling I'm being mixed in with.
        #This is necessary since we override functions
        #like readable(), handle_read(), etc., but we
        #also want to call the sibling's versions.
        for cl in self.__class__.__bases__:
            if cl != TLSAsyncDispatcherMixIn and cl != AsyncStateMachine:
                self.siblingClass = cl
                break
        else:
            raise AssertionError()
    def test_keyingMaterialExporter_invalid_label(self):
        sock = MockSocket(bytearray(0))
        conn = TLSConnection(sock)
        conn._clientRandom = bytearray(b'012345678901234567890123456789ab')
        conn._serverRandom = bytearray(b'987654321098765432109876543210ab')
        conn._recordLayer.version = (3, 1)
        conn.session = Session()
        conn.session.cipherSuite = \
            CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA

        with self.assertRaises(ValueError):
            conn.keyingMaterialExporter(bytearray(b'server finished'), 20)
    def test_keyingMaterialExporter_tls1_3(self):
        sock = MockSocket(bytearray(0))
        conn = TLSConnection(sock)
        conn._clientRandom = bytearray(b'012345678901234567890123456789ab')
        conn._serverRandom = bytearray(b'987654321098765432109876543210ab')
        conn._recordLayer.version = (3, 4)
        conn.session = Session()
        conn.session.cipherSuite = \
            CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256

        with self.assertRaises(AssertionError):
            conn.keyingMaterialExporter(bytearray(b'test'), 20)
Example #27
0
    def test_keyingMaterialExporter_tls1_2_sha384(self):
        sock = MockSocket(bytearray(0))
        conn = TLSConnection(sock)
        conn._clientRandom = bytearray(b'012345678901234567890123456789ab')
        conn._serverRandom = bytearray(b'987654321098765432109876543210ab')
        conn._recordLayer.version = (3, 3)
        conn.session = Session()
        conn.session.cipherSuite = \
            CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384

        mat = conn.keyingMaterialExporter(bytearray(b'test'), 20)
        self.assertEqual(mat,
                bytearray(b'1\xb8X\xef\x9b\xa5\n9p\x13\xfaxXI\\$\xdf\xb5\xc7i'))
Example #28
0
    def test_keyingMaterialExporter_tls1_1(self):
        sock = MockSocket(bytearray(0))
        conn = TLSConnection(sock)
        conn._clientRandom = bytearray(b'012345678901234567890123456789ab')
        conn._serverRandom = bytearray(b'987654321098765432109876543210ab')
        conn._recordLayer.version = (3, 2)
        conn.session = Session()
        conn.session.cipherSuite = \
            CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA

        mat = conn.keyingMaterialExporter(bytearray(b'test'), 20)
        self.assertEqual(mat,
                bytearray(b'\x1f\xf8\x18\x01:\x9f\x15a\xd5x\xaa;Y>' +
                          b'\xafG\x92AH\xa4'))
Example #29
0
    def test_keyingMaterialExporter_tls1_2_sha256(self):
        sock = MockSocket(bytearray(0))
        conn = TLSConnection(sock)
        conn._clientRandom = bytearray(b'012345678901234567890123456789ab')
        conn._serverRandom = bytearray(b'987654321098765432109876543210ab')
        conn._recordLayer.version = (3, 3)
        conn.session = Session()
        conn.session.cipherSuite = \
            CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256

        mat = conn.keyingMaterialExporter(bytearray(b'test'), 20)
        self.assertEqual(mat,
                bytearray(b'\xe6EQ\x93\xcb!\xe7\x87\x1e\xdd\x85' +
                          b'\xb2\x08|\xc9\xbfDh\r\x90'))
Example #30
0
    def setUp(self):
        self.client_socket, self.server_socket = socket.socketpair()

        self.server_socket.settimeout(1)
        self.server = TLSConnection(self.server_socket)

        def server_process(server):
            settings = HandshakeSettings()
            settings.maxVersion = (3, 3)
            server.handshakeServer(certChain=self.cert_chain,
                                   privateKey=self.certKey)
            ret = server.read(min=len("client hello"))
            if ret != bytearray(b"client hello"):
                raise AssertionError("incorrect query")
            server.write(bytearray(b"Conn OK"))
            server.close()

        self.thread = threading.Thread(target=server_process,
                                       args=(self.server, ))
        self.thread.start()
Example #31
0
class POP3_TLS(POP3, ClientHelper):
    """This class extends L{poplib.POP3} with TLS support."""
    def __init__(self,
                 host,
                 port=POP3_TLS_PORT,
                 username=None,
                 password=None,
                 sharedKey=None,
                 certChain=None,
                 privateKey=None,
                 cryptoID=None,
                 protocol=None,
                 x509Fingerprint=None,
                 x509TrustList=None,
                 x509CommonName=None,
                 settings=None):
        """Create a new POP3_TLS.

        For client authentication, use one of these argument
        combinations:
         - username, password (SRP)
         - username, sharedKey (shared-key)
         - certChain, privateKey (certificate)

        For server authentication, you can either rely on the
        implicit mutual authentication performed by SRP or
        shared-keys, or you can do certificate-based server
        authentication with one of these argument combinations:
         - cryptoID[, protocol] (requires cryptoIDlib)
         - x509Fingerprint
         - x509TrustList[, x509CommonName] (requires cryptlib_py)

        Certificate-based server authentication is compatible with
        SRP or certificate-based client authentication.  It is
        not compatible with shared-keys.

        The caller should be prepared to handle TLS-specific
        exceptions.  See the client handshake functions in
        L{tlslite.TLSConnection.TLSConnection} for details on which
        exceptions might be raised.

        @type host: str
        @param host: Server to connect to.

        @type port: int
        @param port: Port to connect to.

        @type username: str
        @param username: SRP or shared-key username.  Requires the
        'password' or 'sharedKey' argument.

        @type password: str
        @param password: SRP password for mutual authentication.
        Requires the 'username' argument.

        @type sharedKey: str
        @param sharedKey: Shared key for mutual authentication.
        Requires the 'username' argument.

        @type certChain: L{tlslite.X509CertChain.X509CertChain} or
        L{cryptoIDlib.CertChain.CertChain}
        @param certChain: Certificate chain for client authentication.
        Requires the 'privateKey' argument.  Excludes the SRP or
        shared-key related arguments.

        @type privateKey: L{tlslite.utils.RSAKey.RSAKey}
        @param privateKey: Private key for client authentication.
        Requires the 'certChain' argument.  Excludes the SRP or
        shared-key related arguments.

        @type cryptoID: str
        @param cryptoID: cryptoID for server authentication.  Mutually
        exclusive with the 'x509...' arguments.

        @type protocol: str
        @param protocol: cryptoID protocol URI for server
        authentication.  Requires the 'cryptoID' argument.

        @type x509Fingerprint: str
        @param x509Fingerprint: Hex-encoded X.509 fingerprint for
        server authentication.  Mutually exclusive with the 'cryptoID'
        and 'x509TrustList' arguments.

        @type x509TrustList: list of L{tlslite.X509.X509}
        @param x509TrustList: A list of trusted root certificates.  The
        other party must present a certificate chain which extends to
        one of these root certificates.  The cryptlib_py module must be
        installed to use this parameter.  Mutually exclusive with the
        'cryptoID' and 'x509Fingerprint' arguments.

        @type x509CommonName: str
        @param x509CommonName: The end-entity certificate's 'CN' field
        must match this value.  For a web server, this is typically a
        server name such as 'www.amazon.com'.  Mutually exclusive with
        the 'cryptoID' and 'x509Fingerprint' arguments.  Requires the
        'x509TrustList' argument.

        @type settings: L{tlslite.HandshakeSettings.HandshakeSettings}
        @param settings: Various settings which can be used to control
        the ciphersuites, certificate types, and SSL/TLS versions
        offered by the client.
        """

        self.host = host
        self.port = port
        msg = "getaddrinfo returns an empty list"
        self.sock = None
        for res in socket.getaddrinfo(self.host, self.port, 0,
                                      socket.SOCK_STREAM):
            af, socktype, proto, canonname, sa = res
            try:
                self.sock = socket.socket(af, socktype, proto)
                self.sock.connect(sa)
            except socket.error, msg:
                if self.sock:
                    self.sock.close()
                self.sock = None
                continue
            break
        if not self.sock:
            raise socket.error, msg

        ### New code below (all else copied from poplib)
        ClientHelper.__init__(self, username, password, sharedKey, certChain,
                              privateKey, cryptoID, protocol, x509Fingerprint,
                              x509TrustList, x509CommonName, settings)

        self.sock = TLSConnection(self.sock)
        self.sock.closeSocket = True
        ClientHelper._handshake(self, self.sock)
        ###

        self.file = self.sock.makefile('rb')
        self._debugging = 0
        self.welcome = self._getresp()
Example #32
0
    def __init__(self,
                 host,
                 port=POP3_SSL_PORT,
                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
                 username=None,
                 password=None,
                 certChain=None,
                 privateKey=None,
                 checker=None,
                 settings=None):
        """Create a new POP3_TLS.

        For client authentication, use one of these argument
        combinations:
         - username, password (SRP)
         - certChain, privateKey (certificate)

        For server authentication, you can either rely on the
        implicit mutual authentication performed by SRP or
        you can do certificate-based server
        authentication with one of these argument combinations:
         - x509Fingerprint

        Certificate-based server authentication is compatible with
        SRP or certificate-based client authentication.

        The caller should be prepared to handle TLS-specific
        exceptions.  See the client handshake functions in
        L{tlslite.TLSConnection.TLSConnection} for details on which
        exceptions might be raised.

        @type host: str
        @param host: Server to connect to.

        @type port: int
        @param port: Port to connect to.

        @type username: str
        @param username: SRP username.
        
        @type password: str
        @param password: SRP password for mutual authentication.
        Requires the 'username' argument.

        @type certChain: L{tlslite.x509certchain.X509CertChain}
        @param certChain: Certificate chain for client authentication.
        Requires the 'privateKey' argument.  Excludes the SRP argument.

        @type privateKey: L{tlslite.utils.rsakey.RSAKey}
        @param privateKey: Private key for client authentication.
        Requires the 'certChain' argument.  Excludes the SRP argument.

        @type checker: L{tlslite.checker.Checker}
        @param checker: Callable object called after handshaking to 
        evaluate the connection and raise an Exception if necessary.

        @type settings: L{tlslite.handshakesettings.HandshakeSettings}
        @param settings: Various settings which can be used to control
        the ciphersuites, certificate types, and SSL/TLS versions
        offered by the client.
        """
        self.host = host
        self.port = port
        sock = socket.create_connection((host, port), timeout)
        ClientHelper.__init__(self, username, password, certChain, privateKey,
                              checker, settings)
        connection = TLSConnection(sock)
        ClientHelper._handshake(self, connection)
        self.sock = connection
        self.file = self.sock.makefile('rb')
        self._debugging = 0
        self.welcome = self._getresp()
Example #33
0
 def connect(self):
     httplib.HTTPConnection.connect(self)
     self.sock = TLSConnection(self.sock)
     self.sock.ignoreAbruptClose = self.ignoreAbruptClose
     ClientHelper._handshake(self, self.sock)
Example #34
0
    def starttls(self,
                 username=None,
                 password=None,
                 sharedKey=None,
                 certChain=None,
                 privateKey=None,
                 cryptoID=None,
                 protocol=None,
                 x509Fingerprint=None,
                 x509TrustList=None,
                 x509CommonName=None,
                 settings=None):
        """Puts the connection to the SMTP server into TLS mode.

        If the server supports TLS, this will encrypt the rest of the SMTP
        session.

        For client authentication, use one of these argument
        combinations:
         - username, password (SRP)
         - username, sharedKey (shared-key)
         - certChain, privateKey (certificate)

        For server authentication, you can either rely on the
        implicit mutual authentication performed by SRP or
        shared-keys, or you can do certificate-based server
        authentication with one of these argument combinations:
         - cryptoID[, protocol] (requires cryptoIDlib)
         - x509Fingerprint
         - x509TrustList[, x509CommonName] (requires cryptlib_py)

        Certificate-based server authentication is compatible with
        SRP or certificate-based client authentication.  It is
        not compatible with shared-keys.

        The caller should be prepared to handle TLS-specific
        exceptions.  See the client handshake functions in
        L{tlslite.TLSConnection.TLSConnection} for details on which
        exceptions might be raised.

        @type username: str
        @param username: SRP or shared-key username.  Requires the
        'password' or 'sharedKey' argument.

        @type password: str
        @param password: SRP password for mutual authentication.
        Requires the 'username' argument.

        @type sharedKey: str
        @param sharedKey: Shared key for mutual authentication.
        Requires the 'username' argument.

        @type certChain: L{tlslite.X509CertChain.X509CertChain} or
        L{cryptoIDlib.CertChain.CertChain}
        @param certChain: Certificate chain for client authentication.
        Requires the 'privateKey' argument.  Excludes the SRP or
        shared-key related arguments.

        @type privateKey: L{tlslite.utils.RSAKey.RSAKey}
        @param privateKey: Private key for client authentication.
        Requires the 'certChain' argument.  Excludes the SRP or
        shared-key related arguments.

        @type cryptoID: str
        @param cryptoID: cryptoID for server authentication.  Mutually
        exclusive with the 'x509...' arguments.

        @type protocol: str
        @param protocol: cryptoID protocol URI for server
        authentication.  Requires the 'cryptoID' argument.

        @type x509Fingerprint: str
        @param x509Fingerprint: Hex-encoded X.509 fingerprint for
        server authentication.  Mutually exclusive with the 'cryptoID'
        and 'x509TrustList' arguments.

        @type x509TrustList: list of L{tlslite.X509.X509}
        @param x509TrustList: A list of trusted root certificates.  The
        other party must present a certificate chain which extends to
        one of these root certificates.  The cryptlib_py module must be
        installed to use this parameter.  Mutually exclusive with the
        'cryptoID' and 'x509Fingerprint' arguments.

        @type x509CommonName: str
        @param x509CommonName: The end-entity certificate's 'CN' field
        must match this value.  For a web server, this is typically a
        server name such as 'www.amazon.com'.  Mutually exclusive with
        the 'cryptoID' and 'x509Fingerprint' arguments.  Requires the
        'x509TrustList' argument.

        @type settings: L{tlslite.HandshakeSettings.HandshakeSettings}
        @param settings: Various settings which can be used to control
        the ciphersuites, certificate types, and SSL/TLS versions
        offered by the client.
        """
        (resp, reply) = self.docmd("STARTTLS")
        if resp == 220:
            helper = ClientHelper(username, password, sharedKey, certChain,
                                  privateKey, cryptoID, protocol,
                                  x509Fingerprint, x509TrustList,
                                  x509CommonName, settings)
            conn = TLSConnection(self.sock)
            conn.closeSocket = True
            helper._handshake(conn)
            self.sock = conn
            self.file = conn.makefile('rb')
        return (resp, reply)
Example #35
0
    def starttls(
        self,
        username=None,
        password=None,
        sharedKey=None,
        certChain=None,
        privateKey=None,
        cryptoID=None,
        protocol=None,
        x509Fingerprint=None,
        x509TrustList=None,
        x509CommonName=None,
        settings=None,
    ):
        """Puts the connection to the SMTP server into TLS mode.

        If the server supports TLS, this will encrypt the rest of the SMTP
        session.

        For client authentication, use one of these argument
        combinations:
         - username, password (SRP)
         - username, sharedKey (shared-key)
         - certChain, privateKey (certificate)

        For server authentication, you can either rely on the
        implicit mutual authentication performed by SRP or
        shared-keys, or you can do certificate-based server
        authentication with one of these argument combinations:
         - cryptoID[, protocol] (requires cryptoIDlib)
         - x509Fingerprint
         - x509TrustList[, x509CommonName] (requires cryptlib_py)

        Certificate-based server authentication is compatible with
        SRP or certificate-based client authentication.  It is
        not compatible with shared-keys.

        The caller should be prepared to handle TLS-specific
        exceptions.  See the client handshake functions in
        L{tlslite.TLSConnection.TLSConnection} for details on which
        exceptions might be raised.

        @type username: str
        @param username: SRP or shared-key username.  Requires the
        'password' or 'sharedKey' argument.

        @type password: str
        @param password: SRP password for mutual authentication.
        Requires the 'username' argument.

        @type sharedKey: str
        @param sharedKey: Shared key for mutual authentication.
        Requires the 'username' argument.

        @type certChain: L{tlslite.X509CertChain.X509CertChain} or
        L{cryptoIDlib.CertChain.CertChain}
        @param certChain: Certificate chain for client authentication.
        Requires the 'privateKey' argument.  Excludes the SRP or
        shared-key related arguments.

        @type privateKey: L{tlslite.utils.RSAKey.RSAKey}
        @param privateKey: Private key for client authentication.
        Requires the 'certChain' argument.  Excludes the SRP or
        shared-key related arguments.

        @type cryptoID: str
        @param cryptoID: cryptoID for server authentication.  Mutually
        exclusive with the 'x509...' arguments.

        @type protocol: str
        @param protocol: cryptoID protocol URI for server
        authentication.  Requires the 'cryptoID' argument.

        @type x509Fingerprint: str
        @param x509Fingerprint: Hex-encoded X.509 fingerprint for
        server authentication.  Mutually exclusive with the 'cryptoID'
        and 'x509TrustList' arguments.

        @type x509TrustList: list of L{tlslite.X509.X509}
        @param x509TrustList: A list of trusted root certificates.  The
        other party must present a certificate chain which extends to
        one of these root certificates.  The cryptlib_py module must be
        installed to use this parameter.  Mutually exclusive with the
        'cryptoID' and 'x509Fingerprint' arguments.

        @type x509CommonName: str
        @param x509CommonName: The end-entity certificate's 'CN' field
        must match this value.  For a web server, this is typically a
        server name such as 'www.amazon.com'.  Mutually exclusive with
        the 'cryptoID' and 'x509Fingerprint' arguments.  Requires the
        'x509TrustList' argument.

        @type settings: L{tlslite.HandshakeSettings.HandshakeSettings}
        @param settings: Various settings which can be used to control
        the ciphersuites, certificate types, and SSL/TLS versions
        offered by the client.
        """
        (resp, reply) = self.docmd("STARTTLS")
        if resp == 220:
            helper = ClientHelper(
                username,
                password,
                sharedKey,
                certChain,
                privateKey,
                cryptoID,
                protocol,
                x509Fingerprint,
                x509TrustList,
                x509CommonName,
                settings,
            )
            conn = TLSConnection(self.sock)
            conn.closeSocket = True
            helper._handshake(conn)
            self.sock = conn
            self.file = conn.makefile("rb")
        return (resp, reply)
Example #36
0
 def finish_request(self, sock, client_address):
     tlsConnection = TLSConnection(sock)
     if self.handshake(tlsConnection) == True:
         self.RequestHandlerClass(tlsConnection, client_address, self)
         tlsConnection.close()
Example #37
0
    def starttls(self,
                 username=None, password=None,
                 certChain=None, privateKey=None,
                 checker=None,
                 settings=None):
        """Puts the connection to the SMTP server into TLS mode.

        If the server supports TLS, this will encrypt the rest of the SMTP
        session.

        For client authentication, use one of these argument
        combinations:
         - username, password (SRP)
         - certChain, privateKey (certificate)

        For server authentication, you can either rely on the
        implicit mutual authentication performed by SRP or
        you can do certificate-based server
        authentication with one of these argument combinations:
         - x509Fingerprint

        Certificate-based server authentication is compatible with
        SRP or certificate-based client authentication.

        The caller should be prepared to handle TLS-specific
        exceptions.  See the client handshake functions in
        L{tlslite.TLSConnection.TLSConnection} for details on which
        exceptions might be raised.

        @type username: str
        @param username: SRP username.  Requires the
        'password' argument.

        @type password: str
        @param password: SRP password for mutual authentication.
        Requires the 'username' argument.

        @type certChain: L{tlslite.x509certchain.X509CertChain}
        @param certChain: Certificate chain for client authentication.
        Requires the 'privateKey' argument.  Excludes the SRP arguments.

        @type privateKey: L{tlslite.utils.rsakey.RSAKey}
        @param privateKey: Private key for client authentication.
        Requires the 'certChain' argument.  Excludes the SRP arguments.

        @type checker: L{tlslite.checker.Checker}
        @param checker: Callable object called after handshaking to 
        evaluate the connection and raise an Exception if necessary.

        @type settings: L{tlslite.handshakesettings.HandshakeSettings}
        @param settings: Various settings which can be used to control
        the ciphersuites, certificate types, and SSL/TLS versions
        offered by the client.
        """
        (resp, reply) = self.docmd("STARTTLS")
        if resp == 220:
            helper = ClientHelper(
                     username, password, 
                     certChain, privateKey,
                     checker,
                     settings)
            conn = TLSConnection(self.sock)
            helper._handshake(conn)
            self.sock = conn
            self.file = conn.makefile('rb')
        return (resp, reply)
Example #38
0
class IMAP4_TLS(IMAP4, ClientHelper):
    """This class extends L{imaplib.IMAP4} with TLS support."""
    def __init__(self,
                 host='',
                 port=IMAP4_TLS_PORT,
                 username=None,
                 password=None,
                 sharedKey=None,
                 certChain=None,
                 privateKey=None,
                 cryptoID=None,
                 protocol=None,
                 x509Fingerprint=None,
                 x509TrustList=None,
                 x509CommonName=None,
                 settings=None):
        """Create a new IMAP4_TLS.

        For client authentication, use one of these argument
        combinations:
         - username, password (SRP)
         - username, sharedKey (shared-key)
         - certChain, privateKey (certificate)

        For server authentication, you can either rely on the
        implicit mutual authentication performed by SRP or
        shared-keys, or you can do certificate-based server
        authentication with one of these argument combinations:
         - cryptoID[, protocol] (requires cryptoIDlib)
         - x509Fingerprint
         - x509TrustList[, x509CommonName] (requires cryptlib_py)

        Certificate-based server authentication is compatible with
        SRP or certificate-based client authentication.  It is
        not compatible with shared-keys.

        The caller should be prepared to handle TLS-specific
        exceptions.  See the client handshake functions in
        L{tlslite.TLSConnection.TLSConnection} for details on which
        exceptions might be raised.

        @type host: str
        @param host: Server to connect to.

        @type port: int
        @param port: Port to connect to.

        @type username: str
        @param username: SRP or shared-key username.  Requires the
        'password' or 'sharedKey' argument.

        @type password: str
        @param password: SRP password for mutual authentication.
        Requires the 'username' argument.

        @type sharedKey: str
        @param sharedKey: Shared key for mutual authentication.
        Requires the 'username' argument.

        @type certChain: L{tlslite.X509CertChain.X509CertChain} or
        L{cryptoIDlib.CertChain.CertChain}
        @param certChain: Certificate chain for client authentication.
        Requires the 'privateKey' argument.  Excludes the SRP or
        shared-key related arguments.

        @type privateKey: L{tlslite.utils.RSAKey.RSAKey}
        @param privateKey: Private key for client authentication.
        Requires the 'certChain' argument.  Excludes the SRP or
        shared-key related arguments.

        @type cryptoID: str
        @param cryptoID: cryptoID for server authentication.  Mutually
        exclusive with the 'x509...' arguments.

        @type protocol: str
        @param protocol: cryptoID protocol URI for server
        authentication.  Requires the 'cryptoID' argument.

        @type x509Fingerprint: str
        @param x509Fingerprint: Hex-encoded X.509 fingerprint for
        server authentication.  Mutually exclusive with the 'cryptoID'
        and 'x509TrustList' arguments.

        @type x509TrustList: list of L{tlslite.X509.X509}
        @param x509TrustList: A list of trusted root certificates.  The
        other party must present a certificate chain which extends to
        one of these root certificates.  The cryptlib_py module must be
        installed to use this parameter.  Mutually exclusive with the
        'cryptoID' and 'x509Fingerprint' arguments.

        @type x509CommonName: str
        @param x509CommonName: The end-entity certificate's 'CN' field
        must match this value.  For a web server, this is typically a
        server name such as 'www.amazon.com'.  Mutually exclusive with
        the 'cryptoID' and 'x509Fingerprint' arguments.  Requires the
        'x509TrustList' argument.

        @type settings: L{tlslite.HandshakeSettings.HandshakeSettings}
        @param settings: Various settings which can be used to control
        the ciphersuites, certificate types, and SSL/TLS versions
        offered by the client.
        """

        ClientHelper.__init__(self, username, password, sharedKey, certChain,
                              privateKey, cryptoID, protocol, x509Fingerprint,
                              x509TrustList, x509CommonName, settings)

        IMAP4.__init__(self, host, port)

    def open(self, host='', port=IMAP4_TLS_PORT):
        """Setup connection to remote server on "host:port".

        This connection will be used by the routines:
        read, readline, send, shutdown.
        """
        self.host = host
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect((host, port))
        self.sock = TLSConnection(self.sock)
        self.sock.closeSocket = True
        ClientHelper._handshake(self, self.sock)
        self.file = self.sock.makefile('rb')
Example #39
0
    def starttls(self,
                 username=None,
                 password=None,
                 certChain=None,
                 privateKey=None,
                 use_fido2=False,
                 domain_name=None,
                 checker=None,
                 settings=None):
        """Puts the connection to the SMTP server into TLS mode.

        If the server supports TLS, this will encrypt the rest of the SMTP
        session.

        For client authentication, use one of these argument
        combinations:

         - username, password (SRP)
         - certChain, privateKey (certificate)
         - use_fido2, domain_name (and username) (FIDO2)

        For server authentication, you can either rely on the
        implicit mutual authentication performed by SRP, FIDO2 or
        you can do certificate-based server
        authentication with one of these argument combinations:

         - x509Fingerprint

        Certificate-based server authentication is compatible with
        SRP or certificate-based client authentication.

        The caller should be prepared to handle TLS-specific
        exceptions.  See the client handshake functions in
        :py:class:`~tlslite.tlsconnection.TLSConnection` for details on which
        exceptions might be raised.

        :type username: str
        :param username: SRP or FIDO2 username.  Requires the
            'password' argument for SRP.

        :type password: str
        :param password: SRP password for mutual authentication.
            Requires the 'username' argument.

        :type certChain: ~tlslite.x509certchain.X509CertChain
        :param certChain: Certificate chain for client authentication.
            Requires the 'privateKey' argument.  Excludes the SRP arguments.

        :type privateKey: ~tlslite.utils.rsakey.RSAKey
        :param privateKey: Private key for client authentication.
            Requires the 'certChain' argument.  Excludes the SRP arguments.

        :type use_fido2: bool
        :param use_fido2: Indication whether or not to use FIDO2
            authentication. Requires the 'domain_name' parameter or 'host'
            as domain name.

        :type domain_name: str
        :param domain_name: The domain name of the server to authenticate
            against using FIDO2. May be omitted if host is given as a domain
            name.

        :type checker: ~tlslite.checker.Checker
        :param checker: Callable object called after handshaking to
            evaluate the connection and raise an Exception if necessary.

        :type settings: ~tlslite.handshakesettings.HandshakeSettings
        :param settings: Various settings which can be used to control
            the ciphersuites, certificate types, and SSL/TLS versions
            offered by the client.
        """
        (resp, reply) = self.docmd("STARTTLS")
        if resp == 220:
            helper = ClientHelper(username, password, certChain, privateKey,
                                  use_fido2, domain_name, checker, settings)
            conn = TLSConnection(self.sock)
            helper._handshake(conn)
            self.sock = conn
            self.file = conn.makefile('rb')
        return (resp, reply)
Example #40
0
class IMAP4_TLS(IMAP4, ClientHelper):
    """This class extends L{imaplib.IMAP4} with TLS support."""
    def __init__(self,
                 host='',
                 port=IMAP4_TLS_PORT,
                 username=None,
                 password=None,
                 certChain=None,
                 privateKey=None,
                 checker=None,
                 settings=None):
        """Create a new IMAP4_TLS.

        For client authentication, use one of these argument
        combinations:
         - username, password (SRP)
         - certChain, privateKey (certificate)

        For server authentication, you can either rely on the
        implicit mutual authentication performed by SRP
        or you can do certificate-based server
        authentication with one of these argument combinations:
         - x509Fingerprint

        Certificate-based server authentication is compatible with
        SRP or certificate-based client authentication.

        The caller should be prepared to handle TLS-specific
        exceptions.  See the client handshake functions in
        L{tlslite.TLSConnection.TLSConnection} for details on which
        exceptions might be raised.

        @type host: str
        @param host: Server to connect to.

        @type port: int
        @param port: Port to connect to.

        @type username: str
        @param username: SRP username.  Requires the
        'password' argument.

        @type password: str
        @param password: SRP password for mutual authentication.
        Requires the 'username' argument.

        @type certChain: L{tlslite.x509certchain.X509CertChain}
        @param certChain: Certificate chain for client authentication.
        Requires the 'privateKey' argument.  Excludes the SRP arguments.

        @type privateKey: L{tlslite.utils.rsakey.RSAKey}
        @param privateKey: Private key for client authentication.
        Requires the 'certChain' argument.  Excludes the SRP arguments.
        
        @type checker: L{tlslite.checker.Checker}
        @param checker: Callable object called after handshaking to 
        evaluate the connection and raise an Exception if necessary.

        @type settings: L{tlslite.handshakesettings.HandshakeSettings}
        @param settings: Various settings which can be used to control
        the ciphersuites, certificate types, and SSL/TLS versions
        offered by the client.
        """

        ClientHelper.__init__(self, username, password, certChain, privateKey,
                              checker, settings)

        IMAP4.__init__(self, host, port)

    def open(self, host='', port=IMAP4_TLS_PORT):
        """Setup connection to remote server on "host:port".

        This connection will be used by the routines:
        read, readline, send, shutdown.
        """
        self.host = host
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect((host, port))
        self.sock = TLSConnection(self.sock)
        ClientHelper._handshake(self, self.sock)
        self.file = self.sock.makefile('rb')
Example #41
0
 def finish_request(self, sock, client_address):
     tlsConnection = TLSConnection(sock)
     if self.handshake(tlsConnection) == True:
         self.RequestHandlerClass(tlsConnection, client_address, self)
         tlsConnection.close()
Example #42
0
class IMAP4_TLS(IMAP4, ClientHelper):
    """This class extends L{imaplib.IMAP4} with TLS support."""

    def __init__(self, host = '', port = IMAP4_TLS_PORT,
                 username=None, password=None, sharedKey=None,
                 certChain=None, privateKey=None,
                 cryptoID=None, protocol=None,
                 x509Fingerprint=None,
                 x509TrustList=None, x509CommonName=None,
                 settings=None):
        """Create a new IMAP4_TLS.

        For client authentication, use one of these argument
        combinations:
         - username, password (SRP)
         - username, sharedKey (shared-key)
         - certChain, privateKey (certificate)

        For server authentication, you can either rely on the
        implicit mutual authentication performed by SRP or
        shared-keys, or you can do certificate-based server
        authentication with one of these argument combinations:
         - cryptoID[, protocol] (requires cryptoIDlib)
         - x509Fingerprint
         - x509TrustList[, x509CommonName] (requires cryptlib_py)

        Certificate-based server authentication is compatible with
        SRP or certificate-based client authentication.  It is
        not compatible with shared-keys.

        The caller should be prepared to handle TLS-specific
        exceptions.  See the client handshake functions in
        L{tlslite.TLSConnection.TLSConnection} for details on which
        exceptions might be raised.

        @type host: str
        @param host: Server to connect to.

        @type port: int
        @param port: Port to connect to.

        @type username: str
        @param username: SRP or shared-key username.  Requires the
        'password' or 'sharedKey' argument.

        @type password: str
        @param password: SRP password for mutual authentication.
        Requires the 'username' argument.

        @type sharedKey: str
        @param sharedKey: Shared key for mutual authentication.
        Requires the 'username' argument.

        @type certChain: L{tlslite.X509CertChain.X509CertChain} or
        L{cryptoIDlib.CertChain.CertChain}
        @param certChain: Certificate chain for client authentication.
        Requires the 'privateKey' argument.  Excludes the SRP or
        shared-key related arguments.

        @type privateKey: L{tlslite.utils.RSAKey.RSAKey}
        @param privateKey: Private key for client authentication.
        Requires the 'certChain' argument.  Excludes the SRP or
        shared-key related arguments.

        @type cryptoID: str
        @param cryptoID: cryptoID for server authentication.  Mutually
        exclusive with the 'x509...' arguments.

        @type protocol: str
        @param protocol: cryptoID protocol URI for server
        authentication.  Requires the 'cryptoID' argument.

        @type x509Fingerprint: str
        @param x509Fingerprint: Hex-encoded X.509 fingerprint for
        server authentication.  Mutually exclusive with the 'cryptoID'
        and 'x509TrustList' arguments.

        @type x509TrustList: list of L{tlslite.X509.X509}
        @param x509TrustList: A list of trusted root certificates.  The
        other party must present a certificate chain which extends to
        one of these root certificates.  The cryptlib_py module must be
        installed to use this parameter.  Mutually exclusive with the
        'cryptoID' and 'x509Fingerprint' arguments.

        @type x509CommonName: str
        @param x509CommonName: The end-entity certificate's 'CN' field
        must match this value.  For a web server, this is typically a
        server name such as 'www.amazon.com'.  Mutually exclusive with
        the 'cryptoID' and 'x509Fingerprint' arguments.  Requires the
        'x509TrustList' argument.

        @type settings: L{tlslite.HandshakeSettings.HandshakeSettings}
        @param settings: Various settings which can be used to control
        the ciphersuites, certificate types, and SSL/TLS versions
        offered by the client.
        """

        ClientHelper.__init__(self,
                 username, password, sharedKey,
                 certChain, privateKey,
                 cryptoID, protocol,
                 x509Fingerprint,
                 x509TrustList, x509CommonName,
                 settings)

        IMAP4.__init__(self, host, port)


    def open(self, host = '', port = IMAP4_TLS_PORT):
        """Setup connection to remote server on "host:port".

        This connection will be used by the routines:
        read, readline, send, shutdown.
        """
        self.host = host
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect((host, port))
        self.sock = TLSConnection(self.sock)
        self.sock.closeSocket = True
        ClientHelper._handshake(self, self.sock)
        self.file = self.sock.makefile('rb')
Example #43
0
    def starttls(self,
                 username=None,
                 password=None,
                 certChain=None,
                 privateKey=None,
                 checker=None,
                 settings=None):
        """Puts the connection to the SMTP server into TLS mode.

        If the server supports TLS, this will encrypt the rest of the SMTP
        session.

        For client authentication, use one of these argument
        combinations:
         - username, password (SRP)
         - certChain, privateKey (certificate)

        For server authentication, you can either rely on the
        implicit mutual authentication performed by SRP or
        you can do certificate-based server
        authentication with one of these argument combinations:
         - x509Fingerprint

        Certificate-based server authentication is compatible with
        SRP or certificate-based client authentication.

        The caller should be prepared to handle TLS-specific
        exceptions.  See the client handshake functions in
        L{tlslite.TLSConnection.TLSConnection} for details on which
        exceptions might be raised.

        @type username: str
        @param username: SRP username.  Requires the
        'password' argument.

        @type password: str
        @param password: SRP password for mutual authentication.
        Requires the 'username' argument.

        @type certChain: L{tlslite.x509certchain.X509CertChain}
        @param certChain: Certificate chain for client authentication.
        Requires the 'privateKey' argument.  Excludes the SRP arguments.

        @type privateKey: L{tlslite.utils.rsakey.RSAKey}
        @param privateKey: Private key for client authentication.
        Requires the 'certChain' argument.  Excludes the SRP arguments.

        @type checker: L{tlslite.checker.Checker}
        @param checker: Callable object called after handshaking to 
        evaluate the connection and raise an Exception if necessary.

        @type settings: L{tlslite.handshakesettings.HandshakeSettings}
        @param settings: Various settings which can be used to control
        the ciphersuites, certificate types, and SSL/TLS versions
        offered by the client.
        """
        (resp, reply) = self.docmd("STARTTLS")
        if resp == 220:
            helper = ClientHelper(username, password, certChain, privateKey,
                                  checker, settings)
            conn = TLSConnection(self.sock)
            helper._handshake(conn)
            self.sock = conn
            self.file = conn.makefile('rb')
        return (resp, reply)
Example #44
0
class IMAP4_TLS(IMAP4, ClientHelper):
    """This class extends L{imaplib.IMAP4} with TLS support."""

    def __init__(self, host = '', port = IMAP4_TLS_PORT,
                 username=None, password=None,
                 certChain=None, privateKey=None,
                 checker=None,
                 settings=None):
        """Create a new IMAP4_TLS.

        For client authentication, use one of these argument
        combinations:
         - username, password (SRP)
         - certChain, privateKey (certificate)

        For server authentication, you can either rely on the
        implicit mutual authentication performed by SRP
        or you can do certificate-based server
        authentication with one of these argument combinations:
         - x509Fingerprint

        Certificate-based server authentication is compatible with
        SRP or certificate-based client authentication.

        The caller should be prepared to handle TLS-specific
        exceptions.  See the client handshake functions in
        L{tlslite.TLSConnection.TLSConnection} for details on which
        exceptions might be raised.

        @type host: str
        @param host: Server to connect to.

        @type port: int
        @param port: Port to connect to.

        @type username: str
        @param username: SRP username.  Requires the
        'password' argument.

        @type password: str
        @param password: SRP password for mutual authentication.
        Requires the 'username' argument.

        @type certChain: L{tlslite.x509certchain.X509CertChain}
        @param certChain: Certificate chain for client authentication.
        Requires the 'privateKey' argument.  Excludes the SRP arguments.

        @type privateKey: L{tlslite.utils.rsakey.RSAKey}
        @param privateKey: Private key for client authentication.
        Requires the 'certChain' argument.  Excludes the SRP arguments.
        
        @type checker: L{tlslite.checker.Checker}
        @param checker: Callable object called after handshaking to 
        evaluate the connection and raise an Exception if necessary.

        @type settings: L{tlslite.handshakesettings.HandshakeSettings}
        @param settings: Various settings which can be used to control
        the ciphersuites, certificate types, and SSL/TLS versions
        offered by the client.
        """

        ClientHelper.__init__(self,
                 username, password,
                 certChain, privateKey,
                 checker,
                 settings)

        IMAP4.__init__(self, host, port)


    def open(self, host = '', port = IMAP4_TLS_PORT):
        """Setup connection to remote server on "host:port".

        This connection will be used by the routines:
        read, readline, send, shutdown.
        """
        self.host = host
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect((host, port))
        self.sock = TLSConnection(self.sock)
        ClientHelper._handshake(self, self.sock)
        self.file = self.sock.makefile('rb')
Example #45
0
    def __init__(self,
                 host,
                 port=POP3_SSL_PORT,
                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
                 username=None,
                 password=None,
                 certChain=None,
                 privateKey=None,
                 use_fido2=False,
                 domain_name=None,
                 checker=None,
                 settings=None):
        """Create a new POP3_TLS.

        For client authentication, use one of these argument
        combinations:

         - username, password (SRP)
         - certChain, privateKey (certificate)
         - use_fido2, domain_name (and username) (FIDO2)

        For server authentication, you can either rely on the
        implicit mutual authentication performed by SRP, FIDO2, or
        you can do certificate-based server
        authentication with one of these argument combinations:

         - x509Fingerprint

        Certificate-based server authentication is compatible with
        SRP or certificate-based client authentication.

        The caller should be prepared to handle TLS-specific
        exceptions.  See the client handshake functions in
        :py:class:`~tlslite.tlsconnection.TLSConnection`
        for details on which
        exceptions might be raised.

        :type host: str
        :param host: Server to connect to.

        :type port: int
        :param port: Port to connect to.

        :type username: str
        :param username: SRP or FIDO2 username.  Requires the
            'password' argument for SRP.

        :type password: str
        :param password: SRP password for mutual authentication.
            Requires the 'username' argument.

        :type certChain: ~tlslite.x509certchain.X509CertChain
        :param certChain: Certificate chain for client authentication.
            Requires the 'privateKey' argument.  Excludes the SRP argument.

        :type privateKey: ~tlslite.utils.rsakey.RSAKey
        :param privateKey: Private key for client authentication.
            Requires the 'certChain' argument.  Excludes the SRP argument.

        :type use_fido2: bool
        :param use_fido2: Indication whether or not to use FIDO2
            authentication. Requires the 'domain_name' parameter or 'host'
            as domain name.

        :type domain_name: str
        :param domain_name: The domain name of the server to authenticate
            against using FIDO2. May be omitted if host is given as a domain
            name.

        :type checker: ~tlslite.checker.Checker
        :param checker: Callable object called after handshaking to
            evaluate the connection and raise an Exception if necessary.

        :type settings: ~tlslite.handshakesettings.HandshakeSettings
        :param settings: Various settings which can be used to control
            the ciphersuites, certificate types, and SSL/TLS versions
            offered by the client.
        """
        self.host = host
        self.port = port
        sock = socket.create_connection((host, port), timeout)
        ClientHelper.__init__(self, username, password, certChain, privateKey,
                              use_fido2, domain_name, checker, settings)
        connection = TLSConnection(sock)
        ClientHelper._handshake(self, connection)
        self.sock = connection
        self.file = self.sock.makefile('rb')
        self._debugging = 0
        self.welcome = self._getresp()