From f839bcd38b556a8319c24fb58ae412140e2c0423 Mon Sep 17 00:00:00 2001 From: ulleo Date: Fri, 28 Aug 2026 17:48:53 +0800 Subject: [PATCH] fix: prevent path traversal in Excel upload (CWE-22) --- backend/apps/data_training/api/data_training.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/backend/apps/data_training/api/data_training.py b/backend/apps/data_training/api/data_training.py index 1d3339945..e395a3b99 100644 --- a/backend/apps/data_training/api/data_training.py +++ b/backend/apps/data_training/api/data_training.py @@ -171,9 +171,13 @@ async def upload_excel(trans: Trans, current_user: CurrentUser, file: UploadFile raise HTTPException(400, "Only support .xlsx/.xls") os.makedirs(path, exist_ok=True) - base_filename = f"{file.filename.split('.')[0]}_{hashlib.sha256(uuid.uuid4().bytes).hexdigest()[:10]}" - filename = f"{base_filename}.{file.filename.split('.')[1]}" - save_path = os.path.join(path, filename) + safe_name = os.path.basename(file.filename) + name_root, name_ext = os.path.splitext(safe_name) + base_filename = f"{name_root}_{hashlib.sha256(uuid.uuid4().bytes).hexdigest()[:10]}" + filename = f"{base_filename}{name_ext}" + save_path = os.path.realpath(os.path.join(path, filename)) + if os.path.commonpath([save_path, os.path.realpath(path)]) != os.path.realpath(path): + raise HTTPException(400, "Invalid filename") with open(save_path, "wb") as f: f.write(await file.read()) @@ -251,7 +255,9 @@ def inner(): df = pd.DataFrame(md_data, columns=_fields_list) error_excel_filename = f"{base_filename}_error.xlsx" - save_error_path = os.path.join(path, error_excel_filename) + save_error_path = os.path.realpath(os.path.join(path, error_excel_filename)) + if os.path.commonpath([save_error_path, os.path.realpath(path)]) != os.path.realpath(path): + raise Exception("Invalid filename") # 保存 DataFrame 到 Excel df.to_excel(save_error_path, index=False)