← Back to all articles

From One False-Positive SAST SQL Alert to Six Real P1 Fixes: A Full White-Box Security Audit of sessfork

An automated scanner flagged a static SQLite column toggle in sessfork as SQL injection. Confirming it was a 100% false positive triggered a full-stack white-box audit across the Rust CDP MCP server, Python CLI, Chrome extension, and Windows installer—uncovering six real P1 flaws beneath a green 29/29 security suite.

🌐 阅读中文版本 →
#Security#Rust#MCP#Browser Automation#White-Box Audit
On this page

It started with a noisy static analysis (SAST) alert: an automated scanner spotted an f-string inside a SQLite SELECT query in chrome.py and labeled it a SQL injection hazard.

Opening the function immediately proved it was a 100% static-literal false positive. The code copies Chrome’s Cookies file using O_NOFOLLOW into a 0600 snapshot inside a 0700 temporary directory, checks PRAGMA table_info(cookies) for legacy schema compatibility, and interpolates exactly one of two compile-time constants:

top_frame_col = "top_frame_site_key" if "top_frame_site_key" in columns else "''"
cur.execute(
    f"""
    SELECT host_key, name, value, encrypted_value, path,
           expires_utc, is_secure, is_httponly, has_expires, samesite,
           {top_frame_col}
    FROM cookies
    """
)

No untrusted input can ever touch top_frame_col. Splitting that query into two static constant SQL strings cleanly silences the scanner noise.

What bothered us was the follow-up question: sessfork already ships with a live adversarial verification harness (scripts/security_verify.py passing 29/29), 67 Python unit tests, and 73 Rust unit tests. If we had simply dismissed the SAST alert and moved on, what real cross-boundary bugs were hiding underneath a green test suite?

So we ran a full-stack white-box audit across all four trust layers—Python session extraction, Chrome MV3 extension, Rust CDP MCP server + native host, and release installers—filtering every candidate through a strict 7-question false-positive triage gate. Underneath the green checks, we found and fixed six concrete P1 boundary flaws.


1. Why a Green 29/29 Adversarial Suite Still Missed Real Bugs

Automated security probes tend to test the invariants you already thought to defend. What usually breaks in production are cross-layer mismatches and execution-window races between components:

  1. Out-of-scope threats stay explicitly documented, not inflated: Same-UID local malware or intentionally reading same-origin non-HttpOnly state via browser_evaluate are already documented as non-goals in SECURITY.md. Every reported issue had to break an active security boundary.
  2. Audit the seams, not just individual modules:
    • OS extraction & state persistence (chrome.py, crypto.py, localstorage.py, state.py)
    • Browser extension ↔ native messaging host (popup.js, idor_engine.js ↔ native_host.rs, api_server.rs, handoff.rs)
    • CDP isolated worlds & frame locking (browser.rs, storage.rs, ws_cdp.rs)
    • Installers & release supply chain (install.sh, install.ps1, Cargo.lock, GitHub Actions)

2. The Six Confirmed P1 Fixes

P1-1: Hot-Reload localStorage Navigation TOCTOU & Silent Main-World Fallback

During browser_set_storage_state or browser_handoff(complete), apply_storage_state_to_context queried Page.getFrameTree to learn top_frame.origin, generated a single-origin script holding only that origin’s localStorage items, and evaluated it via eval_in_isolated_world.

Two weaknesses combined into a cross-origin token leak risk:

  1. No runtime location.origin check inside the injected JS: Because a top-level tab reuses the same CDP frameId across navigations, a fast redirect to another origin between Page.getFrameTree and Runtime.evaluate would write Site A’s localStorage tokens straight into Site B’s window.localStorage.
  2. Silent fallback to main-world Runtime.evaluate: Unlike tool_evaluate (which fails closed), eval_in_isolated_world fell back to main-world evaluation if Page.createIsolatedWorld failed or omitted executionContextId—exposing injected entries to tampered Storage.prototype setters on hostile pages.

The fix:

  • Keep eval_in_isolated_world strictly for non-secret DOM metadata (document.title, readyState, Markdown extraction), and introduce eval_in_isolated_world_strict (rust/sessfork-mcp/src/browser.rs) for localStorage hydration and live handoff extraction—failing closed if an isolated world cannot be created.
  • Inject an origin lock at the top of build_single_origin_local_storage_sync_script (rust/sessfork-mcp/src/storage.rs) before localStorage.clear() / localStorage.setItem(), and strip redundant :80 / :443 default ports in normalize_origin:
const __expected = "https://app.example.com";
if (!__expected || location.origin.toLowerCase() !== __expected) return;

P1-2: browser_evaluate Missing Runtime expectedOrigin Lock Inside Child Frames

