From 4db9abdaa05fd27a469f4892b99d23fafe7e05c9 Mon Sep 17 00:00:00 2001 From: Di Xu Date: Sun, 29 Dec 2019 09:33:01 -0800 Subject: [PATCH] restrict port range for ssh --- .../init-container/runtime/sync.py | 22 ++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/src/docker-images/init-container/runtime/sync.py b/src/docker-images/init-container/runtime/sync.py index b90c02a9b..4b919ed6e 100644 --- a/src/docker-images/init-container/runtime/sync.py +++ b/src/docker-images/init-container/runtime/sync.py @@ -8,6 +8,7 @@ from contextlib import closing import json import time +import random from pathlib import Path from kubernetes import client as k8s_client @@ -22,13 +23,24 @@ "environment": 1, "network": 2, "k8s_api": 3, + "port": 4, } -def find_free_port(): - with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: - s.bind(("", 0)) - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - return s.getsockname()[1] +def find_free_port(min=30000, max=49999): + for i in range(100): # try 100 times + port = random.randint(min, max) + + with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: + try: + s.bind(("", port)) + except OSError: + if i > 10: + logger.warning("failed %d times to get free port", i) + continue + return port + + logger.error("failed to get free port") + sys.exit(ERROR_EXIT_CODE["port"]) def get_pod_name(): return os.environ.get("POD_NAME")