From 6c963614026137df92b666997d94267c98c32e24 Mon Sep 17 00:00:00 2001 From: KoreLogic Disclosures Date: Mon, 1 Apr 2024 15:55:14 -0500 Subject: [PATCH 1/2] Suggested mitigation for KL-CAN-2024-002. --- backend/apps/rag/main.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/backend/apps/rag/main.py b/backend/apps/rag/main.py index cb8cbb6c3..cf82e0887 100644 --- a/backend/apps/rag/main.py +++ b/backend/apps/rag/main.py @@ -448,8 +448,25 @@ def store_doc( log.info(f"file.content_type: {file.content_type}") try: + is_valid_filename = True + unsanitized_filename = file.filename + if not unsanitized_filename.isascii(): + is_valid_filename = False + + unvalidated_file_path = f"{UPLOAD_DIR}/{unsanitized_filename}" + dereferenced_file_path = str(Path(unvalidated_file_path).resolve(strict=False)) + if not dereferenced_file_path.startswith(UPLOAD_DIR): + is_valid_filename = False + + if is_valid_filename: + file_path = dereferenced_file_path + else: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=ERROR_MESSAGES.DEFAULT(), + ) + filename = file.filename - file_path = f"{UPLOAD_DIR}/{filename}" contents = file.file.read() with open(file_path, "wb") as f: f.write(contents) From 5558514ff19c088fd0c8c87205d7a89a0d115a1c Mon Sep 17 00:00:00 2001 From: "Timothy J. Baek" Date: Mon, 1 Apr 2024 15:23:12 -0700 Subject: [PATCH 2/2] fix --- backend/apps/rag/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/apps/rag/main.py b/backend/apps/rag/main.py index cf82e0887..0555cc2c5 100644 --- a/backend/apps/rag/main.py +++ b/backend/apps/rag/main.py @@ -453,7 +453,7 @@ def store_doc( if not unsanitized_filename.isascii(): is_valid_filename = False - unvalidated_file_path = f"{UPLOAD_DIR}/{unsanitized_filename}" + unvalidated_file_path = f"{UPLOAD_DIR}/{unsanitized_filename}" dereferenced_file_path = str(Path(unvalidated_file_path).resolve(strict=False)) if not dereferenced_file_path.startswith(UPLOAD_DIR): is_valid_filename = False