SwiftMCPSecurityShellby

Building a Read-Only MCP Boundary in Shellby: Three Security Gaps Caught in Review

Shellby 2.0.0 embeds a local HTTP MCP server on macOS to expose configured SSH hosts to claude-code and codex. An adversarial code review uncovered relative-path bypasses, orphaned dual-window listeners, weak random fallback, and SFTP channel exhaustion.

In version 2.0.0 for macOS, Shellby introduced an “External Agent” mode: an in-app MCP over HTTP server bound to 127.0.0.1 that exposes configured SSH hosts to claude-code and codex through read-only tools.

Getting the JSON-RPC handshake working was the easy part. Making sure the read-only boundary actually held was harder. A focused adversarial review right before release (commit a44221e) broke three assumptions in a row and caught an SFTP channel leak that could take down a user’s own terminal tabs.

Why the Server Lives Inside the App—and Drops ssh_raw

External agents could always run ssh user@host, provided you hand them your private keys or passwords. Hosting the MCP server inside the Shellby app is a hard platform constraint rather than a preference:

  • Credentials live in the data-protection Keychain, readable only by signed binaries sharing the C4T9277GDX.me.mahui.mshell access group. An external CLI or unsigned test binary fails with -34018 errSecMissingEntitlement.
  • Host definitions live in a SwiftData store inside the app sandbox container, unreachable from outside processes.

So we embedded NIOHTTP1 + hand-written JSON-RPC directly into the macOS target—no launchd daemon (it stops when the app quits), constant-time Bearer token comparison on every request, and Origin rejection against DNS rebinding.

P0 exposes four tools: list_hosts, run_command, read_file, and get_metrics (with interactive command approval arriving later in 2.1.1). One rule in docs/20-mcp-server.md is non-negotiable: no ssh_raw escape hatch. Give an agent an unrestricted tool with simpler arguments, and it will pick that path every time, rendering classification and blocklists meaningless.

Gap 1: ../../etc/shadow Bypassed the Sensitive-Path Guard

read_file originally relied on CommandClassifier.classify("cat \(probe)", rules:). During review, feeding it ../../etc/shadow came back classified as readOnly and passed straight through.

The mismatch came from how each side treats relative paths:

  • An SFTP server resolves relative paths against $HOME, so ../../etc/shadow lands directly on /etc/shadow.
  • CommandClassifier’s sensitive-path regex required /etc/shadow to follow line start, whitespace, quotes, or =. In ../../etc/shadow, it follows .—no match. The same trick bypassed /etc/passwd, /etc/sudoers, and ../../etc/ssh/ssh_host_ed25519_key (whose _key suffix also missed \.key).

Path normalization (MCPRemotePath.normalize) could not save it either: normalizing a relative path has to preserve leading .. segments or else it alters the meaning of the path.

The fix in Sources/MCPKit/MCPTextLimits.swift and Apps/Shared/MCP/MCPToolRunner.swift enforces a strict order: MCPRemotePath.isAbsolute(_:) check first (must start with /), then normalize(_:), then CommandClassifier. MCPReadFileGuardTests.testRelativePathsBypassTheClassifierAndMustBeRejectedUpfront locks down both halves—asserting that the classifier alone misses ../../etc/shadow and that the upfront guard rejects it.

Gap 2: Two Windows Spawned Two Servers, Leaving an Unstoppable Listener

In ShellbyApp.swift, .task { await mcp.startIfEnabled() } sat on WindowGroup content, meaning it ran once per open window.

MCPService.start() previously guarded only with guard !isRunning else { return } (checking .running). Because port binding is asynchronous, a second window opened while the first was still in .starting slipped right past:

  1. Two MCPHTTPServer instances bound and started.
  2. The second call overwrote self.http, stranding the reference to the first listener.
  3. Toggling MCP off, resetting the token, or calling stop() only stopped the second instance.

Even after turning “External Agent” off in Settings, an orphaned read-only listener with the active token stayed alive until process exit. Updating start() to block both .starting and .running closed the race, and hooking NSApplication.willTerminateNotification to shutdownOnTerminate() ensured clean shutdown on quit.

Gap 3: SecRandomCopyBytes Falling Back to UInt8.random

When SecRandomCopyBytes returned anything other than errSecSuccess, MCPToken.generate() in Sources/MCPKit/MCPHTTPServer.swift quietly fell back to (0..<32).map { _ in UInt8.random(in: .min ... .max) }.

Swift’s standard library RNG only promises “secure whenever possible,” not a hard CSPRNG guarantee. Silent fallback was the worst possible failure mode: the server started normally, Settings displayed a normal-looking base64url token, and that token was saved to the Keychain for long-term reuse.

Commit a44221e removed the fallback and made generate() throw MCPToken.GenerationFailed(status:). Failing loudly is far better than persisting a predictable credential. Alongside that, currentToken() stopped treating Keychain read errors as “missing” (which used to overwrite working tokens during transient Keychain hiccups), and write failures now flip tokenIsEphemeral = true so MCPSettingsView warns that the token will rotate on restart.

The Resource Leak: 11 read_file Calls Exhausted MaxSessions

To avoid reconnecting on every call, MCPToolRunner reuses existing SSH connections. However, read_file opened a fresh channel via ssh.openSFTP() on every read and never closed it.

Channel budgets belong to the TCP connection—OpenSSH defaults to MaxSessions 10. By the 11th read_file call on a reused session, SFTP failed permanently and took the user’s own terminal tabs and port forwards on that same host down with it.

We added close() to SSHCore.SFTPClient, wired try? await sftp.close() in CitadelSFTPClient, and wrapped read_file with defer { Task { await sftp.close() } }.

Other Hardening from the Same Pass

The same review also replaced withTaskGroup timeouts in MCPToolRunner with a RaceGate continuation pattern (since CitadelSSHClient.execute ignores cancellation and would stall the group), changed the 64 KB output limit from per-stream to a shared budget (reserving up to 1/4 for stderr first so errors are not crowded out by stdout), redacted commands in the 500-entry audit log, and forced en_US_POSIX on audit export dates.

When opening a local surface to external AI tools, the real vulnerabilities rarely sit in the JSON-RPC parser—they hide in path-resolution baselines, multi-window lifecycles, silent RNG fallbacks, and shared session budgets.

✦

Comments

  • Loading…

Comments are reviewed before publishing; email is visible only to me.