Exemplo n.º 1
0
    def test_set_info_callback(self):
        """
        L{Context.set_info_callback} accepts a callable which will be invoked
        when certain information about an SSL connection is available.
        """
        (server, client) = socket_pair()

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

        called = []

        def info(conn, where, ret):
            called.append((conn, where, ret))

        context = Context(TLSv1_METHOD)
        context.set_info_callback(info)
        context.use_certificate(
            load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
        context.use_privatekey(
            load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))

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

        while not called:
            for ssl in clientSSL, serverSSL:
                try:
                    ssl.do_handshake()
                except WantReadError:
                    pass

        # Kind of lame.  Just make sure it got called somehow.
        self.assertTrue(called)
Exemplo n.º 2
0
    def test_set_info_callback(self):
        """
        L{Context.set_info_callback} accepts a callable which will be invoked
        when certain information about an SSL connection is available.
        """
        (server, client) = socket_pair()

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

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

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

        while not called:
            for ssl in clientSSL, serverSSL:
                try:
                    ssl.do_handshake()
                except WantReadError:
                    pass

        # Kind of lame.  Just make sure it got called somehow.
        self.assertTrue(called)
Exemplo n.º 3
0
	def SNICallback(self, connection):
		prev_context = connection.get_context()

		#Stop Producing Data untill connection is made
		server_object = prev_context._server_context
		server_object.transport.pauseProducing()

		#Get Host from SNI
		host = connection.get_servername()
		if host:
			host = host.decode("utf-8")
		else:
			host = self.default_server

		#Get Certificate from Server
		ssl_certs = self.CA.clone_certificate({"server": host, "port": self.default_port })


		#Update the SSL Context
		new_context = Context(self.default_version)
		new_context.new_host = (host, self.default_port)
		new_context.use_privatekey(load_privatekey(FILETYPE_PEM, open(ssl_certs["keyfile"]).read()))
		new_context.use_certificate(load_certificate(FILETYPE_PEM, open(ssl_certs["certfile"]).read()))
		connection.set_context(new_context)

		#Call Proxy Server to finish setting up the Connection
		server_object.SNICallback(connection)
Exemplo n.º 4
0
    def getServerContext(self):
        """
        Generate a new L{OpenSSL.SSL.Context} object configured to use a
        certificate signed by C{self.ca} and only accept connections from peers
        which are also using a certificate signed by C{self.ca}.
        """
        # Generate a new key for the server and have the CA sign a certificate
        # for it.
        key = KeyPair.generate(size=512)
        req = key.certificateRequest(DN(commonName='localhost'))
        certData = self.ca.signCertificateRequest(req, lambda dn: True, 1)
        cert = PrivateCertificate.load(certData, key)

        # Use the new key/certificate
        context = Context(TLSv1_METHOD)
        context.use_privatekey(key.original)
        context.use_certificate(cert.original)
        context.check_privatekey()

        # Allow peer certificates signed by the CA
        store = context.get_cert_store()
        store.add_cert(self.ca.original)

        # Verify the peer certificate and require that they have one.
        def verify(conn, cert, errno, depth, preverify_ok):
            return preverify_ok
        context.set_verify(VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify)
        return context
Exemplo n.º 5
0
 def test_use_privatekey(self):
     """
     L{Context.use_privatekey} takes an L{OpenSSL.crypto.PKey} instance.
     """
     key = PKey()
     key.generate_key(TYPE_RSA, 128)
     ctx = Context(TLSv1_METHOD)
     ctx.use_privatekey(key)
     self.assertRaises(TypeError, ctx.use_privatekey, "")
Exemplo n.º 6
0
 def test_use_privatekey(self):
     """
     L{Context.use_privatekey} takes an L{OpenSSL.crypto.PKey} instance.
     """
     key = PKey()
     key.generate_key(TYPE_RSA, 128)
     ctx = Context(TLSv1_METHOD)
     ctx.use_privatekey(key)
     self.assertRaises(TypeError, ctx.use_privatekey, "")
Exemplo n.º 7
0
def pick_certificate(connection):
    try:
        key, cert = certificates[connection.get_servername()]
    except KeyError:
        pass
    else:
        new_context = Context(TLSv1_METHOD)
        new_context.use_privatekey(key)
        new_context.use_certificate(cert)
        connection.set_context(new_context)
Exemplo n.º 8
0
def pick_certificate(connection):
    try:
        key, cert = certificates[connection.get_servername()]
    except KeyError:
        pass
    else:
        new_context = Context(TLSv1_METHOD)
        new_context.use_privatekey(key)
        new_context.use_certificate(cert)
        connection.set_context(new_context)
    def prepare_handshake(self, connection):
        raw_sni = connection.get_servername()
        if raw_sni is not None:
            self.sni = str(raw_sni, 'ascii')

        self.build_server_conn()
        cert_dict = self.server_ssl_sock.getpeercert()
        crt_dir = generate_fake_cert(cert_dict)
        try:
            key, cert = load(crt_dir)
        except crypto.Error:
            raise CertificateRaceCondition
        new_context = Context(SSLv23_METHOD)
        new_context.use_privatekey(key)
        new_context.use_certificate(cert)
        connection.set_context(new_context)
