From 78ac8fc5ca9063e6516188da4df598332873aada Mon Sep 17 00:00:00 2001 From: Brayan Almonte Date: Wed, 1 May 2024 15:30:34 -0400 Subject: [PATCH] fix(system-server): sanitize the filename in the upload_splash endpoint for OEM Mode. (#15063) --- .../system_server/system/oem_mode/router.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/system-server/system_server/system/oem_mode/router.py b/system-server/system_server/system/oem_mode/router.py index 0f3b9aa52f4..1b7119b6127 100644 --- a/system-server/system_server/system/oem_mode/router.py +++ b/system-server/system_server/system/oem_mode/router.py @@ -1,5 +1,6 @@ """Router for /system/register endpoint.""" +import re import os import filetype # type: ignore[import-untyped] from fastapi import ( @@ -11,11 +12,16 @@ File, HTTPException, ) +from pathlib import Path from .models import EnableOEMMode from ...settings import SystemServerSettings, get_settings, save_settings +# regex to sanitize the filename +FILENAME_REGEX = re.compile(r"[^a-zA-Z0-9-.]") + + oem_mode_router = APIRouter() @@ -78,7 +84,7 @@ async def upload_splash_image( # Get the file info file_info = filetype.guess(file.file) - if file_info is None: + if file_info is None or not file.filename: raise HTTPException( status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE, detail="Unable to determine file type", @@ -115,8 +121,12 @@ async def upload_splash_image( if settings.oem_mode_splash_custom: os.unlink(settings.oem_mode_splash_custom) + # sanitize the filename + sanatized_filename = FILENAME_REGEX.sub("_", file.filename) + filename = f"{Path(sanatized_filename).stem}.{content_type}" + # file is valid, save to final location - filepath = f"{settings.persistence_directory}/{file.filename}" + filepath = f"{settings.persistence_directory}/{filename}" with open(filepath, "wb+") as f: f.write(file.file.read())