Agent Zero AI framework
better filename check
linklitie5669daf6723
diff --git a/python/api/api_message.py b/python/api/api_message.pyindex 6427934a3..f9199f677 100644--- a/python/api/api_message.py+++ b/python/api/api_message.py@@ -6,7 +6,7 @@ from python.helpers.api import ApiHandler, Request, Responsefrom python.helpers import files, projectsfrom python.helpers.print_style import PrintStylefrom python.helpers.projects import activate_project-from werkzeug.utils import secure_filename+from python.helpers.security import safe_filenamefrom initialize import initialize_agentimport threading@@ -57,9 +57,9 @@ class ApiMessage(ApiHandler):continuetry:- filename = secure_filename(attachment["filename"])+ filename = safe_filename(attachment["filename"])if not filename:- continue+ raise ValueError("Invalid filename")# Decode base64 contentfile_content = base64.b64decode(attachment["base64"])diff --git a/python/api/chat_files_path_get.py b/python/api/chat_files_path_get.pyindex b230d31f7..b2ebb789e 100644--- a/python/api/chat_files_path_get.py+++ b/python/api/chat_files_path_get.py@@ -1,7 +1,6 @@from python.helpers.api import ApiHandler, Request, Responsefrom python.helpers import files, memory, notification, projects, notification, runtimeimport os-from werkzeug.utils import secure_filenameclass GetChatFilesPath(ApiHandler):diff --git a/python/api/import_knowledge.py b/python/api/import_knowledge.pyindex bfc25b649..97ba15e47 100644--- a/python/api/import_knowledge.py+++ b/python/api/import_knowledge.py@@ -1,7 +1,7 @@from python.helpers.api import ApiHandler, Request, Responsefrom python.helpers import files, memoryimport os-from werkzeug.utils import secure_filename+from python.helpers.security import safe_filenameclass ImportKnowledge(ApiHandler):@@ -32,7 +32,9 @@ class ImportKnowledge(ApiHandler):for file in file_list:if file and file.filename:- filename = secure_filename(file.filename) # type: ignore+ filename = safe_filename(file.filename)+ if not filename:+ continuefile.save(os.path.join(KNOWLEDGE_FOLDER, filename))saved_filenames.append(filename)diff --git a/python/api/knowledge_reindex.py b/python/api/knowledge_reindex.pyindex b86eafeaf..d854c9199 100644--- a/python/api/knowledge_reindex.py+++ b/python/api/knowledge_reindex.py@@ -1,7 +1,6 @@from python.helpers.api import ApiHandler, Request, Responsefrom python.helpers import files, memory, notification, projects, notificationimport os-from werkzeug.utils import secure_filenameclass ReindexKnowledge(ApiHandler):diff --git a/python/api/message.py b/python/api/message.pyindex cd63e85fd..2419d8a7b 100644--- a/python/api/message.py+++ b/python/api/message.py@@ -3,7 +3,7 @@ from python.helpers.api import ApiHandler, Request, Responsefrom python.helpers import files, extensionimport os-from werkzeug.utils import secure_filename+from python.helpers.security import safe_filenamefrom python.helpers.defer import DeferredTaskfrom python.helpers.print_style import PrintStyle@@ -37,7 +37,9 @@ class Message(ApiHandler):for attachment in attachments:if attachment.filename is None:continue- filename = secure_filename(attachment.filename)+ filename = safe_filename(attachment.filename)+ if not filename:+ continuesave_path = files.get_abs_path(upload_folder_ext, filename)attachment.save(save_path)attachment_paths.append(os.path.join(upload_folder_int, filename))diff --git a/python/api/upload.py b/python/api/upload.pyindex 4a596a577..892137b3a 100644--- a/python/api/upload.py+++ b/python/api/upload.py@@ -1,6 +1,6 @@from python.helpers.api import ApiHandler, Request, Responsefrom python.helpers import files-from werkzeug.utils import secure_filename+from python.helpers.security import safe_filenameclass UploadFile(ApiHandler):@@ -13,7 +13,11 @@ class UploadFile(ApiHandler):for file in file_list:if file and self.allowed_file(file.filename): # Check file type- filename = secure_filename(file.filename) # type: ignore+ if not file.filename:+ continue+ filename = safe_filename(file.filename)+ if not filename:+ continuefile.save(files.get_abs_path("tmp/upload", filename))saved_filenames.append(filename)diff --git a/python/helpers/attachment_manager.py b/python/helpers/attachment_manager.pyindex aad7c1375..9a737d44c 100644--- a/python/helpers/attachment_manager.py+++ b/python/helpers/attachment_manager.py@@ -3,7 +3,8 @@ import ioimport base64from PIL import Imagefrom typing import Dict, List, Optional, Tuple-from werkzeug.utils import secure_filename+from python.helpers.security import safe_filename+from werkzeug.datastructures import FileStoragefrom python.helpers.print_style import PrintStyle@@ -41,10 +42,10 @@ class AttachmentManager:except AttributeError:return False- def save_file(self, file, filename: str) -> Tuple[str, Dict]:+ def save_file(self, file: FileStorage, name: str) -> Tuple[str, Dict]:"""Save file and return path and metadata"""try:- filename = secure_filename(filename)+ filename = safe_filename(name)if not filename:raise ValueError("Invalid filename")@@ -68,7 +69,7 @@ class AttachmentManager:return file_path, metadataexcept Exception as e:- PrintStyle.error(f"Error saving file {filename}: {e}")+ PrintStyle.error(f"Error saving file {name}: {e}")return None, {} # type: ignoredef generate_image_preview(self, image_path: str, max_size: int = 800) -> Optional[str]:diff --git a/python/helpers/file_browser.py b/python/helpers/file_browser.pyindex 8340b2f62..d69de6d8e 100644--- a/python/helpers/file_browser.py+++ b/python/helpers/file_browser.py@@ -4,7 +4,7 @@ import shutilimport base64import subprocessfrom typing import Dict, List, Tuple, Any-from werkzeug.utils import secure_filename+from python.helpers.security import safe_filenamefrom datetime import datetimefrom python.helpers import files@@ -69,7 +69,9 @@ class FileBrowser:for file in files:try:if file and self._is_allowed_file(file.filename, file):- filename = secure_filename(file.filename)+ filename = safe_filename(file.filename)+ if not filename:+ raise ValueError("Invalid filename")file_path = target_dir / filenamefile.save(str(file_path))diff --git a/python/helpers/security.py b/python/helpers/security.pynew file mode 100644index 000000000..a5edeaa3b--- /dev/null+++ b/python/helpers/security.py@@ -0,0 +1,49 @@+import re+import unicodedata+from pathlib import Path+from typing import Final, Optional++# Forbidden characters:+# Linux/Unix: / and NULL byte+# Windows: < > : " / \ | ? * and ASCII control characters (0-31)+# Shell-sensitive: ~ to prevent accidental home directory access+FORBIDDEN_CHARS_RE: Final = re.compile(r'[<>:"|?*~/\\\x00-\x1f\x7f]')++# Windows reserved filenames+WINDOWS_RESERVED: Final = frozenset({+ "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$",+ "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",+ "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"+})++FILENAME_MAX_LENGTH: Final = 255++def safe_filename(filename: str) -> Optional[str]:+ # Normalize Unicode (NFC)+ filename = unicodedata.normalize("NFC", str(filename))+ # Replace forbidden chars+ filename = FORBIDDEN_CHARS_RE.sub("_", filename)+ # Remove leading/trailing spaces and trailing dots+ filename = filename.lstrip(" ").rstrip(". ")++ path = Path(filename)+ suffixes = ''.join(path.suffixes)+ stem = path.name[:-len(suffixes)] if suffixes else path.name++ # Check Windows reserved names+ if stem.upper() in WINDOWS_RESERVED:+ filename = f"{stem}-{suffixes}"++ # Truncate if too long+ if len(filename) > FILENAME_MAX_LENGTH:+ max_stem_len = FILENAME_MAX_LENGTH - len(suffixes)+ if max_stem_len > 0:+ # Truncate filename+ stem = stem[:max_stem_len]+ filename = stem + suffixes+ else:+ # Extension is too long, truncate everything+ filename = filename[:FILENAME_MAX_LENGTH]+ if not filename:+ return None+ return filename