fix: 增加安全路径解析功能,防止路径穿越请求
This commit is contained in:
@@ -3,7 +3,7 @@
|
|||||||
from importlib import import_module
|
from importlib import import_module
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import mimetypes
|
import mimetypes
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI, HTTPException
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from fastapi.responses import FileResponse
|
from fastapi.responses import FileResponse
|
||||||
from src.common.logger import get_logger
|
from src.common.logger import get_logger
|
||||||
@@ -11,6 +11,19 @@ from src.common.logger import get_logger
|
|||||||
logger = get_logger("webui.app")
|
logger = get_logger("webui.app")
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_safe_static_file_path(static_path: Path, full_path: str) -> Path | None:
|
||||||
|
static_root = static_path.resolve()
|
||||||
|
|
||||||
|
try:
|
||||||
|
candidate_path = (static_root / full_path).resolve()
|
||||||
|
candidate_path.relative_to(static_root)
|
||||||
|
except (OSError, RuntimeError, ValueError):
|
||||||
|
logger.warning(f"🚫 检测到疑似路径穿越请求: {full_path}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
return candidate_path
|
||||||
|
|
||||||
|
|
||||||
def create_app(
|
def create_app(
|
||||||
host: str = "0.0.0.0",
|
host: str = "0.0.0.0",
|
||||||
port: int = 8001,
|
port: int = 8001,
|
||||||
@@ -136,8 +149,11 @@ def _setup_static_files(app: FastAPI):
|
|||||||
response.headers["X-Robots-Tag"] = "noindex, nofollow, noarchive"
|
response.headers["X-Robots-Tag"] = "noindex, nofollow, noarchive"
|
||||||
return response
|
return response
|
||||||
|
|
||||||
file_path = static_path / full_path
|
file_path = _resolve_safe_static_file_path(static_path, full_path)
|
||||||
if file_path.is_file() and file_path.exists():
|
if file_path is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Not Found")
|
||||||
|
|
||||||
|
if file_path.exists() and file_path.is_file():
|
||||||
media_type = mimetypes.guess_type(str(file_path))[0]
|
media_type = mimetypes.guess_type(str(file_path))[0]
|
||||||
response = FileResponse(file_path, media_type=media_type)
|
response = FileResponse(file_path, media_type=media_type)
|
||||||
if str(file_path).endswith(".html"):
|
if str(file_path).endswith(".html"):
|
||||||
|
|||||||
Reference in New Issue
Block a user