To guard cross-origin iframes, browser_evaluate requires both allowCrossOrigin: true and an explicit expectedOrigin matching the frame tree. Previously, after authorize_frame_evaluate checked the frame tree snapshot, the injected guarded_expr only verified window.origin === 'null' (blocking opaque sandboxed frames)—it did not re-check location.origin.toLowerCase() inside the isolated world right before evaluation.

Our earlier D9 probe tested stale removed frameIds, missing the case where an iframe navigates cross-origin while keeping the same frameId.

The fix: Added build_guarded_frame_eval_expression (rust/sessfork-mcp/src/browser.rs) to enforce both non-opaque origins and exact location.origin.toLowerCase() === __exp inside the execution world for child frames (and top frames whenever expectedOrigin is specified).


P1-3: Fail-Open Python load_storage_state Silently Wiping state.json on Corruption

We caught an asymmetric fail-open bug between the Rust and Python layers:

  • Rust’s load_existing_state_strict refuses to overwrite a corrupted or malformed state.json (explicitly covered in security_verify.py);
  • Python’s load_storage_state in src/sessfork/state.py caught (OSError, json.JSONDecodeError) and quietly returned {"cookies": [], "origins": []}.

As a result, running an incremental single-domain sync or sessfork --clear example.com while state.json was truncated or malformed would treat the vault as empty and overwrite every other saved domain’s sessions.

The fix (src/sessfork/state.py):

  • Added _read_regular_file_nofollow using os.O_RDONLY | os.O_NOFOLLOW + fstat regular-file and 16 MiB size checks;
  • Missing files still initialize cleanly, while any invalid UTF-8, corrupt JSON, or non-object schema now fails closed with BrowserProfileError (leaving the original file untouched and emitting only line/column numbers without echoing secrets);
  • Explicit full resets (clear_state(None) or replace_all=True) remain available for deliberate recovery.

P1-4: Extension Session TTL Silently Expiring Only While Popup Remains Open

The Chrome extension offers 15m, 1h, and 4h auto-expire TTL presets. Because the MV3 extension deliberately runs with zero background scripts or service workers, closing the popup halted its setInterval timer:

  1. native_host.rs’s "sync" handler completely ignored the ttlSecs field sent by the popup;
  2. Playwright storageState origins (localStorage JWTs) carry no native expires field;
  3. popup.js’s pruneExpiredDomains() checked exact equality liveDomains.has(dom), skipping cleanup when only subdomain cookies were listed under a parent domain TTL.

If a user synced with a 15m TTL and closed the popup, localStorage tokens remained injectable from ~/.sessfork/state.json indefinitely.

The fix (coordinated across Chrome extension, Rust native_host.rs + storage.rs, and Python state.py):

  • native_host.rs now validates ttlSecs (0..=604800), clamps synced cookie expires, and atomically writes 0600 TTL sidecar files (ttl.json and .sessfork-ttl.json), pruning expired domains on "status" and "clear";
  • Both Rust load_storage_state_file and Python load_storage_state enforce TTL sidecar filtering on every read, guaranteeing expired localStorage JWTs are never re-hydrated even if the popup is never reopened;
  • popup.js now uses subdomain-aware hostMatchesDomain checks and syncs authoritative domainTtls from the native host.

P1-5: Unredacted Query Secrets & Token Prefixes in Extension IDOR Reports

In extension/idor_engine.js, candidate endpoint filtering stripped #fragment but preserved full ?search query strings. Meanwhile, scrubSensitiveText caught JWTs, sk_live, ghp, gho, creem, sbp_, AIza, AKIA, Bearer, and emails—but missed sensitive query parameters (?token=, ?access_token=, ?api_key=, ?code=, ?signature=, ?x-amz-security-token=), URL userinfo (https://user:pass@), and newer prefixes like github_pat_, ghu_/ghs_/ghr_, sk-proj-, sk-ant-, ntn_, glpat-, and xoxb-.

The fix: Expanded scrubSensitiveText with SENSITIVE_QUERY_PARAM_RE and modern token patterns, added redactUrlForDisplay, and applied redaction consistently across response snapshots (summarizeResponseForSnapshot), popup rendering (popup.js), and exported HTML reports—while keeping benign query params like ?org_id=42 intact for endpoint testing.


P1-6: Supply-Chain Asymmetry in install.ps1

While install.ps1 rigorously verified SHA256SUMS.txt hashes for sessfork-mcp-windows-x64.zip and sessfork-extension.zip, its Moli bootstrap block silently downloaded an unpinned, unhashed third-party script from releases/latest and ran it with -ExecutionPolicy ByPass:

