~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix: Address CodeQL security vulnerabilities from PR #637 (#666)
LearningCircuit28f76b1669de
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.pyindex 36e9b66bce..49e9617293 100644--- a/src/local_deep_research/config/llm_config.py+++ b/src/local_deep_research/config/llm_config.py@@ -802,6 +802,16 @@ def get_llm(logger.error("llamacpp_model_path not set in settings")raise ValueError("llamacpp_model_path not set in settings")+ # Validate model path for security using centralized validator+ from ..security.path_validator import PathValidator++ try:+ validated_path = PathValidator.validate_model_path(model_path)+ model_path = str(validated_path)+ except ValueError:+ logger.exception("Model path validation failed")+ raise+# Get additional LlamaCpp parametersn_gpu_layers = get_setting_from_snapshot("llm.llamacpp_n_gpu_layers",diff --git a/src/local_deep_research/security/__init__.py b/src/local_deep_research/security/__init__.pynew file mode 100644index 0000000000..f03e9ee2cd--- /dev/null+++ b/src/local_deep_research/security/__init__.py@@ -0,0 +1,5 @@+"""Security utilities for Local Deep Research."""++from .path_validator import PathValidator++__all__ = ["PathValidator"]diff --git a/src/local_deep_research/security/path_validator.py b/src/local_deep_research/security/path_validator.pynew file mode 100644index 0000000000..229d191cb5--- /dev/null+++ b/src/local_deep_research/security/path_validator.py@@ -0,0 +1,239 @@+"""+Centralized path validation utilities for security.++This module provides secure path validation to prevent path traversal attacks+and other filesystem-based security vulnerabilities.+"""++import re+from pathlib import Path+from typing import Optional, Union+from werkzeug.security import safe_join+from loguru import logger+++class PathValidator:+ """Centralized path validation for security."""++ # Regex for safe filename/path characters+ SAFE_PATH_PATTERN = re.compile(r"^[a-zA-Z0-9._/\-]+$")++ # Allowed config file extensions+ CONFIG_EXTENSIONS = (".json", ".yaml", ".yml", ".toml", ".ini", ".conf")++ @staticmethod+ def validate_safe_path(+ user_input: str,+ base_dir: Union[str, Path],+ allow_absolute: bool = False,+ required_extensions: Optional[tuple] = None,+ ) -> Optional[Path]:+ """+ Validate and sanitize a user-provided path.++ Args:+ user_input: The user-provided path string+ base_dir: The safe base directory to contain paths within+ allow_absolute: Whether to allow absolute paths (with restrictions)+ required_extensions: Tuple of required file extensions (e.g., ('.json', '.yaml'))++ Returns:+ Path object if valid, None if invalid++ Raises:+ ValueError: If the path is invalid or unsafe+ """+ if not user_input or not isinstance(user_input, str):+ raise ValueError("Invalid path input")++ # Strip whitespace+ user_input = user_input.strip()++ # Use werkzeug's safe_join for secure path joining+ # This handles path traversal attempts automatically+ base_dir = Path(base_dir).resolve()++ try:+ # safe_join returns None if the path tries to escape base_dir+ safe_path = safe_join(str(base_dir), user_input)++ if safe_path is None:+ logger.warning(f"Path traversal attempt blocked: {user_input}")+ raise ValueError("Invalid path - potential traversal attempt")++ result_path = Path(safe_path)++ # Check extensions if required+ if (+ required_extensions+ and result_path.suffix not in required_extensions+ ):+ raise ValueError(+ f"Invalid file type. Allowed: {required_extensions}"+ )++ return result_path++ except Exception as e:+ logger.warning(+ f"Path validation failed for input '{user_input}': {e}"+ )+ raise ValueError(f"Invalid path: {e}") from e++ @staticmethod+ def validate_model_path(+ model_path: str, model_root: Optional[str] = None+ ) -> Path:+ """+ Validate a model file path specifically.++ Args:+ model_path: Path to the model file+ model_root: Root directory for models (defaults to ~/.local/share/llm_models)++ Returns:+ Validated Path object++ Raises:+ ValueError: If the path is invalid+ """+ if model_root is None:+ # Default model root if not provided+ model_root = str(Path.home() / ".local" / "share" / "llm_models")++ # Create model root if it doesn't exist+ model_root_path = Path(model_root).resolve()+ model_root_path.mkdir(parents=True, exist_ok=True)++ # Validate the path+ validated_path = PathValidator.validate_safe_path(+ model_path,+ model_root_path,+ allow_absolute=False, # Models should always be relative to model root+ required_extensions=None, # Models can have various extensions+ )++ if not validated_path:+ raise ValueError("Invalid model path")++ # Check if the file exists+ if not validated_path.exists():+ raise ValueError(f"Model file not found: {validated_path}")++ if not validated_path.is_file():+ raise ValueError(f"Model path is not a file: {validated_path}")++ return validated_path++ @staticmethod+ def validate_data_path(file_path: str, data_root: str) -> Path:+ """+ Validate a path within the data directory.++ Args:+ file_path: Path relative to data root+ data_root: The data root directory++ Returns:+ Validated Path object++ Raises:+ ValueError: If the path is invalid+ """+ validated_path = PathValidator.validate_safe_path(+ file_path,+ data_root,+ allow_absolute=False, # Data paths should be relative+ required_extensions=None,+ )++ if not validated_path:+ raise ValueError("Invalid data path")++ return validated_path++ @staticmethod+ def validate_config_path(+ config_path: str, config_root: Optional[str] = None+ ) -> Path:+ """+ Validate a configuration file path.++ Args:+ config_path: Path to config file+ config_root: Root directory for configs (optional for absolute paths)++ Returns:+ Validated Path object++ Raises:+ ValueError: If the path is invalid+ """+ # Sanitize input first - remove any null bytes and normalize+ if not config_path or not isinstance(config_path, str):+ raise ValueError("Invalid config path input")++ # Remove null bytes and normalize+ config_path = config_path.replace("\x00", "").strip()++ # Check for path traversal attempts in the string itself+ # Define restricted system directories that should never be accessed+ RESTRICTED_PREFIXES = ("etc", "proc", "sys", "dev")++ if ".." in config_path:+ raise ValueError("Invalid path - potential traversal attempt")++ # Check if path starts with any restricted system directory+ normalized_path = config_path.lstrip("/").lower()+ for restricted in RESTRICTED_PREFIXES:+ if (+ normalized_path.startswith(restricted + "/")+ or normalized_path == restricted+ ):+ raise ValueError(+ f"Invalid path - restricted system directory: {restricted}"+ )++ # For config files, we might allow absolute paths with restrictions+ # Check if path starts with / or drive letter (Windows) to detect absolute paths+ # This avoids using Path() or os.path on user input+ is_absolute = (+ config_path.startswith("/") # Unix absolute+ or (+ len(config_path) > 2 and config_path[1] == ":"+ ) # Windows absolute+ )++ if is_absolute:+ # For absolute paths, use safe_join with root directory+ # This validates the path without using Path() directly on user input+ # Use safe_join to validate the absolute path+ safe_path = safe_join("/", config_path)+ if safe_path is None:+ raise ValueError("Invalid absolute path")++ # Now it's safe to create Path object from validated string+ path_obj = Path(safe_path)++ # Additional validation for config files+ if path_obj.suffix not in PathValidator.CONFIG_EXTENSIONS:+ raise ValueError(f"Invalid config file type: {path_obj.suffix}")++ # Check existence using validated path+ if not path_obj.exists():+ raise ValueError(f"Config file not found: {path_obj}")++ return path_obj+ else:+ # For relative paths, use the config root+ if config_root is None:+ from ..config.paths import get_data_directory++ config_root = get_data_directory()++ return PathValidator.validate_safe_path(+ config_path,+ config_root,+ allow_absolute=False,+ required_extensions=PathValidator.CONFIG_EXTENSIONS,+ )diff --git a/src/local_deep_research/web/routes/api_routes.py b/src/local_deep_research/web/routes/api_routes.pyindex 3d1ee08720..2ca727f7de 100644--- a/src/local_deep_research/web/routes/api_routes.py+++ b/src/local_deep_research/web/routes/api_routes.py@@ -576,7 +576,7 @@ def check_ollama_model():{"available": False,"model": model_name,- "message": f"Invalid response from Ollama API: {json_err}",+ "message": "Invalid response from Ollama API","error_type": "json_parse_error",})diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pyindex 3397b55326..49b6edb913 100644--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@ -924,22 +924,12 @@ def open_file_location():safe_root = Path(get_data_directory()).resolve()- # Normalize the path and ensure it's within the safe root directory+ # Use centralized path validator for securitytry:- # Convert to absolute path and normalize- file_path = Path(file_path).resolve()+ from ...security.path_validator import PathValidator++ file_path = PathValidator.validate_data_path(file_path, str(safe_root))- # Check if the path is within the safe data directory- if not str(file_path).startswith(str(safe_root)):- logger.warning(- f"Blocked access to path outside data directory: {file_path}"- )- return jsonify(- {- "status": "error",- "message": "Access denied: Path is outside the allowed directory",- }- ), 403except Exception:logger.exception("Path validation error")return jsonify({"status": "error", "message": "Invalid path"}), 400diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex 34d39e601f..a0712f66e4 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -1,7 +1,6 @@import jsonimport platformimport subprocess-from pathlib import Pathfrom typing import Any, Optional, Tuplefrom datetime import datetime, UTC, timedelta@@ -1566,14 +1565,23 @@ def open_file_location():return redirect(url_for("settings.settings_page"))try:- # Validate the file path- file_path = Path(file_path).resolve()- if not file_path.exists():- flash("File path does not exist", "error")+ # Use centralized path validator for security+ from ...security.path_validator import PathValidator+ from ...config.paths import get_data_directory++ try:+ # PathValidator.validate_config_path already checks existence+ resolved_path = PathValidator.validate_config_path(+ file_path, get_data_directory()+ )+ except ValueError as e:+ # The validator will raise ValueError if file doesn't exist+ flash(f"Invalid file path: {str(e)}", "error")return redirect(url_for("settings.settings_page"))# Get the directory containing the file- dir_path = file_path.parent+ dir_path = resolved_path.parent+ file_path = resolved_path # Use resolved path going forward# Open the directory in the file explorerif platform.system() == "Windows":diff --git a/src/local_deep_research/web/static/js/pages/news.js b/src/local_deep_research/web/static/js/pages/news.jsindex dfb1083615..cac3c3bdc6 100644--- a/src/local_deep_research/web/static/js/pages/news.js+++ b/src/local_deep_research/web/static/js/pages/news.js@@ -11,6 +11,32 @@ function escapeHtml(unsafe) {.replace(/'/g, "'");}+// Safe template rendering function+function safeRenderHTML(container, htmlString) {+ // If container is a string (selector), get the element+ if (typeof container === 'string') {+ container = document.querySelector(container);+ }++ if (!container) return;++ // For better security, we should validate that all dynamic content is escaped+ // This is a defense-in-depth approach+ const template = document.createElement('template');++ // Set the HTML content in the template (isolated from DOM)+ template.innerHTML = htmlString;++ // Clear the container safely+ while (container.firstChild) {+ container.removeChild(container.firstChild);+ }++ // Import and append the content+ const content = document.importNode(template.content, true);+ container.appendChild(content);+}+// Escape attributes for use in HTML attributes (onclick, etc)function escapeAttr(unsafe) {if (unsafe === null || unsafe === undefined) return '';@@ -525,7 +551,7 @@ function parseAndDisplayTable(content) {// Render rows with SOURCES as first columnif (rows.length > 0) {- tableBody.innerHTML = rows.map(row => {+ safeRenderHTML(tableBody, rows.map(row => {// Check if we have an impact score column (usually second to last)const impactIndex = row.length >= 7 ? 6 : (row.length >= 6 ? 5 : -1);const hasImpact = impactIndex > 0 && !isNaN(parseInt(row[impactIndex]));@@ -548,7 +574,7 @@ function parseAndDisplayTable(content) {<td>${row[6] || ''}</td>` : ''}</tr>- `}).join('');+ `}).join(''));}}@@ -641,7 +667,7 @@ async function loadSubscriptions() {`;});- container.innerHTML = html;+ safeRenderHTML(container, html);} */// Select subscription@@ -658,7 +684,7 @@ async function loadNewsFeed(focus = null) {console.error('News container not found!');return;}- container.innerHTML = '<div class="loading-placeholder"><div class="loading-spinner"></div><p>Loading news...</p></div>';+ safeRenderHTML(container, '<div class="loading-placeholder"><div class="loading-spinner"></div><p>Loading news...</p></div>');// Update feed header if subscription is selectedupdateFeedHeader();@@ -715,11 +741,11 @@ async function loadNewsFeed(focus = null) {console.error('Failed to load news feed. Status:', response.status);const errorText = await response.text();console.error('Error response:', errorText);- container.innerHTML = `<p class="error-message">Failed to load news feed (${response.status})</p>`;+ safeRenderHTML(container, `<p class="error-message">Failed to load news feed (${response.status})</p>`);}} catch (error) {console.error('Error loading news:', error);- container.innerHTML = '<p class="error-message">Error loading news feed</p>';+ safeRenderHTML(container, '<p class="error-message">Error loading news feed</p>');}}@@ -795,7 +821,7 @@ function renderNewsItems(searchQuery = null) {if (searchQuery) {searchIndicatorHtml = `<div class="search-indicator alert alert-info">- <i class="bi bi-search"></i> Showing results for: <strong>"${searchQuery}"</strong>+ <i class="bi bi-search"></i> Showing results for: <strong>"${escapeHtml(searchQuery)}"</strong><button class="btn btn-sm btn-link" onclick="clearSearch()"><i class="bi bi-x-circle"></i> Clear search</button>@@ -803,7 +829,7 @@ function renderNewsItems(searchQuery = null) {`;}- container.innerHTML = searchIndicatorHtml + itemsToRender.map(item => {+ const fullHtml = searchIndicatorHtml + itemsToRender.map(item => {const priorityClass = getPriorityClass(item.impact_score);const isNew = isNewsNew(item);const isRead = readNewsIds.has(item.id);@@ -926,6 +952,9 @@ function renderNewsItems(searchQuery = null) {`;}).join('');+ // Use safe rendering+ safeRenderHTML(container, fullHtml);+// Update table view if activeconst tableToggle = document.getElementById('table-view-toggle');if (tableToggle && tableToggle.checked) {@@ -943,11 +972,11 @@ function populateNewsTable() {}if (newsItems.length === 0) {- tableBody.innerHTML = '<tr><td colspan="7" style="text-align: center;">No news items to display</td></tr>';+ safeRenderHTML(tableBody, '<tr><td colspan="7" style="text-align: center;">No news items to display</td></tr>');return;}- tableBody.innerHTML = newsItems.map(item => {+ safeRenderHTML(tableBody, newsItems.map(item => {// Extract or format date/timeconst dateTime = formatNewsDateTime(item.created_at || item.time_ago);@@ -975,7 +1004,7 @@ function populateNewsTable() {</td></tr>`;- }).join('');+ }).join(''));}// Format date/time for news items@@ -2346,7 +2375,7 @@ function displayRecentSearches() {`;}).join('');- container.innerHTML = html;+ safeRenderHTML(container, html);}function rerunSearch(query, type = 'quick') {