Add TLS to gRPC server
authorGabriel Cuba <gcuba@whitestack.com>
Wed, 2 Nov 2022 22:21:50 +0000 (17:21 -0500)
committerGabriel Cuba <gcuba@whitestack.com>
Sat, 5 Nov 2022 05:39:35 +0000 (00:39 -0500)
osm_ee/frontend_server.py
osm_ee/util/util_grpc.py [new file with mode: 0644]

index 079503d..32b3afe 100644 (file)
@@ -33,6 +33,7 @@ from osm_ee.frontend_pb2 import SshKeyRequest, SshKeyReply
 
 from osm_ee.base_ee import BaseEE
 import osm_ee.util.util_ee as util_ee
+import osm_ee.util.util_grpc as util_grpc
 
 
 class FrontendExecutor(FrontendExecutorBase):
@@ -75,7 +76,7 @@ async def main(*, host: str = '0.0.0.0', port: int = 50051) -> None:
     # Start server
     server = Server([FrontendExecutor()])
     with graceful_exit([server]):
-        await server.start(host, port)
+        await server.start(host, port, ssl=util_grpc.create_secure_context())
         logging.getLogger('osm_ee.frontend_server').debug(f'Serving on {host}:{port}')
         await server.wait_closed()
 
diff --git a/osm_ee/util/util_grpc.py b/osm_ee/util/util_grpc.py
new file mode 100644 (file)
index 0000000..df904c1
--- /dev/null
@@ -0,0 +1,26 @@
+import logging
+import ssl
+
+logger = logging.getLogger("osm_ee.util_grpc")
+
+SERVER_CERT = "/etc/ssl/grpc-tls/tls.crt"
+SERVER_KEY = "/etc/ssl/grpc-tls/tls.key"
+
+
+def create_secure_context() -> ssl.SSLContext:
+    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+    # ctx.verify_mode = ssl.CERT_REQUIRED
+    try:
+        ctx.load_cert_chain(str(SERVER_CERT), str(SERVER_KEY))
+    except FileNotFoundError:
+        logger.warning("TLS Certificate not found, starting gRPC server in unsecure mode")
+        return None
+    # TODO: client TLS 
+    # ctx.load_verify_locations(str(trusted))
+    ctx.set_ciphers('ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20')
+    ctx.set_alpn_protocols(['h2'])
+    try:
+        ctx.set_npn_protocols(['h2'])
+    except NotImplementedError:
+        pass
+    return ctx
\ No newline at end of file