Invoke-WebRequest -Uri "https://github.com/lexmount/moli/releases/latest/download/moli-installer.ps1" -OutFile $MoliInstaller -UseBasicParsing
& powershell -NoProfile -ExecutionPolicy ByPass -File $MoliInstaller

And at the top of the file, $Version defaulted to querying GitHub releases/latest rather than pinning a release tag.

The fix (install.ps1): Pinned $PinnedDefaultVersion = "v0.4.2" (matching install.sh, with latest strictly opt-in), stopped auto-downloading/executing third-party installers by default when moli.exe is missing, and required explicit SESSFORK_INSTALL_MOLI=1 + 64-hex SESSFORK_MOLI_INSTALLER_SHA256 verification + RemoteSigned when automated Moli installation is requested.


3. Five P2 Defense-in-Depth Hardening Improvements

Alongside splitting chrome.py’s SQL query into two static constants to eliminate the SAST alert, we closed five P2 hardening items:

  1. LevelDB parser memory bounds (src/sessfork/localstorage.py): Capped snappy_decompress at 16 MiB (MAX_SNAPPY_UNCOMPRESSED_BYTES) with incremental bounds checks on literals/copies, bounded WAL batch buffering at 16 MiB, guarded shared > len(prev_key) in _iter_block_entries, and rejected @ userinfo in _parse_localstorage_user_key.
  2. Read-side O_NOFOLLOW & key cache permission checks (src/sessfork/crypto.py, rust/sessfork-mcp/src/browser.rs): _load_key_cache_dict now opens keys.json with O_NOFOLLOW and enforces fstat ownership + 0600 mode (failing closed on 0644 caches); tool_file_upload adds --profiles-dir and active_default_storage_state to forbidden_dirs/forbidden_files.
  3. Eliminating post-reap killpg PID-reuse windows (rust/sessfork-mcp/src/api_server.rs, handoff.rs): Added a reaped: bool flag so libc::killpg(pid, SIGKILL) is never called after child.try_wait() has already reaped the process; validated_handoff_end_host also blocks public suffixes (github.io, co.uk) when collecting final handoff URLs.
  4. Uniform localhost / IP literal matching (chrome.py, localstorage.py, state.py): Aligned Python matchers with Rust’s host_matches_domain so evil.127.0.0.1 and evil.localhost are never accepted as subdomains of 127.0.0.1 or localhost.
  5. Subprocess pipe cleanup (examples/genericagent-sop/sessfork_mcp_client.py): Explicitly closed stdin, stdout, and stderr in __exit__, eliminating test ResourceWarnings.

4. Verification Results & Honest Boundaries (Not tested ≠ clean)

After all fixes and regression tests landed, we ran the full verification suite in isolated temporary sandboxes (zero access to real user browser profiles or ~/.sessfork/*):

  • Python unit suite (unittest discover -s tests -v): 69 / 69 passed (zero ResourceWarnings).
  • Rust unit tests & Clippy (cargo test --locked --all-targets && cargo clippy --locked --all-targets -- -D warnings): 78 / 78 passed, 0 warnings.
  • Adversarial security harness (scripts/security_verify.py against the newly built release sessfork-mcp + moli 1.1.29): 29 / 29 PASS (failed=0).
  • Rust MCP live E2E (test_rust_mcp_e2e.py against the release binary): 11 / 11 passed.

In keeping with Not tested ≠ clean, here is what remains outside this run’s live execution envelope:

  • Everything ran on macOS arm64; Windows live execution of install.ps1 / Win32 Job Objects and Linux secret-tool / OpenSSL behavior were not exercised on live Windows/Linux hosts in this round.
  • Extension UI controls were verified via Node VM harnesses and unit checks rather than interactive clicking inside a live Chrome window.
  • Lower-priority P2 items (such as ui_server.py printing ?token= to stdout and expanding multi-label cloud PSL entries) remain queued for a follow-up cleanup.

5. Five Audit Habits Worth Keeping for Any Credential-Handling Agent Tool

  1. Treat every “inspect-then-act” CDP step as a TOCTOU candidate: Whenever a frameId can navigate between Page.getFrameTree and execution, enforce location.origin inside the evaluated world itself.
  2. Never fail open to {} on corrupt state files: Silent fallbacks turn a single disk glitch into total credential loss on the next incremental write.
  3. Never rely on an ephemeral UI popup to enforce credential TTLs: If the extension has no background worker, the host and consumer loaders must enforce expiration on disk and on read.
  4. Check installer symmetry: Hashing your own binary means very little if the next block pipes an unpinned upstream latest script straight into ByPass.
  5. Patch first, publish second: Keep every draft and write-up offline until the fixed release is shipped.
Discussion & Feedback Join the discussion or share feedback on GitHub Discussions →