Skip to content

fix(windows): scan ports natively instead of encoded PowerShell - #17861

Merged
OrcaWin merged 11 commits into
mainfrom
OrcaWin/win-edr-port-scan-native
Sep 6, 2026
Merged

OrcaWin merged 11 commits into
mainfrom
OrcaWin/win-edr-port-scan-native

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 1, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​405 $\color{#cf222e}{\Huge{\mathbf{−}}}$​60 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​345
Prod 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​284 $\color{#cf222e}{\Huge{\mathbf{−}}}$​65 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​219

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 Bypass beside -EncodedCommand <base64> is the most heavily flagged shape a PowerShell command line can have. (VS Code / Cursor / Antigravity spawn powershell.exe constantly and are not flagged — they use -Command.)
  • The decoded payload enumerated listening ports with their owning processes, which is network discovery (MITRE T1049).

Before / after command lines

Before (primary path, ran on every scan):

powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand JABFAHIAcgBvAHIAQQBjAHQAaQBvAG4AUAByAGUAZgBlAHIAZQBuAGMAZQAg...

with netstat.exe -ano -p tcp only on failure.

After (primary path):

C:\Windows\System32\netstat.exe -ano

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):

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -NonInteractive -Command "$ErrorActionPreference = 'Stop'; Get-NetTCPConnection -State Listen | ForEach-Object { ... }"

Both flagged tokens are gone: no -ExecutionPolicy Bypass, no -EncodedCommand. The script is passed as a single argv element through runProcess (never shell: true), so nothing re-parses it.

-ExecutionPolicy Bypass was deleted rather than downgraded because it was never doing anything. Execution policy gates script files, not -Command. Verified on Windows 11:

powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Restricted -Command "Write-Output 'COMMAND-RAN'"
→ COMMAND-RAN

while -File against an unsigned local .ps1 under the same policy fails with SecurityError ... running scripts is disabled on this system.

Fallback chain

  1. netstat.exe -ano → host / port / pid.
  2. readWindowsProcessTable() → pid → name. Native Toolhelp32 snapshot; on a relay host with no addon this falls through to the existing Get-CimInstance scan, which is already a sanctioned -Command line 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).
  3. PowerShell 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.exe then pwsh.exe.
  4. Empty result.

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

LISTENING is not a string in netstat.exe. It lives in %SystemRoot%\System32\<locale>\netstat.exe.mui alongside ESTABLISHED, TIME_WAIT and the column headers, and MUI selection follows the UI language — so the pinned-locale env in relay-command-env.ts, which exists for exactly this machine-parsing reason, cannot reach it. On a German host the row is TCP 0.0.0.0:135 0.0.0.0:0 ABHÖREN 1116 and 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:

TCP state census: LISTENING 47, ESTABLISHED 49, CLOSE_WAIT 29, TIME_WAIT 213
non-LISTENING rows with a zero peer: 0
LISTENING rows without a zero peer: 0
english rows: 47   localized rows: 47   sets identical: true

(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: BOUND and CLOSED print 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 BOUND or CLOSED socket 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 a BOUND row into the localized capture:

english rows: 47   localized rows: 47   sets identical: true
localized+BOUND rows: 47
phantom 65001 published: false
still identical to english: true

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/CLOSED sockets, 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

createOutputSink discards overflow silently and ProcessResult carries 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 of TIME_WAIT entries would therefore lose every [::] listener silently — the exact loss class dropping -p tcp exists to prevent, and one the zero-listeners guard cannot catch because the IPv4 head still parses.

readWindowsNetstatPorts now refuses a read that reached the cap and falls through instead. A truncated flag on createOutputSink/ProcessResult would be cleaner and would benefit every maxOutputBytes caller; 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 tcp was 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 -ano also prints UDP and non-listening rows — the parser filters those.

Process names keep their old spelling. The process table reports sshd.exe; the retired Get-Process payload reported sshd. Names are published with the .exe stripped, so normalizeWindowsDetectedPorts' 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. scanWindowsListeningPorts runs only in the detached relay daemon: relay.ts returns early for --connect and --orca-cli, so PortScanHandler is reachable 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, the file the documented diagnostics tail reads. Confirmed by installing the real rotation over a temp path and reading the file back:

relay.log captured the port-scan line: true
2026-09-01T07:37:01.026Z [ports] netstat unusable on this host (exited 0 but no listening row parsed); falling back to PowerShell

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-file rotates stdout only, so the file stderr can land in is unrotated.

It goes through relayLogLine, not console.warn. Both land on stderr, but relayLogLine is 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 on process.stderr to pin the stream and the timestamp, rather than asserting that something was merely called.

Ratchets shrink. Both spawns now go through runProcess, so src/relay/windows-port-scan.ts leaves the child_process import allowlist and the windowsHide allowlist.

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.ts marks it optional: 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 sshd filtered):

OLD_POWERSHELL           46 rows
NEW_NETSTAT_PLUS_TABLE   49 rows
only in OLD: []
only in NEW: ["0.0.0.0:445:4:System","0.0.0.0:5357:4:System","0.0.0.0:7680:5236:svchost"]

Nothing is lost. The three extras are dual-stack sockets that netstat reports on both families while Get-NetTCPConnection -State Listen reports only the :: entry — confirmed directly:

