Skip to content

Commit 47628eb

Browse files
authored
time-series-analytics: Fix for bandit (open-edge-platform#1197)
Signed-off-by: Pooja Kumbharkar <[email protected]>
1 parent f24d4dd commit 47628eb

File tree

1 file changed

+29
-17
lines changed

1 file changed

+29
-17
lines changed

microservices/time-series-analytics/src/classifier_startup.py

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,18 @@
2121
import tomlkit
2222
from influxdb import InfluxDBClient
2323

24-
TEMP_KAPACITOR_DIR = tempfile.gettempdir()
24+
# Secure temporary directory management
25+
def get_secure_temp_dir():
26+
"""Get a secure temporary directory path with proper permissions"""
27+
# Use system temp directory as base, but ensure it's secure
28+
base_temp = tempfile.gettempdir()
29+
tmp_path = "/tmp"
30+
if os.path.exists(tmp_path) and os.access(tmp_path, os.W_OK):
31+
return tmp_path
32+
else:
33+
return base_temp
34+
35+
SECURE_TEMP_DIR = get_secure_temp_dir()
2536
KAPACITOR_DEV = "kapacitor_devmode.conf"
2637
KAPACITOR_PROD = "kapacitor.conf"
2738
SUCCESS = 0
@@ -32,7 +43,7 @@
3243
def kapacitor_daemon_logs(logger):
3344
"""Read the kapacitor logs and print it to stdout
3445
"""
35-
kapacitor_log_file = "/tmp/log/kapacitor/kapacitor.log"
46+
kapacitor_log_file = os.path.join(SECURE_TEMP_DIR, "log", "kapacitor", "kapacitor.log")
3647
while True:
3748
if os.path.isfile(kapacitor_log_file):
3849
break
@@ -67,7 +78,7 @@ def check_udf_package(self, config, dir_name):
6778
""" Check if UDF deployment package is present in the container
6879
"""
6980
logger.info("Checking if UDF deployment package is present in the container...")
70-
path = "/tmp/" + dir_name + "/"
81+
path = os.path.join(SECURE_TEMP_DIR, dir_name)
7182
udf_dir = os.path.join(path, "udfs")
7283
model_dir = os.path.join(path, "models")
7384
tick_scripts_dir = os.path.join(path, "tick_scripts")
@@ -125,8 +136,8 @@ def install_udf_package(self, dir_name):
125136
""" Install python package from udf/requirements.txt if exists
126137
"""
127138

128-
python_package_requirement_file = "/tmp/" + dir_name + "/udfs/requirements.txt"
129-
python_package_installation_path = "/tmp/py_package"
139+
python_package_requirement_file = os.path.join(SECURE_TEMP_DIR, dir_name, "udfs", "requirements.txt")
140+
python_package_installation_path = os.path.join(SECURE_TEMP_DIR, "py_package")
130141
status = subprocess.run(["mkdir", "-p", python_package_installation_path], check=False)
131142
if status.returncode != SUCCESS:
132143
self.logger.error("Failed to create directory %s for installing python packages.",
@@ -157,7 +168,7 @@ def start_kapacitor(self,
157168
try:
158169
if secure_mode:
159170
# Populate the certificates for kapacitor server
160-
kapacitor_conf = '/tmp/' + KAPACITOR_PROD
171+
kapacitor_conf = os.path.join(SECURE_TEMP_DIR, KAPACITOR_PROD)
161172

162173
os.environ["KAPACITOR_URL"] = "{}{}".format(https_scheme,
163174
kapacitor_port)
@@ -166,7 +177,7 @@ def start_kapacitor(self,
166177
os.environ["KAPACITOR_INFLUXDB_0_URLS_0"] = "{}{}".format(
167178
https_scheme, influxdb_hostname_port)
168179
else:
169-
kapacitor_conf = '/tmp/' + KAPACITOR_DEV
180+
kapacitor_conf = os.path.join(SECURE_TEMP_DIR, KAPACITOR_DEV)
170181
os.environ["KAPACITOR_URL"] = "{}{}".format(http_scheme,
171182
kapacitor_port)
172183
os.environ["KAPACITOR_UNSAFE_SSL"] = "true"
@@ -265,11 +276,11 @@ def enable_classifier_task(
265276

266277
self.logger.info("Kapacitor Port is Open for Communication....")
267278

268-
path = "/tmp/" + dir_name + "/tick_scripts/"
279+
path = os.path.join(SECURE_TEMP_DIR, dir_name, "tick_scripts")
269280
while retry < retry_count:
270281
define_pointcl_cmd = ["kapacitor", "-skipVerify", "define",
271282
task_name, "-tick",
272-
path + tick_script]
283+
os.path.join(path, tick_script)]
273284

274285
if subprocess.check_call(define_pointcl_cmd) == SUCCESS:
275286
define_pointcl_cmd = ["kapacitor", "-skipVerify", "enable",
@@ -396,10 +407,11 @@ def classifier_startup(config):
396407
if os.environ["KAPACITOR_INFLUXDB_0_URLS_0"] != "":
397408
delete_old_subscription(secure_mode)
398409
conf_file = KAPACITOR_PROD if secure_mode else KAPACITOR_DEV
399-
# Copy the kapacitor conf file to the /tmp directory
400-
shutil.copy("/app/config/" + conf_file, "/tmp/" + conf_file)
410+
# Copy the kapacitor conf file to the secure temp directory
411+
dest_conf_path = os.path.join(SECURE_TEMP_DIR, conf_file)
412+
shutil.copy("/app/config/" + conf_file, dest_conf_path)
401413
# Read the existing configuration
402-
with open("/tmp/" + conf_file, 'r', encoding='utf-8') as file:
414+
with open(dest_conf_path, 'r', encoding='utf-8') as file:
403415
config_data = tomlkit.parse(file.read())
404416
udf_name = config['udfs']['name']
405417
if "models" in config['udfs'].keys():
@@ -427,12 +439,12 @@ def classifier_startup(config):
427439

428440
udf_section[udf_name]['prog'] = 'python3'
429441

430-
udf_section[udf_name]['args'] = ["-u", "/tmp/"+ dir_name +"/udfs/" + udf_name + ".py"]
442+
udf_section[udf_name]['args'] = ["-u", os.path.join(SECURE_TEMP_DIR, dir_name, "udfs", udf_name + ".py")]
431443

432444
udf_section[udf_name]['timeout'] = "60s"
433445
udf_section[udf_name]['env'] = {
434-
'PYTHONPATH': "/tmp/py_package:/app/kapacitor_python/:",
435-
'MODEL_PATH': os.path.join("/tmp", dir_name, "models", model_name),
446+
'PYTHONPATH': f"{os.path.join(SECURE_TEMP_DIR, 'py_package')}:/app/kapacitor_python/:",
447+
'MODEL_PATH': os.path.join(SECURE_TEMP_DIR, dir_name, "models", model_name),
436448
'DEVICE': device
437449
}
438450
if "alerts" in config.keys() and "mqtt" in config["alerts"].keys():
@@ -449,12 +461,12 @@ def classifier_startup(config):
449461
if os.environ["KAPACITOR_INFLUXDB_0_URLS_0"] != "":
450462
config_data["influxdb"][0]["enabled"] = True
451463
# Write the updated configuration back to the file
452-
with open("/tmp/" + conf_file, 'w', encoding='utf-8') as file:
464+
with open(dest_conf_path, 'w', encoding='utf-8') as file:
453465
file.write(tomlkit.dumps(config_data, sort_keys=False))
454466

455467
# Copy the /app/temperature_Classifier folder to /tmp/temperature_classifier
456468
src_dir = "/app/temperature_classifier"
457-
dst_dir = "/tmp/temperature_classifier"
469+
dst_dir = os.path.join(SECURE_TEMP_DIR, "temperature_classifier")
458470
if os.path.exists(dst_dir):
459471
shutil.rmtree(dst_dir)
460472
shutil.copytree(src_dir, dst_dir)

0 commit comments

Comments
 (0)