diff --git a/src/service/windows-guarded-manager.ts b/src/service/windows-guarded-manager.ts index b1a321118d5..8901c6764f3 100644 --- a/src/service/windows-guarded-manager.ts +++ b/src/service/windows-guarded-manager.ts @@ -120,7 +120,7 @@ export function windowsProcessList(): WindowsProcessEntry[] | null { try { // Share owner evidence, but do not add creation-time/terminate authority to this // inspection-only table. Part A still requires windowsProcessSnapshot's native overlay. - return parseWindowsProcessSnapshot(runPowerShell(windowsProcessSnapshotScript())) + return parseWindowsProcessSnapshot(runPowerShell(windowsProcessSnapshotScript(POWERSHELL_TIMEOUT_MS))) ?.map(({ pid, parentPid, name, commandLine, foreignOwner }) => ({ pid, parentPid, name, commandLine, foreignOwner })) ?? null; } catch { return null; diff --git a/src/service/windows-process-evidence.ts b/src/service/windows-process-evidence.ts index 30c5c456ed6..1a3dbf0ae34 100644 --- a/src/service/windows-process-evidence.ts +++ b/src/service/windows-process-evidence.ts @@ -53,6 +53,12 @@ export type WindowsStopProcessEntry = WindowsProcessEntry & { startTime: number const SNAPSHOT_MAX_BUFFER = 16 * 1024 * 1024; const SMALL_MAX_BUFFER = 64 * 1024; const NATIVE_CIM_TOLERANCE_MS = 1; +/** + * Owner reads stop being admitted this long before the snapshot's cap, counted from the + * helper's own process start. It covers one in-flight 1 s CIM call plus serialization and + * exit, so optional owner evidence cannot turn a readable table into a timed-out one. + */ +export const SNAPSHOT_OWNER_RESERVE_MS = 2_000; function trustedProgram(program: WindowsEvidenceCommand["program"]): string { if (program === "powershell") return resolveTrustedWindowsPowerShellExe(); @@ -93,11 +99,16 @@ function powershellArgs(script: string): string[] { /** * Owner enrichment admits at most 32 candidates within 1.5 s; individual CIM calls also * have a 1 s operation cap. Unqueried owners stay unknown and every process row survives. + * No owner read starts later than `timeoutMs - SNAPSHOT_OWNER_RESERVE_MS` after the helper + * process started: a cold PowerShell start and first CIM query can use most of the cap on + * a hosted runner, and the 1.5 s loop budget alone did not count that time. * Owner reads prioritize this home's complete launcher/script tokens before other possible * wrapper candidates. A fresh CIM read after GetOwnerSid binds that owner to the original * creation time; a reused PID cannot prove a foreign owner. */ -export function windowsProcessSnapshotScript(): string { +export function windowsProcessSnapshotScript(timeoutMs: number): string { + // A cap that is not a finite number admits no owner read; it never reaches the script text. + const ownerCutoffMs = Number.isFinite(timeoutMs) ? Math.max(0, Math.floor(timeoutMs) - SNAPSHOT_OWNER_RESERVE_MS) : 0; // The helper's own command line must not contain either installation path as a token. const paths = [windowsLauncherVbsPath(), windowsServiceScriptPath()] .map(path => Buffer.from(path, "utf8").toString("base64")); @@ -110,14 +121,16 @@ export function windowsProcessSnapshotScript(): string { "$priority = @($rows | Where-Object { $_.CommandLine -match $homePath });", "$fallback = @($rows | Where-Object { $_.CommandLine -notmatch $homePath -and", " (($_.Name -match '^(wscript|cscript|cmd)\\.exe$') -or (-not $_.Name) -or ($_.CommandLine -like '*opencodex-service*')) });", - "$ownerBudget = @{ Remaining = 32; Clock = [Diagnostics.Stopwatch]::StartNew() };", + "$ownerBudget = @{ Remaining = 32; Clock = [Diagnostics.Stopwatch]::StartNew();", + " Until = [Diagnostics.Process]::GetCurrentProcess().StartTime.ToUniversalTime().AddMilliseconds(" + ownerCutoffMs + ") };", "$owners = @{};", "foreach ($process in ($priority + $fallback)) {", - " if (!$currentSid -or $ownerBudget.Remaining -le 0 -or $ownerBudget.Clock.ElapsedMilliseconds -ge 1500) { break };", + " if (!$currentSid -or $ownerBudget.Remaining -le 0 -or $ownerBudget.Clock.ElapsedMilliseconds -ge 1500", + " -or [DateTime]::UtcNow -ge $ownerBudget.Until) { break };", " $ownerBudget.Remaining--;", " try {", " $owner = Invoke-CimMethod -InputObject $process -MethodName GetOwnerSid -OperationTimeoutSec 1 -ErrorAction Stop;", - " if ($ownerBudget.Clock.ElapsedMilliseconds -ge 1500) { break };", + " if ($ownerBudget.Clock.ElapsedMilliseconds -ge 1500 -or [DateTime]::UtcNow -ge $ownerBudget.Until) { break };", " $after = Get-CimInstance -InputObject $process -OperationTimeoutSec 1 -ErrorAction Stop;", " $owners[$process.ProcessId] = @{ Sid = $owner.Sid; ReturnValue = $owner.ReturnValue;", " CreationDate = if ($after.CreationDate) { $after.CreationDate.ToUniversalTime().ToString('o') } else { $null } };", @@ -211,7 +224,7 @@ export async function windowsProcessSnapshot(options: WindowsEvidenceOptions): P try { entries = parseWindowsProcessSnapshot(await run({ program: "powershell", - args: powershellArgs(windowsProcessSnapshotScript()), + args: powershellArgs(windowsProcessSnapshotScript(options.timeoutMs)), timeoutMs: options.timeoutMs, maxBufferBytes: SNAPSHOT_MAX_BUFFER, })); diff --git a/structure/ops/windows-checked-stop.md b/structure/ops/windows-checked-stop.md index 1a947a8b594..8ce82db99e5 100644 --- a/structure/ops/windows-checked-stop.md +++ b/structure/ops/windows-checked-stop.md @@ -37,7 +37,10 @@ It reads owner SIDs for command lines carrying this home's launcher or service s tokens first, then other wrapper images, unreadable images, and command lines containing the fixed `opencodex-service` basename prefix. Owner enrichment admits at most 32 candidates within 1.5 s after enumeration and prioritization, with a 1 s operation timeout on each owner or refresh -call. Every row is retained and skipped owners remain unknown. The refresh is skipped if +call. No owner read starts later than the snapshot timeout minus 2 s, counted from the +helper process's start, so a cold PowerShell start or slow first CIM query cannot push owner +enrichment past the cap and lose the whole table. Every row is retained and skipped owners +remain unknown. The refresh is skipped if the owner query spends the budget. Owner verification requires a successful `GetOwnerSid`, valid local/domain or Entra ID SIDs, and a fresh CIM read reporting the original creation time. Matching SIDs prove the current account. Different supported SIDs prove a foreign account. diff --git a/tests/windows/windows-process-evidence.test.ts b/tests/windows/windows-process-evidence.test.ts index 57edf92b91b..00d603841d8 100644 --- a/tests/windows/windows-process-evidence.test.ts +++ b/tests/windows/windows-process-evidence.test.ts @@ -17,6 +17,7 @@ import { type WindowsProcessNativeApi, } from "../../src/service/windows-process-native"; import { + SNAPSHOT_OWNER_RESERVE_MS, windowsProcessSnapshotScript, openWindowsProcessWatch, overlayNativeCreationTimes, @@ -201,7 +202,7 @@ describe("Windows process evidence: facades", () => { }); expect(commands).toHaveLength(1); expect(commands[0]).toMatchObject({ program: "powershell", timeoutMs: 5_000 }); - const script = windowsProcessSnapshotScript(); + const script = windowsProcessSnapshotScript(5_000); expect(commands[0]!.args.at(-1)).toBe(script); // Owner queries only cover potential candidates, and re-read identity AFTER the SID. expect(script).toContain("-like '*opencodex-service*'"); @@ -241,18 +242,21 @@ const portablePowerShell = Bun.which("pwsh"); // The three budgets run in one test that shares one 60 s window: a slow first PowerShell start may use // most of it, but a hang still fails inside the 120 s Linux batch deadline, naming the active budget. +// "cap-reached" is the hosted-runner regression: the loop's own 1.5 s budget is fresh, but the +// helper has already used the snapshot cap's owner window, so no owner read may start. test.skipIf(process.platform !== "win32" && !portablePowerShell)("owner enrichment prioritizes this home and retains every row", async () => { const deadline = Date.now() + 60_000; - for (const budget of ["available", "expired", "expires-during-owner"] as const) { + for (const budget of ["available", "expired", "expires-during-owner", "cap-reached"] as const) { try { await ownerEnrichmentCase(budget, deadline); } catch (error) { throw new Error("budget=" + budget + ": " + (error instanceof Error ? error.message : String(error)), { cause: error }); } } }, 65_000); -async function ownerEnrichmentCase(budget: "available" | "expired" | "expires-during-owner", deadline: number): Promise { +async function ownerEnrichmentCase(budget: "available" | "expired" | "expires-during-owner" | "cap-reached", deadline: number): Promise { const powershell = process.platform === "win32" ? resolveTrustedWindowsPowerShellExe() : portablePowerShell!; const launcher = Buffer.from(windowsLauncherVbsPath(), "utf8").toString("base64"); - const script = windowsProcessSnapshotScript().replace( + // A cap equal to the reserve puts the owner cutoff at the helper's own start. + const script = windowsProcessSnapshotScript(budget === "cap-reached" ? SNAPSHOT_OWNER_RESERVE_MS : 60_000).replace( "[Security.Principal.WindowsIdentity]::GetCurrent().User.Value", "'S-1-5-21-100-200-300-1001'", ).replace("[Diagnostics.Stopwatch]::StartNew()", "[pscustomobject]@{ ElapsedMilliseconds = " + (budget === "expired" ? 1500 : 0) + " }"); const prelude = [ @@ -282,7 +286,7 @@ async function ownerEnrichmentCase(budget: "available" | "expired" | "expires-du const rows = parseWindowsProcessSnapshot(result.Snapshot)!; expect(rows).toHaveLength(40); expect(rows.map(row => row.pid)).toEqual(Array.from({ length: 40 }, (_, index) => index + 1)); - expect(result.OwnerReads).toBe(budget === "available" ? 32 : budget === "expired" ? 0 : 1); + expect(result.OwnerReads).toBe(budget === "available" ? 32 : budget === "expires-during-owner" ? 1 : 0); const refreshed = budget === "available" ? 32 : 0; expect(result.RefreshReads).toBe(refreshed); expect(rows[39]!.foreignOwner).toBe(budget === "available" ? false : null);