Esempio n. 1
0
def serve(socket, get_secrets : Callable[[None], List[Tuple[bytes, bytes]]], handle_message : Callable[[str, str], None], running : bool) -> None:
    patch_context()

    ctx = Context(TLSv1_2_METHOD)
    ctx.set_cipher_list(b'ECDHE-PSK-CHACHA20-POLY1305')
    ctx.use_psk_identity_hint(b'our_chosen_server_identity_hint')
    partial_get_secret = partial(get_secret, get_secrets=get_secrets)
    ctx.set_psk_server_callback(partial_get_secret)

    server = Connection(ctx, socket)

    open_sockets = []

    addr, port = socket.getsockname()
    print(f"Serving on: {addr}:{port}")
    while running:
        try:
            client_socket, from_addr = server.accept()
        except:
            continue

        addr, port = from_addr
        print(f"Accepted connection from {addr}:{port}")
        thread = Thread(target=handle_client, args=(client_socket, handle_message, ))
        thread.start()
        open_sockets.append(thread)

        for thread in open_sockets:
            if not thread.is_alive():
                thread.join()

    for thread in open_sockets:
        thread.join()
Esempio n. 2
0
    def cacheContext(self):
        # Unfortunate code duplication.
        ctx = SSLContext(self.sslmethod)

        # Always disable SSLv2/SSLv3/Compression
        ctx.set_options(OP_NO_SSLv2)
        ctx.set_options(OP_NO_SSLv3)
        ctx.set_options(_OP_NO_COMPRESSION)

        if self.ciphers is not None:
            ctx.set_cipher_list(self.ciphers)
            ctx.set_options(OP_CIPHER_SERVER_PREFERENCE)

        if self.passwdCallback is not None:
            ctx.set_passwd_cb(self.passwdCallback)

        if self.keychainIdentity and hasattr(ctx, "use_keychain_identity"):
            ctx.use_keychain_identity(self.keychainIdentity)
        else:
            if self.certificateFileName:
                ctx.use_certificate_file(self.certificateFileName)
            if self.privateKeyFileName:
                ctx.use_privatekey_file(self.privateKeyFileName)
            if self.certificateChainFile:
                ctx.use_certificate_chain_file(self.certificateChainFile)

        verifyFlags = VERIFY_NONE
        if self.verifyClient:
            verifyFlags = VERIFY_PEER
            if self.requireClientCertificate:
                verifyFlags |= VERIFY_FAIL_IF_NO_PEER_CERT
            if self.verifyClientOnce:
                verifyFlags |= VERIFY_CLIENT_ONCE
            if self.clientCACertFileNames:
                store = ctx.get_cert_store()
                for cert in self.clientCACertFileNames:
                    with open(cert) as f:
                        certpem = f.read()
                    cert = Certificate.loadPEM(certpem)
                    store.add_cert(cert.original)
                    if self.sendCAsToClient:
                        ctx.add_client_ca(cert.original)

            # When a client certificate is used we also need to set a session context id
            # to avoid openssl SSL_F_SSL_GET_PREV_SESSION,SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED
            # errors
            ctx.set_session_id(str(uuid.uuid4()).replace("-", ""))

        # It'd be nice if pyOpenSSL let us pass None here for this behavior (as
        # the underlying OpenSSL API call allows NULL to be passed).  It
        # doesn't, so we'll supply a function which does the same thing.
        def _verifyCallback(conn, cert, errno, depth, preverify_ok):
            return preverify_ok

        ctx.set_verify(verifyFlags, _verifyCallback)

        if self.verifyClientDepth is not None:
            ctx.set_verify_depth(self.verifyClientDepth)

        self._context = ctx