LocalAddress LocalPort OwningProcess
::                7680          5236
::                5357             4
::                 445             4

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.ts covers 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 .exe spelling, the fallback's argv asserted to contain neither -ExecutionPolicy nor -EncodedCommand, the powershell → pwsh walk, netstat timeout fall-through, and abort short-circuit — plus, for the two review findings:

  • a German fixture (ABHÖREN / HERGESTELLT) that must parse to the same listeners;
  • a BOUND fixture proving the shape test does not engage on a host whose state word parsed, and a localized BOUND fixture — 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);
  • a tie fixture pinning the degrade-to-shape-alone behaviour when no state dominates;
  • a truncated fixture (output at the 4 MiB cap) that must fall through rather than publish its parseable IPv4 head;
  • an abort-during-scan case asserting the shared process table is never touched.

src/relay/windows-port-scan.win32.test.ts runs 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.

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-apps

greptile-apps Bot commented Sep 1, 2026

Copy link
Copy Markdown

Greptile Summary

The 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.

  • Makes netstat.exe -ano the primary listener source and includes both address families.
  • Enriches listener PIDs through the shared Windows process table while preserving optional-name behavior.
  • Adds mocked and Windows-host tests and removes obsolete child-process allowlist entries.

Confidence Score: 4/5

The 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

Important Files Changed

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]
Loading

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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Dual-stack rows exhaust cap

When a Windows host has more than roughly 25 dual-stack listeners, the new primary scan retains separate IPv4 and IPv6 rows before applying the 50-row cap, causing higher-numbered development listeners to disappear from the detected-port list.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Truncated scans look complete

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — one minor suggestion inline.

Reviewed changes

  • Native netstat port scan — scanWindowsListeningPorts now runs netstat.exe -ano as the primary reader instead of an encoded PowerShell payload, dropping -p tcp so IPv6 ([::]) listeners are no longer hidden.
  • Process-name enrichment off the shared table — attachWindowsProcessNames fills PID → name from readWindowsProcessTable() and strips the .exe suffix to preserve the wire spelling clients already render.
  • De-escalated PowerShell fallback — the retired Get-NetTCPConnection script survives only as a last resort, now passed via -Command (no -ExecutionPolicy Bypass, no -EncodedCommand) through runProcess.
  • 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.ts leaves the child_process import and windowsHide allowlists now that both spawns go through runProcess.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Comment thread src/relay/windows-port-scan.ts Resolved
Orca Worker added 4 commits September 1, 2026 00:30
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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Locale-independent state parsing — parseWindowsNetstatOutput keeps the English LISTENING fast 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 so BOUND/CLOSED transients 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 from relay.log.
  • Abort short-circuit — attachWindowsProcessNames takes the caller's signal and skips the shared process-table read once the scan is cancelled.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Failure-direction documentation — readDominantZeroPeerState now 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.

Pullfrog  | View workflow run | Using 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Wired the real-host win32 suite into CI — src/relay/windows-port-scan.win32.test.ts is now listed in the package_windows "Test Windows-specific boundaries" step (so it actually executes on windows-2022) and in WINDOWS_PACKAGE_TESTS (so edits to that file re-trigger the job, since test files otherwise fall outside isProductBundlePath). The package (windows) job passed with this suite included.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Orca Worker added 2 commits September 5, 2026 17:53
…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.
@coderabbitai

coderabbitai Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 8f49d528-722b-4e78-96c1-7d937aa96331

📥 Commits

Reviewing files that changed from the base of the PR and between 87287e0 and 6f74df8.

📒 Files selected for processing (1)
  • src/relay/windows-port-scan.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/relay/windows-port-scan.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

The Windows port scanner now runs netstat.exe -ano through runProcess before using PowerShell fallback. It parses localized output by socket shape, caps captured output, supports cancellation, attaches process names from the shared process table, and reports native-path failures. Tests cover fallback, filtering, diagnostics, and parsing. Windows-only integration tests now run in package validation. Child-process boundary counts reflect the migration.

Merge Risk: 🔵 Low · up to 6f74d

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning 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… 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 Checkl…
Docstring Coverage ⚠️ Warning Docstring coverage is 57.89% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 19 functions across 7 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: replacing encoded PowerShell port scanning with native Windows scanning.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

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.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 736276da-fba5-4a3b-9da2-b5f09fb0f37e

📥 Commits

Reviewing files that changed from the base of the PR and between b6ca8da and 24cb788.

📒 Files selected for processing (9)
  • .github/workflows/pr.yml
  • config/scripts/pr-code-change-scope.mjs
  • src/relay/windows-port-scan.test.ts
  • src/relay/windows-port-scan.ts
  • src/relay/windows-port-scan.win32.test.ts
  • src/shared/child-process/__fixtures__/child-process-import-allowlist.txt
  • src/shared/child-process/__fixtures__/windows-console-visibility-allowlist.txt
  • src/shared/child-process/child-process-import-boundary.test.ts
  • src/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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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/shared

Repository: 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.ts

Repository: 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)
  }))
}
JS

Repository: 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.

Orca Worker added 3 commits September 5, 2026 18:35
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.
@OrcaWin
OrcaWin merged commit 975bbde into main Sep 6, 2026
31 checks passed
OrcaWin added a commit that referenced this pull request Sep 6, 2026
…took (#19009)

#17861 and #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>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant