The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Inspired by Claude Code: file tools reject Windows NT-namespace paths (NTLM leak hardening)
Tekniumfaf71eb4c1c0
diff --git a/agent/file_safety.py b/agent/file_safety.pyindex 1ee92367add..89453ef5480 100644--- a/agent/file_safety.py+++ b/agent/file_safety.py@@ -74,6 +74,81 @@ def _home_and_resolved(path: str) -> tuple[str, str]:return tuple(os.path.realpath(os.path.expanduser(p)) for p in ("~", str(path)))+# ---------------------------------------------------------------------------+# Windows NT-namespace path guard+#+# Inspired by Claude Code v2.1.234 (Aug 2026), which made its pre-approval+# file accesses "reject Windows NT-namespace (`\\??\\`) paths, hardening the+# remaining pre-approval file accesses against the NTLM credential-leak+# vector."+#+# The vector: on Windows, merely *resolving or touching* a path such as+# ``\\??\\UNC\\attacker.example\\share\\x`` (or the ``\\\\?\\UNC\\`` /+# ``GLOBALROOT`` re-entry forms) makes the OS initiate SMB authentication to+# the remote host, leaking the user's NTLM hash — even when the read itself+# fails or would later be denied. NT object-namespace paths also bypass+# normal Win32 path normalization, which lets them dodge deny-prefix checks+# built on ``realpath()`` string comparison. A model tricked by injected+# content into "reading" such a path leaks credentials before any denylist+# built on resolved paths can fire.+#+# Consequently this check MUST run on the *raw* path string before any+# ``Path.resolve()`` / ``os.path.realpath()`` call, and it does — it is the+# first check in both :func:`get_read_block_error` and the write-denial+# classifier.+#+# Scope (deliberately narrow to avoid false positives):+# * ``\\??\\...`` — NT object-namespace paths. Never legitimate+# tool input on any platform.+# * ``\\\\.\\...`` — Win32 device namespace (``\\\\.\\pipe\\``,+# ``\\\\.\\PhysicalDrive0``, ...). Not a file+# read/write target for agent tools.+# * ``\\\\?\\UNC\\...`` — extended-length UNC form (remote host).+# * ``\\\\?\\GLOBALROOT...`` — re-entry into the NT namespace.+#+# Plain drive-letter extended-length paths (``\\\\?\\C:\\...``) stay ALLOWED:+# they are a routine local form (see hermes_cli/windows_ssh_runtime.py) and+# carry no remote-auth trigger. Plain UNC shares (``\\\\server\\share``) are+# also unchanged here — blocking ordinary UNC reads is a policy question,+# not part of this namespace-bypass guard.+#+# The guard runs on every platform: these prefixes are never legitimate+# inputs on POSIX either, and path strings can be relayed toward Windows+# hosts (remote terminal backends, desktop bridges).+# ---------------------------------------------------------------------------++def is_nt_namespace_path(path: str) -> bool:+ """Return True if ``path`` is a Windows NT-/device-namespace path.++ Checks the raw string only — never resolves the path (resolving is the+ credential-leak trigger this guard exists to prevent).+ """+ s = str(path).replace("/", "\\")+ if s.startswith("\\??\\"):+ return True+ if s.startswith("\\\\.\\"):+ return True+ if s.startswith("\\\\?\\"):+ rest = s[4:]+ upper = rest.upper()+ if upper.startswith("UNC\\") or upper.startswith("GLOBALROOT"):+ return True+ return False+++def get_nt_namespace_error(path: str, *, verb: str = "Access") -> Optional[str]:+ """Return an error message when ``path`` uses the NT/device namespace."""+ if not is_nt_namespace_path(path):+ return None+ return (+ f"{verb} denied: '{path}' uses a Windows NT/device namespace prefix "+ "(\\??\\, \\\\.\\, \\\\?\\UNC\\, or GLOBALROOT). These paths bypass "+ "normal path normalization and can trigger outbound SMB "+ "authentication (NTLM credential leak) merely by being resolved. "+ "Use a normal absolute path instead."+ )++def build_write_denied_paths(home: str) -> set[str]:"""Return exact sensitive paths that must never be written."""# ``~/.ssh/config`` is deliberately NOT hard-denied: no key bytes, and editing@@ -134,7 +209,12 @@ _HERMES_PROTECTED_SUBPATHS = ("state.db", "sessions", "mcp-tokens", "pairing")def _classify_write_denial(path: str) -> Optional[str]:- """Return ``'credential'``, ``'safe_root'``, or ``None`` if writes are allowed."""+ """Return ``'credential'``, ``'safe_root'``, ``'nt_namespace'``, or ``None`` if writes are allowed."""+ # NT/device-namespace check runs on the RAW string, before realpath():+ # resolving such a path is itself the NTLM-leak trigger, and namespace+ # prefixes defeat string-prefix denylist comparison after normalization.+ if is_nt_namespace_path(path):+ return "nt_namespace"home, resolved = _home_and_resolved(path)# Approval-gated paths are allowed at this layer so interactive tools can@@ -174,6 +254,8 @@ def get_write_denied_error(path: str, *, verb: str = "Write") -> Optional[str]:f"{verb} denied: '{path}' is outside HERMES_WRITE_SAFE_ROOT "f"({roots_display}). Unset the variable or add this path's directory prefix.")+ if denial == "nt_namespace":+ return get_nt_namespace_error(path, verb=verb)return f"{verb} denied: '{path}' is a protected system/credential file." if denial else None@@ -230,6 +312,14 @@ def get_read_block_error(path: str) -> Optional[str]:``TERMINAL_CWD``) MUST pass an absolute path: ``resolve()`` here anchors atthe process cwd, so a relative ``"auth.json"`` would miss the denylist."""+ # NT/device-namespace check runs on the RAW string, before resolve():+ # on Windows, resolving \??\UNC\host\share (or \\?\UNC\, GLOBALROOT)+ # already triggers outbound SMB auth — the NTLM leak happens before any+ # resolved-path denylist could fire. Namespace prefixes also bypass+ # normal path normalization, defeating prefix-comparison denylists.+ nt_error = get_nt_namespace_error(path, verb="Read")+ if nt_error:+ return nt_errorresolved = Path(path).expanduser().resolve()hermes_dirs = _hermes_dirs()reason = Nonediff --git a/tests/agent/test_nt_namespace_guard.py b/tests/agent/test_nt_namespace_guard.pynew file mode 100644index 00000000000..5ff5f09bde1--- /dev/null+++ b/tests/agent/test_nt_namespace_guard.py@@ -0,0 +1,150 @@+"""Tests for the Windows NT-namespace path guard in agent.file_safety.++Inspired by Claude Code v2.1.234 (Aug 2026): file accesses reject Windows+NT-namespace (``\\??\\``) paths to harden against the NTLM credential-leak+vector — merely resolving ``\\??\\UNC\\host\\share`` triggers outbound SMB+authentication on Windows, and NT-namespace prefixes bypass the Win32 path+normalization that prefix-based denylists rely on.++The guard must fire on the RAW string before any ``resolve()``/``realpath()``+call, on every platform (path strings can be relayed toward Windows hosts by+remote terminal backends and desktop bridges).+"""++import unittest++from agent.file_safety import (+ get_nt_namespace_error,+ get_read_block_error,+ get_write_denied_error,+ is_nt_namespace_path,+ is_write_denied,+)+++BLOCKED_PATHS = [+ # NT object namespace — the canonical NTLM-leak form.+ "\\??\\UNC\\attacker.example\\share\\x",+ "\\??\\C:\\Windows\\System32\\config\\SAM",+ # Forward-slash spellings normalize to the same namespace on Windows.+ "/??/UNC/attacker.example/share/x",+ # Win32 device namespace.+ "\\\\.\\PhysicalDrive0",+ "\\\\.\\pipe\\evil",+ "//./pipe/evil",+ # Extended-length UNC (remote host) and NT-namespace re-entry.+ "\\\\?\\UNC\\attacker.example\\share\\x",+ "\\\\?\\unc\\attacker.example\\share\\x", # case-insensitive+ "\\\\?\\GLOBALROOT\\Device\\HarddiskVolume1\\x",+ "//?/UNC/attacker.example/share/x",+]++ALLOWED_PATHS = [+ # Ordinary paths on both platforms.+ "/tmp/test.py",+ "/home/user/notes.txt",+ "C:\\Users\\me\\notes.txt",+ "C:/Users/me/notes.txt",+ "~/projects/readme.md",+ "relative/path.txt",+ # Extended-length local drive paths are routine and carry no remote-auth+ # trigger (see hermes_cli/windows_ssh_runtime.py).+ "\\\\?\\C:\\Users\\me\\notes.txt",+ # Plain UNC shares are a separate policy question — NOT blocked by this+ # namespace guard.+ "\\\\server\\share\\file.txt",+ "//server/share/file.txt",+ # A '??' mid-path is data, not a namespace marker.+ "/tmp/??/weird-dir/file",+]+++class TestIsNtNamespacePath(unittest.TestCase):+ def test_blocked_forms(self):+ for path in BLOCKED_PATHS:+ self.assertTrue(is_nt_namespace_path(path), f"{path!r} should be detected")++ def test_allowed_forms(self):+ for path in ALLOWED_PATHS:+ self.assertFalse(is_nt_namespace_path(path), f"{path!r} should NOT be detected")+++class TestReadGuard(unittest.TestCase):+ def test_read_blocked_with_actionable_message(self):+ for path in BLOCKED_PATHS:+ err = get_read_block_error(path)+ self.assertIsNotNone(err, f"{path!r} should be read-blocked")+ self.assertIn("Read denied", err)+ self.assertIn("NT/device namespace", err)++ def test_legitimate_reads_unaffected(self):+ for path in ("/tmp/test.py", "\\\\?\\C:\\Users\\me\\notes.txt"):+ err = get_read_block_error(path)+ if err is not None:+ # Must not be blocked by THIS guard (other denylist rules+ # could theoretically match in exotic environments).+ self.assertNotIn("NT/device namespace", err)++ def test_guard_does_not_resolve_the_path(self):+ """The check must run on the raw string — resolving is the leak."""+ from unittest.mock import patch++ with patch("agent.file_safety.Path") as mock_path:+ err = get_read_block_error("\\??\\UNC\\attacker.example\\share\\x")+ self.assertIsNotNone(err)+ mock_path.assert_not_called()+++class TestWriteGuard(unittest.TestCase):+ def test_write_blocked(self):+ for path in BLOCKED_PATHS:+ self.assertTrue(is_write_denied(path), f"{path!r} should be write-denied")+ err = get_write_denied_error(path)+ self.assertIsNotNone(err)+ self.assertIn("NT/device namespace", err)+ self.assertIn("Write denied", err)++ def test_legitimate_writes_unaffected(self):+ self.assertFalse(is_write_denied("/tmp/scratch/output.txt"))+ self.assertFalse(is_write_denied("\\\\?\\C:\\Users\\me\\notes.txt"))+++class TestErrorHelper(unittest.TestCase):+ def test_none_for_normal_paths(self):+ self.assertIsNone(get_nt_namespace_error("/tmp/x"))++ def test_verb_customization(self):+ err = get_nt_namespace_error("\\??\\UNC\\h\\s\\f", verb="Read")+ assert err is not None+ self.assertTrue(err.startswith("Read denied"))+++class TestToolLayerChokepoints(unittest.TestCase):+ """The raw string must be rejected at the tool entry points, before the+ task-base join anchors ``\\??\\...`` under a POSIX base dir and hides the+ prefix from resolved-path checks."""++ BAD = "\\??\\UNC\\attacker.example\\share\\x"++ def test_read_file_tool_rejects_raw(self):+ from tools.file_tools import read_file_tool++ result = read_file_tool(self.BAD)+ self.assertIn("NT/device namespace", result)++ def test_write_file_tool_rejects_raw(self):+ from tools.file_tools import write_file_tool++ result = write_file_tool(self.BAD, "data")+ self.assertIn("NT/device namespace", str(result))++ def test_patch_tool_rejects_raw(self):+ from tools.file_tools import patch_tool++ result = patch_tool(mode="replace", path=self.BAD,+ old_string="a", new_string="b")+ self.assertIn("NT/device namespace", str(result))+++if __name__ == "__main__":+ unittest.main()diff --git a/tools/file_tools.py b/tools/file_tools.pyindex 3a556058495..4839723f372 100644--- a/tools/file_tools.py+++ b/tools/file_tools.py@@ -18,7 +18,7 @@ import timefrom contextlib import ExitStackfrom pathlib import Path-from agent.file_safety import get_read_block_error+from agent.file_safety import get_nt_namespace_error, get_read_block_errorfrom tools.binary_extensions import has_binary_extensionfrom tools.file_operations import (ShellFileOperations, normalize_read_pagination, normalize_search_pagination)@@ -560,13 +560,22 @@ def _record_successful_read(task_data: dict, task_id: str, path: str, resolved_sdef read_file_tool(path: str, offset: int = 1, limit: int = DEFAULT_READ_LIMIT, task_id: str = "default") -> str:"""Read a file with pagination and line numbers.- Guard order: device-path blocklist (no I/O) → stat-based special-file- guard (host only) → document extraction → binary-extension guard → Hermes- internal denylist → negative-result cache → dedup stub → real read.+ Guard order: NT/device-namespace prefix (raw string, no resolution) →+ device-path blocklist (no I/O) → stat-based special-file guard (host only)+ → document extraction → binary-extension guard → Hermes internal denylist+ → negative-result cache → dedup stub → real read."""try:offset, limit = normalize_read_pagination(offset, limit)+ # On the RAW model-supplied string, before any expanduser()/resolve():+ # on Windows resolving \??\UNC\host\share already sends SMB auth (NTLM+ # leak); on POSIX the task-base join would anchor the prefix as a+ # relative segment and hide it from every resolved-path check below.+ nt_err = get_nt_namespace_error(path, verb="Read")+ if nt_err:+ return tool_error(nt_err)+device_base = None if Path(path).expanduser().is_absolute() else _resolve_base_dir(task_id)if _is_blocked_device(path, base_dir=device_base):return tool_error(@@ -991,6 +1000,11 @@ def search_tool(pattern: str, target: str = "content", path: str = ".",pattern=pattern,already_searched=count)+ # Raw string before _resolve_path_for_task: resolving is the NTLM-leak+ # trigger and the task-base join would hide the prefix (see read_file_tool).+ nt_err = get_nt_namespace_error(path, verb="Search")+ if nt_err:+ return tool_error(nt_err)try:resolved_search_path = str(_resolve_path_for_task(path, task_id))except (OSError, ValueError, RuntimeError) as exc:diff --git a/tools/file_tools_write_guards.py b/tools/file_tools_write_guards.pyindex 82899a0657c..a1a59792a3d 100644--- a/tools/file_tools_write_guards.py+++ b/tools/file_tools_write_guards.py@@ -14,6 +14,7 @@ import fnmatchimport osfrom pathlib import Path+from agent.file_safety import get_nt_namespace_errorfrom tools import file_statefrom tools.binary_extensions import has_opaque_document_extension, is_pdf_pathfrom tools.file_tools_paths import _expand_tilde, _resolve_path_for_task@@ -138,6 +139,14 @@ def _resolved_or_raw(filepath: str, task_id: str) -> str:def _check_sensitive_path(filepath: str, task_id: str = "default") -> str | None:"""Return an error message if the path targets a sensitive system location."""+ # NT/device-namespace guard on the RAW string, BEFORE the task-base join:+ # on POSIX a leading "\??\" reads as a relative segment and gets anchored+ # under the base dir, hiding the prefix from the resolved-path checks,+ # while the same string relayed to a Windows host (remote backend, desktop+ # bridge) triggers the NTLM-leak vector. See agent/file_safety.py.+ nt_err = get_nt_namespace_error(filepath, verb="Write")+ if nt_err:+ return nt_errcandidates = (_resolved_or_raw(filepath, task_id), os.path.normpath(_expand_tilde(filepath)))if any(c.startswith(_SENSITIVE_PATH_PREFIXES) or c in _SENSITIVE_EXACT_PATHS for c in candidates):return (diff --git a/website/docs/user-guide/security.md b/website/docs/user-guide/security.mdindex c221ec0fd2e..71f6a10d114 100644--- a/website/docs/user-guide/security.md+++ b/website/docs/user-guide/security.md@@ -334,6 +334,7 @@ These categories are always denied, even when `HERMES_WRITE_SAFE_ROOT` is unset:| OS credential stores | `~/.ssh/` (keys, `authorized_keys`), `~/.aws/`, `~/.kube/`, `/etc/sudoers`, `~/.netrc` || Hermes credential stores | `auth.json`, `.env`, `.anthropic_oauth.json`, `mcp-tokens/`, `pairing/` under HERMES_HOME (active profile and global root) || Project secret files | `.env`, `.env.local`, `.env.production`, `.envrc` anywhere on disk |+| Windows NT/device-namespace paths | `\??\...`, `\\.\...`, `\\?\UNC\...`, `\\?\GLOBALROOT...` — rejected for both reads and writes on every platform. On Windows, merely *resolving* such a path (e.g. `\??\UNC\host\share`) triggers outbound SMB authentication and can leak the user's NTLM hash; the prefixes also bypass normal path normalization. Ordinary extended-length local paths (`\\?\C:\...`) and plain UNC shares (`\\server\share`) are unaffected. |Sensitive paths inside the safe root are still blocked — pointing `HERMES_WRITE_SAFE_ROOT` at `$HOME` does not allow writing `~/.ssh/id_rsa`.