Skip to content

fix(windows): copy the daemon host exe verbatim instead of renaming it (MDE T1036) - #17865

Merged
OrcaWin merged 8 commits into
mainfrom
OrcaWin/win-edr-daemon-host-materialization
Sep 6, 2026
Merged

OrcaWin merged 8 commits into
mainfrom
OrcaWin/win-edr-daemon-host-materialization

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 1, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​49 $\color{#cf222e}{\Huge{\mathbf{−}}}$​17 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​32
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​198 $\color{#cf222e}{\Huge{\mathbf{−}}}$​27 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​171

Stacked on #17856 (OrcaWin/win-edr-posture-docs). This branch is rebased onto it and the base is set to that branch; review only the two commits on top. Merge #17856 first, then this.

The MDE finding

Microsoft Defender for Endpoint flagged orca-terminal-daemon.exe in incidents C, D, E and F (same PID). Root cause 1 in the report is that the daemon relocation reads as masquerading, and it is the base multiplier on every other flagged action: each one is attributed to a low-reputation binary running from %LOCALAPPDATA% under a name that does not match its origin.

The old comment said it plainly:

// Copy of Orca.exe renamed to a distinct image name so the NSIS updater's `taskkill /IM Orca.exe` can't match it.
const DAEMON_HOST_EXE_NAME = 'orca-terminal-daemon.exe'

The behavioural signature: a process copies its own image into a user-writable directory under a different name, specifically so a kill-by-image-name cannot match it, then runs detached and survives the installer. MITRE T1036 (Masquerading) plus defence evasion. The reporter's comparison across VS Code, Cursor, Antigravity IDE and T3 Code found no fork that does this.

Signing is not the issue — a byte-for-byte copy of a signed PE retains its Authenticode signature, and the report confirms the file showed Valid CN=SignPath Foundation. The problem is the runtime behaviour, and specifically the name mismatch.

Key finding: the rename was never what made the daemon survive

In the pinned [email protected], FIND_PROCESS / KILL_PROCESS in templates/nsis/include/allowOnlyOneInstallerInstance.nsh have two branches:

Branch Condition Selector
Primary powershell.exe runs, Get-CimInstance resolves, and Get-ExecutionPolicy -Scope Process is not Restricted Get-CimInstance Win32_Process where $_.Path.StartsWith('$INSTDIR', 'CurrentCultureIgnoreCase') — path-scoped
Fallback otherwise per-user: taskkill /F /IM "<AppName>.exe" /FI "PID ne $pid" /FI "USERNAME eq %USERNAME%"; per-machine: the same without the username filter — image-name-scoped

The probe reads the process scope, not the effective policy, and Group Policy writes MachinePolicy/UserPolicy — so a GPO-managed host whose effective policy is Restricted still exits 0 and takes the primary branch. (Reviewer-verified: on such a host the shipped probe exits 0; a probe rewritten to test effective policy exits 1.) The fallback is reached only when powershell.exe is absent, Get-CimInstance does not resolve, PowerShell is blocked outright (WDAC/AppLocker, Server Core), or an inherited PSExecutionPolicyPreference=Restricted is in the environment.

So on essentially every machine the updater's kill sweep matches on image path. The default per-user install is %LOCALAPPDATA%\Programs\Orca; the daemon host is %LOCALAPPDATA%\Orca\daemon-host — not a prefix, so it is out of range whatever the file is called. File deletion is not the killer either: Windows will not delete a running image, so RMDir /r "$INSTDIR" cannot end the daemon on its own.

Survival is a property of the path. The premise in the old comment was already false for the primary code path.

Options evaluated, with measurements

Measured on this machine (Electron 43.4.1, installed 1.4.193 build):

  • Orca.exe — 235,555,328 bytes (224.6 MiB)
  • icudtl.dat 10.4 MiB, v8_context_snapshot.bin 0.71 MiB, snapshot_blob.bin 0.35 MiB
  • Materialized tree at %LOCALAPPDATA%\Orca\daemon-host\1.4.193-adhoc.* — 246 MB (the source comment's "~260MB" checks out)

(A) Move materialization into the NSIS installer — rejected

Writing 246 MB at install time doubles the install footprint and lengthens the window in which the app is down during a silent update (electron-updater runs the same NSIS installer). Two harder problems:

  • Per-machine install (INSTALL_MODE_PER_ALL_USERS) runs elevated as the installing admin, so $LOCALAPPDATA is the wrong user's. Every other user on that machine still needs the runtime path.
  • Therefore the runtime self-copy has to stay in the product as the fallback, so the behaviour MDE flags is only made rarer, not removed.

Partial signal reduction, large cost, and the riskiest change of the three.

(B) Ship a distinct signed orca-terminal-daemon.exe in the installer — rejected

A second 224.6 MiB PE. electron-builder's NSIS uses solid LZMA with a 64 MB dictionary, so a copy 224 MB downstream does not dedupe — the compressed installer grows by roughly a whole compressed Electron binary, paid by every user on every update download.

It also does not remove the runtime copy: the helper still has to reach %LOCALAPPDATA% to escape the sweep, it is just copied verbatim once there. So it buys exactly the same signal reduction as (C) at a large and permanent download cost. Strictly dominated.

(C) Stop the name from being a taskkill dodge — shipped

The customCheckAppRunning variant (force the path-scoped kill on both branches) was rejected — but not for size. It is ~6 lines (!include "getProcessInfo.nsh", Var pid, and a macro pinning IsPowerShellAvailable, reusing upstream's dialog, retry loop and elevated handling wholesale). It is wrong because forcing the PowerShell branch on a host where PowerShell is genuinely absent makes FIND_PROCESS and KILL_PROCESS silently no-op, so the installer proceeds with the real app still running and its files in use — worse than the cold restore it would prevent. Not worth doing ever, not merely not now.

What shipped: DAEMON_HOST_EXE_NAME is gone; the host exe name is derived from process.execPath.

const daemonHostExeName = (execPath: string): string => winPath.basename(execPath)

The relocated image is a byte-for-byte, name-included copy. No image-name mismatch, no taskkill dodge. Nothing else about relocation changes — same path, same marker, same atomic staging/publish, same prune veto, same fail-open.

What this actually buys — calibrated

Two things bound the win, and both belong in the record:

  • The strongest T1036 indicator is a PE-resource-vs-disk-name mismatch, and it was never firing. The reviewer checked the real installed binary: OriginalFilename is empty (only InternalName = Orca), so there was no embedded name for orca-terminal-daemon.exe to contradict.
  • What remains — a signed app copying its own ~225 MB image into user-writable %LOCALAPPDATA% and running it detached under ELECTRON_RUN_AS_NODE=1 — is still execution from a non-standard user-writable location, which maps to T1036.005 and is a standard heuristic on its own.

Expect the score to drop. Do not expect all six incidents to clear. This removes the literal indicator and the incriminating source comment; it does not stop the process being scored.

Behaviour changes and new failure modes

  1. Fallback branch, cold restore. On a host that takes the taskkill /IM branch, the daemon is now killed with the app and terminals cold-restore on relaunch. That is the documented pre-relocation outcome and a first-class harness profile (--expect cold-restore), not a break. Relocation is fail-open end to end anyway.
  2. New update-abort path (fallback branch only). The daemon now matches FIND_PROCESS under the app's image name, so it enters the retry loop at allowOnlyOneInstallerInstance.nsh:136-141. If the taskkill there fails to end it (an elevated or otherwise unkillable host), the loop reaches MessageBox … /SD IDCANCEL and Quits, aborting a silent update. Under the old distinct name the daemon was invisible to that loop. Low probability — fallback branch and an unkillable daemon — but a real new path, documented.
  3. No silent terminal loss on the primary branch. CHECK_APP_RUNNING runs twice per update (the new installer, plus the old uninstaller via un.onInit's silent path, which does run under ONE_CLICK); both are path-scoped.

What else is in the diff

  • config/nsis/daemon-host-uninstall.nsh — the macro no longer has a distinct image name to hunt for, so it kills the app's own image name plus the legacy orca-terminal-daemon.exe, each scoped with /FI "USERNAME eq $1" where $1 comes from NSIS's own ReadEnvStr USERNAME. That matches upstream's per-user KILL_PROCESS so an elevated machine-wide uninstall cannot reach another logged-on user's session, without the two cmd.exe spawns an earlier revision used just to expand %USERNAME% — adding scored cmd.exe /c behaviour in a PR about reducing it would have been an odd note to end on.
    • Verified on Windows 11 that the generated line does the job: a copy of cmd.exe running as orca-nonexistent-probe.exe (pid 34244) was terminated by taskkill /F /IM "orca-nonexistent-probe.exe" /FI "USERNAME eq <user>" — SUCCESS, exit 0, process gone.
    • Guarded on an empty USERNAME, because that case fails silently: taskkill rejects an empty filter value outright (ERROR: The search filter cannot be recognized) and kills nothing, leaving exactly the orphaned daemon the macro exists to reap. * is rejected as a filter value too, so there is no branchless spelling. With no USERNAME to scope by it kills unfiltered, as the macro did before the filter existed. USERNAME is set in every session an uninstaller runs in, so this is a backstop, not the expected path.
    • Stack balance: three pushes, two nsExec pops, three restores. The ${isUpdated} guard is untouched. A path-scoped PowerShell kill was drafted and dropped — spawning powershell.exe from an installer to hunt processes by path cuts against the point of this PR.
  • src/main/daemon/daemon-host-relocation.ts — a comment on the rmSync(dest) before publish: Windows refuses to delete a running image, so a live daemon already hosted in this version's dir (same-version reinstall, or a dev channel reusing a version) throws and materialization fails open to the install-dir host.
  • docs/reference/windows-daemon-host-relocation.md (new) — survival contract, the two-branch kill table, rejected options with these numbers, the new abort path, the calibrated residual, and the invariants (name derived from execPath; daemon identified by PID + command line, never image name). Linked from AGENTS.md, allowlisted in .gitignore.
  • docs/reference/windows-edr-posture.md (docs(windows): document the EDR signal surface #17856's doc) — it documents the rename as a live finding and goes stale the moment this lands, which git would not flag as a conflict. Reconciled to describe the rename as historical-to-these-incidents, cross-referenced to the new doc, with the OriginalFilename and T1036.005 calibration added. The remediation table's "Copying our own image under a different name" row read as outstanding work when this PR is what completes it, so it now points at the relocation doc. Content-only edit — markdown in docs/reference/ is not oxfmt-formatted as a matter of practice (all 24 existing files there fail oxfmt --check, and no CI job gates markdown formatting: pr.yml runs oxlint only). I ran the formatter over it by reflex, saw ~100 lines of whole-file churn, and reverted it — the diff stays at 23/10 and the file stays consistent with all 24 of its neighbours.
  • Comments in tests/tools/win-crash-survival-e2e/ that named the old exe.

De-risking evidence

  • tests/tools/win-update-e2e/daemon-processes.mjs:41-52 finds the daemon by command line (daemon-entry.js), never by exe name — deliberately, with a comment anticipating "a relocated Phase 1 host may run from a differently-named copied binary". That header comment is stale on base and becomes correct again with this change.
  • Nothing in src/ matches the daemon by image name; every taskkill in src/ is PID-scoped (/pid … /t /f). Daemon identity is PID + command line + PID-file records.
  • The original spike (tests/tools/daemon-relocation-spike/) used HOST_EXE = 'Orca.exe' — a verbatim-named copy is the configuration originally proven to boot as a run-as-node host.
  • Version dirs isolate old and new names, so an old-named surviving daemon still pins its own dir against the prune and the uninstall macro still reaps both names.
  • A new unit test locks the invariant in both directions: the copy is byte-identical with the same basename, and a differently-named app exe (Orca Nightly.exe) is followed rather than replaced by a fixed name.

Verification

Check Result
node config/scripts/run-typecheck-projects-in-parallel.mjs (pnpm tc) pass
vitest run src/main/daemon/daemon-host-relocation.test.ts 24 passed, 1 skipped (skip is pre-existing)
vitest run src/main/daemon/ 1592 passed, 11 failed in 6 files
oxlint on changed files (incl. --report-unused-disable-directives-severity warn) clean
oxfmt --check on changed code files clean (windows-edr-posture.md deliberately left unformatted, matching every doc in that directory)
node config/scripts/check-max-lines-ratchet.mjs pass

The 11 failures are pre-existing and environmental: all six files are node-pty/PTY-spawn tests, and the same 11 fail identically on the base commit f088872554 in this worktree (visible as Cannot read properties of undefined (reading 'onData') — node-pty's native binding absent). pnpm install's native rebuild fails here with MSB3491 on @vscode/windows-process-tree (MAX_PATH — the agent worktree path is too long for MSBuild), which takes node-pty's rebuild down with it. None of those tests import daemon-host-relocation. pnpm tc and pnpm test were run via their underlying scripts for the same reason (pnpm re-runs the failing postinstall).

daemon-host-relocation.ts sits at 299/300 counted lines. No max-lines disable and no baseline bump; the one-line arrow keeps it under. Splitting a 299-line file to buy two lines would be worse, so the next edit there should be a deliberate follow-up.

E2E that MUST pass before merge

No unit test can prove terminal survival. All four are workflow_dispatch, so they need a manual dispatch against this branch:

  1. .github/workflows/win-update-survival-e2e.yml with expect: survival — the primary proof. Builds an installer from this branch and updates it over itself. This is the one that would catch a mistake in the naming change.
  2. .github/workflows/win-crash-survival-e2e.yml with expect: survival — daemon survives a main-process crash.
  3. .github/workflows/windows-terminal-restart-e2e.yml (accepts a ref input).
  4. .github/workflows/win-update-e2e.yml — release-tag to release-tag, useful for confirming an old-name daemon and a new-name daemon coexist across the version boundary.

The NSIS macro edit is only exercised by a real uninstall, which no workflow covers; smoke-test it by hand (install → open a terminal → uninstall → confirm no surviving daemon and no %LOCALAPPDATA%\Orca\daemon-host tree).

Risks for a reviewer

  • The fallback-branch trade is deliberate. Cold restore instead of survival on hosts without usable PowerShell. Given the reviewer's finding that GPO-managed hosts take the primary branch, that population is small — but it is not empty (WDAC/AppLocker).
  • Version-dir coexistence. Old builds materialize daemon-host/<old>/orca-terminal-daemon.exe; new builds materialize daemon-host/<new>/Orca.exe. Separate version dirs, no migration.
  • NSIS is compile-time-checked only. A syntax error fails packaging; the runtime path is uninstall-only.
  • Doc claims are version-pinned. The kill-branch table describes [email protected]; re-read allowOnlyOneInstallerInstance.nsh on an electron-builder bump.
  • Cross-PR content coupling. The edit to windows-edr-posture.md will conflict textually if docs(windows): document the EDR signal surface #17856 revises that section before merging.

File overlap

  • docs(windows): document the EDR signal surface #17856 (OrcaWin/win-edr-posture-docs) — resolved by rebasing onto it, as instructed. .gitignore: both allowlist lines kept, sorted windows-daemon-host-relocation.md → windows-edr-posture.md → windows-process-enumeration.md. AGENTS.md: both bullets kept in the existing Cross-Platform Support list, relocation bullet before the EDR-signal one, no new section. Plus the content reconciliation of their doc described above.
  • Uninstaller-signing work — no overlap. This PR touches config/nsis/daemon-host-uninstall.nsh only; it does not touch config/electron-builder.config.cjs (the nsis.include path is unchanged) or .github/workflows/release-cut.yml.

Orca Worker added 2 commits September 1, 2026 00:00
Six Microsoft Defender for Endpoint incidents fired against Orca 1.4.192 in
eight days on one enterprise Windows 11 / Intune tenant. All six were
behavioural process-tree scoring, not signature hits; two escalated to
multi-stage incidents mapped to ATT&CK Execution and Collection.

Add a reference doc mapping each attack-technique-shaped behaviour to the code
that produces it and to why it exists: the renamed daemon image (T1036), the
per-process PEB read, encoded policy-bypassed PowerShell (T1049), caret-escaped
cmd.exe lines, and computer-use screen capture plus runtime-compiled MSIL
(T1113). Records that signing is not the gate -- reputation is signer plus
hash-keyed prevalence -- and carries the two evidence gaps the report noted.

Adds an engineer checklist, deployment guidance for admins (AV path exclusions
do not suppress EDR behavioural alerts; an MDE alert suppression rule does), and
an explicit pre-deployment warning about computer use.
Review corrections to the EDR posture doc.

The "encoded, policy-bypassing PowerShell" list conflated three different
shapes and was incomplete. Split it into the three tiers an EDR actually scores
differently -- bypass plus encoding, encoding alone, and bypass alone -- and add
the sites it missed, including windows-mobile-firewall.ts, which encodes a
script and launches it elevated through Start-Process -Verb RunAs. system-fonts.ts
(-Command) and desktop-script-provider-bridge.ts (-File) were listed as encoded
and are not. Notes that a raw grep under-reports, because the hook sites reach
-EncodedCommand through wrapWindowsPowerShellEncodedCommand.

Attribute the in-payload Set-ExecutionPolicy move to #16576 rather than to
#16003's measurement, which keyed on -WindowStyle Hidden + -EncodedCommand, and
record that the launcher's own tradeoff is unverified on a real box.

Admin guidance was missing two ways a suppression rule pinned to one full path
misses real activity: the .staging-<hex> sibling that exists mid-update, which
is when the update-cluster incidents fire, and the userData fallback when
LOCALAPPDATA is unset.

Also: state the measurement conditions on the process-table timings, note that
Hermes has surface even though we have no telemetry for it, note that the
uninstaller names are electron-builder-generated and in no repo file, drop a
volatile line count, and mark the per-operation computer-use shape as being
addressed by an unmerged change. Drops the duplicated AGENTS.md section, keeping
the indexed bullet.

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

Important

No code defects found — the name derivation, NSIS macro, docs, and tests all check out — but this PR changes terminal-survival behavior on Windows and its only real proof has not run on this branch yet. Hold merge until the packaged survival E2E passes (details below).

Reviewed changes

  • Daemon host exe copied verbatim — DAEMON_HOST_EXE_NAME is replaced by daemonHostExeName(execPath) (winPath.basename), so the relocated image is a byte-for-byte, name-included copy of the signed app exe. Survival is a property of the path, not the name.
  • NSIS uninstall macro — now kills the app's own image name (which reaches the relocated daemon) plus the legacy orca-terminal-daemon.exe, with balanced Push $0 / Pop $0 stack discipline.
  • Docs — new docs/reference/windows-daemon-host-relocation.md allowlisted in .gitignore and linked from AGENTS.md.
  • Tests — existing assertions updated to Orca.exe; two new tests pin the verbatim-copy (same name, same bytes) and dev-channel-rename invariants.

⚠️ Survival proof is still outstanding

I verified the load-bearing claims against the pinned [email protected]: allowOnlyOneInstallerInstance.nsh does have the path-scoped PowerShell primary branch and the taskkill /IM fallback, and ${APP_EXECUTABLE_FILENAME} is defined as "${PRODUCT_FILENAME}.exe". I also confirmed nothing in src/ identifies the daemon by image name (identity is PID + command line, daemon-entry.js), and the new tests would fail if the rename were reintroduced. What remains unproven is the runtime behavior itself — none of the four workflow_dispatch harnesses has a passing run on this branch yet, and a mistake in the name derivation would only surface as terminals dying across an update.

Technical details
# Merge gate: packaged survival E2E

## Required outcome
- `win-update-survival-e2e.yml` with `expect: survival` — the primary proof; this is the one that catches a mistake in the naming change.
- `win-crash-survival-e2e.yml` with `expect: survival` — daemon survives a main-process crash.
- `windows-terminal-restart-e2e.yml` — terminal restart behavior.
- `win-update-e2e.yml` — old-name daemon and new-name daemon coexist across the version boundary.
- Manual uninstall smoke test: install → open a terminal → uninstall → no surviving daemon and no `%LOCALAPPDATA%\Orca\daemon-host` tree (the NSIS edit is exercised only by a real uninstall; no workflow covers it).

## Why this blocks
The fallback-branch trade (cold-restore on no-PowerShell hosts) is deliberate and documented, and the primary branch is provably unaffected. But the unit tests can only pin the copy-plan invariants, not survival — so the packaged harnesses are the only evidence that the change actually preserves live terminals.

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

@OrcaWin
OrcaWin force-pushed the OrcaWin/win-edr-daemon-host-materialization branch 2 times, most recently from 0bbaa34 to fb3d93e Compare September 1, 2026 07:45
@OrcaWin
OrcaWin changed the base branch from main to OrcaWin/win-edr-posture-docs September 1, 2026 07:46
@OrcaWin
OrcaWin force-pushed the OrcaWin/win-edr-daemon-host-materialization branch from fb3d93e to 642de5e Compare September 1, 2026 07:48

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

Important

The two follow-up commits are clean — I found no new code defects in the user-scoped uninstall kill or the doc corrections. The standing merge gate is unchanged: none of the four packaged survival E2E harnesses has a passing run on this branch yet, so this should still not merge until win-update-survival-e2e with expect: survival and the manual uninstall smoke test pass.

Reviewed changes

  • Scoped the uninstall taskkill to the current user — ReadEnvStr USERNAME now feeds a /FI "USERNAME eq $1" filter on both kills, replacing the intermediate cmd.exe /c expansion. An empty USERNAME falls back to an unfiltered kill, and the stack stays balanced (three pushes, two nsExec pops, three restores).
  • Corrected the relocation doc — the fallback-branch table now matches IS_POWERSHELL_AVAILABLE exactly (process-scope Get-ExecutionPolicy, Get-CimInstance resolution), and the GPO/effective-policy gap, the empty-OriginalFilename calibration, and the customCheckAppRunning rejection rationale are all stated accurately.
  • Reconciled windows-edr-posture.md — the rename is now documented as historical and the remediation-table row points at the relocation doc instead of reading as outstanding work.

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

Orca Worker added 4 commits September 1, 2026 18:17
…tion

Three claims in this doc became false once the rest of the Windows EDR set
landed, and two told engineers the opposite of what the release does.

The process-table section still described one shared snapshot taken with
`Memory | CommandLine | CreationTime`, argued that splitting the cache per
field set "would restore exactly the fan-out it exists to prevent", and
concluded the shape was unfixable because "the information is only in the
PEB". The split shipped (identity opens no handle at all), `Memory` is
retired, and the command line now comes from the kernel through
`ProcessCommandLineInformation` -- `ReadProcessMemory` is absent from the
compiled addon and a ratchet asserts it against the import table. An engineer
reading the old text would have concluded both fixes were dead ends.

The PowerShell site inventories were stale in three of four lists: the port
scan went native, every `-ExecutionPolicy Bypass` + `-EncodedCommand` pair
was dropped as a measured no-op, and of the unencoded-bypass list only
`wsl-cli-scripts.ts` survives. Regenerated against the merged tree, including
the sites that reach the flag through `wrapWindowsPowerShellEncodedCommand`
and never spell it, which a raw `rg` misses.

Incident-evidence sections are left alone: they record what the tenant observed
on 1.4.192, not what the code does now.
Microsoft Defender for Endpoint flagged `orca-terminal-daemon.exe` as MITRE
T1036 (Masquerading): Orca copied its own `Orca.exe` into %LOCALAPPDATA% under a
different name, specifically so the NSIS updater's `taskkill /IM Orca.exe` could
not match, then ran it detached. Because that process is what every other flagged
action was attributed to, the name mismatch acted as a reputation multiplier on
unrelated findings.

The rename was never what made the daemon survive. In app-builder-lib 26.15.3 the
installer's FIND_PROCESS/KILL_PROCESS select processes whose image path is under
$INSTDIR; `taskkill /IM` is only the fallback for hosts where PowerShell is
missing or blocked. Survival is a property of the path, and
%LOCALAPPDATA%\Orca\daemon-host is outside $INSTDIR whatever the file is called.

Derive the host exe name from process.execPath so the copy is byte-for-byte,
name included — it keeps its Authenticode signature and carries no renamed-image
signal. On the no-PowerShell fallback the daemon is now killed with the app and
terminals cold-restore, which is the documented pre-relocation outcome the update
harness already asserts, not a regression.

The uninstall macro no longer needs a distinct name to find the daemon; it kills
the app's own image name (plus the legacy name, for hosts left by older builds).

Adds docs/reference/windows-daemon-host-relocation.md with the survival contract,
the rejected alternatives and their measured costs, and the invariants to keep.
Scope the uninstall taskkill to the current user with `/FI "USERNAME eq
%USERNAME%"` via cmd.exe, matching upstream's per-user KILL_PROCESS — without it
an elevated machine-wide uninstall reaches another logged-on user's session, so
the "no collateral" claim in the comment was overstated.

Comment the rmSync-before-publish: Windows refuses to delete a running image, so
a live daemon already hosted in this version's dir (same-version reinstall, or a
dev channel reusing a version) throws and materialization fails open.

Doc corrections:
- The fallback selector is the full per-user `taskkill /F /IM "<app>.exe" /FI
  "PID ne $pid" /FI "USERNAME eq %USERNAME%"`, not a bare `taskkill /IM`.
- The probe reads `Get-ExecutionPolicy -Scope Process`, not the effective policy,
  and GPO writes MachinePolicy/UserPolicy — so GPO-managed hosts take the primary
  path-scoped branch. Narrow the fallback triggers accordingly.
- Drop the Authenticode sentence: the old name was equally byte-identical and
  equally signed, so a filename has no bearing on signature validity.
- Name the new update-abort path: the daemon now matches FIND_PROCESS, so on the
  fallback branch an unkillable host reaches the retry loop's MessageBox /SD
  IDCANCEL and Quits, aborting a silent update.
- Correct the customCheckAppRunning rejection. It is ~6 lines, not a rewrite; it
  is wrong because forcing the PowerShell branch where PowerShell is absent makes
  FIND/KILL silently no-op and leaves the real app running with files in use.
- Bound the win honestly: OriginalFilename is empty on the shipped binary, so the
  strongest T1036 indicator never fired, and the residual copy-and-run-detached
  shape still maps to T1036.005.

Reconcile docs/reference/windows-edr-posture.md, which documents the rename as a
live finding and would otherwise contradict this change. Content-only edit:
markdown under docs/reference/ is not oxfmt-formatted as a matter of practice and
nothing in CI gates it, so the file is left consistent with its neighbours.
The uninstall macro routed both taskkills through `"$SYSDIR\cmd.exe" /C` purely
so `%USERNAME%` would expand — two extra interpreter spawns on the uninstall
path, in a change whose whole point is not adding scored behaviour, and the
exact `cmd.exe /c` shape the new AGENTS.md EDR bullet warns about. NSIS reads
the variable itself with ReadEnvStr, so the spawns buy nothing.

Verified on Windows 11 that the generated command line does what the filter is
there for: a copy of cmd.exe running as orca-nonexistent-probe.exe (pid 34244)
was terminated by `taskkill /F /IM "orca-nonexistent-probe.exe" /FI "USERNAME eq
<user>"` — SUCCESS, exit 0, process gone.

Guarded on an empty USERNAME because the degenerate case is silent: taskkill
rejects an empty filter value outright ("The search filter cannot be
recognized") and kills nothing, which would leave exactly the orphaned daemon
this macro exists to reap. `*` is rejected as a filter value too, so there is no
branchless spelling. With no USERNAME to scope by it kills unfiltered, as the
macro did before the filter was added. Stack stays balanced: three pushes, two
nsExec pops, three restores.

Also strike the last stale row in windows-edr-posture.md's remediation table.
"Copying our own image under a different name" read as outstanding work; it is
done by this change, so the row now points at the relocation doc. Same class of
staleness as the section reconciled in the previous commit, and git would not
have flagged it either.
@OrcaWin
OrcaWin force-pushed the OrcaWin/win-edr-daemon-host-materialization branch from 281038f to 1e126f8 Compare September 2, 2026 01:50
@OrcaWin
OrcaWin changed the base branch from OrcaWin/win-edr-posture-docs to main September 6, 2026 01:42
Orca Worker added 2 commits September 5, 2026 18:47
…n-host-materialization

Conflicts, and how each was resolved:

- config/nsis/daemon-host-uninstall.nsh: main deleted it (#17906 consolidated
  every NSIS hook into config/nsis/orca-installer-hooks.nsh, because
  electron-builder accepts exactly one `nsis.include`). Took the deletion; the
  rewritten uninstall macro is ported into the hooks file in the next commit.
  Doc references repointed at the surviving file.

- docs/reference/windows-edr-posture.md: add/add. This branch's base (#17856)
  squash-landed on main, and #18151 then corrected several process-table claims
  there. Took main's corrected text and re-applied only this branch's
  daemon-host edits (the rename removal, T1036.005, the spawn-tree line, the
  checklist row).

- .gitignore, AGENTS.md: kept both sides' added lines.
… include

The uninstall macro this branch rewrote lived in config/nsis/daemon-host-uninstall.nsh,
which main no longer includes: #17906 consolidated every Windows installer hook into
config/nsis/orca-installer-hooks.nsh because electron-builder accepts exactly one
`nsis.include`. Merged as-is, the rewritten macro would have been dead code while the
shipped uninstaller kept running main's stale sweep — `taskkill /F /IM
orca-terminal-daemon.exe`, which matches nothing now that the relocated host is a
verbatim Orca.exe copy. The RMDir that follows then cannot delete the running image, so
a live orphaned daemon and its ~224 MB tree would survive every uninstall.

Ported into the live include: the ${APP_EXECUTABLE_FILENAME} kill, the USERNAME filter
that keeps an elevated machine-wide uninstall out of another logged-on user's session,
and the register save/restore around both. The legacy orca-terminal-daemon.exe kill
stays so hosts left by older builds are still reaped.

The ratchet that was meant to catch exactly this pinned only the legacy image name,
which main's stale macro already satisfied, so it passed both ways. It now asserts the
app-exe kill and the USERNAME filter, against comment-stripped script — the prose above
the macro names both image names, so a toContain over the raw file proves nothing.
@coderabbitai

coderabbitai Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The daemon host relocation now copies the application executable verbatim and resolves the relocated path from its source basename. Tests cover byte identity, alternate executable names, and idempotent materialization. Genuine uninstall now terminates both the application executable and the legacy daemon name, with per-user filtering when available. Windows reference, EDR, contributor, and crash-survival documentation was updated.

Merge Risk: 🔵 Low · up to 4ecb5

The relocated daemon now keeps the application executable name, but its idempotence coverage does not verify that existing destination contents survive a second materialization. This is a bounded regression-risk gap that should be addressed before relying on the test.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides detailed change rationale, risks, testing results, and required manual E2E steps, but it does not follow the repository template. It omits the required Linked Issue, Visual Pr… Restructure the description using the repository template. Add a linked issue in the Fixes # field, provide visual proof or write N/A with a reason, complete the Testing checkboxes, AI Disclosure, Review, Agent skill upstream boundary, …
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely identifies the primary Windows daemon-host change and its MDE T1036 motivation.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 3 functions across 5 files. (6 skipped: 6 …
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 provides detailed change rationale, risks, testing results, and required manual E2E steps, but it does not follow the repository template. It omits the required Linked Issue, Visual Proof or an explicit N/A explanation, checklist sections, Agent skill upstream boundary, and other required headings.

Resolution

Restructure the description using the repository template. Add a linked issue in the Fixes # field, provide visual proof or write N/A with a reason, complete the Testing checkboxes, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections, and retain the existing technical details under ELI5, What Changed, and Why.

  • Fix all pre-merge checks with AI
✨ Finishing Touches
📝 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: 0005eef8-43de-432c-b632-aba5bd29bc7d

📥 Commits

Reviewing files that changed from the base of the PR and between e7dc9b6 and 4ecb599.

📒 Files selected for processing (11)
  • .gitignore
  • AGENTS.md
  • config/nsis/orca-installer-hooks.nsh
  • config/scripts/electron-builder-markdown-associations.test.mjs
  • docs/reference/windows-daemon-host-relocation.md
  • docs/reference/windows-edr-posture.md
  • src/main/daemon/daemon-host-relocation.test.ts
  • src/main/daemon/daemon-host-relocation.ts
  • tests/tools/win-crash-survival-e2e/README.md
  • tests/tools/win-crash-survival-e2e/crash-step.mjs
  • tests/tools/win-crash-survival-e2e/run.mjs

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

// A recopy would rm the dest; a sentinel inside it must survive the 2nd call.
const sentinel = join(dest, 'sentinel.txt')
writeFileSync(sentinel, 'keep')
const result = materializeRelocatedDaemonHost()

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

Assert that the sentinel survives the second materialization.

Line 234 can rematerialize the destination and still return Orca.exe. The test then passes even if the second call deletes sentinel.txt. Add an assertion for the sentinel after this call.

Proposed fix
     const result = materializeRelocatedDaemonHost()
+    expect(existsSync(sentinel)).toBe(true)
     expect(result?.execPath).toBe(join(dest, 'Orca.exe'))
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const result = materializeRelocatedDaemonHost()
const result = materializeRelocatedDaemonHost()
expect(existsSync(sentinel)).toBe(true)

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

Important

The port is correct — and it fixes a latent bug — but it makes the uninstall sweep live for the first time, and the only real exercise of that sweep (the manual uninstall smoke test) still has no recorded run.

Reviewed changes

  • Ported the daemon-host uninstall sweep into the live NSIS include — the sweep previously lived in a standalone config/nsis/daemon-host-uninstall.nsh that electron-builder.config.cjs never referenced (nsis.include has always pointed at orca-installer-hooks.nsh), so it was dead code and an uninstall would have orphaned the daemon. It now runs from customUnInstall in the merged include, preserving the ${isUpdated} guard, the user-scoped filter, and the balanced stack.
  • Added a regression test — keeps the daemon-host uninstall sweep across the include rename asserts, against comment-stripped script, the app-exe and legacy taskkills, the /FI "USERNAME eq filter, and the ${ifNot} ${isUpdated} guard.
  • Updated doc and comment references — windows-daemon-host-relocation.md, windows-edr-posture.md, and the daemon-host-relocation.ts marker comment now name orca-installer-hooks.nsh; no stale daemon-host-uninstall reference remains except the test's explanatory comment.

⚠️ The uninstall sweep is now live — prove it before merging

Before this commit the daemon cleanup was in a file that never shipped, so no prior revision of this PR could actually reap an orphaned daemon. This is the first revision where that code runs, and its only real exercise is the manual smoke test (install → open a terminal → uninstall → confirm no surviving daemon and no %LOCALAPPDATA%\Orca\daemon-host tree), which no workflow covers and which has no recorded run on this branch. The survival E2E gate is unaffected by this delta — the copy plan did not change — but the smoke test is now load-bearing rather than a formality.

Technical details
# Uninstall sweep now live — run the manual smoke test

## Affected sites
- config/nsis/orca-installer-hooks.nsh:66-96 — `customUnInstall` daemon sweep, previously dead code in `daemon-host-uninstall.nsh`

## Required outcome
- Manual uninstall smoke test on Windows: install → open a terminal → uninstall → confirm no surviving daemon and no `%LOCALAPPDATA%\Orca\daemon-host` tree.

## Open questions for the human (optional)
- None — the code is correct; the outstanding item is evidence, not a fix.

ℹ️ Nitpicks

  • The PR body still describes config/nsis/daemon-host-uninstall.nsh in the "What else is in the diff" and "File overlap" sections, but that file no longer exists after the rename to orca-installer-hooks.nsh.

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

@OrcaWin
OrcaWin merged commit fba90e0 into main Sep 6, 2026
32 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…t (MDE T1036) (stablyai#17865)

* docs(windows): document the EDR signal surface

Six Microsoft Defender for Endpoint incidents fired against Orca 1.4.192 in
eight days on one enterprise Windows 11 / Intune tenant. All six were
behavioural process-tree scoring, not signature hits; two escalated to
multi-stage incidents mapped to ATT&CK Execution and Collection.

Add a reference doc mapping each attack-technique-shaped behaviour to the code
that produces it and to why it exists: the renamed daemon image (T1036), the
per-process PEB read, encoded policy-bypassed PowerShell (T1049), caret-escaped
cmd.exe lines, and computer-use screen capture plus runtime-compiled MSIL
(T1113). Records that signing is not the gate -- reputation is signer plus
hash-keyed prevalence -- and carries the two evidence gaps the report noted.

Adds an engineer checklist, deployment guidance for admins (AV path exclusions
do not suppress EDR behavioural alerts; an MDE alert suppression rule does), and
an explicit pre-deployment warning about computer use.

* docs(windows): correct the PowerShell flag inventory and admin paths

Review corrections to the EDR posture doc.

The "encoded, policy-bypassing PowerShell" list conflated three different
shapes and was incomplete. Split it into the three tiers an EDR actually scores
differently -- bypass plus encoding, encoding alone, and bypass alone -- and add
the sites it missed, including windows-mobile-firewall.ts, which encodes a
script and launches it elevated through Start-Process -Verb RunAs. system-fonts.ts
(-Command) and desktop-script-provider-bridge.ts (-File) were listed as encoded
and are not. Notes that a raw grep under-reports, because the hook sites reach
-EncodedCommand through wrapWindowsPowerShellEncodedCommand.

Attribute the in-payload Set-ExecutionPolicy move to stablyai#16576 rather than to
stablyai#16003's measurement, which keyed on -WindowStyle Hidden + -EncodedCommand, and
record that the launcher's own tradeoff is unverified on a real box.

Admin guidance was missing two ways a suppression rule pinned to one full path
misses real activity: the .staging-<hex> sibling that exists mid-update, which
is when the update-cluster incidents fire, and the userData fallback when
LOCALAPPDATA is unset.

Also: state the measurement conditions on the process-table timings, note that
Hermes has surface even though we have no telemetry for it, note that the
uninstaller names are electron-builder-generated and in no repo file, drop a
volatile line count, and mark the per-operation computer-use shape as being
addressed by an unmerged change. Drops the duplicated AGENTS.md section, keeping
the indexed bullet.

* docs(windows): reconcile the EDR posture doc with the shipped remediation

Three claims in this doc became false once the rest of the Windows EDR set
landed, and two told engineers the opposite of what the release does.

The process-table section still described one shared snapshot taken with
`Memory | CommandLine | CreationTime`, argued that splitting the cache per
field set "would restore exactly the fan-out it exists to prevent", and
concluded the shape was unfixable because "the information is only in the
PEB". The split shipped (identity opens no handle at all), `Memory` is
retired, and the command line now comes from the kernel through
`ProcessCommandLineInformation` -- `ReadProcessMemory` is absent from the
compiled addon and a ratchet asserts it against the import table. An engineer
reading the old text would have concluded both fixes were dead ends.

The PowerShell site inventories were stale in three of four lists: the port
scan went native, every `-ExecutionPolicy Bypass` + `-EncodedCommand` pair
was dropped as a measured no-op, and of the unencoded-bypass list only
`wsl-cli-scripts.ts` survives. Regenerated against the merged tree, including
the sites that reach the flag through `wrapWindowsPowerShellEncodedCommand`
and never spell it, which a raw `rg` misses.

Incident-evidence sections are left alone: they record what the tenant observed
on 1.4.192, not what the code does now.

* fix(windows): copy the daemon host exe verbatim instead of renaming it

Microsoft Defender for Endpoint flagged `orca-terminal-daemon.exe` as MITRE
T1036 (Masquerading): Orca copied its own `Orca.exe` into %LOCALAPPDATA% under a
different name, specifically so the NSIS updater's `taskkill /IM Orca.exe` could
not match, then ran it detached. Because that process is what every other flagged
action was attributed to, the name mismatch acted as a reputation multiplier on
unrelated findings.

The rename was never what made the daemon survive. In app-builder-lib 26.15.3 the
installer's FIND_PROCESS/KILL_PROCESS select processes whose image path is under
$INSTDIR; `taskkill /IM` is only the fallback for hosts where PowerShell is
missing or blocked. Survival is a property of the path, and
%LOCALAPPDATA%\Orca\daemon-host is outside $INSTDIR whatever the file is called.

Derive the host exe name from process.execPath so the copy is byte-for-byte,
name included — it keeps its Authenticode signature and carries no renamed-image
signal. On the no-PowerShell fallback the daemon is now killed with the app and
terminals cold-restore, which is the documented pre-relocation outcome the update
harness already asserts, not a regression.

The uninstall macro no longer needs a distinct name to find the daemon; it kills
the app's own image name (plus the legacy name, for hosts left by older builds).

Adds docs/reference/windows-daemon-host-relocation.md with the survival contract,
the rejected alternatives and their measured costs, and the invariants to keep.

* fix(windows): apply daemon-host relocation review corrections

Scope the uninstall taskkill to the current user with `/FI "USERNAME eq
%USERNAME%"` via cmd.exe, matching upstream's per-user KILL_PROCESS — without it
an elevated machine-wide uninstall reaches another logged-on user's session, so
the "no collateral" claim in the comment was overstated.

Comment the rmSync-before-publish: Windows refuses to delete a running image, so
a live daemon already hosted in this version's dir (same-version reinstall, or a
dev channel reusing a version) throws and materialization fails open.

Doc corrections:
- The fallback selector is the full per-user `taskkill /F /IM "<app>.exe" /FI
  "PID ne $pid" /FI "USERNAME eq %USERNAME%"`, not a bare `taskkill /IM`.
- The probe reads `Get-ExecutionPolicy -Scope Process`, not the effective policy,
  and GPO writes MachinePolicy/UserPolicy — so GPO-managed hosts take the primary
  path-scoped branch. Narrow the fallback triggers accordingly.
- Drop the Authenticode sentence: the old name was equally byte-identical and
  equally signed, so a filename has no bearing on signature validity.
- Name the new update-abort path: the daemon now matches FIND_PROCESS, so on the
  fallback branch an unkillable host reaches the retry loop's MessageBox /SD
  IDCANCEL and Quits, aborting a silent update.
- Correct the customCheckAppRunning rejection. It is ~6 lines, not a rewrite; it
  is wrong because forcing the PowerShell branch where PowerShell is absent makes
  FIND/KILL silently no-op and leaves the real app running with files in use.
- Bound the win honestly: OriginalFilename is empty on the shipped binary, so the
  strongest T1036 indicator never fired, and the residual copy-and-run-detached
  shape still maps to T1036.005.

Reconcile docs/reference/windows-edr-posture.md, which documents the rename as a
live finding and would otherwise contradict this change. Content-only edit:
markdown under docs/reference/ is not oxfmt-formatted as a matter of practice and
nothing in CI gates it, so the file is left consistent with its neighbours.

* fix(windows): expand USERNAME in NSIS instead of spawning cmd.exe

The uninstall macro routed both taskkills through `"$SYSDIR\cmd.exe" /C` purely
so `%USERNAME%` would expand — two extra interpreter spawns on the uninstall
path, in a change whose whole point is not adding scored behaviour, and the
exact `cmd.exe /c` shape the new AGENTS.md EDR bullet warns about. NSIS reads
the variable itself with ReadEnvStr, so the spawns buy nothing.

Verified on Windows 11 that the generated command line does what the filter is
there for: a copy of cmd.exe running as orca-nonexistent-probe.exe (pid 34244)
was terminated by `taskkill /F /IM "orca-nonexistent-probe.exe" /FI "USERNAME eq
<user>"` — SUCCESS, exit 0, process gone.

Guarded on an empty USERNAME because the degenerate case is silent: taskkill
rejects an empty filter value outright ("The search filter cannot be
recognized") and kills nothing, which would leave exactly the orphaned daemon
this macro exists to reap. `*` is rejected as a filter value too, so there is no
branchless spelling. With no USERNAME to scope by it kills unfiltered, as the
macro did before the filter was added. Stack stays balanced: three pushes, two
nsExec pops, three restores.

Also strike the last stale row in windows-edr-posture.md's remediation table.
"Copying our own image under a different name" read as outstanding work; it is
done by this change, so the row now points at the relocation doc. Same class of
staleness as the section reconciled in the previous commit, and git would not
have flagged it either.

* fix(windows): port the daemon-host uninstall sweep into the live NSIS include

The uninstall macro this branch rewrote lived in config/nsis/daemon-host-uninstall.nsh,
which main no longer includes: stablyai#17906 consolidated every Windows installer hook into
config/nsis/orca-installer-hooks.nsh because electron-builder accepts exactly one
`nsis.include`. Merged as-is, the rewritten macro would have been dead code while the
shipped uninstaller kept running main's stale sweep — `taskkill /F /IM
orca-terminal-daemon.exe`, which matches nothing now that the relocated host is a
verbatim Orca.exe copy. The RMDir that follows then cannot delete the running image, so
a live orphaned daemon and its ~224 MB tree would survive every uninstall.

Ported into the live include: the ${APP_EXECUTABLE_FILENAME} kill, the USERNAME filter
that keeps an elevated machine-wide uninstall out of another logged-on user's session,
and the register save/restore around both. The legacy orca-terminal-daemon.exe kill
stays so hosts left by older builds are still reaped.

The ratchet that was meant to catch exactly this pinned only the legacy image name,
which main's stale macro already satisfied, so it passed both ways. It now asserts the
app-exe kill and the USERNAME filter, against comment-stripped script — the prose above
the macro names both image names, so a toContain over the raw file proves nothing.

---------

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