diff --git a/zhenxun/builtin_plugins/web_ui/utils.py b/zhenxun/builtin_plugins/web_ui/utils.py index 8e076dc0..9ff803e9 100644 --- a/zhenxun/builtin_plugins/web_ui/utils.py +++ b/zhenxun/builtin_plugins/web_ui/utils.py @@ -42,14 +42,28 @@ def validate_path(path_str: str | None) -> tuple[Path | None, str | None]: if not path_str: return Path().resolve(), None - # 移除任何可能的路径遍历尝试 + # 1. 移除任何可能的路径遍历尝试 path_str = re.sub(r"[\\/]\.\.[\\/]", "", path_str) - # 规范化路径 + + # 2. 规范化路径并转换为绝对路径 path = Path(path_str).resolve() - # 验证路径是否在项目根目录内 - if not path.is_relative_to(Path().resolve()): - return None, "访问路径超出允许范围" - return path, None + + # 3. 获取项目根目录 + root_dir = Path().resolve() + + # 4. 验证路径是否在项目根目录内 + try: + if not path.is_relative_to(root_dir): + return None, "访问路径超出允许范围" + except ValueError: + return None, "无效的路径格式" + + # 5. 验证路径是否包含任何危险字符 + if any(c in str(path) for c in ["..", "~", "*", "?", ">", "<", "|", '"']): + return None, "路径包含非法字符" + + # 6. 验证路径长度是否合理 + return (None, "路径长度超出限制") if len(str(path)) > 4096 else (path, None) except Exception as e: return None, f"路径验证失败: {e!s}"