Esempio n. 3
0
def testPFSCipher(host,port,cipher):
	try:
		
		# Construct the socket
		client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
		client.settimeout(10)
		client.connect((host, port))	
		
		# Define the method as serverpreferred and use the Cipher from the test
		contextToUse = Context(pfsCipherList[cipher])
		contextToUse.set_cipher_list(cipher) 

		# Estabilish a SSL connection using the server's preferred connection
		client_ssl = Connection(contextToUse, client)
		client_ssl.set_connect_state()
		client_ssl.set_tlsext_host_name(host)
		
		# Try to perform an SSL handshake
		client_ssl.do_handshake()

		# Close the connection
		client_ssl.close()
		client.close()
		return True 
	except openSSLError as e: # Server may be down or avoiding SSL connection
		return False
	except ValueError as e: # Not configured or not allowed
		return False
	pass
Esempio n. 4
0
    def cacheContext(self):
        # Unfortunate code duplication.
        ctx = SSLContext(self.sslmethod)

        if self.ciphers is not None:
            ctx.set_cipher_list(self.ciphers)

        if self.passwdCallback is not None:
            ctx.set_passwd_cb(self.passwdCallback)

        ctx.use_certificate_file(self.certificateFileName)
        ctx.use_privatekey_file(self.privateKeyFileName)

        if self.certificateChainFile != "":
            ctx.use_certificate_chain_file(self.certificateChainFile)

        self._context = ctx
Esempio n. 5
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"
        )
Esempio n. 6
0
def main():
    port = socket()
    port.bind(('', 0))
    port.listen(5)

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

    server = port.accept()[0]

    clientCtx = Context(TLSv1_METHOD)
    clientCtx.set_cipher_list('ALL:ADH')
    clientCtx.load_tmp_dh('dhparam.pem')

    sslClient = Connection(clientCtx, client)
    sslClient.set_connect_state()

    serverCtx = Context(TLSv1_METHOD)
    serverCtx.set_cipher_list('ALL:ADH')
    serverCtx.load_tmp_dh('dhparam.pem')

    sslServer = Connection(serverCtx, server)
    sslServer.set_accept_state()

    t1 = Thread(target=send, args=(sslClient,))
    t2 = Thread(target=send, args=(sslServer,))
    t3 = Thread(target=recv, args=(sslClient,))
    t4 = Thread(target=recv, args=(sslServer,))

    t1.start()
    t2.start()
    t3.start()
    t4.start()
    t1.join()
    t2.join()
    t3.join()
    t4.join()
Esempio n. 7
0
def main():
    port = socket()
    port.bind(("", 0))
    port.listen(5)

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

    server = port.accept()[0]

    clientCtx = Context(TLSv1_METHOD)
    clientCtx.set_cipher_list("ALL:ADH")
    clientCtx.load_tmp_dh("dhparam.pem")

    sslClient = Connection(clientCtx, client)
    sslClient.set_connect_state()

    serverCtx = Context(TLSv1_METHOD)
    serverCtx.set_cipher_list("ALL:ADH")
    serverCtx.load_tmp_dh("dhparam.pem")

    sslServer = Connection(serverCtx, server)
    sslServer.set_accept_state()

    t1 = Thread(target=send, args=(sslClient, ))
    t2 = Thread(target=send, args=(sslServer, ))
    t3 = Thread(target=recv, args=(sslClient, ))
    t4 = Thread(target=recv, args=(sslServer, ))

    t1.start()
    t2.start()
    t3.start()
    t4.start()
    t1.join()
    t2.join()
    t3.join()
    t4.join()
Esempio n. 8
0
    def cacheContext(self):
        # Unfortunate code duplication.
        ctx = SSLContext(self.sslmethod)

        # Always disable SSLv2/SSLv3
        ctx.set_options(OP_NO_SSLv2)
        ctx.set_options(OP_NO_SSLv3)

        if self.ciphers is not None:
            ctx.set_cipher_list(self.ciphers)
            ctx.set_options(OP_CIPHER_SERVER_PREFERENCE)

        if self.passwdCallback is not None:
            ctx.set_passwd_cb(self.passwdCallback)

        ctx.use_certificate_file(self.certificateFileName)
        ctx.use_privatekey_file(self.privateKeyFileName)

        if self.certificateChainFile != "":
            ctx.use_certificate_chain_file(self.certificateChainFile)

        self._context = ctx
