Skip to content

Commit a520fda

Browse files
sebastionossulleo
authored andcommitted
fix: prevent path traversal in terminology excel upload (CWE-22)
1 parent 7155550 commit a520fda

1 file changed

Lines changed: 12 additions & 4 deletions

File tree

backend/apps/terminology/api/terminology.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -180,9 +180,15 @@ async def upload_excel(trans: Trans, current_user: CurrentUser, file: UploadFile
180180
raise HTTPException(400, "Only support .xlsx/.xls")
181181

182182
os.makedirs(path, exist_ok=True)
183-
base_filename = f"{file.filename.split('.')[0]}_{hashlib.sha256(uuid.uuid4().bytes).hexdigest()[:10]}"
184-
filename = f"{base_filename}.{file.filename.split('.')[1]}"
185-
save_path = os.path.join(path, filename)
183+
# Strip any directory components from the client-supplied filename to
184+
# prevent path traversal (CWE-22).
185+
safe_name = os.path.basename(file.filename)
186+
name_root, name_ext = os.path.splitext(safe_name)
187+
base_filename = f"{name_root}_{hashlib.sha256(uuid.uuid4().bytes).hexdigest()[:10]}"
188+
filename = f"{base_filename}{name_ext}"
189+
save_path = os.path.realpath(os.path.join(path, filename))
190+
if os.path.commonpath([save_path, os.path.realpath(path)]) != os.path.realpath(path):
191+
raise HTTPException(400, "Invalid filename")
186192
with open(save_path, "wb") as f:
187193
f.write(await file.read())
188194

@@ -265,7 +271,9 @@ def inner():
265271

266272
df = pd.DataFrame(md_data, columns=_fields_list)
267273
error_excel_filename = f"{base_filename}_error.xlsx"
268-
save_error_path = os.path.join(path, error_excel_filename)
274+
save_error_path = os.path.realpath(os.path.join(path, error_excel_filename))
275+
if os.path.commonpath([save_error_path, os.path.realpath(path)]) != os.path.realpath(path):
276+
raise Exception("Invalid filename")
269277
# 保存 DataFrame 到 Excel
270278
df.to_excel(save_error_path, index=False)
271279

0 commit comments

Comments
 (0)