fix(safety): the guard gated the target and nothing gated the payload (#29)

FlGuardedInject is an exported C ABI on the shipped FrameLedger.Guard.dll.
Between that boundary and CreateRemoteThread the only thing ever asked of
`dllPath` was GetFileAttributesW — exists, and is not a directory. Measured
through the shipped binary with no test seam: C:\Windows\System32\winmm.dll
into a live process, verdict Allow, module present afterwards.

That is the standalone injector §S9 refused to ship, re-exported with a
published calling convention. Under 19_SAFETY's own threat model it is the
worst possible shape — an anti-cheat vendor auditing the binary finds a
general-purpose loader, and the rational response is to block FrameLedger.

Not a wrong assertion; a missing one, behind a scope sentence that read as
though it covered everything. fl_guard_abi.h says "there is no entry point
here that skips a check", which is true, and about the target. Every existing
test passed FL_OVERLAY_DLL as the payload and the one negative case used a
MISSING path, so the whole matrix exercised "is there a file there" and
nothing exercised "whose file is it".

The guard now establishes payload identity before it injects: the payload must
resolve — through symlinks, 8.3 names and junctions, via
GetFinalPathNameByHandleW — into the directory the guard's own code was loaded
from, compared by file id. Equality, not containment, reusing §S18's
OwnDirectory/SameDirectory, which until now existed only to RELAX this gate.
New seam Sources::PayloadIsOurOwn, new Reason::kPayloadNotOurs. A null seam and
a seam that cannot answer refuse the same way.

What it does not cover, stated rather than implied:

  - It proves WHERE THE BYTES LIVE, not that they are FrameLedger.Overlay.dll.
    Whoever can write to that directory can already replace the guard itself,
    and we ship unsigned, so it is exactly as strong as the install location.
  - It is not atomic with the load; the remote LoadLibraryW re-resolves.
  - Absent stays kInjectionFailed. A damaged install and a misuse of the ABI
    need opposite responses, so the existence test runs BEFORE the identity
    test — otherwise "not ours" absorbs "not there", since the identity seam
    works by opening the file.

Nothing shipped FrameLedger.Overlay.dll anywhere, and that had to be fixed in
the same change or the constraint would have been a gate that could not pass:
the native build left the payload in FrameLedger.Overlay/ while the guard built
into FrameLedger.Injector/, and dotnet publish produced an out/app with the
Agent, the guard and the rules seed but no payload at all.
FrameLedger.Overlay.targets now ships it beside the Agent (not the App, which
has no injector), and src/native/tests stages its own copy beside fl_guard_test
— through a target that depends on the Overlay rather than a POST_BUILD step,
so a rebuilt Overlay cannot leave a stale payload under test.

Proven red, green, and recovering. Three canaries — the refusal removed, a seam
failure treated as ours, a null seam allowed through — each turn fl_guard red.
The accepted direction is asserted separately, because a gate that refuses every
payload carries as much information as one that accepts every payload: the
staged Overlay must pass, the SAME FILE staged elsewhere must not, and the test
refuses to run at all if those two paths ever resolve to one directory.

Still open, recorded as §S22(b): the §S18 self-exemption asks about the scan-set
PROCESS, not about the module that matched. Any FrameLedger-family host that
does not sit beside FrameLedger.Guard.dll refuses its own injections with
SuspiciousUnsigned, naming our own DLL — measured, same binary, only the
caller's directory differing. Re-keying it on the matched module is strictly
narrower and fixes launch mode, but NameSink carries base names only, so the
module path never reaches the decision point; it needs the module seam widened
and the first-hit latch restructured, per §S19(b).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5 authored and GitHub committed 2026-08-04 21:28:41 +07:00
1 parent 71f4e33e01
commit 1c1602857c
12 files changed
+698 -2

No files matched your search

+36
View File
@@ -11,7 +11,43 @@ GitHub release body, so a missing section means an empty release note.
## [Unreleased]
### Fixed
- **The anti-cheat guard gated the target process and nothing gated the payload**
(`20_OPEN_QUESTIONS` §S22). `FlGuardedInject` — an exported C ABI on the shipped
`FrameLedger.Guard.dll` — asked only whether a file existed at the caller's
`dllPath`. Measured through the shipped binary with no test seam:
`C:\Windows\System32\winmm.dll` loaded into a live process, verdict `Allow`.
That is the standalone injector §S9 refused to ship, re-exported with a
published calling convention.
- The guard now requires the payload to resolve — through symlinks, 8.3 names
and junctions — into the directory its own code was loaded from, compared by
file id, and refuses with a new `PayloadNotOurs` reason otherwise. A null
seam and a seam that cannot answer refuse the same way.
- **It proves where the bytes live, not what is in them.** Anyone who can write
to that directory can already replace `FrameLedger.Guard.dll` itself, and the
project ships unsigned, so the check is exactly as strong as the install
location. It is also not atomic with the load.
- `kInjectionFailed` still covers a payload that is simply absent: a damaged
install and a misuse of the ABI need opposite responses.
- **Nothing shipped `FrameLedger.Overlay.dll` anywhere**, which had to be fixed
in the same change or the new constraint would have been a gate that could
not pass. `dotnet publish` produced an `out/app` with the Agent, the guard and
the rules seed and no payload at all.
- Proven red, green and recovering: three canaries each turn `fl_guard` red, and
the accepted direction is asserted separately — the staged Overlay passes, the
same file staged elsewhere does not, and the test refuses to run if those two
paths ever resolve to one directory.
### Known issues
- **The §S18 self-exemption asks about the process, not the module that matched**
(`20_OPEN_QUESTIONS` §S22(b)). Any FrameLedger-family host that does not sit
beside `FrameLedger.Guard.dll` refuses its own injections with
`SuspiciousUnsigned`, naming our own DLL as the signal — measured, same binary,
only the caller's directory differing. The Agent works because
`FrameLedger.Guard.targets` puts the DLL beside it. Until this is re-keyed, an
injection host must be installed beside the guard. The fix needs the module seam
widened to carry paths and the first-hit latch restructured, which §S19(b)
already describes; it is not the one-line change it looks like.
- **The anti-cheat guard's fuzzy "unknown-but-suspicious" tier matches benign
system DLLs, and one of its rules can never fire** (`20_OPEN_QUESTIONS` §S19).
Re-measured unelevated on Windows 11 26300: 290 processes, 0 inaccessible,
+56
View File
@@ -0,0 +1,56 @@
<Project>
<!--
Ships FrameLedger.Overlay.dll beside the importing project's output.
§S22. The guard now refuses a payload that does not resolve into the
directory the guard's own code was loaded from — so the Overlay must LAND
there, or the constraint is a gate that cannot pass and the product refuses
its own injection.
Nothing copied the Overlay anywhere before this file existed. It was built
into build/native/x64-release/FrameLedger.Overlay/ and left there, so
`dotnet publish` produced an out/app containing the Agent, the guard and the
rules seed but no payload at all. That was invisible while the Agent had no
injector control, and it would have surfaced as an unexplained
kPayloadNotOurs the first time one was wired — which is the diagnosis §S22
warns is easy to misread as the guard being over-eager.
Imported by FrameLedger.Agent only, and for the same reason
FrameLedger.Guard.targets is: the Agent is the sole host of the guard (§S18
blocker 3, ratified). FrameLedger.App has no injector and must not carry a
payload it cannot use.
NOT imported by the native test suite. src/native/tests/CMakeLists.txt stages
its own copy beside fl_guard_test, because there the guard is compiled INTO
the test binary and "the guard's own directory" is the test's directory.
UNEXERCISED TODAY, stated rather than implied: the Agent builds no host, no
watcher and no injector control (Program.cs seeds the rules file and exits),
so nothing in a published build injects anything yet. This places the payload
where the gate will look when that lands; it does not make injection work.
-->
<PropertyGroup>
<FlNativeOverlayDir>$(MSBuildThisFileDirectory)build\native\x64-release\FrameLedger.Overlay\</FlNativeOverlayDir>
</PropertyGroup>
<ItemGroup>
<None Include="$(FlNativeOverlayDir)FrameLedger.Overlay.dll"
Condition="Exists('$(FlNativeOverlayDir)FrameLedger.Overlay.dll')">
<Link>FrameLedger.Overlay.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<!--
Warn rather than fail, exactly as FrameLedger.Guard.targets does: build.ps1
runs the native build first, so by the time this evaluates the DLL exists. A
hard error would make `dotnet build` on a fresh clone fail for a reason that
has nothing to do with the managed code.
-->
<Target Name="FlWarnOnMissingOverlay" AfterTargets="Build"
Condition="!Exists('$(FlNativeOverlayDir)FrameLedger.Overlay.dll')">
<Warning Text="FrameLedger.Overlay.dll was not found at $(FlNativeOverlayDir). Run build.ps1 native first; the guard refuses a payload that is not beside it (§S22)." />
</Target>
</Project>
+35
View File
@@ -277,6 +277,41 @@ Implemented in `FrameLedger.Injector` and reached from managed code through a th
Any check failing ⇒ **injection is refused**. The UI shows which check fired and offers Tier-2 (ETW) capture instead, which requires no injection — but does require an elevated Agent, so the offer must state that plainly and fall through to Tier 3 rather than appearing to succeed and recording nothing (`04_CAPTURE` §Frame source abstraction).
### The payload is checked too, and for a long time it was not
Checks 1–4 all answer *"is it safe to be inside this process"*. **None of them
asks what we are putting there**, and until 2026-08-04 nothing did: the exported
`FlGuardedInject` took a caller-supplied `dllPath` and asked only whether a file
existed at it. Measured through the shipped `FrameLedger.Guard.dll` with no test
seam, `C:\Windows\System32\winmm.dll` went into a live process and the verdict
was `Allow`. That is the standalone injector `20_OPEN_QUESTIONS` §S9 refused to
ship, re-exported with a published calling convention — the worst possible shape
under this document's own threat model, because an anti-cheat vendor auditing the
binary would find a general-purpose loader and the rational response is to block
FrameLedger outright.
So there is now a fifth thing the guard establishes before it injects: **the
payload resolves into the same directory the guard's own code was loaded from**,
compared by file id, through symlinks and 8.3 names and junctions. Refusal is
`Reason::kPayloadNotOurs`. A seam that cannot answer refuses, exactly as
everywhere else here.
It is deliberately **not** listed as "check 5". Checks 1–4 are numbered in
`05_DETECTION`, in the managed mirror and in the reason codes, and renumbering a
gate is how stored values start meaning something else. It is a precondition of
the injection primitive, not a fifth question about the title.
**What this does not buy**, stated here rather than left to be assumed:
- It proves *where the bytes live*, not that they are `FrameLedger.Overlay.dll`.
Whoever can write to that directory can already replace the guard itself, so
the check is exactly as strong as the install location — and the project ships
unsigned (CLAUDE.md rule 9), so nothing attests to that directory's contents.
- It is not atomic with the load: the remote `LoadLibraryW` resolves the path
again. Same trust base.
- **Absent** is still `kInjectionFailed`, not `kPayloadNotOurs`. A damaged install
and a misuse of the ABI are different problems and must not share a reason.
> There is no override. No hidden setting, no config-file flag, no CLI switch, no "advanced users" escape hatch. If a user disagrees with a specific entry, the path is a GitHub issue against the rules file, reviewed in public — not a local bypass.
### The floor data cannot remove
+127
View File
@@ -1083,6 +1083,133 @@ through.
more likely than a browser to have both already. Recorded rather than waved
away; delay-loading would not help, since the layer resolves the path at init.
### S22 ◐ · The guard gated the TARGET and nothing gated the PAYLOAD — **(a) closed, (b) open**
Found 2026-08-04 by a completeness critic over the next-phase plan, in code that
had been merged for days and passed every gate in the repository. Recorded in
full because it is the second *fail-open* found in the guard, and because the
reason it stayed invisible is instructive: every reader, every doc and every
review framed the guard as a gate whose subject is **the process we are entering**.
Nobody asked what we were putting there.
#### (a) ✅ Any DLL, into any process without anti-cheat — **closed**
`FlGuardedInject(targetPid, dllPath, out)` is an exported C ABI on the shipped
`FrameLedger.Guard.dll`. Between that boundary and `CreateRemoteThread` the only
thing ever asked of `dllPath` was `GetFileAttributesW` — *exists, and is not a
directory*. Measured through the shipped DLL with no test seam:
`C:\Windows\System32\winmm.dll` into a live process, verdict `reason=0 (Allow)`,
module present afterwards.
That is **§S9's user-runnable injector**, which this project refused to ship,
re-shipped as a documented export with a published calling convention. §S9's own
reasoning names the hazard exactly and then stops one step short — it rejected a
standalone injector as "a path into a game process **that the guard did not stand
in front of**", and `fl_guard_abi.h` concluded "there is no entry point here that
skips a check". Both true, and both about the target.
Note what the shape is, because it is this file's recurring one: not a wrong
assertion, a **missing** one, behind a scope sentence that reads as though it
covered everything. Every existing test passed `FL_OVERLAY_DLL` as the payload,
and the one negative case used a *missing* path — so the whole matrix exercised
"is there a file there" and nothing exercised "whose file is it".
**Closed by a new seam and a new reason.** `Sources::PayloadIsOurOwn` resolves
the payload — through symlinks, 8.3 names and junctions, via
`GetFinalPathNameByHandleW` — and requires its directory to be the one the
guard's own code was loaded from, compared by file id. Equality, not containment,
reusing §S18's `OwnDirectory`/`SameDirectory`, which until now existed only to
*relax* this gate. A null seam, a seam that cannot answer, and "not ours" are one
outcome: `Reason::kPayloadNotOurs`.
**What it does NOT cover, with the boundary stated rather than implied:**
- It is not proof the payload is `FrameLedger.Overlay.dll`. It is proof of
**where the bytes live**. Anyone who can write to that directory can already
replace `FrameLedger.Guard.dll` itself — the same trust base §S18 rests on, and
the project ships unsigned (CLAUDE.md rule 9), so there is no integrity check on
that directory's contents.
- It is not atomic with the load. The remote `LoadLibraryW` re-resolves the path,
so a file swapped between check and call is not caught. Same trust base again.
- **Absent** and **foreign** are kept distinct on purpose: a damaged install and a
misuse of the ABI need opposite responses, so a path naming no file still
returns `kInjectionFailed`. The existence test therefore runs *before* the
identity test — otherwise "not ours" absorbs "not there", since the identity
seam works by opening the file. Caught by the pre-existing test that asserts
exactly this distinction.
**A layout bug came with it, and it had to be fixed in the same change or the
gate could not pass.** Nothing in this repository copied `FrameLedger.Overlay.dll`
anywhere. The native build left it in `FrameLedger.Overlay/` while the guard
built into `FrameLedger.Injector/`, and `dotnet publish` produced an `out/app`
with the Agent, the guard and the rules seed **but no payload at all**. Invisible
while the Agent had no injector control; it would have surfaced as an
unexplained `kPayloadNotOurs` the first time one was wired.
`FrameLedger.Overlay.targets` now ships it beside the Agent, and
`src/native/tests` stages its own copy beside `fl_guard_test` — where the guard
is compiled *into* the test binary, so "the guard's directory" is the test's.
Proven red **and** green, and proven to recover: three canaries (the refusal
removed, a seam failure treated as ours, a null seam allowed through) each turn
`fl_guard` red. The green direction is asserted separately, because a gate that
refuses every payload carries as much information as one that accepts every
payload — the staged Overlay must be accepted, the *same file staged elsewhere*
must not, and the test refuses to run at all if those two paths ever resolve to
one directory.
> **The canary harness lied again, and the mechanism is worth writing down.**
> Restoring the file from a backup with `Copy-Item` preserved the backup's
> **old** timestamp, so ninja judged the source up to date and never rebuilt —
> leaving the last canary's binary in place while the tree read clean. It then
> segfaulted on the exact case that canary had disarmed, which is a symptom that
> invites diagnosing the code instead of the harness. Restores must stamp the
> file. That is the fourth time this session's own verification tooling was the
> broken thing.
#### (b) ◐ The §S18 exemption asks about the PROCESS, not the module — **open**
Same probe, same binary, same target; only the caller's directory differs:
| Caller's location | Verdict |
|---|---|
| Beside `FrameLedger.Guard.dll` | `Allow` |
| Anywhere else | `SuspiciousUnsigned`, family `unknown`, signal `FrameLedger.Guard.dll` |
`SuppressFragmentTier` delegates to `ProcessIsOurOwn`, which compares the
scan-set **process image** directory to `OwnDirectory()`. The module that matched
is *our own guard DLL* — it contains the fragment `guard` — but the exemption
never asks about it. So any FrameLedger-family host that does not sit beside the
guard poisons its own scan set. The Agent works by accident:
`FrameLedger.Guard.targets` copies the DLL beside `FrameLedger.Agent.exe`.
This matters now rather than in the abstract, because every throwaway
inject-host proposal puts the tool in its own build directory — the arrangement
measured RED — and a launch-mode host is by construction in the §S16 scan set.
Whoever hits it will read the refusal as the fuzzy tier being over-eager (§S19
says so, in writing) and go rewriting a safety gate instead of moving a file.
**The right fix is to key the exemption on the MATCHED MODULE** — a scan-set
process is exempt when the module that tripped the fragment tier is ours by file
id. Strictly narrower than today's process-level exemption, and it fixes launch
mode. It also removes a real over-reach nobody had costed: today a genuinely
foreign suspicious module loaded into a FrameLedger process — an AppInit DLL, an
AV user-mode hook, an IME — is suppressed along with our own.
**Deliberately not done in the same change, because it is not the size the plan
assumed.** `NameSink` is `bool(*)(void*, const char*)` fed by
`GetModuleBaseNameA`, so the module's **path never reaches the decision point** —
the constraint §S19(b) already recorded. Keying on the module therefore needs the
module seam widened to carry paths, which is a new row in the fail-closed matrix
and changes every fake in `guard_test.cpp`. Worse, it forces the restructure
§S19(b) predicted: `NameSinkFn` latches the FIRST fragment-matching module and
discards the rest, so per-module suppression turns that latch into a **fail-open
reachable by load order** — our guard DLL matches first, is suppressed, and a
foreign suspicious module loaded afterwards is never recorded. The detection half
has to be restructured, not extended.
Until it lands: an inject host must be installed beside `FrameLedger.Guard.dll`,
and that requirement belongs in a test rather than in this paragraph.
### S14 ◐ · Pre-injection check 3 is **unwired**, and has no "cannot determine" state
Found 2026-08-02 while hardening the rules toolchain. `19_SAFETY` §Pre-injection
+2
View File
@@ -10,6 +10,8 @@ To measure what a game is *actually* doing — its real render resolution, which
None of this information is obtainable from outside the process, which is why the software works this way.
**Only FrameLedger's own component is ever loaded.** The injection path refuses any library that does not come from FrameLedger's own installation directory, and there is no setting that changes this. Be aware of the limit of that promise: it establishes where the file came from, not what is in it, and FrameLedger is distributed unsigned — so anyone able to write to your FrameLedger installation could alter what gets loaded. Install it somewhere only you can write to, and verify the published SHA-256 checksums.
**What it observes:** arguments the game passes to graphics APIs we intercept (presentation, upscaling, ray tracing, pipeline creation) and video-memory usage reported by the graphics runtime.
**What it never does:** read or write the game's memory outside those API arguments; read save files, input, chat, or network traffic; modify game behavior; hide itself from any security software; or install a kernel driver of its own.
@@ -39,4 +39,11 @@
<!-- The seed the Agent installs to the product location on first run (§S20). -->
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Rules.targets" />
<!--
The payload, which must land in the SAME directory as the guard: §S22 makes
the guard refuse a DLL that does not resolve there. Nothing shipped the
Overlay anywhere before this import existed.
-->
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Overlay.targets" />
</Project>
@@ -111,4 +111,25 @@ public enum AntiCheatRefusalReason
/// a failure the user could act on.
/// </remarks>
TargetIsWow64 = 19,
/// <summary>
/// The DLL the caller asked us to inject is not one of FrameLedger's own
/// binaries.
/// </summary>
/// <remarks>
/// <para>
/// Every other value here is about the target process or the machine. This
/// one is about the <em>payload</em>, and it exists because the gate had a
/// hole of exactly that shape (<c>20_OPEN_QUESTIONS</c> §S22): the exported
/// <c>FlGuardedInject</c> took a caller-supplied path and asked only whether
/// a file was there, so the shipped guard was a documented "load any DLL
/// into any x64 process without anti-cheat" primitive.
/// </para>
/// <para>
/// Nothing was attempted when this is returned, which is why it is not a
/// flavour of <see cref="InjectionFailed"/>. It means the payload does not
/// resolve into the directory the guard itself was loaded from.
/// </para>
/// </remarks>
PayloadNotOurs = 20,
}
@@ -107,6 +107,21 @@ enum class Reason : std::uint8_t {
// Tier 2 rather than reporting a failure the user could act on.
kTargetIsWow64,
// The PAYLOAD is not ours (§S22).
//
// Every other reason in this enum is about the TARGET or about the machine.
// This one is about the DLL we were asked to load, and it exists because the
// gate had a hole exactly that shape: FlGuardedInject takes a caller-supplied
// path and, until this reason existed, the only thing asked of it was
// GetFileAttributesW — "exists and is not a directory". A caller could hand
// the shipped, exported guard any DLL on the machine and have it loaded into
// any x64 process that happened to carry no anti-cheat.
//
// Refusing here is not a failed injection: nothing was attempted. It is the
// guard declining, which is why it is a Reason and not a kInjectionFailed
// variant — a mislabelled reason is a wrong answer for whoever has to fix it.
kPayloadNotOurs,
// NOT A REASON. The count, so appending above it updates the exported
// FlGuardReasonCount by construction.
//
@@ -218,6 +233,40 @@ struct Sources {
// QueryService is: "no" and "could not tell" are different answers and the
// caller has to be able to distinguish them.
Collected (*ProcessIsOurOwn)(std::uint32_t pid, bool* isOurs) = nullptr;
// §S22 — is the DLL we were asked to inject one of OUR OWN binaries?
//
// The guard gated the target and nothing gated the payload. Every check
// above answers "is it safe to be inside this process"; none of them asks
// "and what are we putting there". `dllPath` arrives from the caller across
// the C ABI, so without this the shipped FrameLedger.Guard.dll exports a
// documented "load an arbitrary DLL into an arbitrary x64 process" primitive
// — which is §S9's user-runnable injector, the exact thing this project
// refused to ship, wearing a different shape.
//
// "Ours" means: the payload resolves — through symlinks, 8.3 names and
// junctions — into the SAME DIRECTORY the guard's own code was loaded from,
// compared by file id, exactly as §S18 compares directories. Equality, not
// containment, for the same reason §S18 chose it.
//
// kFailed and a null seam both mean REFUSE. This is the ordinary polarity of
// every other seam here, not the inverted one ProcessIsOurOwn needs: there,
// "could not tell" must not SUPPRESS a refusal; here, "could not tell" must
// not AUTHORISE a load.
//
// What it does NOT cover, stated here rather than discovered later:
// - It is not proof the payload is FrameLedger.Overlay.dll. It is proof of
// WHERE the bytes live. Anyone who can write to that directory can
// already replace FrameLedger.Guard.dll itself, which
// NativeAntiCheatGuard calls a worse outcome than any other DLL-hijack in
// this application — so the check is exactly as strong as the install
// location and no stronger. The project ships unsigned (CLAUDE.md rule
// 9), so there is no integrity check on that directory's contents.
// - It is not atomic with the load. The remote LoadLibraryW re-resolves the
// path, so a file swapped between the check and the call is not caught.
// Same trust base as above: that swap needs write access we have already
// conceded.
Collected (*PayloadIsOurOwn)(const wchar_t* dllPath, bool* isOurs) = nullptr;
};
// The real Windows implementations. Behaviour measured in spike-notes.md §1;
@@ -44,6 +44,17 @@ Reason InjectViaLoadLibrary(std::uint32_t pid, const wchar_t* dllPath) noexcept
// The payload must exist and be a file before we ask another process to
// load it. A missing DLL turns into a remote LoadLibraryW that fails inside
// the game rather than an error we can report here.
//
// THIS IS NOT THE PAYLOAD CHECK. It answers "is there a file there", which
// for a long time was the ONLY thing ever asked of `dllPath` — and that is
// how the shipped, exported guard came to load any DLL on the machine into
// any process without anti-cheat (§S22). Identity is established by
// Sources::PayloadIsOurOwn in GuardedInjectImpl, which also runs this same
// test first so that "absent" and "not ours" get different reasons.
//
// Kept here anyway, and deliberately redundant: this function is the
// primitive, and it must not depend on its one caller having asked the right
// questions. If it ever acquires a second caller, the check travels with it.
const DWORD attrs = GetFileAttributesW(dllPath);
if (attrs == INVALID_FILE_ATTRIBUTES || (attrs & FILE_ATTRIBUTE_DIRECTORY) != 0) {
return Reason::kInjectionFailed;
@@ -414,6 +425,8 @@ const char* ReasonName(Reason r) noexcept {
return "InjectionFailed";
case Reason::kTargetIsWow64:
return "TargetIsWow64";
case Reason::kPayloadNotOurs:
return "PayloadNotOurs";
case Reason::kSuspiciousUnsigned:
return "SuspiciousUnsigned";
case Reason::kRulesUnreadable:
@@ -488,6 +501,45 @@ Verdict GuardedInjectImpl(std::uint32_t targetPid, const wchar_t* dllPath, const
// answer for whoever has to fix it.
return Refuse(Reason::kInjectionFailed, nullptr, "no payload path");
}
// ABSENT and FOREIGN are different problems, and collapsing them would be
// this project's own recurring defect. A damaged install and a misuse of the
// exported ABI call for opposite responses, which is exactly why
// kInjectionFailed was split out in the first place.
//
// It has to come BEFORE the identity check, because "not ours" would
// otherwise absorb "not there": the identity seam works by opening the file,
// so a path naming nothing comes back kFailed and would be reported as a
// foreign payload. The primitive keeps its own copy of this test as a last
// line of defence; this one exists to name the right cause.
const DWORD payloadAttrs = GetFileAttributesW(dllPath);
if (payloadAttrs == INVALID_FILE_ATTRIBUTES || (payloadAttrs & FILE_ATTRIBUTE_DIRECTORY) != 0) {
return Refuse(Reason::kInjectionFailed, nullptr, "the payload path does not name a file");
}
// §S22 — the payload, not just the target.
//
// Placed AFTER EvaluateImpl on purpose. A caller who hands a foreign payload
// at a target that is running anti-cheat must see the anti-cheat refusal:
// that is the fact that matters to the user, and it is the more permanent of
// the two. This ordering costs a full scan on a call that was going to be
// refused anyway, which is a price paid on a path nobody legitimate reaches.
//
// Every uncertainty refuses, in the ordinary direction of this file: a null
// seam, a seam that could not answer, and an answer of "not ours" are one
// outcome. Sources members default to nullptr, so forgetting to wire this
// fails towards refusing rather than towards loading.
bool payloadIsOurs = false;
if (sources.PayloadIsOurOwn == nullptr) {
return Refuse(Reason::kPayloadNotOurs, nullptr, "no payload identity source");
}
if (sources.PayloadIsOurOwn(dllPath, &payloadIsOurs) != Collected::kOk) {
return Refuse(Reason::kPayloadNotOurs, nullptr, "the payload could not be identified");
}
if (!payloadIsOurs) {
return Refuse(Reason::kPayloadNotOurs, nullptr, "the payload is not one of FrameLedger's own binaries");
}
// Injection failing is not a guard refusal — the gate passed — but it is
// also NOT an allow. Allowed() means "the DLL is loaded in the target",
// which is the only reading a caller can act on. The reason says whose
@@ -598,6 +598,65 @@ Collected EnumerateDirEntriesImpl(const wchar_t* dir, DirEntrySink sink, void* c
return truncated ? Collected::kIncomplete : Collected::kOk;
}
// §S22 — the payload identity check.
//
// Deliberately resolves the FILE and asks where it ACTUALLY is, rather than
// parsing the string it was handed. `C:\ours\..\evil\x.dll`, an 8.3 short name,
// a junction, a subst drive and a symlink under our own directory pointing
// somewhere else all name a location the string does not admit to — and the
// remote LoadLibraryW is going to resolve them, not us.
//
// Every failure returns kFailed, which the caller turns into a refusal. There is
// no branch here that answers "ours" without having opened the file.
Collected PayloadIsOurOwnImpl(const wchar_t* dllPath, bool* isOurs) noexcept {
if (isOurs == nullptr || dllPath == nullptr || dllPath[0] == L'\0') {
return Collected::kFailed;
}
*isOurs = false;
wchar_t mine[kMaxPreScanPathLen] = {};
if (!OwnDirectory(mine, kMaxPreScanPathLen)) {
return Collected::kFailed;
}
// FILE_READ_ATTRIBUTES is all GetFinalPathNameByHandleW needs, and asking
// for no more is the same discipline the module scan applies to OpenProcess.
//
// No FILE_FLAG_BACKUP_SEMANTICS, deliberately: without it this open FAILS on
// a directory, which subsumes the "exists and is not a directory" test the
// injection primitive used to do on its own. Share every mode, as every
// other reader in this file now does (§S21) — denying delete sharing here
// would make us the reason an updater could not replace our own DLL.
HANDLE h = CreateFileW(dllPath, FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (h == INVALID_HANDLE_VALUE) {
return Collected::kFailed;
}
wchar_t resolved[kMaxPreScanPathLen] = {};
const DWORD n = GetFinalPathNameByHandleW(h, resolved, static_cast<DWORD>(kMaxPreScanPathLen),
FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
CloseHandle(h);
// n >= cap means truncation, and a truncated path names a different file.
if (n == 0 || n >= kMaxPreScanPathLen) {
return Collected::kFailed;
}
wchar_t* lastSep = nullptr;
for (wchar_t* p = resolved; *p != L'\0'; ++p) {
if (*p == L'\\' || *p == L'/') {
lastSep = p;
}
}
if (lastSep == nullptr || lastSep == resolved) {
return Collected::kFailed;
}
*lastSep = L'\0';
*isOurs = SameDirectory(resolved, mine);
return Collected::kOk;
}
} // namespace
Sources SystemSources() noexcept {
@@ -610,6 +669,7 @@ Sources SystemSources() noexcept {
s.ImageDirectory = &ImageDirectoryImpl;
s.EnumerateDirEntries = &EnumerateDirEntriesImpl;
s.ProcessIsOurOwn = &ProcessIsOurOwnImpl;
s.PayloadIsOurOwn = &PayloadIsOurOwnImpl;
return s;
}
+38 -2
View File
@@ -51,11 +51,47 @@ target_compile_definitions(fl_guard_test PRIVATE FL_GUARD_TESTABLE)
# Real cross-process injection, against our own dummy D3D11 app — no game and
# no anti-cheat surface (14_TESTING §Integration tests).
#
# THE PAYLOAD IS STAGED BESIDE THE TEST BINARY, and that is load-bearing rather
# than tidiness (§S22). The guard now refuses a payload that does not resolve
# into the directory the guard's own code was loaded from, and in this target the
# guard IS the test executable — the injector sources are compiled in (above), so
# OwnDirectory() answers with the test's directory. Pointing FL_OVERLAY_DLL at
# $<TARGET_FILE:FrameLedger.Overlay> would name a sibling build directory, and
# every injection test would refuse kPayloadNotOurs. It would also stop matching
# the shipped arrangement, where 12_BUILD publishes the Agent, the guard and the
# Overlay into one out/app.
#
# Staged through a target that DEPENDS ON THE OVERLAY rather than a POST_BUILD
# step on fl_guard_test. A POST_BUILD copy only refreshes when the TEST relinks,
# so a rebuilt Overlay would leave a stale payload in place and the suite would
# keep testing the previous DLL — the stale-artifact defect 20_OPEN_QUESTIONS
# records having already shipped once.
# A plain path, not $<TARGET_FILE_DIR:fl_guard_test>: add_custom_command's OUTPUT
# may not carry a target-dependent generator expression. No target here sets
# RUNTIME_OUTPUT_DIRECTORY, so fl_guard_test lands in CMAKE_CURRENT_BINARY_DIR —
# and that assumption is not left to hold quietly. The "payload check can PASS"
# case REQUIREs that FL_OVERLAY_DLL resolves into the running binary's own
# directory, so if the two ever diverge the suite goes red instead of the staging
# silently landing somewhere the guard does not look.
set(FL_STAGED_OVERLAY "${CMAKE_CURRENT_BINARY_DIR}/FrameLedger.Overlay.dll")
add_custom_command(
OUTPUT "${FL_STAGED_OVERLAY}"
COMMAND ${CMAKE_COMMAND} -E copy_if_different "$<TARGET_FILE:FrameLedger.Overlay>" "${FL_STAGED_OVERLAY}"
DEPENDS FrameLedger.Overlay
COMMENT "Staging FrameLedger.Overlay.dll beside fl_guard_test (payload identity, §S22)"
VERBATIM
)
add_custom_target(fl_stage_overlay_payload DEPENDS "${FL_STAGED_OVERLAY}")
target_compile_definitions(fl_guard_test PRIVATE
FL_HARNESS_EXE=L"$<TARGET_FILE:hook-harness>"
FL_OVERLAY_DLL=L"$<TARGET_FILE:FrameLedger.Overlay>"
FL_OVERLAY_DLL=L"${FL_STAGED_OVERLAY}"
# The un-staged original, so a test can prove the check discriminates on
# DIRECTORY rather than on filename: same bytes, same name, wrong place.
FL_OVERLAY_DLL_ELSEWHERE=L"$<TARGET_FILE:FrameLedger.Overlay>"
)
add_dependencies(fl_guard_test hook-harness FrameLedger.Overlay)
add_dependencies(fl_guard_test hook-harness FrameLedger.Overlay fl_stage_overlay_payload)
add_test(NAME fl_guard COMMAND fl_guard_test)
+215
View File
@@ -113,6 +113,24 @@ struct Fake {
// from the fragment tier by adding this.
std::set<std::uint32_t> ourOwnPids;
Collected ourOwnResult = Collected::kOk;
// §S22 — the payload identity seam.
//
// DEFAULTS TO THE REAL IMPLEMENTATION, unlike every other member here, and
// the asymmetry is deliberate. A fake that answered "ours" by default would
// make every injection test below green whether or not the real check works
// and whether or not the payload is actually where the guard requires it —
// which is the whole subject of §S22. With kReal, the cross-process cases
// exercise PayloadIsOurOwnImpl against a real file on a real disk, so the
// CMake staging that puts the Overlay beside this binary is load-bearing:
// break it and these tests go red.
enum class Payload : std::uint8_t {
kReal, // call SystemSources().PayloadIsOurOwn
kOurs, // force "ours"
kForeign, // force "not ours"
kCannotTell, // force kFailed
};
Payload payload = Payload::kReal;
};
Fake g;
@@ -196,6 +214,22 @@ Collected FakeProcessIsOurOwn(std::uint32_t pid, bool* isOurs) {
return Collected::kOk;
}
Collected FakePayloadIsOurOwn(const wchar_t* dllPath, bool* isOurs) {
switch (g.payload) {
case Fake::Payload::kOurs:
*isOurs = true;
return Collected::kOk;
case Fake::Payload::kForeign:
*isOurs = false;
return Collected::kOk;
case Fake::Payload::kCannotTell:
return Collected::kFailed;
case Fake::Payload::kReal:
default:
return SystemSources().PayloadIsOurOwn(dllPath, isOurs);
}
}
Sources FakeSources() {
Sources s;
s.ReadRulesFile = &FakeReadRules;
@@ -206,6 +240,7 @@ Sources FakeSources() {
s.ImageDirectory = &FakeImageDirectory;
s.EnumerateDirEntries = &FakeEnumDirEntries;
s.ProcessIsOurOwn = &FakeProcessIsOurOwn;
s.PayloadIsOurOwn = &FakePayloadIsOurOwn;
return s;
}
@@ -929,6 +964,22 @@ struct Child {
}
};
// Spawn the harness and wait for its loader. Returns false if it died, which the
// caller must REQUIRE on: a dead child makes every assertion below fail for a
// reason unrelated to what is being tested, and that is exactly what happened
// the first time the injection tests were written.
bool StartHarness(Child& child) {
std::wstring cmd = std::wstring(L"\"") + FL_HARNESS_EXE + L"\" --hold 30";
STARTUPINFOW si{};
si.cb = sizeof(si);
if (!CreateProcessW(FL_HARNESS_EXE, cmd.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si,
&child.pi)) {
return false;
}
Sleep(800);
return WaitForSingleObject(child.pi.hProcess, 0) == WAIT_TIMEOUT;
}
} // namespace
TEST_CASE("the injection primitive really loads our DLL into another process", "[guard][inject]") {
@@ -1039,6 +1090,170 @@ TEST_CASE("a 32-bit target gets its own reason, not a generic failure", "[guard]
CHECK(v.reason != Reason::kInjectionFailed); // specific, not the catch-all
}
// ===========================================================================
// §S22 — the payload, not just the target.
//
// Until these existed, the ONLY thing ever asked of `dllPath` was
// GetFileAttributesW. The shipped, exported FlGuardedInject would load any DLL
// on the machine into any x64 process that happened to carry no anti-cheat —
// §S9's user-runnable injector, re-shipped as a documented C ABI.
//
// Every case here runs the REAL PayloadIsOurOwnImpl (Fake::Payload::kReal is the
// default) except the two that exist to force the seam's failure paths. Real
// files, real directories, a real child process, and the assertion that matters
// is always "and nothing was loaded".
// ===========================================================================
TEST_CASE("a payload that is not ours is refused, and nothing is loaded", "[guard][inject][payload]") {
// The measured defect, as a test. C:\Windows\System32\winmm.dll is a real,
// loadable, Microsoft-signed DLL that has nothing to do with FrameLedger —
// and before §S22 this call returned Allow and put it in the target.
Child child;
REQUIRE(StartHarness(child));
ResetFake();
g.modules = {"kernel32.dll"}; // a clean target: the payload is the only objection
g.scanSet = {child.pi.dwProcessId};
wchar_t sys[MAX_PATH]{};
REQUIRE(GetSystemDirectoryW(sys, MAX_PATH) != 0);
const std::wstring foreign = std::wstring(sys) + L"\\winmm.dll";
REQUIRE(GetFileAttributesW(foreign.c_str()) != INVALID_FILE_ATTRIBUTES); // it really is loadable
// If the harness already carries it, the assertion below proves nothing —
// "not loaded by us" and "was there all along" would look identical. Fail
// loudly rather than pass vacuously.
REQUIRE_FALSE(TargetHasModule(child.pi.dwProcessId, L"winmm.dll"));
const Verdict v = GuardedInjectWithSources(child.pi.dwProcessId, foreign.c_str(), FakeSources());
INFO("reason " << ReasonName(v.reason) << " signal=" << v.signal);
CHECK_FALSE(v.Allowed());
CHECK(v.reason == Reason::kPayloadNotOurs);
CHECK(v.family[0] == '\0'); // no anti-cheat was found; this is about us
CHECK_FALSE(TargetHasModule(child.pi.dwProcessId, L"winmm.dll"));
}
TEST_CASE("the payload check discriminates on DIRECTORY, not on filename", "[guard][inject][payload]") {
// Same file name, same bytes, wrong place. A check keyed on
// "FrameLedger.Overlay.dll" would pass this and would be defeated by any
// DLL that borrowed the name.
//
// Guarded against becoming vacuous: if the staged copy and the build output
// ever resolve to one directory there is nothing here to discriminate, and a
// test that cannot fail is worse than an absent one.
REQUIRE(std::wstring(FL_OVERLAY_DLL) != std::wstring(FL_OVERLAY_DLL_ELSEWHERE));
Child child;
REQUIRE(StartHarness(child));
ResetFake();
g.modules = {"kernel32.dll"};
g.scanSet = {child.pi.dwProcessId};
const Verdict v = GuardedInjectWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL_ELSEWHERE, FakeSources());
INFO("reason " << ReasonName(v.reason) << " signal=" << v.signal);
CHECK_FALSE(v.Allowed());
CHECK(v.reason == Reason::kPayloadNotOurs);
CHECK_FALSE(TargetHasModule(child.pi.dwProcessId, L"FrameLedger.Overlay.dll"));
}
TEST_CASE("a payload identity seam that cannot answer refuses", "[guard][inject][payload]") {
// The ordinary polarity of this file. "I could not tell whose DLL this is"
// must never be spelled the same way as "it is ours".
Child child;
REQUIRE(StartHarness(child));
ResetFake();
g.modules = {"kernel32.dll"};
g.scanSet = {child.pi.dwProcessId};
g.payload = Fake::Payload::kCannotTell;
const Verdict v = GuardedInjectWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, FakeSources());
CHECK_FALSE(v.Allowed());
CHECK(v.reason == Reason::kPayloadNotOurs);
CHECK_FALSE(TargetHasModule(child.pi.dwProcessId, L"FrameLedger.Overlay.dll"));
}
TEST_CASE("a guard wired without the payload seam refuses", "[guard][inject][payload]") {
// Sources members default to nullptr, so the failure mode of FORGETTING to
// wire this must be a refusal rather than a load. Every other seam in this
// file carries the same case for the same reason.
Child child;
REQUIRE(StartHarness(child));
ResetFake();
g.modules = {"kernel32.dll"};
g.scanSet = {child.pi.dwProcessId};
Sources s = FakeSources();
s.PayloadIsOurOwn = nullptr;
const Verdict v = GuardedInjectWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, s);
CHECK_FALSE(v.Allowed());
CHECK(v.reason == Reason::kPayloadNotOurs);
CHECK_FALSE(TargetHasModule(child.pi.dwProcessId, L"FrameLedger.Overlay.dll"));
}
TEST_CASE("a blocked TARGET outranks a foreign payload", "[guard][inject][payload]") {
// Ordering, asserted rather than left to reading order. Both objections are
// real; the user must be told the one that matters — anti-cheat is in the
// target — and not "your payload is wrong", which would send them looking at
// their FrameLedger install for a problem in the game.
ResetFake();
g.modules = {"kernel32.dll", "BEClient_x64.dll"};
g.scanSet = {GetCurrentProcessId()};
g.payload = Fake::Payload::kForeign;
const Verdict v = GuardedInjectWithSources(GetCurrentProcessId(), FL_OVERLAY_DLL, FakeSources());
CHECK_FALSE(v.Allowed());
CHECK(v.reason == Reason::kBlockedModule);
CHECK(v.reason != Reason::kPayloadNotOurs);
}
TEST_CASE("the payload check can PASS — the staged Overlay is accepted", "[guard][inject][payload]") {
// The green direction, against the real implementation. A gate that refuses
// every input carries exactly as much information as one that accepts every
// input, and this project has shipped both kinds. Asserted here without
// injecting anything: the identity seam alone, called the way the guard
// calls it.
bool ours = false;
const Collected c = SystemSources().PayloadIsOurOwn(FL_OVERLAY_DLL, &ours);
INFO("payload " << "FL_OVERLAY_DLL" << " must resolve into this binary's own directory");
REQUIRE(c == Collected::kOk);
CHECK(ours);
// ...and the same call must say NO for the same file staged elsewhere.
bool elsewhere = true;
REQUIRE(SystemSources().PayloadIsOurOwn(FL_OVERLAY_DLL_ELSEWHERE, &elsewhere) == Collected::kOk);
CHECK_FALSE(elsewhere);
// A path that names nothing cannot be answered, and must not be "ours".
bool absent = true;
CHECK(SystemSources().PayloadIsOurOwn(LR"(C:\definitely\not\here.dll)", &absent) == Collected::kFailed);
CHECK_FALSE(absent);
// A directory is not a payload. FILE_READ_ATTRIBUTES without
// FILE_FLAG_BACKUP_SEMANTICS cannot open one, which is what makes this
// fail-closed rather than a separate test we would have to remember.
wchar_t sys[MAX_PATH]{};
REQUIRE(GetSystemDirectoryW(sys, MAX_PATH) != 0);
bool dir = true;
CHECK(SystemSources().PayloadIsOurOwn(sys, &dir) == Collected::kFailed);
CHECK_FALSE(dir);
// Null and empty are the caller getting it wrong, and get the same answer.
bool n = true;
CHECK(SystemSources().PayloadIsOurOwn(nullptr, &n) == Collected::kFailed);
CHECK(SystemSources().PayloadIsOurOwn(L"", &n) == Collected::kFailed);
CHECK(SystemSources().PayloadIsOurOwn(FL_OVERLAY_DLL, nullptr) == Collected::kFailed);
}
#endif // FL_HARNESS_EXE && FL_OVERLAY_DLL
// ===========================================================================