From 17e530da836aff15c4ccb113833a129d703f8f7c Mon Sep 17 00:00:00 2001 From: Florian Agbuya Date: Wed, 2 Oct 2024 17:16:22 +0800 Subject: [PATCH] add optional ssl support Signed-off-by: Florian Agbuya --- sipyco/asyncio_tools.py | 13 ++++++++++++- sipyco/pc_rpc.py | 36 ++++++++++++++++++++++++++++-------- 2 files changed, 40 insertions(+), 9 deletions(-) diff --git a/sipyco/asyncio_tools.py b/sipyco/asyncio_tools.py index 4a96dcb..04c56df 100644 --- a/sipyco/asyncio_tools.py +++ b/sipyco/asyncio_tools.py @@ -4,6 +4,7 @@ import atexit import collections import logging +import ssl from copy import copy from sipyco import keepalive @@ -43,9 +44,18 @@ class AsyncioServer: Users of this class must derive from it and define the :meth:`~sipyco.asyncio_server.AsyncioServer._handle_connection_cr` method/coroutine. + + :param certfile: Path to the server's SSL certificate file. If provided along + with keyfile, the server will use SSL encryption. + :param keyfile: Path to the server's SSL private key file. """ - def __init__(self): + def __init__(self, certfile=None, keyfile=None): self._client_tasks = set() + if certfile: + self.ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + self.ssl_context.load_cert_chain(certfile, keyfile) + else: + self.ssl_context = None async def start(self, host, port): """Starts the server. @@ -61,6 +71,7 @@ async def start(self, host, port): """ self.server = await asyncio.start_server(self._handle_connection, host, port, + ssl=self.ssl_context, limit=4*1024*1024) async def stop(self): diff --git a/sipyco/pc_rpc.py b/sipyco/pc_rpc.py index aa2bf19..d48070c 100644 --- a/sipyco/pc_rpc.py +++ b/sipyco/pc_rpc.py @@ -17,6 +17,7 @@ import socket import threading import time +import ssl from operator import itemgetter from sipyco import keepalive, pyon @@ -97,6 +98,9 @@ class Client: Use ``None`` to skip selecting a target. The list of targets can then be retrieved using :meth:`~sipyco.pc_rpc.Client.get_rpc_id` and then one can be selected later using :meth:`~sipyco.pc_rpc.Client.select_rpc_target`. + :param cafile: Path to a CA certificate file for SSL verification. If provided, + the connection will be encrypted using SSL. The server's hostname must match + the hostname in the server's certificate. :param timeout: Socket operation timeout. Use ``None`` for blocking (default), ``0`` for non-blocking, and a finite value to raise ``socket.timeout`` if an operation does not complete within the @@ -106,9 +110,12 @@ class Client: client). """ - def __init__(self, host, port, target_name=AutoTarget, timeout=None): + def __init__(self, host, port, target_name=AutoTarget, cafile=None, timeout=None): self.__socket = socket.create_connection((host, port), timeout) + if cafile: + ssl_context = ssl.create_default_context(cafile=cafile) + self.__socket = ssl_context.wrap_socket(self.__socket, server_hostname=host) try: self.__socket.sendall(_init_string) @@ -206,12 +213,16 @@ def __init__(self): self.__description = None self.__valid_methods = set() - async def connect_rpc(self, host, port, target_name=AutoTarget): + async def connect_rpc(self, host, port, target_name=AutoTarget, cafile=None): """Connects to the server. This cannot be done in __init__ because this method is a coroutine. See :class:`sipyco.pc_rpc.Client` for a description of the parameters.""" + if cafile: + ssl_context = ssl.create_default_context(cafile=cafile) + else: + ssl_context = None self.__reader, self.__writer = \ - await keepalive.async_open_connection(host, port, limit=100 * 1024 * 1024) + await keepalive.async_open_connection(host, port, ssl=ssl_context, limit=100 * 1024 * 1024) try: self.__writer.write(_init_string) server_identification = await self.__recv() @@ -309,11 +320,12 @@ class BestEffortClient: in the background. """ - def __init__(self, host, port, target_name, + def __init__(self, host, port, target_name, cafile=None, firstcon_timeout=1.0, retry=5.0): self.__host = host self.__port = port self.__target_name = target_name + self.__cafile = cafile self.__retry = retry self.__conretry_terminate = False @@ -337,6 +349,10 @@ def __coninit(self, timeout): else: self.__socket = socket.create_connection( (self.__host, self.__port), timeout) + if self.__cafile: + ssl_context = ssl.create_default_context(cafile=self.__cafile) + self.__socket = ssl_context.wrap_socket(self.__socket, + server_hostname=self.__host) self.__socket.sendall(_init_string) server_identification = self.__recv() target_name = _validate_target_name(self.__target_name, @@ -485,11 +501,14 @@ class Server(_AsyncioServer): requests from clients. :param allow_parallel: Allow concurrent asyncio calls to the target's methods. + :param certfile: Path to the server's SSL certificate file. If provided along + with ``keyfile``, the server will use SSL encryption. + :param keyfile: Path to the server's SSL private key file. """ def __init__(self, targets, description=None, builtin_terminate=False, - allow_parallel=False): - _AsyncioServer.__init__(self) + allow_parallel=False, certfile=None, keyfile=None): + _AsyncioServer.__init__(self, certfile=certfile, keyfile=keyfile) self.targets = targets self.description = description self.builtin_terminate = builtin_terminate @@ -636,7 +655,8 @@ async def wait_terminate(self): await self._terminate_request.wait() -def simple_server_loop(targets, host, port, description=None, allow_parallel=False, *, loop=None): +def simple_server_loop(targets, host, port, description=None, allow_parallel=False, *, loop=None, + certfile=None, keyfile=None): """Runs a server until an exception is raised (e.g. the user hits Ctrl-C) or termination is requested by a client. @@ -651,7 +671,7 @@ def simple_server_loop(targets, host, port, description=None, allow_parallel=Fal signal_handler = SignalHandler() signal_handler.setup() try: - server = Server(targets, description, True, allow_parallel) + server = Server(targets, description, True, allow_parallel, certfile, keyfile) used_loop.run_until_complete(server.start(host, port)) try: _, pending = used_loop.run_until_complete(asyncio.wait(