Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(security): detect URL-encoded and unicode-traversal attacks in PathValidator (#4291)

LearningCircuit4d309a5523ac
diff --git a/src/local_deep_research/security/path_validator.py b/src/local_deep_research/security/path_validator.py
index 6073e9a1c0..11dcdf299c 100644
--- a/src/local_deep_research/security/path_validator.py
+++ b/src/local_deep_research/security/path_validator.py
@@ -7,8 +7,10 @@ and other filesystem-based security vulnerabilities.
import os
import re
+import unicodedata
from pathlib import Path
from typing import Optional, Union
+from urllib.parse import unquote
from loguru import logger
from werkzeug.security import safe_join
@@ -16,6 +18,63 @@ from werkzeug.security import safe_join
from ..config.paths import get_models_directory
+# Encoded forms of ".." and "." that path traversal attacks use to bypass
+# naive `..`-substring checks. The list covers both single and double URL
+# encoding (where the % itself is encoded as %25).
+_ENCODED_TRAVERSAL_TOKENS = (
+ "%2e%2e", # ..
+ "%2E%2E",
+ "%2e.", # .. (mixed)
+ ".%2e",
+ "%252e%252e", # double-encoded ..
+ "%252E%252E",
+ "%2f", # /
+ "%2F",
+)
+
+
+def _has_encoded_traversal(text: str) -> bool:
+ """Return True if `text` contains URL-encoded path-traversal tokens.
+
+ Checks for both single and double URL encoding of '..', '.', and '/'.
+ Decoders downstream may convert these into real '..' segments that
+ escape the base directory; reject the input before that happens.
+ """
+ lowered = text.lower()
+ for tok in _ENCODED_TRAVERSAL_TOKENS:
+ if tok.lower() in lowered:
+ return True
+ # Recursive decode: if unquote changes the string, the original
+ # contained encoded characters. Re-check the decoded form for ".."
+ # in case the encoding used is one not enumerated above.
+ decoded = unquote(text)
+ if decoded != text and ".." in decoded:
+ return True
+ # Double-decode catches %252e%252e -> %2e%2e -> ..
+ double_decoded = unquote(decoded)
+ if double_decoded != decoded and ".." in double_decoded:
+ return True
+ return False
+
+
+def _has_unicode_traversal(text: str) -> bool:
+ """Return True if `text` contains unicode look-alikes for path traversal.
+
+ Many unicode characters NFKC-normalize to '.' or '/', so an attacker
+ can use full-width periods (U+FF0E '.') or other look-alikes to
+ bypass naive '..'-substring checks. After normalization, '..' or
+ '/..' segments indicate an attempt to traverse.
+ """
+ normalized = unicodedata.normalize("NFKC", text)
+ if normalized == text:
+ return False
+ return (
+ ".." in normalized
+ or normalized.startswith("/..")
+ or "/.." in normalized
+ )
+
+
class PathValidator:
"""Centralized path validation for security."""
@@ -56,6 +115,29 @@ class PathValidator:
# Strip whitespace
user_input = user_input.strip()
+ # Reject URL-encoded traversal tokens (single or double encoded).
+ # safe_join's literal-".."-check doesn't catch %2e%2e or %252e%252e,
+ # so do it explicitly here before any decoding takes place.
+ if _has_encoded_traversal(user_input):
+ logger.warning(
+ f"Encoded path-traversal attempt blocked: {user_input!r}"
+ )
+ raise ValueError(
+ "Invalid path - encoded traversal pattern detected"
+ )
+
+ # Reject unicode look-alike traversal (e.g. full-width '..').
+ # NFKC normalization is the same form most filesystems / browsers
+ # apply; if normalizing produces a '..' segment the original was a
+ # disguised traversal attempt.
+ if _has_unicode_traversal(user_input):
+ logger.warning(
+ f"Unicode path-traversal attempt blocked: {user_input!r}"
+ )
+ raise ValueError(
+ "Invalid path - unicode traversal pattern detected"
+ )
+
# Use werkzeug's safe_join for secure path joining
# This handles path traversal attempts automatically
base_dir = Path(base_dir).resolve()
diff --git a/tests/security/test_path_validator.py b/tests/security/test_path_validator.py
index 5d4f9b6867..a860ee77be 100644
--- a/tests/security/test_path_validator.py
+++ b/tests/security/test_path_validator.py
@@ -376,36 +376,40 @@ class TestSecurityScenarios:
with tempfile.TemporaryDirectory() as tmpdir:
yield Path(tmpdir)
- @pytest.mark.xfail(
- reason="Unicode normalization attack detection not yet implemented"
- )
def test_unicode_normalization_attack(self, temp_base_dir):
- """Handles unicode normalization attacks."""
- # Try various unicode tricks
- with pytest.raises(ValueError):
+ """Unicode look-alike traversal is rejected.
+
+ Full-width periods (U+FF0E '.') NFKC-normalize to '.', which a
+ downstream consumer might apply silently. PathValidator rejects
+ the input before that happens.
+ """
+ with pytest.raises(ValueError, match="unicode traversal"):
PathValidator.validate_safe_path(
"../etc/passwd", # Full-width periods
temp_base_dir,
)
- @pytest.mark.xfail(
- reason="URL encoding attack detection not yet implemented"
- )
def test_url_encoded_traversal(self, temp_base_dir):
- """Handles URL-encoded path traversal."""
- # The %2e%2e should be decoded to .. somewhere in the chain
- with pytest.raises(ValueError):
+ """URL-encoded path traversal is rejected.
+
+ Some downstream consumers urldecode strings before joining them
+ into paths; werkzeug.safe_join's literal-'..' check can't see
+ through '%2e%2e'. PathValidator catches this earlier.
+ """
+ with pytest.raises(ValueError, match="encoded traversal"):
PathValidator.validate_safe_path(
"%2e%2e/etc/passwd",
temp_base_dir,
)
- @pytest.mark.xfail(
- reason="Double URL encoding attack detection not yet implemented"
- )
def test_double_encoded_traversal(self, temp_base_dir):
- """Handles double-encoded path traversal."""
- with pytest.raises(ValueError):
+ """Double-encoded path traversal is rejected.
+
+ '%252e%252e' decodes once to '%2e%2e' and again to '..';
+ detection runs two levels of unquote() to catch this layered
+ encoding.
+ """
+ with pytest.raises(ValueError, match="encoded traversal"):
PathValidator.validate_safe_path(
"%252e%252e/etc/passwd",
temp_base_dir,