Exemplo n.º 10
0
    def _load_verify_locations_test(self, *args):
        port = socket()
        port.bind(('', 0))
        port.listen(1)

        client = socket()
        client.setblocking(False)
        client.connect_ex(port.getsockname())

        clientContext = Context(TLSv1_METHOD)
        clientContext.load_verify_locations(*args)
        # Require that the server certificate verify properly or the
        # connection will fail.
        clientContext.set_verify(
            VERIFY_PEER,
            lambda conn, cert, errno, depth, preverify_ok: preverify_ok)

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

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

        serverContext = Context(TLSv1_METHOD)
        serverContext.use_certificate(
            load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
        serverContext.use_privatekey(
            load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))

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

        for i in range(3):
            for ssl in clientSSL, serverSSL:
                try:
                    # Without load_verify_locations above, the handshake
                    # will fail:
                    # Error: [('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE',
                    #          'certificate verify failed')]
                    ssl.do_handshake()
                except WantReadError:
                    pass

        cert = clientSSL.get_peer_certificate()
        self.assertEqual(cert.get_subject().CN, 'Testing Root CA')
Exemplo n.º 11
0
    def configure_context(context: SSL.Context, config: HomeServerConfig) -> None:
        try:
            _ecCurve = crypto.get_elliptic_curve(_defaultCurveName)
            context.set_tmp_ecdh(_ecCurve)
        except Exception:
            logger.exception("Failed to enable elliptic curve for TLS")

        context.set_options(
            SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3 | SSL.OP_NO_TLSv1 | SSL.OP_NO_TLSv1_1
        )
        context.use_certificate_chain_file(config.tls.tls_certificate_file)
        assert config.tls.tls_private_key is not None
        context.use_privatekey(config.tls.tls_private_key)

        # https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
        context.set_cipher_list(
            b"ECDH+AESGCM:ECDH+CHACHA20:ECDH+AES256:ECDH+AES128:!aNULL:!SHA1:!AESCCM"
        )
Exemplo n.º 12
0
 def _client(self, sock):
     """
     Create a new client-side SSL L{Connection} object wrapped around
     C{sock}.
     """
     # Now create the client side Connection.  Similar boilerplate to the
     # above.
     client_ctx = Context(TLSv1_METHOD)
     client_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE )
     client_ctx.set_verify(VERIFY_PEER|VERIFY_FAIL_IF_NO_PEER_CERT|VERIFY_CLIENT_ONCE, verify_cb)
     client_store = client_ctx.get_cert_store()
     client_ctx.use_privatekey(load_privatekey(FILETYPE_PEM, client_key_pem))
     client_ctx.use_certificate(load_certificate(FILETYPE_PEM, client_cert_pem))
     client_ctx.check_privatekey()
     client_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
     client_conn = Connection(client_ctx, sock)
     client_conn.set_connect_state()
     return client_conn
Exemplo n.º 13
0
def test_create_self_signed_cert():
    cert_a, _ = cssc(join(getcwd(), "data"), "a.pem", "a.key")
    cert_b, _ = cssc(join(getcwd(), "data"), "b.pem", "b.key")
    key_a = load_privatekey(FP, open(join(getcwd(), "data", "a.key")).read())
    cert_a = load_certificate(FP, open(join(getcwd(), "data", "a.pem")).read())
    cert_b = load_certificate(FP, open(join(getcwd(), "data", "b.pem")).read())

    ctx = Context(TLSv1_METHOD)
    ctx.use_privatekey(key_a)
    ctx.use_certificate(cert_a)
    ctx.check_privatekey()
    ctx.use_certificate(cert_b)
    with pytest.raises(Error):
        ctx.check_privatekey()

    remove(join(getcwd(), "data", "a.pem"))
    remove(join(getcwd(), "data", "a.key"))
    remove(join(getcwd(), "data", "b.pem"))
    remove(join(getcwd(), "data", "b.key"))
Exemplo n.º 14
0
 def _server(self, sock):
     """
     Create a new server-side SSL L{Connection} object wrapped around
     C{sock}.
     """
     # Create the server side Connection.  This is mostly setup boilerplate
     # - use TLSv1, use a particular certificate, etc.
     server_ctx = Context(TLSv1_METHOD)
     server_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE )
     server_ctx.set_verify(VERIFY_PEER|VERIFY_FAIL_IF_NO_PEER_CERT|VERIFY_CLIENT_ONCE, verify_cb)
     server_store = server_ctx.get_cert_store()
     server_ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
     server_ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
     server_ctx.check_privatekey()
     server_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
     # Here the Connection is actually created.  If None is passed as the 2nd
     # parameter, it indicates a memory BIO should be created.
     server_conn = Connection(server_ctx, sock)
     server_conn.set_accept_state()
     return server_conn
