Compare commits
1
Commits
alpha
...
p1/launch-mode
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cae3231869 |
No files matched your search
@@ -19,6 +19,19 @@ GitHub release body, so a missing section will mean an empty release note.
|
||||
|
||||
### Added
|
||||
|
||||
- **P1 item 2 — launch mode, built as "inject late" (2026-09-06; `20_OPEN_QUESTIONS` §S1 ◐, §S13(c) ✅).**
|
||||
The guard gains `FlGuardedInjectWhenReady(pid, dll, timeoutMs)`: it polls the launched target through
|
||||
the module seam — matching no blocklist — until a presentation runtime is mapped, then runs every
|
||||
check and injects exactly as `FlGuardedInject` does; a target that exits first or maps no runtime in
|
||||
the budget answers the new `LaunchTargetExited` / `LaunchNoPresentationRuntime` with nothing injected
|
||||
(ctest `fl_guard` `[launch]`, five cases incl. the real seam against `hook-harness`). The CaptureHost
|
||||
gains `launch --exe <path> [--args "…"] [--seconds n]` (`ProcessLauncher`: handle held from birth,
|
||||
`FRAMELEDGER_ENABLE_VK_LAYER=1`; the host never terminates what it launched), routed through the same
|
||||
gate by `HookRequest.WaitForPresentationRuntimeMs`, with `IAntiCheatGuard.GuardedInjectWhenReadyAsync`
|
||||
as the port's fourth method. The Overlay publishes `FlWriterState.dxgiPresentsBeforeHook` @60 — DXGI's
|
||||
count of presents before the first hooked one, the early-init cost §S1 deferred on — from the last
|
||||
reserved word (no layout bump; the writer state now has no slack), and the report prints it beside the
|
||||
measured wait. `04_CAPTURE` §Launch mode carries the shape and why it is not `CREATE_SUSPENDED`.
|
||||
- **P1 item 1 — the `LoadLibrary` detour, both jobs (2026-09-06).** The Overlay patches
|
||||
`kernelbase.dll!LoadLibraryExW` after its present hooks (`17_HOOK_ENGINE` §DLL entry step 3): a module
|
||||
the hook inventory or runtime census names **wakes the watchdog** through an auto-reset event, so the
|
||||
|
||||
@@ -66,6 +66,11 @@ watcher sees tracked exe launch
|
||||
|
||||
**Launch mode (preferred when FrameLedger starts the game):** `CreateProcess(CREATE_SUSPENDED)` → guard → inject → `ResumeThread`. This catches swapchain creation and early upscaler init, which attach mode can miss. Attach mode remains for games launched from Steam/GOG directly.
|
||||
|
||||
> **Built 2026-09-06 as start → the guard waits for a presentation runtime → the full guard → inject**
|
||||
> (`FlGuardedInjectWhenReady`, P1 item 2), because a suspended target has loaded nothing for the module
|
||||
> scan to read (`20_OPEN_QUESTIONS` §S1). What it costs is measured by the session itself:
|
||||
> `FlWriterState.dxgiPresentsBeforeHook`. `04_CAPTURE` §Launch mode carries the shape.
|
||||
|
||||
Guard re-runs every 30 s for the life of the session; anti-cheat appearing late ⇒ clean unhook (`19_SAFETY` §During a session).
|
||||
|
||||
## Lifecycle
|
||||
|
||||
@@ -77,6 +77,35 @@ which makes the notification more important than it was, not less.
|
||||
|
||||
**Launch mode (preferred).** User starts the game from FrameLedger (or FrameLedger is set as the launch wrapper): `CreateProcess(CREATE_SUSPENDED)` → guard → inject → `ResumeThread`. Catches swapchain creation and upscaler init, which attach mode can miss entirely — a game that creates its DLSS feature during startup will otherwise report `upscaler = unknown` for the whole session.
|
||||
|
||||
> **Built 2026-09-06 (P1 item 2) as "inject late", which is the only shape §S1 left possible, and the
|
||||
> sentence above is kept as the intent it does not quite describe.** A `CREATE_SUSPENDED` target has
|
||||
> loaded nothing and the module scan *fails* against it (`ERROR_PARTIAL_COPY`, §S1 measured), so the guard
|
||||
> cannot run before the loader has. The built order is **start → the guard WAITS → inject**: the host
|
||||
> starts the consented executable (`ProcessLauncher`: working directory beside the exe,
|
||||
> `FRAMELEDGER_ENABLE_VK_LAYER=1` in its environment for the Vulkan layer, the handle held from birth so
|
||||
> the pid cannot recycle), then asks the guard through its new waiting entry, `FlGuardedInjectWhenReady`,
|
||||
> which polls the loader every 50 ms — through the module seam, matching **no** blocklist — until
|
||||
> `dxgi.dll` with `d3d11.dll` or `d3d12.dll`, or `opengl32.dll`, or `vulkan-1.dll` is mapped, and *then*
|
||||
> runs every check and injects exactly as attach mode does. The poll decides **when** the full scan runs,
|
||||
> never whether it passes. A target that exits first, or maps no runtime inside the budget (60 s in the
|
||||
> host), answers `LaunchTargetExited` / `LaunchNoPresentationRuntime` with nothing injected; a launcher
|
||||
> that spawns the real game and quits lands on the first, and re-electing the descendant is the Agent's
|
||||
> (P2, §Process watcher). **The host never terminates what it launched**: any refusal after the start
|
||||
> leaves the title running unhooked, which is Tier 2.
|
||||
>
|
||||
> **What it measures about itself, which is the input §S1 deferred on.** The report prints the wait
|
||||
> (`launch: the guard injected N ms after the process was started`) and `FlWriterState.dxgiPresentsBeforeHook`
|
||||
> — DXGI's own count, read at the first hooked present on the first hooked chain, of presents completed
|
||||
> before the hook was in. **0 means nothing ran unhooked on that chain**; N is the early-init cost, per
|
||||
> title, from the title itself. On `hook-harness` (device at startup, presenting every 8 ms) the real-seam
|
||||
> fixture injects within one poll and reports the ~1 s of presents the fixture ran before asking — a
|
||||
> measurement of the fixture, not a bound on a title. What launch mode can *never* see is anything before
|
||||
> its own injection, and a swapchain created before the runtime-mapped poll fired is exactly that; the
|
||||
> number says how much.
|
||||
>
|
||||
> The CaptureHost's verb is `launch --exe <path> [--args "<game's own arguments>"] [--seconds <n>]`; the
|
||||
> consent record, the gate and the payload are the ones `capture` uses, reached one process later.
|
||||
|
||||
**Attach mode.** Game launched from Steam/GOG/Epic normally; watcher sees it, guard runs, inject. Feature hooks install late, so early-init facts may be missed; the Overlay compensates by re-reading state on the first `EvaluateFeature` call it does observe, and the session is flagged `late_attach = true` so the UI can note that startup-time settings may be incomplete.
|
||||
|
||||
Steam users can also set FrameLedger as a launch option wrapper; documented in the UI rather than automated (never modify a user's Steam config for them).
|
||||
|
||||
+3
-1
@@ -287,7 +287,9 @@ Findings written to `docs/spike-notes.md`. Nothing in P1 starts until the exit c
|
||||
> **P1 item 1 landed 2026-09-06: the `LoadLibrary` detour** (`kernelbase!LoadLibraryExW`; wake for lazily
|
||||
> loaded runtimes + §S6's in-process anti-cheat stop, `FL_STATUS_STOPPED_BLOCKLISTED`), measured in
|
||||
> ctest `fl_guard` `[loader]` / `[S6]`. Order for the rest, as proposed and accepted: **2** the Injector's
|
||||
> launch mode (§S13(c), §S1's deferred input); **3** the Vulkan layer to `vkQueuePresentKHR` with §S2's
|
||||
> launch mode (§S13(c), §S1's deferred input) — **landed 2026-09-06 as "inject late"**
|
||||
> (`FlGuardedInjectWhenReady`, the CaptureHost `launch` verb, `dxgiPresentsBeforeHook` as the cost meter;
|
||||
> `04_CAPTURE` §Launch mode); **3** the Vulkan layer to `vkQueuePresentKHR` with §S2's
|
||||
> in-layer supervision and a harness Vulkan mode (reopens §S29(d)'s CI leg); **4** the unhook path,
|
||||
> native logging, D3D9 / OpenGL.
|
||||
|
||||
|
||||
@@ -166,7 +166,7 @@ Every hook must be listed here with a purpose. Anything not on this list is not
|
||||
### Presentation
|
||||
| Hook | Purpose |
|
||||
|---|---|
|
||||
| ✅ `IDXGISwapChain::Present`, `Present1` | Frame boundary, QPC, sync interval, present flags. **`DXGI_PRESENT_TEST` calls are dropped without a record** — the occlusion probe submits nothing, and a minimised game emits a stream of them (`07_IPC` §Protocol rules). **Since 2026-09-05 the hook also reads `IDXGISwapChain::GetLastPresentCount` on the chain it just saw** (rule 4: the same COM object `FindOrAdd` already calls `GetDesc` on, no new hook) and publishes `dxgiPresentSamples` / `dxgiPresentsUnseen` — DXGI's count of presents on that chain that this hook never saw, the in-process half of `20_OPEN_QUESTIONS` §H5 Leg 1. One virtual call per hooked present, costed by `hook-harness --probe-frames`. **And per record since the same night: `dxgiUnseen` @52 under `FL_MEASURED_DXGI_PRESENTS`**, so the consumer's window counts `Displayed = hooked + unseen` per bucket (`03_METRICS` §Displayed may be DXGI-COUNTED) — measured 2.90 / 2.95 on DL:TB at Streamline 2.8.0, 0 on 2.7.3 and 2.10.3 |
|
||||
| ✅ `IDXGISwapChain::Present`, `Present1` | Frame boundary, QPC, sync interval, present flags. **`DXGI_PRESENT_TEST` calls are dropped without a record** — the occlusion probe submits nothing, and a minimised game emits a stream of them (`07_IPC` §Protocol rules). **Since 2026-09-05 the hook also reads `IDXGISwapChain::GetLastPresentCount` on the chain it just saw** (rule 4: the same COM object `FindOrAdd` already calls `GetDesc` on, no new hook) and publishes `dxgiPresentSamples` / `dxgiPresentsUnseen` — DXGI's count of presents on that chain that this hook never saw, the in-process half of `20_OPEN_QUESTIONS` §H5 Leg 1. One virtual call per hooked present, costed by `hook-harness --probe-frames`. **And per record since the same night: `dxgiUnseen` @52 under `FL_MEASURED_DXGI_PRESENTS`**, so the consumer's window counts `Displayed = hooked + unseen` per bucket (`03_METRICS` §Displayed may be DXGI-COUNTED) — measured 2.90 / 2.95 on DL:TB at Streamline 2.8.0, 0 on 2.7.3 and 2.10.3. **And since 2026-09-06 (P1 item 2) the same read, at the FIRST hooked present on the first hooked chain, is published once as `FlWriterState.dxgiPresentsBeforeHook` @60** — DXGI's count of presents that ran before the hook was in, launch mode's cost meter (`20_OPEN_QUESTIONS` §S1); 0xFFFFFFFF until a present is seen, set before the present hooks go in |
|
||||
| ✅ `IDXGISwapChain::ResizeBuffers` · ⏳ `ResizeTarget` | Output resolution changes mid-session. `ResizeBuffers` re-reads the swapchain description *after* the original returns; `ResizeTarget` is not hooked |
|
||||
| ⏳ `IDXGISwapChain::SetFullscreenState` | Fullscreen ↔ borderless transitions |
|
||||
| ⏳ `IDXGISwapChain3::SetColorSpace1` | HDR output detection. **`IDXGISwapChain3`, not 4** — 4 adds only `SetHDRMetaData` (`20_OPEN_QUESTIONS` §H9). Unbuilt, which is why `colorSpace` reads `NOT_REPORTED` and `FL_MEASURED_HDR` stays clear. **When it is built, the writer must initialise `colorSpace = FL_COLOR_SPACE_SDR` at swapchain identification** — an SDR title never calls `SetColorSpace1`, so "hook live, no call" would otherwise sit at `NOT_REPORTED` forever and HDR's definite `No` would be unreachable. DXGI documents G22/Rec.709 as the default, which makes SDR a *measured* default rather than an affirmative negative |
|
||||
|
||||
@@ -50,6 +50,13 @@ Implemented in `FrameLedger.Injector` and reached from managed code through a th
|
||||
> against a suspended target (§S1). Neither is "no modules found". The read
|
||||
> handle rights above are confirmed sufficient for every target this call can
|
||||
> legitimately reach.
|
||||
>
|
||||
> **Launch mode (2026-09-06, P1 item 2) does not weaken this.** `FlGuardedInjectWhenReady` polls
|
||||
> the same enumeration to learn *when* the launched target has mapped a presentation runtime, and a
|
||||
> failing enumeration there means "not yet" — the poll continues. That is not a pass: the poll
|
||||
> matches nothing against the blocklist, and the injection happens only after check 1 has run in
|
||||
> full, with the enumeration succeeding, exactly as in attach mode. A launched target that never
|
||||
> becomes scannable is never injected (`LaunchNoPresentationRuntime`).
|
||||
> **Which processes get scanned: the game's own subtree.** `04_CAPTURE`
|
||||
> §The guard writes `Check(pid)` — singular — while `04_CAPTURE` §Process
|
||||
> watcher says the capture target is a *descendant* elected from a ppid
|
||||
|
||||
@@ -73,8 +73,8 @@ or it becomes the next stale status claim this file exists to record.
|
||||
| **S28** | ✅ **resolved 2026-08-05** | The guard's entry points share process-wide statics; a concurrent call cleared the blocklist mid-match and every check fell through to `Allow`. Reproduced by CI, not argued |
|
||||
| **S27** | ✅ **resolved, and restated 2026-08-06** | The chokepoint is the anti-cheat gate, not the consent gate. It was closed by *not building* a capture host; item 1 built one, and the ✅ survives on the clause that was always load-bearing — **no injecting entry point on any SHIPPED binary**. `FrameLedger.CaptureHost` is unpublished, and `tools/package-closure-check.ps1` makes that a gate rather than a fact about today's csproj. `HookRequest` is get-only behind one factory, so this entry's own rejected synthesis no longer compiles |
|
||||
| S12 | 🅓 **deferred, rationale written** | Cautious mode → v1.1; it disabled nothing in v1. *(Marked ✅ until 2026-08-27 — same disposition, different glyph.)* |
|
||||
| **S1** | 🅓 **deferred, rationale written** | Owner decision 2026-08-05. Deciding input — a title loading a presentation runtime lazily — is not on this machine |
|
||||
| **S13(c)** | 🅓 **deferred, rationale written** | Same decision as S1; (a) and (b) were already settled |
|
||||
| **S1** | ◐ **launch mode built as "inject late" 2026-09-06 (P1 item 2); the cost is now measured per title** | `FlGuardedInjectWhenReady` polls until a presentation runtime is mapped, then runs the full guard; `dxgiPresentsBeforeHook` and the reported wait are the input the 2026-08-05 deferral lacked. The ruling "inject late vs. no launch mode" is answered by construction — inject late exists — and whether it is *preferred* per title is what the numbers decide |
|
||||
| **S13(c)** | ✅ **salvageable, and salvaged 2026-09-06** | The externally observable proxy the entry proposed is what was built; the missing input is produced by every launched session |
|
||||
| **S19(b)** | 🅓 **deferred, rationale written — and MEASURED** | CI 2026-08-05: the fragment fires on `System.Security.Cryptography.ProtectedData.dll` loaded by a .NET **test host**, i.e. inside a real scan set in the launch-mode arrangement — refusing our own injection. The entry's "plausible and unmeasured" is superseded; the deferral rationale (a `CryptCATAdmin*` PR doing network I/O inside the hard gate, NFR-10) still stands. *(Marked 🔴 until 2026-08-27. The measurement belongs in this cell, not in the marker — a glyph that means "deferred" and a glyph that means "open defect" cannot be the same one in a table audited by counting.)* |
|
||||
| **S14** | 🅓 **exe half wired 2026-08-05; store-id half deferred to P4, rationale written 2026-09-06** | The store-id half's only in-policy route is P4's platform metadata extractors feeding a guard-side resolver; a resolver with no extractor would refuse every title. No title is blocked by store id today because none is listed |
|
||||
| **S23-1** | ✅ **resolved 2026-08-05** | `FlGuardBuildId` gives the Agent a build id of its own, and `ShmHandshakeValidator` performs the comparison `07_IPC` and `04_CAPTURE` both specify. Every refusal path is driven, including **both ids empty** — the shape the feature shipped in, where `"" == ""` reported `Ok` for every process on the machine |
|
||||
@@ -1246,7 +1246,32 @@ is still no fault-policy test at all**, so the fix has no regression net. The
|
||||
vehicle is the blocker, not the assertions; `src/native/tests/CMakeLists.txt`
|
||||
records both rejected approaches and why.
|
||||
|
||||
### S1 · The guard is structurally blind in launch mode
|
||||
### S1 ◐ · The guard is structurally blind in launch mode — **launch mode built as "inject late", 2026-09-06 (P1 item 2)**
|
||||
|
||||
> **Built, and the deferral's missing input is now something every launched session produces.**
|
||||
> The guard gained `GuardedInjectWhenReady(pid, dll, timeoutMs)` (ABI `FlGuardedInjectWhenReady`): it
|
||||
> polls the target every 50 ms through the module seam — a `Collected::kFailed` (the suspended /
|
||||
> still-in-loader `ERROR_PARTIAL_COPY`) is "not yet", never a pass — until `dxgi.dll` with
|
||||
> `d3d11.dll`/`d3d12.dll`, or `opengl32.dll`, or `vulkan-1.dll` is mapped, then runs `GuardedInjectImpl`
|
||||
> in full. The poll matches nothing against the blocklist; it chooses WHEN the guard runs and nothing
|
||||
> about whether it passes. Two new reasons end the poll with nothing injected: `LaunchTargetExited`
|
||||
> (24) and `LaunchNoPresentationRuntime` (25). The CaptureHost's `launch` verb starts the consented
|
||||
> executable itself (`ProcessLauncher`, `FRAMELEDGER_ENABLE_VK_LAYER=1`, handle held from birth) and
|
||||
> routes the same gate through `HookRequest.WaitForPresentationRuntimeMs`; it never terminates what it
|
||||
> launched. Measured, ctest `fl_guard` `[launch]`: the fake-driven poll injects on the first
|
||||
> enumeration that shows the runtime and not one before (7 polls, ~300 ms), a target that exits first
|
||||
> and a budget that runs out each answer their own reason, anti-cheat mapped beside the runtime is the
|
||||
> full scan's refusal, and the real-seam case against `hook-harness` injects within one poll (15 ms).
|
||||
>
|
||||
> **The number nobody had:** `FlWriterState.dxgiPresentsBeforeHook` @60 — DXGI's `GetLastPresentCount`
|
||||
> at the first hooked present on the first hooked chain, i.e. presents that ran before the hook was in
|
||||
> (0xFFFFFFFF = the hook never saw a present). With the reported wait (`launch: the guard injected N ms
|
||||
> after the process was started`) that is the early-init cost §S13(c) said needed a lazily loading title:
|
||||
> it now comes from every title, on every launched session. **What the numbers decide is whether launch
|
||||
> mode is *preferred* for a given title, not whether it exists.** The 2026-08-05 rationale stands as
|
||||
> written below; what it deferred is now measurable rather than argued. Owed: the first real-title launch
|
||||
> (the owner's next captures), which will also be the first look at a launcher-first title landing on
|
||||
> `LaunchTargetExited` and needing the Agent's descendant election (P2).
|
||||
|
||||
> **§S1 does not gate the Vulkan path.** Added 2026-08-03, because "launch mode
|
||||
> is blocked by §S1 anyway" was being used as a reason to deprioritise §S18 and
|
||||
@@ -1562,6 +1587,10 @@ prologue) cannot produce a figure that generalises.
|
||||
> entry proposes (resume, then poll until the target has mapped a presentation
|
||||
> runtime *and* the scan passes *and* the blocklist is clean) remains the only
|
||||
> candidate design for "inject late". It is unbuilt, not rejected.
|
||||
>
|
||||
> > **✅ Built 2026-09-06 (P1 item 2), exactly that proxy** — `FlGuardedInjectWhenReady`, §S1 carries
|
||||
> > the mechanism and the measurements. "Salvageable" is answered yes; the cost of injecting late is
|
||||
> > reported by the session itself (`dxgiPresentsBeforeHook`, and the wait).
|
||||
|
||||
### S15 ✅ · The four consequences of putting the guard in C++ (§S13(a)) — **closed**
|
||||
|
||||
|
||||
+2
-1
@@ -39,7 +39,8 @@ hook installation for D3D11/12/9/OGL, the `LoadLibrary` detour that §S6's early
|
||||
and lazily loaded runtimes both hang on, unhook path, native logging; the Injector's
|
||||
launch mode (§S13(c), §S1's deferred input); the Vulkan layer to `vkQueuePresentKHR`
|
||||
with §S2's in-layer supervision. **P1 item 1 — the `LoadLibrary` detour — landed 2026-09-06
|
||||
(§S6 ✅); next is item 2, the Injector's launch mode.** The ~~three~~ two P1-deferred S-items (~~S6~~, S2 part three, and
|
||||
(§S6 ✅); item 2, launch mode, landed the same day as "inject late" (§S1 ◐, §S13(c) ✅ —
|
||||
`04_CAPTURE` §Launch mode); next is item 3, the Vulkan layer to `vkQueuePresentKHR`.** The ~~three~~ two P1-deferred S-items (~~S6~~, S2 part three, and
|
||||
the hand-run blast-radius script behind S29(d)) are the reminders. The text below is
|
||||
P0's history and stays as it stood.
|
||||
|
||||
|
||||
@@ -335,6 +335,9 @@ owner's before anything is built.
|
||||
loads a presentation runtime lazily, and the only local fixtures are
|
||||
`hook-harness` (creates D3D at startup) and a 2D GOG prologue. A number from
|
||||
those would not generalise, which is worse than recording it as unmeasured.
|
||||
*(2026-09-06: built as "inject late" — P1 item 2 — and the number now comes
|
||||
from every launched session, as `dxgiPresentsBeforeHook` plus the reported
|
||||
wait. `20_OPEN_QUESTIONS` §S1.)*
|
||||
|
||||
### ✅ Signer field for the unknown-but-suspicious heuristic — **`O=`, not `CN=`**
|
||||
|
||||
|
||||
@@ -31,15 +31,27 @@ namespace FrameLedger.Application.AntiCheat;
|
||||
public sealed class HookRequest
|
||||
{
|
||||
private HookRequest(int targetPid, string payloadPath, bool hookEnabled, DateTimeOffset? consentedAt,
|
||||
string? blockedReason)
|
||||
string? blockedReason, int waitForPresentationRuntimeMs)
|
||||
{
|
||||
TargetPid = targetPid;
|
||||
PayloadPath = payloadPath;
|
||||
HookEnabled = hookEnabled;
|
||||
ConsentedAt = consentedAt;
|
||||
BlockedReason = blockedReason;
|
||||
WaitForPresentationRuntimeMs = waitForPresentationRuntimeMs;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Launch mode's budget: how long the guard may wait for the target to map a presentation runtime
|
||||
/// before injecting. Zero — the default, and attach mode — asks the guard to inject now.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// It cannot widen what is injected or skip a check: a positive value routes the request through
|
||||
/// <see cref="IAntiCheatGuard.GuardedInjectWhenReadyAsync"/>, which runs the same full scan later
|
||||
/// rather than a smaller one sooner.
|
||||
/// </remarks>
|
||||
public int WaitForPresentationRuntimeMs { get; }
|
||||
|
||||
/// <summary>The process to inject into.</summary>
|
||||
public int TargetPid { get; }
|
||||
|
||||
@@ -75,17 +87,20 @@ public sealed class HookRequest
|
||||
/// <param name="observed">The executable as it is on disk right now.</param>
|
||||
/// <param name="targetPid">The process to inject into.</param>
|
||||
/// <param name="payloadPath">The Overlay, resolved beside the guard (§S22).</param>
|
||||
/// <param name="waitForPresentationRuntimeMs">Launch mode's budget; zero is attach mode.</param>
|
||||
public static HookRequest FromConsent(
|
||||
GameConsentRecord record, ExecutableFingerprint observed, int targetPid, string payloadPath)
|
||||
GameConsentRecord record, ExecutableFingerprint observed, int targetPid, string payloadPath,
|
||||
int waitForPresentationRuntimeMs = 0)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(payloadPath);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(waitForPresentationRuntimeMs);
|
||||
|
||||
// A record nobody stored has enabled nothing and consented to nothing. Checked first so the
|
||||
// fields below are never read off a default value.
|
||||
if (!record.IsFromStore)
|
||||
{
|
||||
return new HookRequest(targetPid, payloadPath, hookEnabled: false, consentedAt: null,
|
||||
blockedReason: null);
|
||||
blockedReason: null, waitForPresentationRuntimeMs);
|
||||
}
|
||||
|
||||
// A TIMESTAMP IS NOT CONSENT. games.hook_consent_at is a bare DateTime, so a record could carry
|
||||
@@ -106,6 +121,7 @@ public sealed class HookRequest
|
||||
consentedAt = null;
|
||||
}
|
||||
|
||||
return new HookRequest(targetPid, payloadPath, record.HookEnabled, consentedAt, record.BlockedReason);
|
||||
return new HookRequest(targetPid, payloadPath, record.HookEnabled, consentedAt, record.BlockedReason,
|
||||
waitForPresentationRuntimeMs);
|
||||
}
|
||||
}
|
||||
@@ -76,6 +76,11 @@ public sealed class HookedCaptureGate(IAntiCheatGuard guard)
|
||||
return AntiCheatVerdict.Refused(AntiCheatRefusalReason.PreviouslyBlocked, "previously blocked", blocked);
|
||||
}
|
||||
|
||||
return await _guard.GuardedInjectAsync(request.TargetPid, request.PayloadPath, ct).ConfigureAwait(false);
|
||||
// Launch mode is the same gate reached through the guard's WAITING entry: the consent checks
|
||||
// above are identical, and what differs is only WHEN the guard's full scan runs (P1 item 2).
|
||||
return request.WaitForPresentationRuntimeMs > 0
|
||||
? await _guard.GuardedInjectWhenReadyAsync(request.TargetPid, request.PayloadPath,
|
||||
request.WaitForPresentationRuntimeMs, ct).ConfigureAwait(false)
|
||||
: await _guard.GuardedInjectAsync(request.TargetPid, request.PayloadPath, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,23 @@ public interface IAntiCheatGuard
|
||||
/// </summary>
|
||||
ValueTask<AntiCheatVerdict> GuardedInjectAsync(int targetPid, string payloadPath, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Launch mode (P1 item 2). Wait — up to <paramref name="timeoutMs"/> — until the target has mapped a
|
||||
/// presentation runtime, then run every check and inject exactly as <see cref="GuardedInjectAsync"/>
|
||||
/// does. The wait decides WHEN the guard runs and nothing about whether it passes.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <c>20_OPEN_QUESTIONS</c> §S1: a target held at its first instruction has loaded nothing, so the
|
||||
/// module scan cannot run before the loader has. The guard therefore polls the loader's own answer
|
||||
/// (through the module seam, matching no blocklist) and runs in full the moment a runtime is there. A
|
||||
/// target that exits first, or never maps one, refuses with
|
||||
/// <see cref="AntiCheatRefusalReason.LaunchTargetExited"/> /
|
||||
/// <see cref="AntiCheatRefusalReason.LaunchNoPresentationRuntime"/>. The caller launched and holds
|
||||
/// the process; the guard creates and terminates nothing.
|
||||
/// </remarks>
|
||||
ValueTask<AntiCheatVerdict> GuardedInjectWhenReadyAsync(int targetPid, string payloadPath, int timeoutMs,
|
||||
CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Check 4 asked before anything is launched: does this game directory ship
|
||||
/// anti-cheat? Answers FR-2.2's question — whether the hooking toggle may be
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Diagnostics;
|
||||
using FrameLedger.Application.AntiCheat;
|
||||
using FrameLedger.Application.Consent;
|
||||
using FrameLedger.CaptureHost.Consume;
|
||||
@@ -31,7 +32,8 @@ internal sealed class CaptureLoop(
|
||||
Func<int, (ICaptureSink? Sink, ShmAttachRefusal Refusal)> attach,
|
||||
CaptureOptions options,
|
||||
Func<int, RuntimeModuleSet>? modules = null,
|
||||
Func<int, NgxDriverState>? ngx = null)
|
||||
Func<int, NgxDriverState>? ngx = null,
|
||||
Func<string, string, (int Pid, ITargetLiveness Alive)?>? launcher = null)
|
||||
{
|
||||
/// <summary>Start one session, or say why not.</summary>
|
||||
/// <remarks>
|
||||
@@ -84,24 +86,84 @@ internal sealed class CaptureLoop(
|
||||
}
|
||||
|
||||
GameConsentRecord record = await store.FindAsync(normalisedExePath, ct).ConfigureAwait(false);
|
||||
if (ConsentRefusal(record, observed) is SessionEndReason refused)
|
||||
{
|
||||
return new CaptureResult { Reason = refused };
|
||||
}
|
||||
|
||||
return await SessionAsync(pid.Value, alive, record, observed!.Value, payloadPath, started: null, ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Launch mode (P1 item 2): start the consented executable, then the same session.</summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>The process is started FIRST and consent is still the gate's, one process later.</b> Attach mode
|
||||
/// resolves a pid before consent because a <see cref="HookRequest"/> needs one; here the pid is made
|
||||
/// rather than found, and the operator asked for the game to start. A refusal of any kind — no
|
||||
/// record, an anti-cheat hit, no runtime inside the budget — leaves the title running, unhooked,
|
||||
/// which is the product's Tier 2: this host never terminates what it launched.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>The guard is reached through its waiting entry, with the loop's budget, and never the plain
|
||||
/// one</b>: <see cref="HookRequest.WaitForPresentationRuntimeMs"/> is what routes it, and the wait is
|
||||
/// measured here — from the start of the process to the guard's answer — because that number is
|
||||
/// the cost <c>20_OPEN_QUESTIONS</c> §S1 deferred on. <c>FlWriterState.dxgiPresentsBeforeHook</c>
|
||||
/// is its other half.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public async Task<CaptureResult> RunLaunchedAsync(string normalisedExePath, ExecutableFingerprint? observed,
|
||||
string payloadPath, string arguments, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(normalisedExePath);
|
||||
if (launcher is null)
|
||||
{
|
||||
throw new InvalidOperationException("this loop was built without a launcher; launch mode is unavailable");
|
||||
}
|
||||
|
||||
var started = Stopwatch.StartNew();
|
||||
(int Pid, ITargetLiveness Alive)? launched = launcher(normalisedExePath, arguments ?? string.Empty);
|
||||
if (launched is null)
|
||||
{
|
||||
return new CaptureResult { Reason = SessionEndReason.LaunchCannotStart };
|
||||
}
|
||||
|
||||
using ITargetLiveness alive = launched.Value.Alive;
|
||||
GameConsentRecord record = await store.FindAsync(normalisedExePath, ct).ConfigureAwait(false);
|
||||
if (ConsentRefusal(record, observed) is SessionEndReason refused)
|
||||
{
|
||||
return new CaptureResult { Reason = refused };
|
||||
}
|
||||
|
||||
return await SessionAsync(launched.Value.Pid, alive, record, observed!.Value, payloadPath, started, ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The two refusals the loop makes itself, before the gate (see <see cref="RunAsync"/>'s remarks).</summary>
|
||||
private static SessionEndReason? ConsentRefusal(GameConsentRecord record, ExecutableFingerprint? observed)
|
||||
{
|
||||
if (record.PreScanUnverified)
|
||||
{
|
||||
return new CaptureResult { Reason = SessionEndReason.PreScanCouldNotVerify };
|
||||
return SessionEndReason.PreScanCouldNotVerify;
|
||||
}
|
||||
|
||||
if (observed is null)
|
||||
{
|
||||
return new CaptureResult { Reason = SessionEndReason.ExecutableUnreadable };
|
||||
}
|
||||
return observed is null ? SessionEndReason.ExecutableUnreadable : null;
|
||||
}
|
||||
|
||||
HookRequest request = HookRequest.FromConsent(record, observed.Value, pid.Value, payloadPath);
|
||||
/// <summary>Gate, attach, drain — shared by both modes; <paramref name="started"/> non-null is launch mode.</summary>
|
||||
private async Task<CaptureResult> SessionAsync(int pid, ITargetLiveness alive, GameConsentRecord record,
|
||||
ExecutableFingerprint observed, string payloadPath, Stopwatch? started, CancellationToken ct)
|
||||
{
|
||||
int waitMs = started is null ? 0 : checked((int)options.LaunchWaitBudget.TotalMilliseconds);
|
||||
HookRequest request = HookRequest.FromConsent(record, observed, pid, payloadPath, waitMs);
|
||||
AntiCheatVerdict verdict = await gate.StartAsync(request, ct).ConfigureAwait(false);
|
||||
TimeSpan? launchWait = started?.Elapsed;
|
||||
if (!verdict.IsAllowed)
|
||||
{
|
||||
return new CaptureResult { Reason = RefusalOf(verdict.Reason), Verdict = verdict };
|
||||
return new CaptureResult { Reason = RefusalOf(verdict.Reason), Verdict = verdict, LaunchWait = launchWait };
|
||||
}
|
||||
|
||||
(ICaptureSink? sink, ShmAttachRefusal refusal) = await AttachAsync(pid.Value, ct).ConfigureAwait(false);
|
||||
(ICaptureSink? sink, ShmAttachRefusal refusal) = await AttachAsync(pid, ct).ConfigureAwait(false);
|
||||
if (sink is null)
|
||||
{
|
||||
return new CaptureResult
|
||||
@@ -109,12 +171,14 @@ internal sealed class CaptureLoop(
|
||||
Reason = SessionEndReason.AttachRefused,
|
||||
Verdict = verdict,
|
||||
AttachRefusal = refusal,
|
||||
LaunchWait = launchWait,
|
||||
};
|
||||
}
|
||||
|
||||
using (sink)
|
||||
{
|
||||
return await DrainAsync(pid.Value, alive, sink, verdict, ct).ConfigureAwait(false);
|
||||
CaptureResult result = await DrainAsync(pid, alive, sink, verdict, ct).ConfigureAwait(false);
|
||||
return result with { LaunchWait = launchWait };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,6 +187,8 @@ internal sealed class CaptureLoop(
|
||||
AntiCheatRefusalReason.HookNotEnabled => SessionEndReason.RefusedHookNotEnabled,
|
||||
AntiCheatRefusalReason.ConsentMissing => SessionEndReason.RefusedConsentMissing,
|
||||
AntiCheatRefusalReason.PreviouslyBlocked => SessionEndReason.RefusedPreviouslyBlocked,
|
||||
AntiCheatRefusalReason.LaunchTargetExited => SessionEndReason.LaunchTargetExited,
|
||||
AntiCheatRefusalReason.LaunchNoPresentationRuntime => SessionEndReason.LaunchNoPresentationRuntime,
|
||||
_ => SessionEndReason.RefusedByGuard,
|
||||
};
|
||||
|
||||
|
||||
@@ -14,4 +14,11 @@ internal sealed record CaptureOptions
|
||||
|
||||
/// <summary>Zero means "until the target exits".</summary>
|
||||
public TimeSpan MaxDuration { get; init; } = TimeSpan.Zero;
|
||||
|
||||
/// <summary>
|
||||
/// Launch mode: how long the guard may wait for the launched target to map a presentation runtime
|
||||
/// before it gives up with <c>LaunchNoPresentationRuntime</c>. A launcher that sits on its window
|
||||
/// past this is a launcher, and the descendant election is the Agent's (P2).
|
||||
/// </summary>
|
||||
public TimeSpan LaunchWaitBudget { get; init; } = TimeSpan.FromSeconds(60);
|
||||
}
|
||||
@@ -65,4 +65,10 @@ internal sealed record CaptureResult
|
||||
/// frame stream can be checked against what FrameLedger itself was doing at that moment.
|
||||
/// </summary>
|
||||
public IReadOnlyList<long> TouchQpc { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Launch mode only: from the process being started to the guard's answer — the wait for a
|
||||
/// presentation runtime plus the full scan and the injection. Null in attach mode.
|
||||
/// </summary>
|
||||
public TimeSpan? LaunchWait { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using FrameLedger.Infrastructure.Io;
|
||||
|
||||
namespace FrameLedger.CaptureHost.Capture;
|
||||
|
||||
/// <summary>
|
||||
/// Launch mode's first step: start the consented executable and hold it from birth.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>Not <c>CREATE_SUSPENDED</c>, and the spec's sentence is why.</b> <c>04_CAPTURE</c> §Launch mode
|
||||
/// wrote <i>create suspended → guard → inject → resume</i>, and <c>20_OPEN_QUESTIONS</c> §S1 measured
|
||||
/// that a suspended target has loaded nothing: <c>EnumProcessModulesEx</c> fails against it, so the guard
|
||||
/// cannot run before the loader has. The built shape is <i>create → guard WAITS for a presentation
|
||||
/// runtime → inject</i> (<c>FlGuardedInjectWhenReady</c>), and nothing in it needs the process held at
|
||||
/// its first instruction. What the launch buys instead: the pid is ours before any code runs, the handle
|
||||
/// is held from the start so it cannot recycle under us (§S29(e)), and the Vulkan layer's
|
||||
/// <c>enable_environment</c> is set — which only the launching process can do (<c>17_HOOK_ENGINE</c>
|
||||
/// §Vulkan). The layer still gates on its own enabled-list; the variable alone enables nothing.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>This host never terminates what it launched.</b> A refusal after the launch — no consent, an
|
||||
/// anti-cheat hit, no runtime inside the budget — leaves the title running unhooked, exactly as the
|
||||
/// product's Tier 2 does (duration and the reason, no measurement). The operator asked for the game to
|
||||
/// start; the guard decides only whether FrameLedger goes into it.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal static class ProcessLauncher
|
||||
{
|
||||
/// <summary>The Vulkan loader's enable variable for <c>VK_LAYER_FRAMELEDGER_overlay</c> (<c>17_HOOK_ENGINE</c> §Vulkan).</summary>
|
||||
public const string VulkanLayerEnableVariable = "FRAMELEDGER_ENABLE_VK_LAYER";
|
||||
|
||||
/// <summary>Start <paramref name="exePath"/> with <paramref name="arguments"/>; null when it could not be started or pinned.</summary>
|
||||
public static (int Pid, ITargetLiveness Alive)? Start(string exePath, string arguments)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(exePath);
|
||||
|
||||
var psi = new ProcessStartInfo(exePath, arguments ?? string.Empty)
|
||||
{
|
||||
UseShellExecute = false,
|
||||
WorkingDirectory = Path.GetDirectoryName(exePath) ?? string.Empty,
|
||||
};
|
||||
psi.Environment[VulkanLayerEnableVariable] = "1";
|
||||
|
||||
Process? process;
|
||||
try
|
||||
{
|
||||
process = Process.Start(psi);
|
||||
}
|
||||
catch (Exception e) when (e is Win32Exception or InvalidOperationException or IOException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (process is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
using (process)
|
||||
{
|
||||
// The same pin attach mode takes, taken here before anything else looks at the pid. The
|
||||
// liveness OWNS the handle from here; the caller disposes it with the session (CA2000 is
|
||||
// satisfied by that transfer, stated rather than suppressed).
|
||||
HeldProcessHandle? held = HeldProcessHandle.TryOpen(process.Id);
|
||||
if (held is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
ITargetLiveness alive = new ProcessTargetLiveness(held, process.Id);
|
||||
return (process.Id, alive);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -107,4 +107,19 @@ internal enum SessionEndReason
|
||||
|
||||
/// <summary>The ring could not be attached to, and the refusal was not retryable.</summary>
|
||||
AttachRefused,
|
||||
|
||||
/// <summary>Launch mode: the executable could not be started, or the new process could not be pinned.</summary>
|
||||
LaunchCannotStart,
|
||||
|
||||
/// <summary>
|
||||
/// Launch mode: the guard was waiting for a presentation runtime and the target exited first
|
||||
/// (<see cref="Domain.AntiCheat.AntiCheatRefusalReason.LaunchTargetExited"/>). Nothing was injected.
|
||||
/// </summary>
|
||||
LaunchTargetExited,
|
||||
|
||||
/// <summary>
|
||||
/// Launch mode: the budget ran out with no presentation runtime mapped
|
||||
/// (<see cref="Domain.AntiCheat.AntiCheatRefusalReason.LaunchNoPresentationRuntime"/>). Nothing was injected.
|
||||
/// </summary>
|
||||
LaunchNoPresentationRuntime,
|
||||
}
|
||||
@@ -22,7 +22,7 @@ namespace FrameLedger.CaptureHost;
|
||||
internal sealed record CommandLine
|
||||
{
|
||||
/// <summary>Every option this host accepts. A test pins it.</summary>
|
||||
public static readonly string[] AcceptedOptions = ["--exe", "--seconds"];
|
||||
public static readonly string[] AcceptedOptions = ["--exe", "--seconds", "--args"];
|
||||
|
||||
public Verb Verb { get; init; }
|
||||
|
||||
@@ -48,6 +48,16 @@ internal sealed record CommandLine
|
||||
/// </remarks>
|
||||
public int Seconds { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The command line handed to the executable <c>launch</c> starts, verbatim. Empty by default.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// It names nothing about injection: the payload is still the Overlay beside this binary, the target
|
||||
/// is still the consented executable, and the guard still collects its own evidence. What it changes
|
||||
/// is what the GAME sees, which is the operator's business and not this host's.
|
||||
/// </remarks>
|
||||
public string Arguments { get; init; } = string.Empty;
|
||||
|
||||
public string? Error { get; init; }
|
||||
|
||||
public static CommandLine Parse(string[] args)
|
||||
@@ -58,11 +68,12 @@ internal sealed record CommandLine
|
||||
|
||||
if (verb == Verb.None)
|
||||
{
|
||||
return new CommandLine { Error = "usage: consent list | consent grant --exe <path> | consent revoke --exe <path> | capture --exe <path> [--seconds <n>] | probe-lhm [--seconds <n>]" };
|
||||
return new CommandLine { Error = "usage: consent list | consent grant --exe <path> | consent revoke --exe <path> | capture --exe <path> [--seconds <n>] | launch --exe <path> [--args \"<string>\"] [--seconds <n>] | probe-lhm [--seconds <n>]" };
|
||||
}
|
||||
|
||||
string? exe = null;
|
||||
int seconds = 0;
|
||||
string arguments = string.Empty;
|
||||
for (int i = 0; i < args.Length; i++)
|
||||
{
|
||||
if (args[i].StartsWith("--", StringComparison.Ordinal))
|
||||
@@ -91,6 +102,10 @@ internal sealed record CommandLine
|
||||
return new CommandLine { Error = "'--seconds' needs a positive whole number" };
|
||||
}
|
||||
}
|
||||
else if (string.Equals(option, "--args", StringComparison.Ordinal))
|
||||
{
|
||||
arguments = value;
|
||||
}
|
||||
else
|
||||
{
|
||||
exe = value;
|
||||
@@ -105,7 +120,7 @@ internal sealed record CommandLine
|
||||
return new CommandLine { Error = "--exe <path> is required" };
|
||||
}
|
||||
|
||||
return new CommandLine { Verb = verb, ExePath = exe, Seconds = seconds };
|
||||
return new CommandLine { Verb = verb, ExePath = exe, Seconds = seconds, Arguments = arguments };
|
||||
}
|
||||
|
||||
private static Verb VerbOf(string[] args) => args switch
|
||||
@@ -114,6 +129,7 @@ internal sealed record CommandLine
|
||||
["consent", "grant", ..] => Verb.ConsentGrant,
|
||||
["consent", "revoke", ..] => Verb.ConsentRevoke,
|
||||
["capture", ..] => Verb.Capture,
|
||||
["launch", ..] => Verb.Launch,
|
||||
["probe-lhm", ..] => Verb.ProbeLhm,
|
||||
_ => Verb.None,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
using System.Globalization;
|
||||
using FrameLedger.Shared;
|
||||
|
||||
namespace FrameLedger.CaptureHost.Consume;
|
||||
|
||||
/// <summary>
|
||||
/// Launch mode's cost, as the report reads it: how long the guard waited before it injected, and how many
|
||||
/// presents DXGI had already counted on the first hooked chain when the hook saw its first one — the number
|
||||
/// <c>20_OPEN_QUESTIONS</c> §S1 said nobody had.
|
||||
/// </summary>
|
||||
internal static class LaunchNote
|
||||
{
|
||||
/// <summary>One line when the session was launched, and one line always.</summary>
|
||||
public static IEnumerable<string> Describe(TimeSpan? launchWait, FlWriterState writer)
|
||||
{
|
||||
if (launchWait is TimeSpan wait)
|
||||
{
|
||||
yield return " launch: the guard injected "
|
||||
+ ((long)wait.TotalMilliseconds).ToString(CultureInfo.InvariantCulture)
|
||||
+ " ms after the process was started (it waited for a presentation runtime to map, then ran every check)";
|
||||
}
|
||||
|
||||
yield return writer.DxgiPresentsBeforeHook == FlWriterState.DxgiPresentsBeforeHookNotRead
|
||||
? " presents before the first hooked present: not read (the hook saw no present)"
|
||||
: " presents before the first hooked present: "
|
||||
+ writer.DxgiPresentsBeforeHook.ToString(CultureInfo.InvariantCulture)
|
||||
+ " (DXGI's count on the first hooked chain; 0 means nothing ran unhooked on it -- §S1's number)";
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,7 @@ internal static class Program
|
||||
Verb.ConsentGrant => await GrantAsync(store, cmd.ExePath!).ConfigureAwait(false),
|
||||
Verb.ConsentRevoke => await RevokeAsync(store, cmd.ExePath!).ConfigureAwait(false),
|
||||
Verb.Capture => await CaptureAsync(store, cmd.ExePath!, cmd.Seconds).ConfigureAwait(false),
|
||||
Verb.Launch => await LaunchAsync(store, cmd.ExePath!, cmd.Arguments, cmd.Seconds).ConfigureAwait(false),
|
||||
Verb.ProbeLhm => LhmProbe.Run(cmd.Seconds == 0 ? LhmProbe.DefaultSeconds : cmd.Seconds),
|
||||
_ => _exitUsage,
|
||||
};
|
||||
@@ -131,18 +132,37 @@ internal static class Program
|
||||
return outcome is ConsentWriteOutcome.Written or ConsentWriteOutcome.NotFound ? _exitOk : _exitRefused;
|
||||
}
|
||||
|
||||
// §S22: the payload must resolve into the directory the GUARD's own code was loaded from,
|
||||
// compared by file id. There is no way to name a different one, which is the point.
|
||||
private static string Payload => Path.Combine(AppContext.BaseDirectory, "FrameLedger.Overlay.dll");
|
||||
|
||||
private static async Task<int> CaptureAsync(FileGameConsentStore store, string exePath, int seconds)
|
||||
{
|
||||
string normalised = ExecutableIdentity.Normalise(exePath);
|
||||
ExecutableFingerprint? observed = ExecutableIdentity.Read(exePath);
|
||||
|
||||
// §S22: the payload must resolve into the directory the GUARD's own code was loaded from,
|
||||
// compared by file id. There is no way to name a different one, which is the point.
|
||||
string payload = Path.Combine(AppContext.BaseDirectory, "FrameLedger.Overlay.dll");
|
||||
CaptureResult result = await BuildLoop(store, seconds)
|
||||
.RunAsync(normalised, observed, Payload).ConfigureAwait(false);
|
||||
|
||||
return await ConcludeAsync(store, normalised, observed, result).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Launch mode: the same loop, entered by starting the executable rather than finding it.</summary>
|
||||
private static async Task<int> LaunchAsync(FileGameConsentStore store, string exePath, string arguments,
|
||||
int seconds)
|
||||
{
|
||||
string normalised = ExecutableIdentity.Normalise(exePath);
|
||||
ExecutableFingerprint? observed = ExecutableIdentity.Read(exePath);
|
||||
|
||||
CaptureResult result = await BuildLoop(store, seconds)
|
||||
.RunAsync(normalised, observed, payload).ConfigureAwait(false);
|
||||
.RunLaunchedAsync(normalised, observed, Payload, arguments).ConfigureAwait(false);
|
||||
|
||||
return await ConcludeAsync(store, normalised, observed, result).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task<int> ConcludeAsync(FileGameConsentStore store, string normalised,
|
||||
ExecutableFingerprint? observed, CaptureResult result)
|
||||
{
|
||||
HostConsole.Line($"session: {result.Reason}");
|
||||
if (result.Verdict.Reason != Domain.AntiCheat.AntiCheatRefusalReason.Allow)
|
||||
{
|
||||
@@ -166,7 +186,7 @@ internal static class Program
|
||||
SessionEndReason.TargetExited => _exitOk,
|
||||
SessionEndReason.Running => _exitOk,
|
||||
SessionEndReason.TargetNotRunning or SessionEndReason.TargetAmbiguous
|
||||
or SessionEndReason.TargetCannotBePinned => _exitTargetNotResolved,
|
||||
or SessionEndReason.TargetCannotBePinned or SessionEndReason.LaunchCannotStart => _exitTargetNotResolved,
|
||||
SessionEndReason.AttachRefused => _exitAttachRefused,
|
||||
SessionEndReason.SafetyUnhook or SessionEndReason.SupervisionLost
|
||||
or SessionEndReason.SupervisionFaulted or SessionEndReason.WriterStoppedBlocklisted => _exitStoppedForSafety,
|
||||
@@ -335,7 +355,8 @@ internal static class Program
|
||||
MaxDuration = seconds > 0 ? TimeSpan.FromSeconds(seconds) : TimeSpan.Zero,
|
||||
},
|
||||
pid => RuntimeModuleSnapshot.Take(pid, CensusNames.ModuleFileNames),
|
||||
NgxDriverProbe.Run);
|
||||
NgxDriverProbe.Run,
|
||||
ProcessLauncher.Start);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -396,6 +417,11 @@ internal static class Program
|
||||
{
|
||||
HostConsole.Line(line);
|
||||
}
|
||||
|
||||
foreach (string line in LaunchNote.Describe(result.LaunchWait, result.WriterState))
|
||||
{
|
||||
HostConsole.Line(line);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -9,6 +9,13 @@ internal enum Verb
|
||||
ConsentRevoke,
|
||||
Capture,
|
||||
|
||||
/// <summary>
|
||||
/// Launch mode (P1 item 2): start the consented executable, hold it, and let the guard inject the
|
||||
/// moment it has mapped a presentation runtime. The same consent record, the same gate, the same
|
||||
/// payload; only WHEN the full scan runs differs.
|
||||
/// </summary>
|
||||
Launch,
|
||||
|
||||
/// <summary>
|
||||
/// §M5's instrument: open LibreHardwareMonitor GPU-only, print the raw sensor tree
|
||||
/// and the mapped sample for a few seconds, and name the pre-committed row it landed on.
|
||||
|
||||
@@ -170,4 +170,20 @@ public enum AntiCheatRefusalReason
|
||||
/// watchlist resurrecting the game after <c>hook_enabled</c> was forced to 0.
|
||||
/// </remarks>
|
||||
PreviouslyBlocked = 23,
|
||||
|
||||
/// <summary>
|
||||
/// Launch mode (P1 item 2): the guard was waiting for the launched target to map a presentation
|
||||
/// runtime and the target exited first. Nothing was injected.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A launcher that spawned the real game and quit is the ordinary cause (the descendant election is
|
||||
/// the Agent's, P2); a crash is the other. <c>20_OPEN_QUESTIONS</c> §S1 / §S13(c).
|
||||
/// </remarks>
|
||||
LaunchTargetExited = 24,
|
||||
|
||||
/// <summary>
|
||||
/// Launch mode: the budget ran out and the target had mapped no presentation runtime — a 2D title,
|
||||
/// or a launcher still sitting on its window. Nothing was injected.
|
||||
/// </summary>
|
||||
LaunchNoPresentationRuntime = 25,
|
||||
}
|
||||
@@ -64,6 +64,11 @@ public sealed class NativeAntiCheatGuard : IAntiCheatGuard
|
||||
[DllImport(_guardDll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
|
||||
private static extern void FlGuardedInject(uint targetPid, string dllPath, out FlGuardResult result);
|
||||
|
||||
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
|
||||
[DllImport(_guardDll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
|
||||
private static extern void FlGuardedInjectWhenReady(uint targetPid, string dllPath, uint timeoutMs,
|
||||
out FlGuardResult result);
|
||||
|
||||
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
|
||||
[DllImport(_guardDll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
|
||||
private static extern void FlStaticPreScan(string gameDirectory, out FlGuardResult result);
|
||||
@@ -128,6 +133,20 @@ public sealed class NativeAntiCheatGuard : IAntiCheatGuard
|
||||
}, ct);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask<AntiCheatVerdict> GuardedInjectWhenReadyAsync(int targetPid, string payloadPath, int timeoutMs,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(payloadPath);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(timeoutMs);
|
||||
return RunAsync(() =>
|
||||
{
|
||||
FlGuardedInjectWhenReady(checked((uint)targetPid), payloadPath, checked((uint)timeoutMs),
|
||||
out FlGuardResult r);
|
||||
return AntiCheatVerdict.FromNative(r.Reason, r.Family, r.Signal);
|
||||
}, ct);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask<AntiCheatVerdict> PreScanGameDirectoryAsync(string gameDirectory,
|
||||
CancellationToken ct = default)
|
||||
|
||||
@@ -583,8 +583,15 @@ public unsafe struct FlWriterState
|
||||
/// </summary>
|
||||
public ushort EarlyStopFamily;
|
||||
|
||||
/// <summary>Must be zero; room for additive fields.</summary>
|
||||
public fixed uint Reserved[1];
|
||||
/// <summary>
|
||||
/// DXGI's count of presents the first hooked chain had completed before this hook saw one — how many
|
||||
/// presents ran unhooked, launch mode's own cost meter. <see cref="DxgiPresentsBeforeHookNotRead"/> (all
|
||||
/// bits set) means the hook never saw a present.
|
||||
/// </summary>
|
||||
public uint DxgiPresentsBeforeHook;
|
||||
|
||||
/// <summary>The value <see cref="DxgiPresentsBeforeHook"/> carries until the first hooked present.</summary>
|
||||
public const uint DxgiPresentsBeforeHookNotRead = 0xFFFFFFFF;
|
||||
|
||||
// WHY THE COUNTERS ARE PUBLISHED AT 1 Hz AND NOT ACCUMULATED HERE PER FRAME: this struct is
|
||||
// region 2, which the Overlay writes on the present path, and the regions are separate cache lines
|
||||
|
||||
@@ -152,6 +152,19 @@ enum class Reason : std::uint8_t {
|
||||
kConsentMissing,
|
||||
kPreviouslyBlocked,
|
||||
|
||||
// LAUNCH MODE (P1 item 2; 20_OPEN_QUESTIONS §S1 / §S13(c)): the guard was asked
|
||||
// to inject AS SOON AS the target had mapped a presentation runtime, and it
|
||||
// never did. A CREATE_SUSPENDED target has loaded nothing and
|
||||
// EnumProcessModulesEx fails against it with ERROR_PARTIAL_COPY (§S1, measured),
|
||||
// so launch mode cannot be create -> guard -> inject -> resume. It is create ->
|
||||
// resume -> POLL until dxgi+d3d11/d3d12, opengl32 or vulkan-1 is mapped -> the
|
||||
// full guard -> inject. These two are the poll's own ends: the process exited
|
||||
// first (a launcher that spawned the real game and quit -- the Agent's election,
|
||||
// P2 -- or a crash), or the budget ran out with no runtime mapped (a 2D title, or
|
||||
// a launcher still sitting on its window). Nothing was injected in either case.
|
||||
kLaunchTargetExited,
|
||||
kLaunchNoPresentationRuntime,
|
||||
|
||||
// NOT A REASON. The count, so appending above it updates the exported
|
||||
// FlGuardReasonCount by construction.
|
||||
//
|
||||
@@ -408,6 +421,18 @@ struct Sources {
|
||||
// a way into a game process that never consulted a single genuine signal.
|
||||
[[nodiscard]] Verdict GuardedInject(std::uint32_t targetPid, const wchar_t* dllPath) noexcept;
|
||||
|
||||
// LAUNCH MODE. Poll `targetPid` -- every 50 ms, up to `timeoutMs` -- until it has
|
||||
// mapped a presentation runtime (dxgi.dll with d3d11.dll or d3d12.dll, or
|
||||
// opengl32.dll, or vulkan-1.dll: the earliest externally observable moment at which
|
||||
// a swapchain can exist), then run GuardedInject in full. The poll reads module
|
||||
// names through the same seam the module scan uses and matches NOTHING against the
|
||||
// blocklist: it decides WHEN the guard runs, never WHETHER it passes. A target that
|
||||
// exits first, or never maps a runtime inside the budget, is refused with
|
||||
// kLaunchTargetExited / kLaunchNoPresentationRuntime and nothing is injected.
|
||||
// 04_CAPTURE §Launch mode; 20_OPEN_QUESTIONS §S1 / §S13(c).
|
||||
[[nodiscard]] Verdict GuardedInjectWhenReady(std::uint32_t targetPid, const wchar_t* dllPath,
|
||||
std::uint32_t timeoutMs) noexcept;
|
||||
|
||||
// Evaluate the guard WITHOUT injecting. Exists for the 30 s in-session re-scan
|
||||
// (19_SAFETY §During a session), which must reach a verdict on a process it is
|
||||
// already inside and has nothing to inject. Deliberately cannot be used to
|
||||
@@ -430,6 +455,8 @@ struct Sources {
|
||||
[[nodiscard]] Verdict EvaluateWithSources(std::uint32_t targetPid, const Sources& sources) noexcept;
|
||||
[[nodiscard]] Verdict GuardedInjectWithSources(std::uint32_t targetPid, const wchar_t* dllPath,
|
||||
const Sources& sources) noexcept;
|
||||
[[nodiscard]] Verdict GuardedInjectWhenReadyWithSources(std::uint32_t targetPid, const wchar_t* dllPath,
|
||||
std::uint32_t timeoutMs, const Sources& sources) noexcept;
|
||||
#endif
|
||||
|
||||
// Human-readable reason, for logs and for mapping to resx keys.
|
||||
|
||||
@@ -55,6 +55,17 @@ FL_GUARD_ABI void FlGuardEvaluate(std::uint32_t targetPid, FlGuardResult* out);
|
||||
// in evidence — the guard collects its own.
|
||||
FL_GUARD_ABI void FlGuardedInject(std::uint32_t targetPid, const wchar_t* dllPath, FlGuardResult* out);
|
||||
|
||||
// LAUNCH MODE (P1 item 2). Wait -- polling every 50 ms, up to `timeoutMs` -- until
|
||||
// `targetPid` has mapped a presentation runtime, then run every check and inject
|
||||
// exactly as FlGuardedInject does. The wait decides WHEN the guard runs and
|
||||
// nothing about whether it passes: the poll matches no blocklist and the full scan
|
||||
// runs once the runtime is there. A target that exits first, or never maps a
|
||||
// runtime inside the budget, answers LaunchTargetExited / LaunchNoPresentationRuntime
|
||||
// with nothing injected. The caller launches and holds the process; this never
|
||||
// creates or terminates one (04_CAPTURE §Launch mode, 20_OPEN_QUESTIONS §S1).
|
||||
FL_GUARD_ABI void FlGuardedInjectWhenReady(std::uint32_t targetPid, const wchar_t* dllPath, std::uint32_t timeoutMs,
|
||||
FlGuardResult* out);
|
||||
|
||||
// Check 4 against a directory, before anything is launched (FR-2.2). ADVISORY:
|
||||
// it answers "may this game's hooking toggle be offered at all", and gates
|
||||
// nothing. The same scan runs inside FlGuardEvaluate and FlGuardedInject
|
||||
|
||||
@@ -518,6 +518,10 @@ const char* ReasonName(Reason r) noexcept {
|
||||
return "RulesMalformed";
|
||||
case Reason::kRulesIncomplete:
|
||||
return "RulesIncomplete";
|
||||
case Reason::kLaunchTargetExited:
|
||||
return "LaunchTargetExited";
|
||||
case Reason::kLaunchNoPresentationRuntime:
|
||||
return "LaunchNoPresentationRuntime";
|
||||
case Reason::kCount:
|
||||
break; // not a reason; falls through to the guard below
|
||||
}
|
||||
@@ -689,12 +693,94 @@ Verdict GuardedInjectImpl(std::uint32_t targetPid, const wchar_t* dllPath, const
|
||||
return v;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Launch mode (P1 item 2) -- WHEN the guard runs, never WHETHER it passes.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// The poll's one question: has the target mapped a presentation runtime yet? Read
|
||||
// through Sources::EnumerateModules -- the module scan's own seam -- so a test can
|
||||
// drive it and so the answer comes from the loader rather than from a guess about
|
||||
// the title. The sink looks for five system names and MATCHES NOTHING AGAINST THE
|
||||
// BLOCKLIST; the verdict is GuardedInjectImpl's, run in full once the answer is
|
||||
// yes. An enumeration that fails is "not yet" here rather than a refusal, because
|
||||
// ERROR_PARTIAL_COPY is exactly what a target still inside its loader returns
|
||||
// (§S1), and the refusal, if one is due, is the full scan's to make.
|
||||
struct RuntimeProbe {
|
||||
bool dxgi = false;
|
||||
bool d3d = false;
|
||||
bool gl = false;
|
||||
bool vk = false;
|
||||
};
|
||||
|
||||
bool RuntimeSinkFn(void* ctx, const char* name, const wchar_t*) noexcept {
|
||||
auto* p = static_cast<RuntimeProbe*>(ctx);
|
||||
if (p == nullptr || name == nullptr) {
|
||||
return false;
|
||||
}
|
||||
if (_stricmp(name, "dxgi.dll") == 0) {
|
||||
p->dxgi = true;
|
||||
} else if (_stricmp(name, "d3d11.dll") == 0 || _stricmp(name, "d3d12.dll") == 0) {
|
||||
p->d3d = true;
|
||||
} else if (_stricmp(name, "opengl32.dll") == 0) {
|
||||
p->gl = true;
|
||||
} else if (_stricmp(name, "vulkan-1.dll") == 0) {
|
||||
p->vk = true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool HasPresentationRuntime(const Sources& s, std::uint32_t pid) noexcept {
|
||||
if (s.EnumerateModules == nullptr) {
|
||||
return false;
|
||||
}
|
||||
RuntimeProbe p;
|
||||
if (s.EnumerateModules(pid, &RuntimeSinkFn, &p) == Collected::kFailed) {
|
||||
return false; // still in its loader, or unreadable -- the full scan is what refuses the latter
|
||||
}
|
||||
return (p.dxgi && p.d3d) || p.gl || p.vk;
|
||||
}
|
||||
|
||||
Verdict GuardedInjectWhenReadyImpl(std::uint32_t targetPid, const wchar_t* dllPath, std::uint32_t timeoutMs,
|
||||
const Sources& sources) noexcept {
|
||||
// SYNCHRONIZE only: this handle exists to notice an exit and for nothing else.
|
||||
HANDLE proc = OpenProcess(SYNCHRONIZE, FALSE, targetPid);
|
||||
if (proc == nullptr) {
|
||||
return Refuse(Reason::kProcessUnreadable, nullptr, "could not open the launched target to wait on it");
|
||||
}
|
||||
constexpr DWORD kPollMs = 50;
|
||||
const ULONGLONG start = GetTickCount64();
|
||||
Verdict v; // fail-closed default, like every Verdict
|
||||
for (;;) {
|
||||
if (WaitForSingleObject(proc, 0) == WAIT_OBJECT_0) {
|
||||
v = Refuse(Reason::kLaunchTargetExited, nullptr,
|
||||
"the target exited before it mapped a presentation runtime; nothing was injected");
|
||||
break;
|
||||
}
|
||||
if (HasPresentationRuntime(sources, targetPid)) {
|
||||
v = GuardedInjectImpl(targetPid, dllPath, sources);
|
||||
break;
|
||||
}
|
||||
if (GetTickCount64() - start >= timeoutMs) {
|
||||
v = Refuse(Reason::kLaunchNoPresentationRuntime, nullptr,
|
||||
"no presentation runtime was mapped within the launch budget; nothing was injected");
|
||||
break;
|
||||
}
|
||||
Sleep(kPollMs);
|
||||
}
|
||||
CloseHandle(proc);
|
||||
return v;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Verdict Evaluate(std::uint32_t targetPid) noexcept {
|
||||
return EvaluateImpl(targetPid, SystemSources());
|
||||
}
|
||||
|
||||
Verdict GuardedInjectWhenReady(std::uint32_t targetPid, const wchar_t* dllPath, std::uint32_t timeoutMs) noexcept {
|
||||
return GuardedInjectWhenReadyImpl(targetPid, dllPath, timeoutMs, SystemSources());
|
||||
}
|
||||
|
||||
Verdict GuardedInject(std::uint32_t targetPid, const wchar_t* dllPath) noexcept {
|
||||
return GuardedInjectImpl(targetPid, dllPath, SystemSources());
|
||||
}
|
||||
@@ -707,6 +793,11 @@ Verdict EvaluateWithSources(std::uint32_t targetPid, const Sources& sources) noe
|
||||
Verdict GuardedInjectWithSources(std::uint32_t targetPid, const wchar_t* dllPath, const Sources& sources) noexcept {
|
||||
return GuardedInjectImpl(targetPid, dllPath, sources);
|
||||
}
|
||||
|
||||
Verdict GuardedInjectWhenReadyWithSources(std::uint32_t targetPid, const wchar_t* dllPath, std::uint32_t timeoutMs,
|
||||
const Sources& sources) noexcept {
|
||||
return GuardedInjectWhenReadyImpl(targetPid, dllPath, timeoutMs, sources);
|
||||
}
|
||||
#endif
|
||||
|
||||
} // namespace fl::guard
|
||||
@@ -40,6 +40,14 @@ void FlGuardedInject(std::uint32_t targetPid, const wchar_t* dllPath, FlGuardRes
|
||||
Fill(out, fl::guard::GuardedInject(targetPid, dllPath));
|
||||
}
|
||||
|
||||
void FlGuardedInjectWhenReady(std::uint32_t targetPid, const wchar_t* dllPath, std::uint32_t timeoutMs,
|
||||
FlGuardResult* out) {
|
||||
if (!Usable(out)) {
|
||||
return;
|
||||
}
|
||||
Fill(out, fl::guard::GuardedInjectWhenReady(targetPid, dllPath, timeoutMs));
|
||||
}
|
||||
|
||||
void FlStaticPreScan(const wchar_t* gameDirectory, FlGuardResult* out) {
|
||||
if (!Usable(out)) {
|
||||
return;
|
||||
|
||||
@@ -949,6 +949,9 @@ std::atomic<uint32_t> g_slTagCensus{0};
|
||||
// watchdog-published, monotonic.
|
||||
std::atomic<uint32_t> g_dxgiUnseen{0};
|
||||
std::atomic<uint32_t> g_dxgiSamples{0};
|
||||
// Whether FlWriterState::dxgiPresentsBeforeHook has been written: once, at the first
|
||||
// hooked present, whichever chain it lands on.
|
||||
std::atomic<bool> g_dxgiBeforeHookPublished{false};
|
||||
|
||||
// A PRESENT THIS HOOK SAW AND DECLINED TO RECORD IS NOT ONE IT NEVER SAW. While a
|
||||
// session is paused (MayObserve false) the title keeps presenting and DXGI keeps
|
||||
@@ -2194,6 +2197,12 @@ void RecordPresent(IDXGISwapChain* sc, UINT syncInterval, UINT flags) noexcept {
|
||||
g_dxgiUnseen.fetch_add(delta - 1u, std::memory_order_relaxed);
|
||||
dxgiUnseenHere = fl::slseen::SaturateToByte(delta - 1u);
|
||||
}
|
||||
} else if (!slot->haveDxgiCount && g_state != nullptr &&
|
||||
!g_dxgiBeforeHookPublished.exchange(true, std::memory_order_relaxed)) {
|
||||
// The FIRST hooked present: DXGI's count is the presents that ran before
|
||||
// this hook was in (fl_shm.h §dxgiPresentsBeforeHook). One store, once.
|
||||
std::atomic_ref<uint32_t> before{g_state->dxgiPresentsBeforeHook};
|
||||
before.store(dxgiCount, std::memory_order_relaxed);
|
||||
}
|
||||
slot->lastDxgiCount = dxgiCount;
|
||||
slot->dxgiEpoch = epoch;
|
||||
@@ -2750,6 +2759,16 @@ DWORD WINAPI InitThread(LPVOID) noexcept {
|
||||
|
||||
std::atomic_ref<uint32_t> status{g_state->status};
|
||||
|
||||
// "Not read" until the first hooked present, so a title that never presents is
|
||||
// distinguishable from one whose first present the hook was in for. BEFORE the
|
||||
// present hooks go in: a title presenting every 8 ms had its first hooked present
|
||||
// between the install and a store placed after it, and the sentinel overwrote the
|
||||
// measurement (caught by ctest fl_guard [launch] on the first run).
|
||||
{
|
||||
std::atomic_ref<uint32_t> before{g_state->dxgiPresentsBeforeHook};
|
||||
before.store(0xFFFFFFFFu, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
if (MH_Initialize() != MH_OK || !InstallPresentHooks()) {
|
||||
// Hooking failed, so nothing will ever be recorded. Staying at INIT says
|
||||
// exactly that; READY would be a claim about a capture side that does not
|
||||
|
||||
@@ -731,7 +731,16 @@ struct alignas(64) FlWriterState {
|
||||
// FL_STATUS_STOPPED_BLOCKLISTED on the next present or watchdog wake.
|
||||
uint16_t earlyStopFamily; // @58
|
||||
|
||||
uint32_t reserved[1]; // @60..63 must be zero; room for additive fields
|
||||
// PRESENTS BEFORE THE FIRST HOOKED ONE (2026-09-06, P1 item 2 -- launch mode's
|
||||
// own cost meter; 20_OPEN_QUESTIONS §S1 / §S13(c)). IDXGISwapChain::GetLastPresentCount
|
||||
// as read at the FIRST present this hook saw, on the first chain it saw: DXGI's
|
||||
// count of presents that chain had completed before we were there. 0 means the hook
|
||||
// was in before the title's first present on that chain; N means N presents ran
|
||||
// unhooked, which is the number §S1 said nobody had. 0xFFFFFFFF = not read (set at
|
||||
// init; a title that never presents keeps it). Took the LAST reserved word --
|
||||
// additive, no layout bump -- and the writer state now has NO slack: the next
|
||||
// additive field is a layout bump.
|
||||
uint32_t dxgiPresentsBeforeHook; // @60
|
||||
|
||||
// NOTE: there is deliberately no droppedRecords here. The writer has no
|
||||
// reader index and cannot know whether the slot it overwrites was ever
|
||||
@@ -941,7 +950,7 @@ static_assert(offsetof(FlWriterState, dxgiPresentsUnseen) == 48);
|
||||
static_assert(offsetof(FlWriterState, dxgiPresentSamples) == 52);
|
||||
static_assert(offsetof(FlWriterState, loaderSignals) == 56);
|
||||
static_assert(offsetof(FlWriterState, earlyStopFamily) == 58);
|
||||
static_assert(offsetof(FlWriterState, reserved) == 60);
|
||||
static_assert(offsetof(FlWriterState, dxgiPresentsBeforeHook) == 60);
|
||||
|
||||
static_assert(offsetof(FlControlBlock, pauseRequested) == 0);
|
||||
static_assert(offsetof(FlControlBlock, unhookRequested) == 4);
|
||||
|
||||
@@ -101,8 +101,15 @@ struct Fake {
|
||||
// keeps its meaning and only the tests that care about identity pay for it.
|
||||
std::vector<std::string> modules;
|
||||
std::map<std::uint32_t, std::vector<std::string>> modulesByPid;
|
||||
std::map<std::uint32_t, Collected> moduleResultByPid;
|
||||
Collected moduleResult = Collected::kOk;
|
||||
// Launch mode's fixture: after `moduleCallsBeforeLate` enumerations have answered
|
||||
// with `modules`, every later one answers with `modulesLate` (when non-empty).
|
||||
// The poll runs on the caller's thread, so a call count is what "later" means
|
||||
// and no second thread has to write into this struct.
|
||||
std::vector<std::string> modulesLate;
|
||||
int moduleCallsBeforeLate = 0;
|
||||
int moduleCalls = 0;
|
||||
std::map<std::uint32_t, Collected> moduleResultByPid;
|
||||
Collected moduleResult = Collected::kOk;
|
||||
|
||||
// Check 3's evidence. Defaults to a name no blocklist entry matches, so every
|
||||
// pre-existing case keeps its meaning: check 3 runs, looks, and allows.
|
||||
@@ -193,8 +200,10 @@ std::wstring FakeModulePath(const std::string& name) {
|
||||
}
|
||||
|
||||
Collected FakeEnumModules(std::uint32_t pid, ModuleSink sink, void* ctx) {
|
||||
const int call = g.moduleCalls++;
|
||||
const auto it = g.modulesByPid.find(pid);
|
||||
const auto& list = (it != g.modulesByPid.end()) ? it->second : g.modules;
|
||||
const bool late = !g.modulesLate.empty() && call >= g.moduleCallsBeforeLate;
|
||||
const auto& list = (it != g.modulesByPid.end()) ? it->second : (late ? g.modulesLate : g.modules);
|
||||
for (const auto& m : list) {
|
||||
const std::wstring path = FakeModulePath(m);
|
||||
const bool pathless = g.pathlessModules.count(m) != 0;
|
||||
@@ -2032,6 +2041,124 @@ TEST_CASE("the LoadLibrary detour stops the Overlay by itself when an anti-cheat
|
||||
DeleteFileW(copy.c_str());
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// P1 item 2 -- launch mode as "inject late" (20_OPEN_QUESTIONS §S1 / §S13(c)):
|
||||
// the poll decides WHEN the guard runs, never WHETHER it passes.
|
||||
// ===========================================================================
|
||||
TEST_CASE("launch mode injects the moment a presentation runtime is mapped, and not one poll before",
|
||||
"[guard][inject][launch]") {
|
||||
Child child;
|
||||
REQUIRE(StartHarness(child));
|
||||
|
||||
ResetFake();
|
||||
g.modules = {"kernel32.dll"}; // a target still in its loader: no runtime yet
|
||||
g.modulesLate = {"kernel32.dll", "dxgi.dll", "d3d11.dll"};
|
||||
g.moduleCallsBeforeLate = 6; // the seventh poll (~300 ms) is the first that sees it
|
||||
g.scanSet = {child.pi.dwProcessId};
|
||||
|
||||
const ULONGLONG t0 = GetTickCount64();
|
||||
const Verdict v = GuardedInjectWhenReadyWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, 10000, FakeSources());
|
||||
const ULONGLONG waited = GetTickCount64() - t0;
|
||||
INFO("reason " << ReasonName(v.reason) << " signal=" << v.signal << " waited " << waited << " ms, polls "
|
||||
<< g.moduleCalls);
|
||||
REQUIRE(v.Allowed());
|
||||
CHECK(g.moduleCalls >= 7); // it really waited for the runtime rather than injecting on sight
|
||||
CHECK(waited >= 250);
|
||||
CHECK(waited < 3000);
|
||||
CHECK(TargetHasModule(child.pi.dwProcessId, L"FrameLedger.Overlay.dll"));
|
||||
}
|
||||
|
||||
TEST_CASE("launch mode: a target that exits before mapping a runtime is refused and nothing is injected",
|
||||
"[guard][inject][launch]") {
|
||||
Child child;
|
||||
std::wstring cmd = std::wstring(L"\"") + FL_HARNESS_EXE + L"\" --hold 1";
|
||||
STARTUPINFOW si{};
|
||||
si.cb = sizeof(si);
|
||||
REQUIRE(CreateProcessW(FL_HARNESS_EXE, cmd.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si,
|
||||
&child.pi));
|
||||
|
||||
ResetFake();
|
||||
g.modules = {"kernel32.dll"}; // never a runtime
|
||||
g.scanSet = {child.pi.dwProcessId};
|
||||
|
||||
const Verdict v = GuardedInjectWhenReadyWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, 20000, FakeSources());
|
||||
INFO("reason " << ReasonName(v.reason) << " signal=" << v.signal);
|
||||
CHECK(v.reason == Reason::kLaunchTargetExited);
|
||||
CHECK_FALSE(v.Allowed());
|
||||
}
|
||||
|
||||
TEST_CASE("launch mode: no presentation runtime inside the budget refuses, naming the budget's end",
|
||||
"[guard][inject][launch]") {
|
||||
Child child;
|
||||
REQUIRE(StartHarness(child));
|
||||
|
||||
ResetFake();
|
||||
g.modules = {"kernel32.dll"};
|
||||
g.scanSet = {child.pi.dwProcessId};
|
||||
|
||||
const ULONGLONG t0 = GetTickCount64();
|
||||
const Verdict v = GuardedInjectWhenReadyWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, 400, FakeSources());
|
||||
const ULONGLONG waited = GetTickCount64() - t0;
|
||||
INFO("reason " << ReasonName(v.reason) << " waited " << waited << " ms");
|
||||
CHECK(v.reason == Reason::kLaunchNoPresentationRuntime);
|
||||
CHECK(waited >= 400);
|
||||
CHECK(waited < 2500);
|
||||
CHECK_FALSE(TargetHasModule(child.pi.dwProcessId, L"FrameLedger.Overlay.dll"));
|
||||
}
|
||||
|
||||
TEST_CASE("launch mode: the poll matches no blocklist, so anti-cheat mapped beside the runtime is the FULL scan's "
|
||||
"refusal, and nothing is injected",
|
||||
"[guard][inject][launch]") {
|
||||
Child child;
|
||||
REQUIRE(StartHarness(child));
|
||||
|
||||
ResetFake();
|
||||
g.modules = {"kernel32.dll"};
|
||||
g.modulesLate = {"kernel32.dll", "EasyAntiCheat_EOS.dll", "dxgi.dll", "d3d12.dll"};
|
||||
g.moduleCallsBeforeLate = 2;
|
||||
g.scanSet = {child.pi.dwProcessId};
|
||||
|
||||
const Verdict v = GuardedInjectWhenReadyWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, 10000, FakeSources());
|
||||
INFO("reason " << ReasonName(v.reason) << " family=" << v.family << " signal=" << v.signal);
|
||||
CHECK(v.reason == Reason::kBlockedModule);
|
||||
CHECK(std::string(v.signal) == "EasyAntiCheat_EOS.dll");
|
||||
CHECK_FALSE(TargetHasModule(child.pi.dwProcessId, L"FrameLedger.Overlay.dll"));
|
||||
}
|
||||
|
||||
TEST_CASE("launch mode against the real harness through the real module seam: injected once dxgi maps, and the "
|
||||
"writer says how many presents ran unhooked",
|
||||
"[guard][inject][shm][launch]") {
|
||||
// The harness creates its device at startup and presents every 8 ms; the seam is
|
||||
// the real EnumProcessModulesEx. What the writer reports afterwards is exactly the
|
||||
// number 20_OPEN_QUESTIONS §S1 said nobody had: presents completed on the chain
|
||||
// before the hook was in. Here that is however many the harness managed between
|
||||
// its first present and our injection -- a measurement, not a target.
|
||||
Child child;
|
||||
REQUIRE(StartHarness(child, L"--real --hold-presenting 12"));
|
||||
|
||||
ResetFake();
|
||||
g.scanSet = {child.pi.dwProcessId};
|
||||
const ULONGLONG t0 = GetTickCount64();
|
||||
const Verdict v =
|
||||
GuardedInjectWhenReadyWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, 10000, RealModulesAndSigner());
|
||||
const ULONGLONG waited = GetTickCount64() - t0;
|
||||
INFO("reason " << ReasonName(v.reason) << " signal=" << v.signal << " waited " << waited << " ms");
|
||||
REQUIRE(v.Allowed());
|
||||
CHECK(waited < 2000); // the runtime was already there: one poll, then the full guard
|
||||
|
||||
MappedRing r;
|
||||
REQUIRE(OpenRingFor(child.pi.dwProcessId, r));
|
||||
for (int i = 0; i < 60 && r.st->writeIndex == 0; ++i) {
|
||||
++r.ctl->guardTicks;
|
||||
Sleep(50);
|
||||
}
|
||||
REQUIRE(r.st->writeIndex > 0);
|
||||
const uint32_t before = r.st->dxgiPresentsBeforeHook;
|
||||
INFO("presents before the first hooked present: " << before);
|
||||
CHECK(before != 0xFFFFFFFFu); // read at the first hooked present
|
||||
CHECK(before < 5000); // the harness ran ~1 s at ~120/s before we were in; not a bound on a title
|
||||
}
|
||||
|
||||
TEST_CASE("the injected Overlay records real presents into the ring", "[guard][inject][shm]") {
|
||||
// The end-to-end claim the whole hook layer exists for, against a target that
|
||||
// is PRESENTING WHILE WE INJECT. --hold cannot be used here: it presents 240
|
||||
|
||||
@@ -68,7 +68,7 @@ int main() {
|
||||
Field("dxgiPresentSamples", offsetof(FlWriterState, dxgiPresentSamples), sizeof(uint32_t));
|
||||
Field("loaderSignals", offsetof(FlWriterState, loaderSignals), sizeof(uint16_t));
|
||||
Field("earlyStopFamily", offsetof(FlWriterState, earlyStopFamily), sizeof(uint16_t));
|
||||
Field("reserved", offsetof(FlWriterState, reserved), sizeof(uint32_t) * 1, true);
|
||||
Field("dxgiPresentsBeforeHook", offsetof(FlWriterState, dxgiPresentsBeforeHook), sizeof(uint32_t), true);
|
||||
std::printf(" ] },\n");
|
||||
|
||||
std::printf(" \"FlControlBlock\": { \"size\": %zu, \"fields\": [\n", sizeof(FlControlBlock));
|
||||
|
||||
@@ -32,6 +32,13 @@ public sealed class HookRequestFromConsentTests
|
||||
return ValueTask.FromResult(AntiCheatVerdict.Allowed());
|
||||
}
|
||||
|
||||
public ValueTask<AntiCheatVerdict> GuardedInjectWhenReadyAsync(int targetPid, string payloadPath,
|
||||
int timeoutMs, CancellationToken ct = default)
|
||||
{
|
||||
InjectCalls++;
|
||||
return ValueTask.FromResult(AntiCheatVerdict.Allowed());
|
||||
}
|
||||
|
||||
public ValueTask<AntiCheatVerdict> PreScanGameDirectoryAsync(string gameDirectory,
|
||||
CancellationToken ct = default) => ValueTask.FromResult(AntiCheatVerdict.Allowed());
|
||||
}
|
||||
@@ -160,6 +167,10 @@ public sealed class HookRequestFromConsentTests
|
||||
public void ThePayloadPathIsRequired()
|
||||
{
|
||||
Action act = () => HookRequest.FromConsent(Consented(), OnDisk, 1, " ");
|
||||
Action negativeWait = () => HookRequest.FromConsent(Consented(), OnDisk, 1, _payload, waitForPresentationRuntimeMs: -1);
|
||||
negativeWait.Should().Throw<ArgumentOutOfRangeException>("a negative budget is a mistake, never attach mode");
|
||||
HookRequest.FromConsent(Consented(), OnDisk, 1, _payload).WaitForPresentationRuntimeMs
|
||||
.Should().Be(0, "attach mode is the default: inject now");
|
||||
act.Should().Throw<ArgumentException>();
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,10 @@ public sealed class GuardSupervisorTests
|
||||
CancellationToken ct = default) =>
|
||||
ValueTask.FromResult(AntiCheatVerdict.Allowed());
|
||||
|
||||
public ValueTask<AntiCheatVerdict> GuardedInjectWhenReadyAsync(int targetPid, string payloadPath,
|
||||
int timeoutMs, CancellationToken ct = default) =>
|
||||
throw new InvalidOperationException("the supervisor must not launch or inject");
|
||||
|
||||
// The supervisor never asks check 4 anything: it re-evaluates a process
|
||||
// it is already inside, and the pre-scan is the pre-launch question.
|
||||
public ValueTask<AntiCheatVerdict> PreScanGameDirectoryAsync(string gameDirectory,
|
||||
|
||||
@@ -23,6 +23,18 @@ public sealed class HookedCaptureGateTests
|
||||
return ValueTask.FromResult(Next);
|
||||
}
|
||||
|
||||
public int WhenReadyCalls { get; private set; }
|
||||
|
||||
public int WhenReadyWaitMs { get; private set; }
|
||||
|
||||
public ValueTask<AntiCheatVerdict> GuardedInjectWhenReadyAsync(int targetPid, string payloadPath,
|
||||
int timeoutMs, CancellationToken ct = default)
|
||||
{
|
||||
WhenReadyCalls++;
|
||||
WhenReadyWaitMs = timeoutMs;
|
||||
return ValueTask.FromResult(Next);
|
||||
}
|
||||
|
||||
public int PreScanCalls { get; private set; }
|
||||
|
||||
public ValueTask<AntiCheatVerdict> PreScanGameDirectoryAsync(string gameDirectory,
|
||||
@@ -47,14 +59,16 @@ public sealed class HookedCaptureGateTests
|
||||
private static HookRequest Request(
|
||||
bool enabled = true,
|
||||
ConsentProvenance provenance = ConsentProvenance.UnshippedHostOperator,
|
||||
string? blocked = null) =>
|
||||
string? blocked = null,
|
||||
int waitMs = 0) =>
|
||||
HookRequest.FromConsent(
|
||||
GameConsentRecord.Stored(
|
||||
OnDisk, enabled, DateTimeOffset.UnixEpoch, provenance, "unshipped-host-operator/1",
|
||||
blocked, preScanUnverified: false, updatedAt: DateTimeOffset.UnixEpoch),
|
||||
OnDisk,
|
||||
targetPid: 1234,
|
||||
payloadPath: @"C:\FrameLedger\FrameLedger.Overlay.dll");
|
||||
payloadPath: @"C:\FrameLedger\FrameLedger.Overlay.dll",
|
||||
waitMs);
|
||||
|
||||
[Fact]
|
||||
public async Task AnEnabledConsentedGame_ReachesTheGuard()
|
||||
@@ -66,6 +80,37 @@ public sealed class HookedCaptureGateTests
|
||||
|
||||
v.IsAllowed.Should().BeTrue();
|
||||
guard.InjectCalls.Should().Be(1);
|
||||
guard.WhenReadyCalls.Should().Be(0, "attach mode injects now, not after a wait");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ALaunchModeRequest_ReachesTheGuardThroughTheWaitingEntryOnly()
|
||||
{
|
||||
// P1 item 2. The consent checks are the same three, in the same order; the only thing a wait
|
||||
// changes is WHICH guard entry runs the full scan -- and it must never be both.
|
||||
RecordingGuard guard = new();
|
||||
HookedCaptureGate gate = new(guard);
|
||||
|
||||
AntiCheatVerdict v = await gate.StartAsync(Request(waitMs: 60_000), TestContext.Current.CancellationToken);
|
||||
|
||||
v.IsAllowed.Should().BeTrue();
|
||||
guard.WhenReadyCalls.Should().Be(1);
|
||||
guard.WhenReadyWaitMs.Should().Be(60_000);
|
||||
guard.InjectCalls.Should().Be(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ALaunchModeRequestWithoutConsent_ReachesNeitherEntry()
|
||||
{
|
||||
RecordingGuard guard = new();
|
||||
HookedCaptureGate gate = new(guard);
|
||||
|
||||
AntiCheatVerdict v = await gate.StartAsync(Request(provenance: ConsentProvenance.NotRecorded, waitMs: 60_000),
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
v.Reason.Should().Be(AntiCheatRefusalReason.ConsentMissing);
|
||||
guard.WhenReadyCalls.Should().Be(0);
|
||||
guard.InjectCalls.Should().Be(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Application.AntiCheat;
|
||||
using FrameLedger.Application.Consent;
|
||||
using FrameLedger.CaptureHost.Capture;
|
||||
using FrameLedger.CaptureHost.Consent;
|
||||
using FrameLedger.Domain.AntiCheat;
|
||||
using FrameLedger.Domain.Consent;
|
||||
using FrameLedger.Infrastructure.Ipc;
|
||||
using FrameLedger.Shared;
|
||||
|
||||
namespace FrameLedger.CaptureHost.Tests.Capture;
|
||||
|
||||
/// <summary>
|
||||
/// Launch mode's ordering (P1 item 2): the host starts what it was asked to start, consent is the gate's
|
||||
/// and only the gate's, and the guard is reached through the WAITING entry with the budget, never the plain one.
|
||||
/// </summary>
|
||||
public sealed class CaptureLoopLaunchTests : IDisposable
|
||||
{
|
||||
private readonly string _dir = Path.Combine(Path.GetTempPath(), "fl-launch-" + Guid.NewGuid().ToString("N"));
|
||||
|
||||
private const string _exe = @"C:\Games\Title\game.exe";
|
||||
private const int _pid = 5151;
|
||||
|
||||
private static ExecutableFingerprint Fingerprint =>
|
||||
new() { ExePath = _exe, SizeBytes = 90_000, MtimeUnixMs = 1_700_000_000_000 };
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(_dir, recursive: true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class WaitingGuard : IAntiCheatGuard
|
||||
{
|
||||
public int InjectCalls { get; private set; }
|
||||
|
||||
public int WhenReadyCalls { get; private set; }
|
||||
|
||||
public int WhenReadyWaitMs { get; private set; }
|
||||
|
||||
public AntiCheatVerdict Verdict { get; set; } = AntiCheatVerdict.Allowed();
|
||||
|
||||
public ValueTask<AntiCheatVerdict> EvaluateAsync(int targetPid, CancellationToken ct = default) =>
|
||||
ValueTask.FromResult(AntiCheatVerdict.Allowed());
|
||||
|
||||
public ValueTask<AntiCheatVerdict> GuardedInjectAsync(int targetPid, string payloadPath,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
InjectCalls++;
|
||||
return ValueTask.FromResult(Verdict);
|
||||
}
|
||||
|
||||
public ValueTask<AntiCheatVerdict> GuardedInjectWhenReadyAsync(int targetPid, string payloadPath,
|
||||
int timeoutMs, CancellationToken ct = default)
|
||||
{
|
||||
WhenReadyCalls++;
|
||||
WhenReadyWaitMs = timeoutMs;
|
||||
return ValueTask.FromResult(Verdict);
|
||||
}
|
||||
|
||||
public ValueTask<AntiCheatVerdict> PreScanGameDirectoryAsync(string gameDirectory,
|
||||
CancellationToken ct = default) => ValueTask.FromResult(AntiCheatVerdict.Allowed());
|
||||
}
|
||||
|
||||
private sealed class NoLiveness : ITargetLiveness
|
||||
{
|
||||
public bool HasExited => false;
|
||||
|
||||
public bool IsForeground => true;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class NeverResolves : ITargetResolver
|
||||
{
|
||||
public int? Resolve(string normalisedExePath, out SessionEndReason reason)
|
||||
{
|
||||
reason = SessionEndReason.TargetNotRunning;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<FileGameConsentStore> StoreAsync(bool consented)
|
||||
{
|
||||
var store = new FileGameConsentStore(Path.Combine(_dir, "games.json"));
|
||||
if (consented)
|
||||
{
|
||||
await store.RecordOperatorAcknowledgementAsync(new OperatorAcknowledgement
|
||||
{
|
||||
Fingerprint = Fingerprint,
|
||||
DisclosureVersion = OperatorDisclosure.Version,
|
||||
AcknowledgedAt = DateTimeOffset.UnixEpoch,
|
||||
}, TestContext.Current.CancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return store;
|
||||
}
|
||||
|
||||
private static CaptureLoop Loop(IGameConsentStore store, WaitingGuard guard,
|
||||
Func<string, string, (int Pid, ITargetLiveness Alive)?>? launcher) =>
|
||||
new(store,
|
||||
new HookedCaptureGate(guard),
|
||||
guard,
|
||||
new NeverResolves(),
|
||||
_ => new NoLiveness(),
|
||||
_ => (null, ShmAttachRefusal.BuildIdMismatch),
|
||||
new CaptureOptions
|
||||
{
|
||||
DrainInterval = TimeSpan.FromMilliseconds(1),
|
||||
ScanInterval = TimeSpan.FromMilliseconds(5),
|
||||
AttachBudget = TimeSpan.FromMilliseconds(20),
|
||||
MaxDuration = TimeSpan.FromMilliseconds(50),
|
||||
LaunchWaitBudget = TimeSpan.FromSeconds(42),
|
||||
},
|
||||
launcher: launcher);
|
||||
|
||||
[Fact]
|
||||
public async Task AConsentedLaunchReachesTheGuardThroughTheWaitingEntryWithTheBudget()
|
||||
{
|
||||
var guard = new WaitingGuard();
|
||||
string? launchedWith = null;
|
||||
CaptureLoop loop = Loop(await StoreAsync(consented: true), guard, (exe, args) =>
|
||||
{
|
||||
launchedWith = exe + " | " + args;
|
||||
return (_pid, new NoLiveness());
|
||||
});
|
||||
|
||||
CaptureResult r = await loop.RunLaunchedAsync(_exe, Fingerprint, "payload.dll", "--real --hold 3",
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
launchedWith.Should().Be(_exe + " | --real --hold 3");
|
||||
guard.WhenReadyCalls.Should().Be(1);
|
||||
guard.WhenReadyWaitMs.Should().Be(42_000, "the loop's budget is what the guard polls against");
|
||||
guard.InjectCalls.Should().Be(0, "launch mode never takes the plain entry, which would inject on sight");
|
||||
r.LaunchWait.Should().NotBeNull("the report prints how long the guard waited before it injected");
|
||||
r.Reason.Should().Be(SessionEndReason.AttachRefused, "this fixture has no ring; the guard's answer is what is under test");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ALaunchThatCannotStartIsItsOwnReasonAndTheGuardIsNeverAsked()
|
||||
{
|
||||
var guard = new WaitingGuard();
|
||||
CaptureLoop loop = Loop(await StoreAsync(consented: true), guard, (_, _) => null);
|
||||
|
||||
CaptureResult r = await loop.RunLaunchedAsync(_exe, Fingerprint, "payload.dll", string.Empty,
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
r.Reason.Should().Be(SessionEndReason.LaunchCannotStart);
|
||||
guard.WhenReadyCalls.Should().Be(0);
|
||||
guard.InjectCalls.Should().Be(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WithoutConsentTheProcessIsStillStartedAndTheGateRefusesBeforeTheGuard()
|
||||
{
|
||||
// The operator asked for the game to start; consent decides whether FrameLedger goes INTO it, and
|
||||
// that decision is the gate's alone — reached one process later than in attach mode, never skipped.
|
||||
var guard = new WaitingGuard();
|
||||
int launches = 0;
|
||||
CaptureLoop loop = Loop(await StoreAsync(consented: false), guard, (_, _) =>
|
||||
{
|
||||
launches++;
|
||||
return (_pid, new NoLiveness());
|
||||
});
|
||||
|
||||
CaptureResult r = await loop.RunLaunchedAsync(_exe, Fingerprint, "payload.dll", string.Empty,
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
launches.Should().Be(1);
|
||||
r.Reason.Should().Be(SessionEndReason.RefusedHookNotEnabled);
|
||||
guard.WhenReadyCalls.Should().Be(0);
|
||||
guard.InjectCalls.Should().Be(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheGuardsTwoLaunchRefusalsAreTheirOwnSessionEndReasons()
|
||||
{
|
||||
foreach ((AntiCheatRefusalReason native, SessionEndReason expected) in new[]
|
||||
{
|
||||
(AntiCheatRefusalReason.LaunchTargetExited, SessionEndReason.LaunchTargetExited),
|
||||
(AntiCheatRefusalReason.LaunchNoPresentationRuntime, SessionEndReason.LaunchNoPresentationRuntime),
|
||||
})
|
||||
{
|
||||
var guard = new WaitingGuard { Verdict = AntiCheatVerdict.Refused(native, string.Empty, "poll ended") };
|
||||
CaptureLoop loop = Loop(await StoreAsync(consented: true), guard, (_, _) => (_pid, new NoLiveness()));
|
||||
|
||||
CaptureResult r = await loop.RunLaunchedAsync(_exe, Fingerprint, "payload.dll", string.Empty,
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
r.Reason.Should().Be(expected);
|
||||
r.Verdict.Reason.Should().Be(native);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ALoopBuiltWithoutALauncherCannotLaunch()
|
||||
{
|
||||
var guard = new WaitingGuard();
|
||||
CaptureLoop loop = Loop(await StoreAsync(consented: true), guard, launcher: null);
|
||||
|
||||
Func<Task> act = () => loop.RunLaunchedAsync(_exe, Fingerprint, "payload.dll", string.Empty,
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
await act.Should().ThrowAsync<InvalidOperationException>();
|
||||
}
|
||||
}
|
||||
@@ -74,6 +74,13 @@ public sealed class CaptureLoopTests : IDisposable
|
||||
return ValueTask.FromResult(Verdict);
|
||||
}
|
||||
|
||||
public ValueTask<AntiCheatVerdict> GuardedInjectWhenReadyAsync(int targetPid, string payloadPath,
|
||||
int timeoutMs, CancellationToken ct = default)
|
||||
{
|
||||
InjectCalls++;
|
||||
return ValueTask.FromResult(Verdict);
|
||||
}
|
||||
|
||||
public ValueTask<AntiCheatVerdict> PreScanGameDirectoryAsync(string gameDirectory,
|
||||
CancellationToken ct = default) => ValueTask.FromResult(AntiCheatVerdict.Allowed());
|
||||
}
|
||||
|
||||
@@ -248,6 +248,32 @@ public sealed class CaptureHostEndToEndTests : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LaunchModeStartsTheHarnessItselfAndReportsWhatRanUnhooked()
|
||||
{
|
||||
// P1 item 2, from OUTSIDE the process: the host starts the consented harness, the guard waits
|
||||
// for dxgi to map and injects, and the report carries the two numbers 20_OPEN_QUESTIONS §S1
|
||||
// deferred on -- the wait, and DXGI's count of presents before the first hooked one.
|
||||
var store = new FileGameConsentStore(HostConsentFile);
|
||||
ExecutableFingerprint fingerprint = FrameLedger.Infrastructure.Io.ExecutableIdentity.Read(ConsentedExecutable)!.Value;
|
||||
(await store.RecordOperatorAcknowledgementAsync(new OperatorAcknowledgement
|
||||
{
|
||||
Fingerprint = fingerprint,
|
||||
DisclosureVersion = OperatorDisclosure.Version,
|
||||
AcknowledgedAt = DateTimeOffset.UtcNow,
|
||||
}, TestContext.Current.CancellationToken)).Should().Be(ConsentWriteOutcome.Written);
|
||||
|
||||
using Process host = StartHost("launch", "--exe", ConsentedExecutable, "--args", "--real --hold-presenting 6",
|
||||
"--seconds", "4");
|
||||
string stdout = await host.StandardOutput.ReadToEndAsync(TestContext.Current.CancellationToken);
|
||||
await host.WaitForExitAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
stdout.Should().Contain("launch: the guard injected", "the wait is printed, because it is the number §S1 lacked");
|
||||
stdout.Should().Contain("presents before the first hooked present:");
|
||||
stdout.Should().NotContain("not read", "the harness presents, so the first hooked present happened");
|
||||
host.ExitCode.Should().Be(0, stdout);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WhenTheTargetExitsTheHostStopsAndSaysWhy()
|
||||
{
|
||||
|
||||
@@ -24,7 +24,24 @@ public sealed class CommandLineSurfaceTests
|
||||
// property that separates it from the --pid / --payload / --force / --yes this host
|
||||
// refuses. It exists because CaptureLoop honoured MaxDuration and nothing could set
|
||||
// it, so a bounded real-title measurement was impossible to take.
|
||||
CommandLine.AcceptedOptions.Should().BeEquivalentTo(["--exe", "--seconds"]);
|
||||
// THREE since P1 item 2: `--args` is the command line the launched GAME receives. It names
|
||||
// nothing about injection -- payload, target and evidence are exactly what they were -- so it
|
||||
// has the same property `--seconds` has: it cannot widen what is injected or skip a check.
|
||||
CommandLine.AcceptedOptions.Should().BeEquivalentTo(["--exe", "--seconds", "--args"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LaunchTakesTheExecutableItsArgumentsAndABound()
|
||||
{
|
||||
CommandLine parsed = CommandLine.Parse(["launch", "--exe", @"C:\a\game.exe", "--args", "--real --hold 3", "--seconds", "9"]);
|
||||
|
||||
parsed.Error.Should().BeNull();
|
||||
parsed.Verb.Should().Be(Verb.Launch);
|
||||
parsed.ExePath.Should().Be(@"C:\a\game.exe");
|
||||
parsed.Arguments.Should().Be("--real --hold 3", "handed to the game verbatim");
|
||||
parsed.Seconds.Should().Be(9);
|
||||
CommandLine.Parse(["launch"]).Error.Should().NotBeNull("--exe is required: there is nothing else to launch");
|
||||
CommandLine.Parse(["launch", "--exe", "g.exe"]).Arguments.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
using FluentAssertions;
|
||||
using FrameLedger.CaptureHost.Consume;
|
||||
using FrameLedger.Shared;
|
||||
|
||||
namespace FrameLedger.CaptureHost.Tests.Consume;
|
||||
|
||||
public sealed class LaunchNoteTests
|
||||
{
|
||||
[Fact]
|
||||
public void AnAttachSessionPrintsOnlyTheBeforeHookCount()
|
||||
{
|
||||
List<string> lines = [.. LaunchNote.Describe(null, new FlWriterState { DxgiPresentsBeforeHook = 137 })];
|
||||
|
||||
lines.Should().ContainSingle().Which.Should().Contain("presents before the first hooked present: 137");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ALaunchedSessionPrintsTheWaitFirst()
|
||||
{
|
||||
List<string> lines = [.. LaunchNote.Describe(TimeSpan.FromMilliseconds(842), new FlWriterState { DxgiPresentsBeforeHook = 0 })];
|
||||
|
||||
lines.Should().HaveCount(2);
|
||||
lines[0].Should().Contain("injected 842 ms after the process was started");
|
||||
lines[1].Should().Contain("presents before the first hooked present: 0");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheNotReadSentinelIsNamedAndNeverPrintedAsANumber()
|
||||
{
|
||||
var writer = new FlWriterState { DxgiPresentsBeforeHook = FlWriterState.DxgiPresentsBeforeHookNotRead };
|
||||
|
||||
List<string> lines = [.. LaunchNote.Describe(null, writer)];
|
||||
|
||||
lines.Should().ContainSingle().Which.Should().Contain("not read").And.NotContain("4294967295");
|
||||
}
|
||||
}
|
||||
@@ -71,14 +71,18 @@ public sealed class NoSecondMatcherTests
|
||||
// seam out of everything that ships.
|
||||
MethodInfo[] methods = typeof(IAntiCheatGuard).GetMethods();
|
||||
|
||||
// Raised from 2 to 3 as a reviewed act when the static pre-scan landed.
|
||||
// Raised from 2 to 3 as a reviewed act when the static pre-scan landed,
|
||||
// and from 3 to 4 when launch mode's WAITING entry landed (P1 item 2):
|
||||
// GuardedInjectWhenReadyAsync takes a pid, a path and a budget in
|
||||
// milliseconds -- primitives, as the loop below insists -- and the budget
|
||||
// decides only WHEN the guard's full scan runs, never what it sees.
|
||||
//
|
||||
// The alternative was a second port, which would have kept this number
|
||||
// at 2 while the new surface grew somewhere this test never looks — the
|
||||
// count would have gone on passing precisely because the thing it
|
||||
// guards had moved. A number that has to be edited deliberately is the
|
||||
// point of it.
|
||||
methods.Should().HaveCount(3);
|
||||
methods.Should().HaveCount(4);
|
||||
|
||||
// Stronger than the count, and it survives the port growing: every
|
||||
// parameter must be a primitive the caller cannot smuggle evidence
|
||||
|
||||
Reference in new issue
Block a user