Repository navigation
fix(windows): scan ports natively instead of encoded PowerShell - #17861
Conversation
Microsoft Defender for Endpoint scored the relay's Windows port scan as suspicious PowerShell plus network discovery (T1049). The command line was `-ExecutionPolicy Bypass -EncodedCommand <base64>` around a Get-NetTCPConnection/Get-Process join -- base64 next to a policy override is the highest-weighted token pair on a PowerShell command line, and netstat only ever ran as its fallback. Invert the chain. `netstat.exe -ano` is now the primary reader and the owning process name comes from the shared native process table, which exists to keep PID lookups off PowerShell. The payload survives only as a last resort, and without the override: execution policy gates script files, never `-Command`, so nothing needed it (verified: `-ExecutionPolicy Restricted -Command` runs). Drop `-p tcp` while inverting: on Windows that protocol name means IPv4 only, so as a primary reader it would have hidden every `[::]` listener the payload used to report. Names arrive as `sshd.exe` from the table and are published as `sshd`, keeping the sshd filter and old clients' rendering intact. Routes both spawns through runProcess, removing the file from the child_process and windowsHide ratchets.
Greptile SummaryThe PR replaces the routine encoded PowerShell port scan on Windows with native netstat collection and shared process-table enrichment, retaining a de-escalated PowerShell fallback.
Confidence Score: 4/5The PR should not merge until dual-stack listener rows stop exhausting the 50-entry discovery budget; silent output truncation is an additional non-blocking robustness issue. The netstat-first path preserves both address families as separate rows before applying a fixed 50-row cap, which can hide valid higher-numbered listeners on ordinary multi-listener Windows hosts. Files Needing Attention: src/relay/windows-port-scan.ts
|
| Filename | Overview |
|---|---|
| src/relay/windows-port-scan.ts | Reorders Windows discovery around native netstat and shared process enrichment, but dual-stack rows consume the existing cap and bounded output can be accepted after silent truncation. |
| src/relay/windows-port-scan.test.ts | Thoroughly tests command ordering, fallback, abort, enrichment, and filtering, but does not cover the 50-row cap or output truncation. |
| src/relay/windows-port-scan.win32.test.ts | Adds valuable real-Windows coverage for both address families and executable fallback syntax, while using a host-sized result that does not stress result or output limits. |
| src/shared/child-process/fixtures/child-process-import-allowlist.txt | Correctly removes the scanner after migration away from direct child_process imports. |
| src/shared/child-process/fixtures/windows-console-visibility-allowlist.txt | Correctly removes the scanner now that process visibility is centralized through runProcess. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Poll Windows listening ports] --> B[Run netstat.exe -ano]
B --> C{Successful with parsed listeners?}
C -->|Yes| D[Read shared Windows process table]
D --> E[Attach optional process names]
E --> F[Normalize, filter, sort, cap]
C -->|No and not aborted| G[Run Windows PowerShell fallback]
G --> H{Successful?}
H -->|No| I[Try pwsh.exe]
H -->|Yes| F
I --> F
C -->|Aborted| J[Return empty result]
Reviews (1): Last reviewed commit: "fix(windows): scan ports natively instea..." | Re-trigger Greptile
| /** Rows, or null when netstat could not answer and the fallback should run. */ | ||
| async function readWindowsNetstatPorts(signal?: AbortSignal): Promise<DetectedPort[] | null> { | ||
| let stdout: string | ||
| try { |
There was a problem hiding this comment.
| const execFileAsync = promisify(execFile) | ||
| // Wide enough for `netstat -ano` on a busy host: it prints every connection, not | ||
| // just the listeners, and a truncated table silently drops the tail. | ||
| const WINDOWS_PORT_SCAN_MAX_OUTPUT_BYTES = 4 * 1024 * 1024 |
There was a problem hiding this comment.
If netstat.exe -ano produces more than 4 MiB, the bounded sink silently discards the tail while this path accepts the remaining prefix as successful, so later listeners are omitted without invoking the PowerShell fallback or reporting an incomplete scan.
Knowledge Base Used: Relay protocol and transport
There was a problem hiding this comment.
ℹ️ No critical issues — one minor suggestion inline.
Reviewed changes
- Native netstat port scan —
scanWindowsListeningPortsnow runsnetstat.exe -anoas the primary reader instead of an encoded PowerShell payload, dropping-p tcpso IPv6 ([::]) listeners are no longer hidden. - Process-name enrichment off the shared table —
attachWindowsProcessNamesfills PID → name fromreadWindowsProcessTable()and strips the.exesuffix to preserve the wire spelling clients already render. - De-escalated PowerShell fallback — the retired
Get-NetTCPConnectionscript survives only as a last resort, now passed via-Command(no-ExecutionPolicy Bypass, no-EncodedCommand) throughrunProcess. - Test coverage — the unit suite is rewritten around the new ordering, and a new win32-only test executes the fallback command line and asserts both address families against a real host.
- Ratchet allowlists —
windows-port-scan.tsleaves thechild_processimport andwindowsHideallowlists now that both spawns go throughrunProcess.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Review of the port-scan inversion found two ways the new primary path could be silently wrong, both of which would have kept the flagged PowerShell payload running on exactly the hosts this change targets. `LISTENING` is not in netstat.exe. It lives in System32\<locale>\netstat.exe.mui and MUI selection follows the UI language, so the pinned-locale env in relay-command-env.ts cannot reach it -- a German host prints `ABHOEREN` and the word test parsed zero rows. The zero-listeners guard then read that as a blocked reader and ran `Get-NetTCPConnection` every 12-30s forever, or returned nothing at all where PowerShell is also restricted. Keep the word as the fast path and, when it finds nothing over output that did contain TCP rows, re-read by shape: only a listening socket has no peer. Measured on this host across all four states present (LISTENING 47, ESTABLISHED 49, CLOSE_WAIT 29, TIME_WAIT 213): zero non-listening rows with a zero peer, zero listening rows without one, and the same 47 rows parse after substituting the German state words. Shape stays the fallback because `BOUND` also prints a zero peer. Truncation was invisible: createOutputSink discards overflow, ProcessResult carries no flag, so a capped read still exits 0 and its head still parses. netstat orders IPv4 TCP, then IPv6 TCP, then UDP, so a host with tens of thousands of TIME_WAIT rows would have lost every `[::]` listener -- the exact loss dropping `-p tcp` exists to prevent, and one the zero-listeners guard cannot see. Refuse the read instead. A `truncated` flag on the shared sink would be cleaner and is left as a follow-up rather than widened into this PR. Also: decline to wait on the shared process table once the request is aborted (it takes no signal and must not be cancelled for other callers); note the name lookup as best-effort, since a TTL-cached snapshot can hand a recycled PID its previous owner name; log once on either fall-through, because both are permanent and invisible when wrong; and drop a stderr assertion that any PowerShell autoload banner would redden. Correcting the cost claim in the previous commit: the aggregate win holds with the native addon (netstat 21ms vs the retired payload 860ms at 532 processes), not without it. The addon is optional, the snapshot TTL is 500ms and the scan cadence is 12-30s, so a relay with no active agent pane never warms its own cache and pays ~1.4s cold on the CIM path -- slower than what it replaced.
…stream Checked where this code actually runs before trusting the log. `console.warn` did reach a file, but relayLogLine is the right call and the reasoning is worth recording. `scanWindowsListeningPorts` runs only in the detached relay daemon: relay.ts returns early for --connect and --orca-cli, so PortScanHandler is reached only through runRelayDaemon, and both launchers start it detached with a log file (POSIX `> relay.log 2>&1`, Windows `1>relay.log 2>relay.err.log` via Win32_Process.Create). installRelayLogRotation then wraps both streams into relay.log, which is the file the documented diagnostics tail reads. Verified by installing the real rotation over a temp path and reading the file back. So the line surfaced -- but untimestamped, in a log whose format exists so reconnect flaps can be correlated with the events around them (#7773). relayLogLine is that format and the relay idiom in 41 other places, and "since when has this host been stuck on PowerShell" is most of what this line is for. The test spies on process.stderr to pin the stream and the ISO stamp rather than just asserting something was called, since a fall-through logged somewhere unread is the failure being guarded against. Also fixes a comment that ended its own block early: `relay-*/relay.log` in a doc comment contains `*/`.
…zed netstat Shape alone promoted any zero-peer TCP row, not just listeners. `BOUND` and `CLOSED` print a zero peer too, and on a localized host their state words are exactly as unreadable as the listening one -- so a German host with listeners plus one BOUND socket published a phantom listener. Reachable on an English host too: with zero listeners a lone BOUND row is promoted AND, because the result is then non-empty, it suppresses the blocked-reader fall-through. Group the zero-peer rows by state word and keep only the largest group. A transient BOUND or CLOSED socket cannot outnumber the listeners (51 against 0 on this host), so this removes the class rather than special-casing the words, which would just be the localization bug again. An exact tie keeps every tied group rather than guessing -- no worse than reading shape alone. Verified against real netstat output: injecting a BOUND row into the localized capture leaves the result identical to the English answer (47 rows, no phantom 65001). The new test has teeth -- reverting the grouping fails it and nothing else. Corrects two claims that were slightly wrong: the docblock said shape was the fallback because BOUND prints a zero peer, which described the hazard without saying it was unhandled; and a test comment said an English host "never sees a bound socket", true only when it has at least one readable LISTENING row. Also gates the fall-through log per reason instead of per module, so a host that parses nothing today and truncates tomorrow reports both faults. Same one-shot cost, and the vocabulary is two fixed strings so the set cannot grow. That guard matters more than it looks: --log-file rotates stdout only, so the file stderr can land in is unrotated.
…l in The docblock described the tie case and stopped there, which reads as a complete account of the limits when it is not: a majority rule inverts if the majority is wrong, and enough transient zero-peer sockets would publish the phantoms and drop the real listeners. Someone would reasonably have concluded the rule was safe in both directions. Trigger numbers and the repro stay in the PR discussion; the code only needs the reader to know the rule has a direction, and the hatch (defer to the PowerShell reader, which reads the state word instead of inferring it) since that is the part a future editor would otherwise re-derive.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Locale-independent state parsing —
parseWindowsNetstatOutputkeeps the EnglishLISTENINGfast path and, when the state word does not parse, re-reads by socket shape (zero foreign port), keeping only the dominant zero-peer state group soBOUND/CLOSEDtransients are not published as listeners. - Truncation refusal — a netstat read that reached the 4 MiB capture cap now falls through to PowerShell rather than publishing a parseable IPv4 head that would silently drop every
[::]listener. - Fall-through diagnostics — each fall-through reason logs once per host via
relayLogLine, so a host stuck on the PowerShell path is diagnosable fromrelay.log. - Abort short-circuit —
attachWindowsProcessNamestakes the caller's signal and skips the shared process-table read once the scan is cancelled.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Failure-direction documentation —
readDominantZeroPeerStatenow documents that its majority rule inverts when transient zero-peer sockets outnumber listeners (phantoms win, real listeners dropped), and records the escape hatch: return[]and defer to the PowerShell reader, which reads the state word instead of inferring it.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
The win32 suite only self-skips off Windows, so it passed vacuously in every lane. Register it the way the cmd-shim suite is registered.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Wired the real-host win32 suite into CI —
src/relay/windows-port-scan.win32.test.tsis now listed in thepackage_windows"Test Windows-specific boundaries" step (so it actually executes onwindows-2022) and inWINDOWS_PACKAGE_TESTS(so edits to that file re-trigger the job, since test files otherwise fall outsideisProductBundlePath). Thepackage (windows)job passed with this suite included.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…R took Migrating the port scan off `node:child_process` onto `runProcess` drops `src/relay/windows-port-scan.ts` from both allowlists, so both offender counts fall by one. Each ratchet pins the count from below as well as above, so a pin left above reality fails and re-opens room for the next direct import to land for free.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review. 📝 WalkthroughWalkthroughThe Windows port scanner now runs Merge Risk: 🔵 Low · up to Windows relay scanning now prefers netstat, but truncated native output may be treated as complete and omit active ports or processes. Resolve the truncation signal handling before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description gives extensive technical context, rationale, fallback behavior, performance details, and test coverage. However, it omits required template sections, including ELI5, What Changed, Why, an explicit Linked Issue with a Fixes reference, Visual Proof or N/A, Review, Agent skill upstream boundary, Notes, and Checklist confirmations. Resolution Add the required template sections. Provide an explicit linked issue using a Fixes # reference, add Visual Proof or state N/A with a reason if applicable, complete the Agent skill upstream boundary section, and complete the Notes and Checklist items.
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 736276da-fba5-4a3b-9da2-b5f09fb0f37e
📒 Files selected for processing (9)
.github/workflows/pr.ymlconfig/scripts/pr-code-change-scope.mjssrc/relay/windows-port-scan.test.tssrc/relay/windows-port-scan.tssrc/relay/windows-port-scan.win32.test.tssrc/shared/child-process/__fixtures__/child-process-import-allowlist.txtsrc/shared/child-process/__fixtures__/windows-console-visibility-allowlist.txtsrc/shared/child-process/child-process-import-boundary.test.tssrc/shared/child-process/windows-console-visibility.test.ts
💤 Files with no reviewable changes (2)
- src/shared/child-process/fixtures/windows-console-visibility-allowlist.txt
- src/shared/child-process/fixtures/child-process-import-allowlist.txt
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.
| // TCP, then IPv6 TCP, then UDP, so the rows lost first are exactly the | ||
| // `[::]` listeners that dropping `-p tcp` above exists to keep. Refuse the | ||
| // whole read rather than publish its head. | ||
| if (Buffer.byteLength(result.stdout) >= WINDOWS_PORT_SCAN_MAX_OUTPUT_BYTES) { |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
# Description: Determine whether a truncated output sink retains exactly maxOutputBytes.
fd -t f 'run-process' src/shared/child-process | xargs -r rg -n -C 20 'createOutputSink'
rg -n -C 20 --type=ts 'function createOutputSink' src/sharedRepository: stablyai/orca
Length of output: 8789
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- bounded-output-sink.ts ---'
cat -n src/shared/child-process/bounded-output-sink.ts
printf '%s\n' '--- run-process result construction ---'
rg -n -C 12 'outputTruncated|resolveFromClose|stdout:|stderr:' src/shared/child-process/run-process.ts src/shared/child-process/process-spec.ts
printf '%s\n' '--- windows-port-scan.ts ---'
cat -n src/relay/windows-port-scan.ts
printf '%s\n' '--- relevant tests ---'
sed -n '280,345p' src/relay/windows-port-scan.test.tsRepository: stablyai/orca
Length of output: 35322
🤖 get_repo_knowledge executed:
get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions
Length of output: 43546
🏁 Script executed:
node - <<'JS'
const cap = 8
const samples = [
Buffer.from('a'.repeat(cap) + 'x', 'utf8'),
Buffer.concat([Buffer.from('a'.repeat(cap - 3)), Buffer.from('€')]),
Buffer.concat([Buffer.from('a'.repeat(cap - 2)), Buffer.from('€')]),
Buffer.concat([Buffer.from('a'.repeat(cap - 1)), Buffer.from('😀')]),
Buffer.concat([Buffer.from('a'.repeat(cap - 3)), Buffer.from('😀')]),
]
for (const input of samples) {
const retained = input.subarray(0, cap)
const stdout = retained.toString('utf8')
console.log(JSON.stringify({
inputBytes: input.length,
retainedBytes: retained.length,
decodedByteLength: Buffer.byteLength(stdout),
stdoutTail: stdout.slice(-3)
}))
}
JSRepository: stablyai/orca
Length of output: 533
Use result.outputTruncated instead of the decoded-length check.
createOutputSink clips output to exactly maxOutputBytes, and runProcess reports truncation through result.outputTruncated. The current >= check treats complete output with exactly maxOutputBytes as truncated and incorrectly triggers the PowerShell fallback. Update the mock to set outputTruncated: true.
The scan starts no PowerShell of its own, but no released relay carries the optional `windows-process-tree.node` addon (only dev-channel-win-build.yml builds it), so the shared process-table read falls back to a CIM scan that forks one `powershell.exe`. The EDR win is the removal of the `-EncodedCommand` / `-ExecutionPolicy Bypass` shape, not the elimination of PowerShell. Comment-only.
…e's addon attachWindowsProcessNames reads only `name`, so it should move to `readWindowsProcessIdentityTable` once #17866 lands -- on that PR's detailed reader it would open per-process handles for a field it discards. The reader does not exist on this branch, so the call stays as-is with the follow-up recorded rather than pulling #17866 in. The process-table perf table's two Toolhelp32 rows assume the optional `windows-process-tree.node` addon. The desktop bundles it; no released relay does, so on an SSH host the CIM row is the operative number. Comment-only.
…allback No released relay carries the optional `windows-process-tree.node` addon -- release-cut.yml has zero references to it and only dev-channel-win-build.yml builds it -- so the PowerShell CIM scan is what every SSH host runs. The call-site docstring read as a conditional fallback standalone. Comment-only.
…lyai#17861) * fix(windows): scan ports natively instead of encoded PowerShell Microsoft Defender for Endpoint scored the relay's Windows port scan as suspicious PowerShell plus network discovery (T1049). The command line was `-ExecutionPolicy Bypass -EncodedCommand <base64>` around a Get-NetTCPConnection/Get-Process join -- base64 next to a policy override is the highest-weighted token pair on a PowerShell command line, and netstat only ever ran as its fallback. Invert the chain. `netstat.exe -ano` is now the primary reader and the owning process name comes from the shared native process table, which exists to keep PID lookups off PowerShell. The payload survives only as a last resort, and without the override: execution policy gates script files, never `-Command`, so nothing needed it (verified: `-ExecutionPolicy Restricted -Command` runs). Drop `-p tcp` while inverting: on Windows that protocol name means IPv4 only, so as a primary reader it would have hidden every `[::]` listener the payload used to report. Names arrive as `sshd.exe` from the table and are published as `sshd`, keeping the sshd filter and old clients' rendering intact. Routes both spawns through runProcess, removing the file from the child_process and windowsHide ratchets. * fix(windows): read netstat state by shape and refuse a truncated table Review of the port-scan inversion found two ways the new primary path could be silently wrong, both of which would have kept the flagged PowerShell payload running on exactly the hosts this change targets. `LISTENING` is not in netstat.exe. It lives in System32\<locale>\netstat.exe.mui and MUI selection follows the UI language, so the pinned-locale env in relay-command-env.ts cannot reach it -- a German host prints `ABHOEREN` and the word test parsed zero rows. The zero-listeners guard then read that as a blocked reader and ran `Get-NetTCPConnection` every 12-30s forever, or returned nothing at all where PowerShell is also restricted. Keep the word as the fast path and, when it finds nothing over output that did contain TCP rows, re-read by shape: only a listening socket has no peer. Measured on this host across all four states present (LISTENING 47, ESTABLISHED 49, CLOSE_WAIT 29, TIME_WAIT 213): zero non-listening rows with a zero peer, zero listening rows without one, and the same 47 rows parse after substituting the German state words. Shape stays the fallback because `BOUND` also prints a zero peer. Truncation was invisible: createOutputSink discards overflow, ProcessResult carries no flag, so a capped read still exits 0 and its head still parses. netstat orders IPv4 TCP, then IPv6 TCP, then UDP, so a host with tens of thousands of TIME_WAIT rows would have lost every `[::]` listener -- the exact loss dropping `-p tcp` exists to prevent, and one the zero-listeners guard cannot see. Refuse the read instead. A `truncated` flag on the shared sink would be cleaner and is left as a follow-up rather than widened into this PR. Also: decline to wait on the shared process table once the request is aborted (it takes no signal and must not be cancelled for other callers); note the name lookup as best-effort, since a TTL-cached snapshot can hand a recycled PID its previous owner name; log once on either fall-through, because both are permanent and invisible when wrong; and drop a stderr assertion that any PowerShell autoload banner would redden. Correcting the cost claim in the previous commit: the aggregate win holds with the native addon (netstat 21ms vs the retired payload 860ms at 532 processes), not without it. The addon is optional, the snapshot TTL is 500ms and the scan cadence is 12-30s, so a relay with no active agent pane never warms its own cache and pays ~1.4s cold on the CIM path -- slower than what it replaced. * fix(windows): log the port-scan fall-through on the relay diagnostic stream Checked where this code actually runs before trusting the log. `console.warn` did reach a file, but relayLogLine is the right call and the reasoning is worth recording. `scanWindowsListeningPorts` runs only in the detached relay daemon: relay.ts returns early for --connect and --orca-cli, so PortScanHandler is reached only through runRelayDaemon, and both launchers start it detached with a log file (POSIX `> relay.log 2>&1`, Windows `1>relay.log 2>relay.err.log` via Win32_Process.Create). installRelayLogRotation then wraps both streams into relay.log, which is the file the documented diagnostics tail reads. Verified by installing the real rotation over a temp path and reading the file back. So the line surfaced -- but untimestamped, in a log whose format exists so reconnect flaps can be correlated with the events around them (stablyai#7773). relayLogLine is that format and the relay idiom in 41 other places, and "since when has this host been stuck on PowerShell" is most of what this line is for. The test spies on process.stderr to pin the stream and the ISO stamp rather than just asserting something was called, since a fall-through logged somewhere unread is the failure being guarded against. Also fixes a comment that ended its own block early: `relay-*/relay.log` in a doc comment contains `*/`. * fix(windows): keep the dominant zero-peer state when reading a localized netstat Shape alone promoted any zero-peer TCP row, not just listeners. `BOUND` and `CLOSED` print a zero peer too, and on a localized host their state words are exactly as unreadable as the listening one -- so a German host with listeners plus one BOUND socket published a phantom listener. Reachable on an English host too: with zero listeners a lone BOUND row is promoted AND, because the result is then non-empty, it suppresses the blocked-reader fall-through. Group the zero-peer rows by state word and keep only the largest group. A transient BOUND or CLOSED socket cannot outnumber the listeners (51 against 0 on this host), so this removes the class rather than special-casing the words, which would just be the localization bug again. An exact tie keeps every tied group rather than guessing -- no worse than reading shape alone. Verified against real netstat output: injecting a BOUND row into the localized capture leaves the result identical to the English answer (47 rows, no phantom 65001). The new test has teeth -- reverting the grouping fails it and nothing else. Corrects two claims that were slightly wrong: the docblock said shape was the fallback because BOUND prints a zero peer, which described the hazard without saying it was unhandled; and a test comment said an English host "never sees a bound socket", true only when it has at least one readable LISTENING row. Also gates the fall-through log per reason instead of per module, so a host that parses nothing today and truncates tomorrow reports both faults. Same one-shot cost, and the vocabulary is two fixed strings so the set cannot grow. That guard matters more than it looks: --log-file rotates stdout only, so the file stderr can land in is unrotated. * docs(windows): note the direction the zero-peer majority rule can fail in The docblock described the tie case and stopped there, which reads as a complete account of the limits when it is not: a majority rule inverts if the majority is wrong, and enough transient zero-peer sockets would publish the phantoms and drop the real listeners. Someone would reasonably have concluded the rule was safe in both directions. Trigger numbers and the repro stay in the PR discussion; the code only needs the reader to know the rule has a direction, and the hatch (defer to the PowerShell reader, which reads the state word instead of inferring it) since that is the part a future editor would otherwise re-derive. * ci(windows): run the real-netstat port scan suite in CI The win32 suite only self-skips off Windows, so it passed vacuously in every lane. Register it the way the cmd-shim suite is registered. * test(windows): lower both child-process ratchets to the ground this PR took Migrating the port scan off `node:child_process` onto `runProcess` drops `src/relay/windows-port-scan.ts` from both allowlists, so both offender counts fall by one. Each ratchet pins the count from below as well as above, so a pin left above reality fails and re-opens room for the next direct import to land for free. * docs(windows): qualify the no-PowerShell claim on the netstat scan The scan starts no PowerShell of its own, but no released relay carries the optional `windows-process-tree.node` addon (only dev-channel-win-build.yml builds it), so the shared process-table read falls back to a CIM scan that forks one `powershell.exe`. The EDR win is the removal of the `-EncodedCommand` / `-ExecutionPolicy Bypass` shape, not the elimination of PowerShell. Comment-only. * docs(windows): record the identity-reader follow-up and the perf table's addon attachWindowsProcessNames reads only `name`, so it should move to `readWindowsProcessIdentityTable` once stablyai#17866 lands -- on that PR's detailed reader it would open per-process handles for a field it discards. The reader does not exist on this branch, so the call stays as-is with the follow-up recorded rather than pulling stablyai#17866 in. The process-table perf table's two Toolhelp32 rows assume the optional `windows-process-tree.node` addon. The desktop bundles it; no released relay does, so on an SSH host the CIM row is the operative number. Comment-only. * docs(windows): state the CIM scan as the relay's normal path, not a fallback No released relay carries the optional `windows-process-tree.node` addon -- release-cut.yml has zero references to it and only dev-channel-win-build.yml builds it -- so the PowerShell CIM scan is what every SSH host runs. The call-site docstring read as a conditional fallback standalone. Comment-only. --------- Co-authored-by: Orca Worker <orca-worker@localhost>
…took (stablyai#19009) stablyai#17861 and stablyai#17884 each migrated one file off node:child_process and each lowered the pin 158 -> 157 independently. Together they took two, so the true count is 156 and the two-sided assertion fails on main. Co-authored-by: Orca Worker <orca-worker@localhost>

MDE factor addressed
Root cause 3 of the Defender for Endpoint incident report — suspicious PowerShell commands — and the suspicious network activity factor it produced on incident C.
The relay's Windows port scan ran an encoded PowerShell payload first, on every port poll, for every connected workspace. Two things stacked:
-ExecutionPolicy Bypassbeside-EncodedCommand <base64>is the most heavily flagged shape a PowerShell command line can have. (VS Code / Cursor / Antigravity spawnpowershell.execonstantly and are not flagged — they use-Command.)Before / after command lines
Before (primary path, ran on every scan):
with
netstat.exe -ano -p tcponly on failure.After (primary path):
plus a
readWindowsProcessTable()call for PID→name — a Toolhelp32 snapshot behind a shared TTL cache, no child process at all.After (last-resort fallback only, if netstat cannot answer):
Both flagged tokens are gone: no
-ExecutionPolicy Bypass, no-EncodedCommand. The script is passed as a single argv element throughrunProcess(nevershell: true), so nothing re-parses it.-ExecutionPolicy Bypasswas deleted rather than downgraded because it was never doing anything. Execution policy gates script files, not-Command. Verified on Windows 11:while
-Fileagainst an unsigned local.ps1under the same policy fails withSecurityError ... running scripts is disabled on this system.Fallback chain
netstat.exe -ano→ host / port / pid.readWindowsProcessTable()→ pid → name. Native Toolhelp32 snapshot; on a relay host with no addon this falls through to the existingGet-CimInstancescan, which is already a sanctioned-Commandline and is shared and TTL-cached across every caller. If the table cannot be read at all, rows are published without names rather than forking a shell of our own (docs/reference/windows-process-enumeration.md).Get-NetTCPConnection, de-escalated as above, only when netstat exits non-zero, times out, fails to spawn, returns a truncated table, or parses to zero listeners.powershell.exethenpwsh.exe.An aborted signal short-circuits before step 3, and step 2 is skipped rather than awaited once the request is abandoned (the shared snapshot takes no signal and must not be cancelled for other callers).
Reading netstat's state column without depending on its language
LISTENINGis not a string innetstat.exe. It lives in%SystemRoot%\System32\<locale>\netstat.exe.muialongsideESTABLISHED,TIME_WAITand the column headers, and MUI selection follows the UI language — so the pinned-locale env inrelay-command-env.ts, which exists for exactly this machine-parsing reason, cannot reach it. On a German host the row isTCP 0.0.0.0:135 0.0.0.0:0 ABHÖREN 1116and a word test parses nothing.That mattered specifically because netstat is now the primary reader: zero parsed rows would trip the "blocked reader" guard, and the scan would run the T1049 command line every 12–30 s, permanently, on every non-English host — or return
[]where PowerShell is also restricted, despite netstat having answered perfectly.The state word is kept as the fast path. When it yields nothing over output that did contain TCP rows, the parser re-reads by shape: only a listening socket has no peer, so its foreign address is
0.0.0.0:0/[::]:0. Measured here across all four states present:(the localized figure is the same capture with the German state words substituted).
Shape stays the fallback rather than the primary test because the converse does not hold:
BOUNDandCLOSEDprint a zero peer too. On a localized host their words are exactly as unreadable as the listening one, so shape alone would publish a phantom listener — and on a host with zero real listeners it would also suppress the blocked-reader fall-through, because the result is then non-empty.So within the fallback, the zero-peer rows are grouped by state word and only the largest group is kept. A transient
BOUNDorCLOSEDsocket cannot outnumber the listeners (51 against 0 here), which removes the class rather than special-casing the words — special-casing would just be the localization bug again. An exact tie keeps every tied group rather than guessing, which is no worse than reading shape alone. Verified by injecting aBOUNDrow into the localized capture:Known limit of the grouping
Dominance is a majority rule, so it inverts if the majority is wrong. If a non-listening zero-peer state ever outnumbers the listeners on a localized host, the grouping publishes those phantoms and drops the real listeners — trading over-reporting for under-reporting, which is the worse direction. Forced in review with 2 listeners against 3
BOUND.Left as-is deliberately: triggering it needs somewhere north of 30-50 simultaneous
BOUND/CLOSEDsockets, against 47 listeners on an ordinary host and 0 transients observed at any point during this work. The escape hatch, if someone does hit it, is to treat the ambiguous case as unanswered — return[]from the shape pass so the scan falls through to the PowerShell reader, which can actually read the state word and does not have to infer it. That costs the EDR win on exactly those hosts, which is why it is not the default.Truncation now refuses rather than publishes a head
createOutputSinkdiscards overflow silently andProcessResultcarries no truncation field, so a capped read still exits 0 and its head still parses. At ~75 bytes/row a 4 MiB cap truncates around 56,000 connections, and netstat orders IPv4 TCP → IPv6 TCP → UDP with the first IPv6 row at ~84% of the stream. A proxy or relay host with tens of thousands ofTIME_WAITentries would therefore lose every[::]listener silently — the exact loss class dropping-p tcpexists to prevent, and one the zero-listeners guard cannot catch because the IPv4 head still parses.readWindowsNetstatPortsnow refuses a read that reached the cap and falls through instead. Atruncatedflag oncreateOutputSink/ProcessResultwould be cleaner and would benefit everymaxOutputBytescaller; it touches the shared spawn contract and several unrelated test literals, so it is left as a follow-up rather than widened into this PR.Behaviour notes for a reviewer
-p tcpwas dropped. On Windows that protocol name means TCP over IPv4 only. It was harmless when netstat was a rarely-reached fallback; as the primary reader it silently hid every[::]listener. Caught by running both paths side by side on a real box.netstat -anoalso prints UDP and non-listening rows — the parser filters those.Process names keep their old spelling. The process table reports
sshd.exe; the retiredGet-Processpayload reportedsshd. Names are published with the.exestripped, sonormalizeWindowsDetectedPorts'processName === 'sshd'filter still fires and clients render what they always did (docs/reference/remote-wire-compatibility.md).Name lookup is best-effort. The snapshot is shared and TTL-cached, so it can predate netstat and hand a recycled PID its previous owner's name. Only labels consume the field, and a fresh read would cost every other caller a scan, so this is commented rather than paid for.
Both fall-throughs log once per reason, on a stream that is actually read. A host stuck on the PowerShell path is otherwise undiagnosable, and both rules are permanent when they are wrong — so the log is only worth having if it surfaces.
Traced rather than assumed.
scanWindowsListeningPortsruns only in the detached relay daemon:relay.tsreturns early for--connectand--orca-cli, soPortScanHandleris reachable only throughrunRelayDaemon, and both launchers start it detached with a log file — POSIX> relay.log 2>&1, Windows1>relay.log 2>relay.err.logviaWin32_Process.Create.installRelayLogRotationthen wraps both streams intorelay.log, the file the documented diagnostics tail reads. Confirmed by installing the real rotation over a temp path and reading the file back:The guard is per reason rather than per module, so a host that parses nothing today and truncates tomorrow reports both faults instead of only the first. It matters more than it looks:
--log-filerotates stdout only, so the file stderr can land in is unrotated.It goes through
relayLogLine, notconsole.warn. Both land on stderr, butrelayLogLineis the relay's idiom in 41 other places and carries the ISO stamp the log format exists for — correlating events with the reconnect flaps around them (#7773). "Since when has this host been stuck on PowerShell" is most of what this line is for. The test spies onprocess.stderrto pin the stream and the timestamp, rather than asserting that something was merely called.Ratchets shrink. Both spawns now go through
runProcess, sosrc/relay/windows-port-scan.tsleaves thechild_processimport allowlist and thewindowsHideallowlist.Cost
With the native addon this is a large win: netstat 21 ms vs. the retired payload 860 ms at 532 processes.
Without the addon it is not.
relay-artifacts.tsmarks itoptional: true, the snapshot TTL is 500 ms and the port-scan cadence is 12–30 s, so the scan never warms its own cache — it can only ride the relay's foreground-process tracker (750 ms / 2 s per pane), and a relay with no active agent pane pays a cold CIM read (~1.4 s) on every scan, which is slower than the 860 ms it replaces. The security argument stands on its own there; the performance argument does not, and an earlier version of this description overstated it.Live verification (Windows 11, this box)
Old PowerShell path vs. new netstat + process-table path, run back to back, after the same normalization (port 22, relay self/parent pid, and
sshdfiltered):Nothing is lost. The three extras are dual-stack sockets that
netstatreports on both families whileGet-NetTCPConnection -State Listenreports only the::entry — confirmed directly:Names and both address families come through:
0.0.0.0:135 svchost,:::135 svchost,127.0.0.1:5174 node,fd7a:115c:a1e0::9633:ea76:52660 tailscaled. End-to-end latency 327–612 ms including the process-table read.Tests
src/relay/windows-port-scan.test.tscovers the new ordering (netstat-first with no PowerShell spawned), name enrichment off the native table, the no-binding path, the sshd/self-pid filters surviving the.exespelling, the fallback's argv asserted to contain neither-ExecutionPolicynor-EncodedCommand, thepowershell → pwshwalk, netstat timeout fall-through, and abort short-circuit — plus, for the two review findings:ABHÖREN/HERGESTELLT) that must parse to the same listeners;BOUNDfixture proving the shape test does not engage on a host whose state word parsed, and a localizedBOUNDfixture — the case with no coverage before — proving the dominant-state rule drops a phantom listener the shape test alone would publish (reverting the grouping fails this test and nothing else);src/relay/windows-port-scan.win32.test.tsruns against the real host: both address families come back with names, and it executes the fallback command line. That second assertion is not decoration — it caught a missing;between statements in the joined one-line script, a ParserError that would have left the fallback dead on the day it was needed and that no mocked test can see.