Skip to content

Commit f839bcd

Browse files
committed
fix: prevent path traversal in Excel upload (CWE-22)
1 parent 49a50e3 commit f839bcd

1 file changed

Lines changed: 10 additions & 4 deletions

File tree

‎backend/apps/data_training/api/data_training.py‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -171,9 +171,13 @@ async def upload_excel(trans: Trans, current_user: CurrentUser, file: UploadFile
171171
raise HTTPException(400, "Only support .xlsx/.xls")
172172

173173
os.makedirs(path, exist_ok=True)
174-
base_filename = f"{file.filename.split('.')[0]}_{hashlib.sha256(uuid.uuid4().bytes).hexdigest()[:10]}"
175-
filename = f"{base_filename}.{file.filename.split('.')[1]}"
176-
save_path = os.path.join(path, filename)
174+
safe_name = os.path.basename(file.filename)
175+
name_root, name_ext = os.path.splitext(safe_name)
176+
base_filename = f"{name_root}_{hashlib.sha256(uuid.uuid4().bytes).hexdigest()[:10]}"
177+
filename = f"{base_filename}{name_ext}"
178+
save_path = os.path.realpath(os.path.join(path, filename))
179+
if os.path.commonpath([save_path, os.path.realpath(path)]) != os.path.realpath(path):
180+
raise HTTPException(400, "Invalid filename")
177181
with open(save_path, "wb") as f:
178182
f.write(await file.read())
179183

@@ -251,7 +255,9 @@ def inner():
251255

252256
df = pd.DataFrame(md_data, columns=_fields_list)
253257
error_excel_filename = f"{base_filename}_error.xlsx"
254-
save_error_path = os.path.join(path, error_excel_filename)
258+
save_error_path = os.path.realpath(os.path.join(path, error_excel_filename))
259+
if os.path.commonpath([save_error_path, os.path.realpath(path)]) != os.path.realpath(path):
260+
raise Exception("Invalid filename")
255261
# 保存 DataFrame 到 Excel
256262
df.to_excel(save_error_path, index=False)
257263

0 commit comments

Comments
 (0)