Exemplo n.º 15
0
def go():
    port = socket()
    port.bind(('', 0))
    port.listen(1)

    called = []

    def info(*args):
        print count.next()
        called.append(None)
        return 1

    context = Context(TLSv1_METHOD)
    context.set_verify(VERIFY_PEER, info)
    context.use_certificate(
        load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
    context.use_privatekey(
        load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))

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

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

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

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

        del called[:]
        while not called:
            for ssl in clientSSL, serverSSL:
                try:
                    ssl.send('foo')
                except WantReadError, e:
                    pass
Exemplo n.º 16
0
 def _client(self, sock):
     """
     Create a new client-side SSL L{Connection} object wrapped around
     C{sock}.
     """
     # Now create the client side Connection.  Similar boilerplate to the
     # above.
     client_ctx = Context(TLSv1_METHOD)
     client_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
     client_ctx.set_verify(
         VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
         verify_cb)
     client_store = client_ctx.get_cert_store()
     client_ctx.use_privatekey(load_privatekey(FILETYPE_PEM,
                                               client_key_pem))
     client_ctx.use_certificate(
         load_certificate(FILETYPE_PEM, client_cert_pem))
     client_ctx.check_privatekey()
     client_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
     client_conn = Connection(client_ctx, sock)
     client_conn.set_connect_state()
     return client_conn
Exemplo n.º 17
0
def go():
    port = socket()
    port.bind(('', 0))
    port.listen(1)

    called = []

    def info(conn, where, ret):
        print count.next()
        called.append(None)

    context = Context(TLSv1_METHOD)
    context.set_info_callback(info)
    context.use_certificate(
        load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
    context.use_privatekey(
        load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))

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

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

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

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

        del called[:]
        while not called:
            for ssl in clientSSL, serverSSL:
                try:
                    ssl.do_handshake()
                except WantReadError:
                    pass
Exemplo n.º 18
0
def go():
    port = socket()
    port.bind(('', 0))
    port.listen(1)

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

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

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

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

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

        del called[:]
        while not called:
            for ssl in clientSSL, serverSSL:
                try:
                    ssl.send('foo')
                except WantReadError, e:
                    pass
Exemplo n.º 19
0
def go():
    port = socket()
    port.bind(('', 0))
    port.listen(1)

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

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

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

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

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

        del called[:]
        while not called:
            for ssl in clientSSL, serverSSL:
                try:
                    ssl.do_handshake()
                except WantReadError:
                    pass
Exemplo n.º 20
0
    def _load_verify_locations_test(self, *args):
        (server, client) = socket_pair()

        clientContext = Context(TLSv1_METHOD)
        clientContext.load_verify_locations(*args)
        # Require that the server certificate verify properly or the
        # connection will fail.
        clientContext.set_verify(
            VERIFY_PEER,
            lambda conn, cert, errno, depth, preverify_ok: preverify_ok)

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

        serverContext = Context(TLSv1_METHOD)
        serverContext.use_certificate(
            load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
        serverContext.use_privatekey(
            load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))

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

        for i in range(3):
            for ssl in clientSSL, serverSSL:
                try:
                    # Without load_verify_locations above, the handshake
                    # will fail:
                    # Error: [('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE',
                    #          'certificate verify failed')]
                    ssl.do_handshake()
                except WantReadError:
                    pass

        cert = clientSSL.get_peer_certificate()
        self.assertEqual(cert.get_subject().CN, 'Testing Root CA')
Exemplo n.º 21
0
 def _server(self, sock):
     """
     Create a new server-side SSL L{Connection} object wrapped around
     C{sock}.
     """
     # Create the server side Connection.  This is mostly setup boilerplate
     # - use TLSv1, use a particular certificate, etc.
     server_ctx = Context(TLSv1_METHOD)
     server_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
     server_ctx.set_verify(
         VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
         verify_cb)
     server_store = server_ctx.get_cert_store()
     server_ctx.use_privatekey(load_privatekey(FILETYPE_PEM,
                                               server_key_pem))
     server_ctx.use_certificate(
         load_certificate(FILETYPE_PEM, server_cert_pem))
     server_ctx.check_privatekey()
     server_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
     # Here the Connection is actually created.  If None is passed as the 2nd
     # parameter, it indicates a memory BIO should be created.
     server_conn = Connection(server_ctx, sock)
     server_conn.set_accept_state()
     return server_conn
Exemplo n.º 22
0
 def getContext(self):
     ctx = Context(TLSv1_METHOD)
     ctx.use_certificate(self.flocker_credential.certificate.original)
     ctx.use_privatekey(self.flocker_credential.keypair.keypair.original)
     return ctx
Exemplo n.º 23
0
 def getContext(self):
     ctx = Context(TLSv1_METHOD)
     ctx.use_certificate(self.flocker_credential.certificate.original)
     ctx.use_privatekey(self.flocker_credential.keypair.keypair.original)
     return ctx