Esempio n. 9
0
from socket import socket
from OpenSSL.SSL import Connection, Context, SSLv23_METHOD
from OpenSSL import _util

ssl_context = Context(SSLv23_METHOD)
ssl_context.set_cipher_list("ALL:COMPLEMENT")
conn = Connection(ssl_context)
cipher_ptr = _util.lib.SSL_get_ciphers(conn._ssl)
for i in range(_util.lib.sk_SSL_CIPHER_num(cipher_ptr)):
    cipher = _util.lib.sk_SSL_CIPHER_value(cipher_ptr, i)
    print _util.ffi.string(_util.lib.SSL_CIPHER_get_name(cipher))
'''
ssl_context.set_timeout(30)
ip='113.57.133.147'
port=443
s=socket()
s.connect((ip,port))
c=Connection(ssl_context,s)
c.set_connect_state()
print "%s try to handshake" % (ip)
c.do_handshake()
cert = c.get_peer_certificate()
print "issuer: ",cert.get_issuer()
print "subject: ",cert.get_subject().get_components()
c.shutdown()
s.close()
'''
Esempio n. 10
0
def index():
    form = ActionForm(request.form, csrf_context=session)

    if request.method == 'POST' and form.validate(
    ) and current_user.is_authenticated:
        comment_value = request.form['comment']
        action_value = request.form['action']
        user_name = current_user.username
        user_ip = get_client_ip()

        action_data = dict(comment=comment_value,
                           action=action_value,
                           user=user_name,
                           ip=user_ip)

        rx = ""

        try:
            print('Creating socket', file=sys.stderr)
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            #s.settimeout(10.0)
            if repeater_listen_psk:
                ctx = Context(TLSv1_2_METHOD)
                ctx.set_cipher_list(b'PSK')
                ctx.set_psk_client_callback(client_callback)
                s = Connection(ctx, s)
                print('PSK Context created', file=sys.stderr)

            print('Connecting:', REPEATER_LISTENER)
            s.connect(REPEATER_LISTENER)
            print('Connected')

            try:
                hello_msg = s.recv(5)
                print(f'hello msg: {hello_msg}', file=sys.stderr)
            except socket.timeout:
                traceback.print_exc(file=sys.stderr)

            #send_delay = request.form.get('test_send_delay') or 0
            #sleep(int(send_delay))
            #if action_value == 'test_send':
            #    msg = comment_value.encode()
            #else:
            #    msg = json.dumps(action_data).encode()
            msg = json.dumps(action_data).encode()
            msg_len = len(msg)
            print(f'Sending {msg_len}b message: {msg}', file=sys.stderr)
            s.send(msg)
            #recv_delay = request.form.get('test_recv_delay') or 0
            #sleep(int(recv_delay))

            try:
                rx = s.recv(2)
            except ConnectionResetError:
                traceback.print_exc(file=sys.stderr)
                pass
            s.close()

            if len(rx) > 0:
                action_data['submitted'] = True
                action_data['submit_result'] = "Server reply: " + rx.decode()
            else:
                action_data['submitted'] = True
                action_data['submit_result'] = '<Unknown - no reply>'

        except Exception as e:
            traceback.print_exc(file=sys.stderr)
            action_data['submitted'] = False
            action_data[
                'submit_result'] = 'Unexpected error while sending: ' + str(e)

        ev = LogEvent.from_action(action_data, current_user)
        db.session.add(ev)
        db.session.commit()
    else:
        action_data = None

    connections = ''
    logs = []

    if current_user.is_authenticated:
        if os.path.exists(LISTENER_FILE):
            with open(LISTENER_FILE) as f:
                connections = f.read()
        else:
            connections = 'No file'

        logs = LogEvent.query.order_by(LogEvent.ts.desc()).limit(10).all()

    return render_template("index.html",
                           actions=REPEATER_ACTIONS,
                           form=form,
                           connections=connections,
                           logs=logs,
                           action=action_data)