fix(safety): the §S21 floor shipped too narrow, and is now generated from the seed (#26)

Found by the adversarial review of §S20's seeding design, and it is a correction
to work already merged.

§S21 gave the guard a compiled-in blocklist floor that a rules file may extend and
can never shrink. It carried exactly the three families the completeness check
required, kept minimal because a larger **hand-written** table would be a second
copy of the blocklist that drifts from the data.

Measured against the shipped seed, that reasoning bought **4 of 22 values, 2 of 5
groups and 0 of 5 name fragments**.

So §S21 closed *"a crafted rules file makes the guard allow everything"* and left
open *"a crafted rules file removes most of the blocklist"* — Denuvo, GameGuard,
Xigncode3, mhyprot, FACEIT, ESEA, PunkBuster, EAC's directories and services,
BattlEye's directories, Vanguard's service, and the entire fuzzy tier. The §S21
write-up read as though the floor bounded more than it did; this corrects the
record as well as the code.

The gap was tolerable only while nothing delivered a rules file to any machine.
It surfaced now because a seeder turns a repo-only defect into a **push channel**.

## Generating it removes the objection that kept it small

`tools/gen-ac-floor.ps1` emits the floor from `rules/detection-rules.json` at
build time. A table derived from the data cannot drift from it, so the floor is
now the whole shipped blocklist plus the name fragments. Output goes into the
build tree: generated code under `src/native` would be swept by clang-format, and
a generated file under version control is a copy somebody can edit independently.

`trustedSigners` is deliberately **not** floored — it is an ALLOW-widening list,
so "data may only add" has the wrong polarity there.

## It also delivers §S19(d)'s substance, without §S19(d)'s cost

A rules file with no `heuristic` block can no longer make the fuzzy tier stop
existing. §S19(d) proposed a new `ParseResult` cause, which its own text said
would make `kRulesIncomplete`'s signal a lie and drive `layer.cpp` to machine-wide
inert passthrough. A floor needs neither.

## Three consequences, each of which broke a test before it was handled

- **Dedup.** A file family identical to a floor entry is skipped, or an unmodified
  seed spends `kMaxFamilies` twice. `rules-validate.ps1` bounds the file at HALF
  the cap — the worst case of a drifted file duplicating none of the floor — and
  prints that worst case instead of the raw count.
- **Completeness is judged on what the file SUPPLIED**, not on what was stored:
  an unmodified seed is now entirely duplicate and stores nothing.
- **"Removing a family from the data stops it firing" is no longer true of a
  floored family**, which is §S21 working. That test now uses a fixture-only
  family, and a second test asserts the other direction.

## Also corrected: §S21 prescribed the wrong replace primitive

A comment on the reader and a line in the ledger both told whoever implements
§S20 to use temp-file + `MoveFileExW(MOVEFILE_REPLACE_EXISTING)`. Measured
against a handle opened exactly as the guard opens it:

    MoveFileExW(MOVEFILE_REPLACE_EXISTING)   ERROR_ACCESS_DENIED (5)
    ReplaceFileW, backup file named          succeeds

Delete sharing is necessary and nowhere near sufficient. Unifying the share modes
is still right — it is what lets `ReplaceFileW` proceed — but the named call fails
on exactly the machines where the guard is busy, and its error goes nowhere.

## Proven red, all four recovering

    generator drops 4 of the 5 groups      -> rules_budget_test 178, 234
    floor keeps 1 of 5 name fragments      -> rules_budget_test 178, 234
    kMaxFamilies below 2x the seed         -> rules-validate names the shortfall
    kMaxNameFragments below 2x             -> same, for fragments

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5 authored and GitHub committed 2026-08-04 16:31:58 +07:00
1 parent d816678209
commit 9e0bcec905
13 files changed
+656 -140

No files matched your search

+38
View File
@@ -348,6 +348,44 @@ GitHub release body, so a missing section means an empty release note.
pinned 0.9.6 package, not just the repository.
### Fixed
- **The compiled-in blocklist floor shipped too narrow, and it is now generated
from the rules file** (§S21). As first written the floor carried exactly the
three families the completeness check required, kept minimal because a larger
hand-written table would be a second copy of the blocklist that drifts from the
data. Measured against the shipped seed, that bought **4 of 22 values, 2 of 5
groups and 0 of 5 name fragments** — so §S21 closed *"a crafted rules file makes
the guard allow everything"* and left open *"a crafted rules file removes most
of the blocklist"*: Denuvo, GameGuard, Xigncode3, mhyprot, FACEIT, ESEA,
PunkBuster, EAC's directories and services, BattlEye's directories, Vanguard's
service, and the entire fuzzy tier. The write-up read as though it bounded more
than it did.
- **Generating it removes the objection that kept it small.** A table derived
from `rules/detection-rules.json` at build time cannot drift from it, so the
floor is now the whole shipped blocklist plus the name fragments.
`trustedSigners` is deliberately excluded — it is an ALLOW-widening list, so
"data may only add" has the wrong polarity there.
- **It also delivers §S19(d)'s substance** without the new `ParseResult` cause
that entry proposed, which its own text said would make `kRulesIncomplete`'s
signal a lie and drive `layer.cpp` to machine-wide inert passthrough. A file
with no `heuristic` block can no longer make the tier stop existing.
- A file family identical to a floor entry is now **deduplicated**, or an
unmodified seed would spend `kMaxFamilies` twice; `rules-validate.ps1`
therefore bounds the file at **half** the cap, the worst case of a drifted
file duplicating none of the floor, and prints that worst case rather than the
raw count. Completeness is judged on what the file **supplied**, since an
unmodified seed now stores nothing.
- Found by the adversarial review of §S20's design: the gap was tolerable only
while nothing delivered a rules file to any machine, and a seeder turns it
into a push channel.
- **§S21 prescribed the wrong replace primitive.** A comment on the reader and a
line in §S21 both told whoever implements §S20 to use temp-file +
`MoveFileExW(MOVEFILE_REPLACE_EXISTING)`. Measured against a handle opened
exactly as the guard opens it, that returns `ERROR_ACCESS_DENIED (5)`;
`ReplaceFileW` with a backup file named succeeds. Delete sharing is necessary
and nowhere near sufficient. The unification of share modes is still right — it
is what lets `ReplaceFileW` proceed — but the named call would have failed on
exactly the machines where the guard is busy, silently, since the writer's error
goes nowhere.
- **The guard refused itself, so launch mode could not work** (§S18).
`FrameLedger.Guard.dll` contains the substring `guard`, one of the heuristic's
`nameFragments`, and the project ships unsigned so the signer half can never
+59 -7
View File
@@ -870,13 +870,51 @@ which nobody re-asked. **When a doc says an input cannot be redirected, the
question is "through which channel", and the answer has to enumerate the rest.**
**Fixed by the floor, not by the path.** `fl::guard::FloorFamilies` carries the
three required families inside the binary; `ParseRules` seeds them before reading
a byte and nothing merges, rewrites or removes them. §S8's mechanism applied to
data: a family data cannot remove cannot be bypassed. Path resolution moved to
blocklist inside the binary; `ParseRules` seeds it before reading a byte and
nothing merges, rewrites or removes it. §S8's mechanism applied to data: a family
data cannot remove cannot be bypassed. Path resolution moved to
`SHGetKnownFolderPath` as well, and that is written down as a **narrowing, not a
guarantee** — a user can still move their own Local AppData; what is gone is the
per-launch vector.
> #### The floor shipped too narrow, and that is worth recording (2026-08-04)
>
> As first written it carried **exactly the three families `IsCompleteEnoughToGate`
> required**, kept minimal on the grounds that a larger hand-written table would
> be a second copy of the blocklist and drift from the data. Measured against the
> shipped seed, that bought **4 of 22 values, 2 of 5 groups and 0 of 5 name
> fragments**.
>
> So this entry closed *"a crafted rules file makes the guard allow everything"*
> and left open *"a crafted rules file removes most of the blocklist"* — Denuvo,
> GameGuard, Xigncode3, mhyprot, FACEIT, ESEA, PunkBuster, EAC's directories and
> services, BattlEye's directories, Vanguard's service, and the entire fuzzy tier.
> The write-up above read as though the floor bounded more than it did.
>
> That gap was tolerable only while nothing delivered a rules file to any machine.
> The §S20 review is what surfaced it, because a seeder turns a repo-only defect
> into a **push channel**.
>
> **The floor is now GENERATED from `rules/detection-rules.json` at build time**
> (`tools/gen-ac-floor.ps1`), which removes the objection that kept it small — a
> table derived from the data cannot drift from it. It carries the whole shipped
> blocklist and the name fragments; `trustedSigners` is deliberately excluded,
> because it is an ALLOW-widening list and "data may only add" has the wrong
> polarity there.
>
> Two consequences worth stating. A file family identical to a floor entry is
> **deduplicated**, or an unmodified seed would spend `kMaxFamilies` twice — so
> `rules-validate.ps1` now bounds the file at **half** the cap, which is the
> worst case of a drifted file duplicating none of the floor. And completeness is
> judged on what the file **supplied**, not on what was stored, because an
> unmodified seed now stores nothing.
>
> **It also delivers §S19(d)'s substance** — a rules file with no `heuristic`
> block can no longer make the fuzzy tier stop existing — without the new
> `ParseResult` cause that entry proposed, which would have made
> `kRulesIncomplete`'s signal a lie and driven `layer.cpp` to machine-wide inert
> passthrough. A floor needs neither.
Kept able to fail: the completeness check now runs over the **file's** families
only. Running it over the merged set would have retired a real refusal by
accident, since the floor satisfies it by construction — a gate that cannot fail,
@@ -913,10 +951,24 @@ assertion matters most for §S20: a seeder writing where the gate does not read
reports success, and its own test would agree with it.
Sharing mode unified too — all readers now `FILE_SHARE_READ | FILE_SHARE_WRITE |
FILE_SHARE_DELETE`. The guard denied delete sharing and the layer denied nothing;
§S20's replace must be temp-file + `MoveFileExW(MOVEFILE_REPLACE_EXISTING)`, and
a reader denying delete sharing turns every routine rules update into a silent
failed update.
FILE_SHARE_DELETE`. The guard denied delete sharing and the layer denied nothing.
> **The primitive this prescribed was wrong, and it is corrected rather than
> quietly edited.** It said §S20's replace must be temp-file +
> `MoveFileExW(MOVEFILE_REPLACE_EXISTING)`. Measured 2026-08-04 against a handle
> opened exactly as the guard opens it:
>
> | Call | Against a live reader |
> |---|---|
> | `MoveFileExW(MOVEFILE_REPLACE_EXISTING)` | `ERROR_ACCESS_DENIED (5)` |
> | `ReplaceFileW`, backup file named | succeeds |
>
> Delete sharing is **necessary and nowhere near sufficient**. The unification is
> still right — it is what lets `ReplaceFileW` proceed — but the named call was
> the one that fails on exactly the machines where the guard is busy, and its
> error goes nowhere, so the update would simply not have happened. Same shape as
> the two `layer.cpp` comments that documented measured-wrong designs: a reader
> designs a gate around them.
Proven red, all four ways, before being called done: emptying `FloorFamilies`
makes the disarmed-rules test allow; pointing a floor value at something the seed
+43
View File
@@ -107,6 +107,49 @@ target_compile_definitions(fl_hostile_env_flags INTERFACE _HAS_EXCEPTIONS=0)
target_compile_options(fl_hostile_env_flags INTERFACE /EHsc-)
target_link_options(fl_hostile_env_flags INTERFACE /guard:cf)
# ---------------------------------------------------------------------------
# The compiled-in blocklist floor (§S21), GENERATED from the shipped rules file.
#
# The floor is what a rules file may extend and can never shrink. §S21 shipped a
# hand-written one covering the three required families, kept minimal because a
# larger hand-written table would be a second copy of the blocklist that drifts
# from the data. Measured afterwards, that bought 4 of the seed's 22 values, 2 of
# its 5 groups and none of its 5 name fragments — so a crafted rules file could
# still delete most of the blocklist.
#
# Generating it removes the objection that kept it small: a table derived from
# rules/detection-rules.json at build time cannot drift from it.
#
# Output goes in the BUILD tree. Generated code in src/native would be swept by
# clang-format, and a generated file under version control is a copy somebody can
# edit independently — the exact thing this exists to prevent.
# ---------------------------------------------------------------------------
find_program(FL_PWSH pwsh REQUIRED
DOC "PowerShell 7+, used to generate the blocklist floor from the rules file")
set(FL_REPO_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../..")
set(FL_AC_FLOOR_DIR "${CMAKE_BINARY_DIR}/generated")
set(FL_AC_FLOOR_HEADER "${FL_AC_FLOOR_DIR}/fl_ac_floor.generated.h")
add_custom_command(
OUTPUT "${FL_AC_FLOOR_HEADER}"
COMMAND "${FL_PWSH}" -NoProfile -File "${FL_REPO_ROOT}/tools/gen-ac-floor.ps1"
-RulesPath "${FL_REPO_ROOT}/rules/detection-rules.json"
-OutPath "${FL_AC_FLOOR_HEADER}"
DEPENDS "${FL_REPO_ROOT}/rules/detection-rules.json"
"${FL_REPO_ROOT}/tools/gen-ac-floor.ps1"
COMMENT "Generating the anti-cheat blocklist floor from rules/detection-rules.json"
VERBATIM)
add_custom_target(fl_ac_floor_gen DEPENDS "${FL_AC_FLOOR_HEADER}")
# Carries only the include directory. Every target that compiles fl_ac_rules.cpp
# links this AND depends on fl_ac_floor_gen — the dependency is stated per target
# rather than hidden here, so a new target that forgets it fails to compile
# immediately and loudly rather than picking up a stale header.
add_library(fl_ac_floor INTERFACE)
target_include_directories(fl_ac_floor INTERFACE "${FL_AC_FLOOR_DIR}")
add_subdirectory(third_party)
add_subdirectory(FrameLedger.Shm)
add_subdirectory(FrameLedger.Overlay)
@@ -32,8 +32,9 @@ target_include_directories(FrameLedger.Injector PUBLIC include)
# carrying two system libs.
target_link_libraries(FrameLedger.Injector
PUBLIC FrameLedger.Shm fl_native_flags Shell32 Ole32
PRIVATE fl_jsmn
PRIVATE fl_jsmn fl_ac_floor
)
add_dependencies(FrameLedger.Injector fl_ac_floor_gen)
# ---------------------------------------------------------------------------
# The C ABI the managed Agent reaches the guard through (§S15 item 1).
@@ -56,7 +57,8 @@ add_library(FrameLedger.Guard SHARED
src/fl_guard_abi.cpp
)
target_include_directories(FrameLedger.Guard PUBLIC include)
target_link_libraries(FrameLedger.Guard PRIVATE FrameLedger.Shm fl_native_flags fl_jsmn Shell32 Ole32)
target_link_libraries(FrameLedger.Guard PRIVATE FrameLedger.Shm fl_native_flags fl_jsmn Shell32 Ole32 fl_ac_floor)
add_dependencies(FrameLedger.Guard fl_ac_floor_gen)
target_compile_definitions(FrameLedger.Guard PRIVATE FL_GUARD_ABI_BUILD)
set_target_properties(FrameLedger.Guard PROPERTIES OUTPUT_NAME "FrameLedger.Guard")
fl_add_version_resource(FrameLedger.Guard "FrameLedger anti-cheat guard (hard gate; refuses where anti-cheat is present)")
@@ -35,11 +35,13 @@ enum class Group : std::uint8_t { kModules = 0, kDrivers, kDirectories, kService
inline constexpr std::size_t kMaxFamilies = 64;
inline constexpr std::size_t kMaxValuesPerFamily = 16;
// The floor occupies family slots before any data is read, so the budget
// available to the FILE is kMaxFamilies - kFloorFamilyCount. tools/rules-validate.ps1
// reads this constant out of this header and subtracts it, rather than restating
// the arithmetic.
inline constexpr std::size_t kFloorFamilyCount = 3;
// The floor is GENERATED from rules/detection-rules.json and occupies family
// slots before any data is read, so the budget available to the FILE is
// kMaxFamilies minus the floor. Since the floor IS the shipped seed's blocklist,
// the worst case is a file that duplicates none of it: 2 x its families must fit.
// tools/rules-validate.ps1 checks exactly that, computed from the same JSON
// rather than from a constant here — a count in this header would be the copy
// that drifts.
inline constexpr std::size_t kMaxValueLen = 96;
inline constexpr std::size_t kMaxFamilyNameLen = 64;
@@ -152,13 +154,34 @@ enum class ParseResult : std::uint8_t {
// or reachable from anything the file says. The file adds families and values;
// it can take nothing away.
//
// Deliberately minimal — exactly the three families `IsCompleteEnoughToGate`
// already required. A larger floor would be a second blocklist that drifts from
// rules/detection-rules.json; ctest fl_rules_budget asserts every value here is
// present in the shipped seed under the same family and group, so the two cannot
// disagree without failing the build.
// GENERATED from rules/detection-rules.json at build time by
// tools/gen-ac-floor.ps1. §S21 shipped a hand-written floor of three families,
// kept minimal because a larger hand-written table would be a second copy of the
// blocklist that drifts from the data.
//
// Measured afterwards, that reasoning bought **4 of the seed's 22 values, 2 of
// its 5 groups and none of its 5 name fragments** — so §S21 closed "a crafted
// rules file makes the guard allow everything" and left open "a crafted rules
// file removes most of the blocklist": Denuvo, GameGuard, Xigncode3, mhyprot,
// FACEIT, ESEA, PunkBuster, EAC's directories and services, BattlEye's
// directories, Vanguard's service, and the whole fuzzy tier.
//
// Generating it removes the objection that kept it small. A table derived from
// the data at build time cannot drift from it, so the floor is now the whole
// shipped blocklist and "data may extend, never shrink" means what it says.
[[nodiscard]] const Family* FloorFamilies(std::size_t& count) noexcept;
// The floored half of the unknown-but-suspicious heuristic, same source and same
// reasoning — which is also §S19(d)'s substance, arriving as a floor rather than
// as the parse refusal that entry proposed. A refusal would have needed a new
// `ParseResult` cause, made `kRulesIncomplete`'s signal a lie, and driven
// `layer.cpp` to machine-wide inert passthrough. A floor needs none of that: the
// tier cannot stop existing because the data never supplied it.
//
// `trustedSigners` is deliberately NOT floored. It is an ALLOW-widening list, so
// "data may only add" has the wrong polarity there.
[[nodiscard]] const char* const* FloorFragments(std::size_t& count) noexcept;
// Parse, then verify the result is USABLE AS A GATE. A syntactically valid
// rules file with an empty `modules` array parses fine and blocks nothing, so
// completeness is checked here rather than being left to whoever wrote the file
@@ -13,6 +13,12 @@
#include <objbase.h>
#include <shlobj_core.h>
// Its own block, below the sorted one, because it needs Family/Group/MatchKind
// from fl_ac_rules.h and clang-format sorts each block independently.
// Generated at build time from rules/detection-rules.json — see
// tools/gen-ac-floor.ps1 and src/native/CMakeLists.txt §the floor.
#include <fl_ac_floor.generated.h>
namespace fl::guard {
namespace {
@@ -155,27 +161,74 @@ bool ReadFamily(const char* json, const jsmntok_t* toks, int count, int objIndex
return out.valueCount > 0;
}
// Copy a NUL-terminated literal into a fixed buffer, refusing rather than
// truncating. Used for the generated floor, whose entries the schema already
// bounds — but a generator bug must not produce a SHORTER token that matches
// MORE, which is the same rule CopyToken follows.
bool CopyLiteral(const char* text, char (&out)[kMaxValueLen]) noexcept {
if (text == nullptr) {
return false;
}
const std::size_t len = std::strlen(text);
if (len == 0 || len >= kMaxValueLen) {
return false;
}
std::memcpy(out, text, len + 1);
return true;
}
// APPENDS from the caller's current count rather than resetting it, because the
// floor is already in the array by the time the file is read (§S21). Duplicates
// are skipped case-insensitively: the floor is generated FROM the shipped seed,
// so an unmodified file repeats every entry, and storing both would spend the cap
// twice over — a seed with 9 fragments would then need 18 of kMaxNameFragments 16
// and refuse the whole file.
bool ReadStringArray(const char* json, const jsmntok_t* toks, int count, int arrayTok, char (*out)[kMaxValueLen],
std::size_t cap, std::size_t& outCount) noexcept {
outCount = 0;
if (arrayTok < 0 || toks[arrayTok].type != JSMN_ARRAY) {
return false;
}
if (static_cast<std::size_t>(toks[arrayTok].size) > cap) {
return false;
}
for (int i = arrayTok + 1; i < count && outCount < cap; ++i) {
for (int i = arrayTok + 1; i < count; ++i) {
if (toks[i].parent != arrayTok) {
continue;
}
if (!CopyToken(json, toks[i], out[outCount], kMaxValueLen)) {
char buf[kMaxValueLen] = {};
if (!CopyToken(json, toks[i], buf, kMaxValueLen)) {
return false;
}
bool already = false;
for (std::size_t j = 0; j < outCount && !already; ++j) {
already = IEquals(out[j], buf);
}
if (already) {
continue;
}
if (outCount >= cap) {
return false; // genuinely more distinct entries than we can hold
}
std::memcpy(out[outCount], buf, kMaxValueLen);
++outCount;
}
return true;
}
// True when `candidate` is already in the floor, entry for entry. The floor is
// generated from the shipped seed, so an unmodified rules file repeats all of it;
// appending both copies would spend kMaxFamilies twice and refuse any seed larger
// than half the cap. A family that differs in ANY respect is not a duplicate and
// is kept — matching then sees both, which is what "data may extend" means.
bool SameFamily(const Family& a, const Family& b) noexcept {
if (a.group != b.group || a.match != b.match || a.valueCount != b.valueCount || !IEquals(a.name, b.name)) {
return false;
}
for (std::size_t i = 0; i < a.valueCount; ++i) {
if (!IEquals(a.values[i], b.values[i])) {
return false;
}
}
return true;
}
// Read one blockedExecutables entry: { family, match, values[], reason }.
//
// The schema has always required all four (acBlockedExecutable), while this
@@ -308,16 +361,19 @@ bool ReadTitleArray(const char* json, const jsmntok_t* toks, int count, int arra
return true;
}
// The gate has to be usable, not merely well-formed. A syntactically perfect
// file with an empty `modules` array blocks nothing.
// What the FILE supplied, recorded as it is read.
//
// `first` is where the FILE's families begin. Everything below it is the floor,
// which satisfies this check by construction — so scanning from 0 would make
// this a gate that cannot fail, which is the defect class 20_OPEN_QUESTIONS
// exists to record. The floor protects the GATE; this check polices the DATA,
// and "the rules file you shipped is missing BattlEye" is still worth refusing
// over and telling someone about.
bool IsCompleteEnoughToGate(const Rules& r, std::size_t first) noexcept {
// The gate has to be usable, not merely well-formed, and a syntactically perfect
// file with an empty `modules` array blocks nothing — so completeness is checked
// here rather than left to whoever wrote the file.
//
// It is asked of what the file OFFERED, never of what ended up in `Rules`. Two
// reasons, and both have already bitten a version of this code: the floor
// satisfies the check by construction, so scanning the merged set would make this
// a gate that cannot fail; and the floor is generated FROM the shipped seed, so
// an unmodified file is entirely duplicate and stores nothing, which would make
// the correct seed report kIncomplete.
struct SuppliedFamilies {
struct Required {
const char* family;
Group group;
@@ -328,41 +384,43 @@ bool IsCompleteEnoughToGate(const Rules& r, std::size_t first) noexcept {
{"BattlEye", Group::kModules},
{"Riot Vanguard", Group::kDrivers},
};
static constexpr std::size_t kRequiredCount = sizeof(kRequired) / sizeof(kRequired[0]);
for (const auto& req : kRequired) {
bool found = false;
for (std::size_t i = first; i < r.familyCount && !found; ++i) {
found = r.families[i].group == req.group && IEquals(r.families[i].name, req.family);
}
if (!found) {
return false;
bool seen[kRequiredCount] = {};
bool any = false;
void Note(const Family& f) noexcept {
any = true;
for (std::size_t i = 0; i < kRequiredCount; ++i) {
if (f.group == kRequired[i].group && IEquals(f.name, kRequired[i].family)) {
seen[i] = true;
}
}
}
return true;
}
[[nodiscard]] bool Complete() const noexcept {
if (!any) {
return false;
}
for (std::size_t i = 0; i < kRequiredCount; ++i) {
if (!seen[i]) {
return false;
}
}
return true;
}
};
} // namespace
const Family* FloorFamilies(std::size_t& count) noexcept {
// §S21. Exactly the three families IsCompleteEnoughToGate already required —
// no more, because every extra entry here is a blocklist that can drift from
// rules/detection-rules.json, and ctest fl_rules_budget pins these against the
// shipped seed for that reason.
//
// Values are the ones that carry the coverage, not every value in the seed:
// "EasyAntiCheat" is a PREFIX rule, so it already subsumes
// "EasyAntiCheat_EOS". The subset assertion is "every value here appears in
// the seed", never "these two lists are equal".
static constexpr Family kFloor[kFloorFamilyCount] = {
{"Easy Anti-Cheat", Group::kModules, MatchKind::kPrefix, {"EasyAntiCheat"}, 1},
{"BattlEye", Group::kModules, MatchKind::kPrefix, {"BEClient", "BEService"}, 2},
{"Riot Vanguard", Group::kDrivers, MatchKind::kExact, {"vgk.sys"}, 1},
};
static_assert(sizeof(kFloor) / sizeof(kFloor[0]) == kFloorFamilyCount,
"kFloorFamilyCount must match the table; rules-validate.ps1 subtracts it from the file's budget");
count = sizeof(generated::kFloorFamilies) / sizeof(generated::kFloorFamilies[0]);
return generated::kFloorFamilies;
}
count = kFloorFamilyCount;
return kFloor;
const char* const* FloorFragments(std::size_t& count) noexcept {
count = sizeof(generated::kFloorFragments) / sizeof(generated::kFloorFragments[0]);
return generated::kFloorFragments;
}
ParseResult ParseRules(const char* json, std::size_t length, Rules& out) noexcept {
@@ -379,6 +437,23 @@ ParseResult ParseRules(const char* json, std::size_t length, Rules& out) noexcep
}
const std::size_t dataFirst = out.familyCount;
// The fuzzy tier is floored too. §S19(d) records that a rules file with no
// `heuristic` block parses kOk and the tier silently stops existing, and
// proposed fixing it with a new ParseResult cause — which its own text says
// would make kRulesIncomplete's signal a lie and would drive layer.cpp to
// machine-wide inert passthrough. A floor needs neither: the tier cannot stop
// existing, because the data never supplied it.
//
// trustedSigners is deliberately NOT floored. It is an ALLOW-widening list,
// so "data may only add" has the wrong polarity there — forcing entries in
// would be forcing suppressions in.
std::size_t fragCount = 0;
const char* const* frags = FloorFragments(fragCount);
for (std::size_t i = 0; i < fragCount && out.nameFragmentCount < kMaxNameFragments; ++i) {
if (CopyLiteral(frags[i], out.nameFragments[out.nameFragmentCount])) {
++out.nameFragmentCount;
}
}
if (json == nullptr || length == 0) {
return ParseResult::kMalformed;
}
@@ -401,6 +476,8 @@ ParseResult ParseRules(const char* json, std::size_t length, Rules& out) noexcep
return ParseResult::kMalformed;
}
SuppliedFamilies supplied;
static constexpr const char* kGroupNames[] = {"modules", "drivers", "directories", "services", "files"};
for (const char* groupName : kGroupNames) {
bool ok = false;
@@ -416,13 +493,29 @@ ParseResult ParseRules(const char* json, std::size_t length, Rules& out) noexcep
if (toks[i].parent != arrTok || toks[i].type != JSMN_OBJECT) {
continue;
}
Family fam;
if (!ReadFamily(json, toks, count, i, group, fam)) {
return ParseResult::kMalformed;
}
// Completeness is judged on what the FILE supplied, so it is recorded
// here — before the duplicate check. The floor is generated from the
// shipped seed, so an unmodified file duplicates all of it and stores
// nothing; judging completeness by what was STORED would then report
// the correct seed as incomplete.
supplied.Note(fam);
bool duplicate = false;
for (std::size_t f = 0; f < dataFirst && !duplicate; ++f) {
duplicate = SameFamily(out.families[f], fam);
}
if (duplicate) {
continue;
}
if (out.familyCount >= kMaxFamilies) {
return ParseResult::kTooLarge;
}
if (!ReadFamily(json, toks, count, i, group, out.families[out.familyCount])) {
return ParseResult::kMalformed;
}
++out.familyCount;
out.families[out.familyCount++] = fam;
}
}
@@ -454,12 +547,11 @@ ParseResult ParseRules(const char* json, std::size_t length, Rules& out) noexcep
}
}
// Both questions are asked of the FILE, not of the merged set (see
// IsCompleteEnoughToGate). A file that supplies no families at all is still
// kIncomplete even though the floor would gate perfectly well without it:
// shipping an empty blocklist is a mistake worth surfacing, and the floor is
// a backstop, not a substitute.
if (out.familyCount == dataFirst || !IsCompleteEnoughToGate(out, dataFirst)) {
// Asked of the FILE, never of the merged set (see SuppliedFamilies). A file
// that supplies no families at all is still kIncomplete even though the floor
// would gate perfectly well without it: shipping an empty blocklist is a
// mistake worth surfacing, and the floor is a backstop, not a substitute.
if (!supplied.Complete()) {
return ParseResult::kIncomplete;
}
return ParseResult::kOk;
@@ -616,11 +708,21 @@ std::size_t ReadRulesFile(char* buffer, std::size_t cap) noexcept {
// FILE_SHARE_DELETE matters as much as the other two, and it is the half that
// is easy to leave out. §S20's delivery path must replace this file
// atomically (temp file + MoveFileExW(MOVEFILE_REPLACE_EXISTING)) rather than
// rewriting it in place, or a reader can see it half-written and refuse every
// title mid-session. A rename cannot proceed against a handle that denies
// delete sharing, so denying it here would turn every routine rules update
// into a failed update — silently, since the writer's error goes nowhere.
// atomically rather than rewriting it in place, or a reader can see it
// half-written and refuse every title mid-session.
//
// **The primitive is ReplaceFileW, and this comment used to prescribe the
// wrong one.** It said MoveFileExW(MOVEFILE_REPLACE_EXISTING), reasoning that
// delete sharing is what lets a rename proceed against a live reader.
// Measured 2026-08-04 against a handle opened exactly as below:
//
// MoveFileExW(MOVEFILE_REPLACE_EXISTING) ERROR_ACCESS_DENIED (5)
// ReplaceFileW, backup file named succeeds
//
// Delete sharing is NECESSARY and nowhere near sufficient. Naming the wrong
// call here would have sent whoever implements §S20 to a primitive that fails
// on exactly the machines where the guard is busy — and its error goes
// nowhere, so the update would simply not happen.
//
// The guard and the Vulkan layer previously disagreed here (READ vs
// READ|WRITE) about what fl_ac_rules.h calls "the ONE location": by that
@@ -26,7 +26,8 @@ target_include_directories(FrameLedger.VkLayer PRIVATE ../FrameLedger.Injector/i
# both are core Windows components already resident in any process that has a
# window, and the calls happen once at init, never in a dispatch path.
target_link_libraries(FrameLedger.VkLayer PRIVATE
FrameLedger.Shm fl_native_flags fl_hostile_env_flags fl_vulkan_headers fl_jsmn Shell32 Ole32)
FrameLedger.Shm fl_native_flags fl_hostile_env_flags fl_vulkan_headers fl_jsmn Shell32 Ole32 fl_ac_floor)
add_dependencies(FrameLedger.VkLayer fl_ac_floor_gen)
set_target_properties(FrameLedger.VkLayer PROPERTIES OUTPUT_NAME "FrameLedger.VkLayer")
# Same requirement as the Overlay, and arguably sharper here: an implicit layer
+6 -2
View File
@@ -21,8 +21,11 @@ add_test(NAME fl_shm_layout COMMAND fl_shm_layout_test)
# duplicate every symbol, which is the compiler telling us the same thing.
add_executable(fl_guard_test guard_test.cpp ${FL_INJECTOR_SOURCES})
target_include_directories(fl_guard_test PRIVATE "${CMAKE_SOURCE_DIR}/FrameLedger.Injector/include")
# Shell32/Ole32: fl_ac_rules.cpp resolves the rules path via SHGetKnownFolderPath
# (§S21). fl_ac_floor: the generated blocklist floor it compiles in.
target_link_libraries(fl_guard_test PRIVATE FrameLedger.Shm fl_native_flags fl_jsmn Catch2::Catch2WithMain
Shell32 Ole32) # §S21: fl_ac_rules.cpp resolves the rules path via SHGetKnownFolderPath
Shell32 Ole32 fl_ac_floor)
add_dependencies(fl_guard_test fl_ac_floor_gen)
# /EHsc on the TEST BINARY only. Catch2 reports failures by throwing, and the
# top-level CMakeLists strips the compiler's default /EHsc so every target has
@@ -74,7 +77,8 @@ add_executable(fl_rules_budget_test
"${CMAKE_SOURCE_DIR}/FrameLedger.Injector/src/fl_ac_rules.cpp"
)
target_include_directories(fl_rules_budget_test PRIVATE "${CMAKE_SOURCE_DIR}/FrameLedger.Injector/include")
target_link_libraries(fl_rules_budget_test PRIVATE fl_native_flags fl_jsmn Catch2::Catch2WithMain Shell32 Ole32)
target_link_libraries(fl_rules_budget_test PRIVATE fl_native_flags fl_jsmn Catch2::Catch2WithMain Shell32 Ole32 fl_ac_floor)
add_dependencies(fl_rules_budget_test fl_ac_floor_gen)
target_compile_options(fl_rules_budget_test PRIVATE /EHsc)
# The repository seed, by absolute path at compile time.
+41 -6
View File
@@ -1186,9 +1186,41 @@ TEST_CASE("unusable rules make the pre-scan undetermined, never clean", "[guard]
}
TEST_CASE("the pre-scan uses the SAME matcher: removing a family stops it firing", "[guard][prescan][blocklist]") {
// The claim "it reuses fl_ac_rules" is proved rather than reviewed. Drop the
// directories group from the data and the directory hit must disappear —
// if it survived, there would be a second matcher somewhere.
// The claim "it reuses fl_ac_rules" is proved rather than reviewed. Drop a
// family from the data and its directory hit must disappear — if it survived,
// there would be a second matcher somewhere.
//
// It uses a family the FLOOR does not carry, and that is now the whole
// difficulty. Removing `Easy Anti-Cheat` from the file no longer stops it
// matching, because the generated floor carries the shipped blocklist and
// data cannot shrink it — which is §S21 working, not a regression. Proving
// "one matcher" therefore needs a family that exists only in the fixture.
static constexpr const char* kFixtureOnlyDir = "ZzFixtureOnlyAcDir";
std::string withExtra = GoodRulesJson();
const std::string dirs = R"("directories": [ { "family": "Easy Anti-Cheat", "values": ["EasyAntiCheat"] } ],)";
const std::size_t at = withExtra.find(dirs);
REQUIRE(at != std::string::npos); // the fixture moved; this test is not testing what it thinks
withExtra.replace(at, dirs.size(),
R"("directories": [ { "family": "Easy Anti-Cheat", "values": ["EasyAntiCheat"] },)"
R"( { "family": "Fixture Only", "values": ["ZzFixtureOnlyAcDir"] } ],)");
ResetFake();
g.dirEntries = {{kFixtureOnlyDir, true}};
g.rulesJson = withExtra;
REQUIRE(EvaluateWithSources(1234, FakeSources()).reason == Reason::kAntiCheatDirectory);
// Same input, family removed from the data: the hit must be gone.
ResetFake();
g.dirEntries = {{kFixtureOnlyDir, true}};
g.rulesJson = GoodRulesJson();
CHECK(EvaluateWithSources(1234, FakeSources()).Allowed());
}
TEST_CASE("a family the FLOOR carries cannot be removed by editing the data", "[guard][prescan][floor]") {
// The other direction, and the one §S21's narrow floor could not deliver.
// Strip Easy Anti-Cheat from every group of the file and the directory hit
// survives, because the floor is generated from the shipped blocklist.
ResetFake();
g.dirEntries = {{"EasyAntiCheat", true}};
REQUIRE(EvaluateWithSources(1234, FakeSources()).reason == Reason::kAntiCheatDirectory);
@@ -1196,13 +1228,16 @@ TEST_CASE("the pre-scan uses the SAME matcher: removing a family stops it firing
std::string stripped = GoodRulesJson();
const std::string dirs = R"("directories": [ { "family": "Easy Anti-Cheat", "values": ["EasyAntiCheat"] } ],)";
const std::size_t at = stripped.find(dirs);
REQUIRE(at != std::string::npos); // the fixture moved; this test is not testing what it thinks
stripped.replace(at, dirs.size(), R"("directories": [ { "family": "BattlEye", "values": ["BattlEye"] } ],)");
REQUIRE(at != std::string::npos);
stripped.replace(at, dirs.size(), R"("directories": [],)");
ResetFake();
g.dirEntries = {{"EasyAntiCheat", true}};
g.rulesJson = stripped;
CHECK(EvaluateWithSources(1234, FakeSources()).Allowed());
const Verdict v = EvaluateWithSources(1234, FakeSources());
INFO("reason was " << ReasonName(v.reason));
REQUIRE_FALSE(v.Allowed());
CHECK(v.reason == Reason::kAntiCheatDirectory);
}
TEST_CASE("the install root is resolved from the exe directory, not used as-is", "[guard][prescan]") {
+102 -43
View File
@@ -152,23 +152,17 @@ TEST_CASE("the rules file that SHIPS parses in the guard", "[rules][seed]") {
std::printf("[seed] %zu bytes, %zu families of %zu\n", seed.size(), rules.familyCount, kMaxFamilies);
}
// §S21. The compiled-in floor is a blocklist that lives in the binary, which
// makes it a candidate to become the FOURTH unreconciled copy of this data
// (§S19(d) already counts three of the fragment list). This is what stops that:
// every floor value must be present in the file we ship, under the same family
// and the same group.
// §S21. The floor is generated from rules/detection-rules.json, so it cannot be
// a fourth unreconciled copy of the blocklist — but a GENERATOR can still drift
// from its input, by dropping a group, mangling a match kind or losing a value.
//
// Deliberately a SUBSET assertion, not equality. The floor carries only the
// values that carry coverage — "EasyAntiCheat" is a prefix rule and already
// subsumes "EasyAntiCheat_EOS" — so requiring the two lists to match would force
// the floor to grow every time the seed does, which is the drift it exists to
// avoid.
//
// Direction matters: this goes red if someone edits the floor to something the
// seed does not carry, AND if someone deletes one of the three required families
// from the seed. tools/rules-validate.ps1 already refuses the second in CI; this
// is the half that runs against the parser.
TEST_CASE("every compiled-in floor value is present in the shipped seed", "[rules][seed][floor]") {
// This is the assertion that catches all of it at once, and it is stronger than
// the subset check it replaces: parse the SHIPPED seed and require that it added
// NOTHING. ParseRules skips a data family only when it is identical to a floor
// entry — name, group, match kind and every value — so a stored count equal to
// the floor count means the floor reproduces the file exactly. Any drift shows up
// as an extra family, whatever the direction of the drift.
TEST_CASE("the generated floor reproduces the shipped seed exactly", "[rules][seed][floor]") {
const std::string seed = ReadSeed();
Rules rules;
@@ -176,28 +170,76 @@ TEST_CASE("every compiled-in floor value is present in the shipped seed", "[rule
std::size_t floorCount = 0;
const Family* floor = FloorFamilies(floorCount);
REQUIRE(floorCount == kFloorFamilyCount);
REQUIRE(rules.familyCount > kFloorFamilyCount);
REQUIRE(floorCount > 0);
(void)floor;
for (std::size_t f = 0; f < floorCount; ++f) {
for (std::size_t v = 0; v < floor[f].valueCount; ++v) {
bool found = false;
// Start past the floor: ParseRules seeded it into `rules` itself, so
// scanning from 0 would match the floor against itself and pass no
// matter what the seed says. That is the whole failure mode here.
for (std::size_t i = kFloorFamilyCount; i < rules.familyCount && !found; ++i) {
if (rules.families[i].group != floor[f].group || _stricmp(rules.families[i].name, floor[f].name) != 0) {
continue;
}
for (std::size_t j = 0; j < rules.families[i].valueCount && !found; ++j) {
found = _stricmp(rules.families[i].values[j], floor[f].values[v]) == 0;
}
}
INFO("floor family '" << floor[f].name << "' value '" << floor[f].values[v]
<< "' is not in rules/detection-rules.json");
CHECK(found);
}
INFO("the seed contributed " << (rules.familyCount - floorCount)
<< " families the generated floor does not already carry");
CHECK(rules.familyCount == floorCount);
std::size_t fragCount = 0;
const char* const* frags = FloorFragments(fragCount);
REQUIRE(fragCount > 0);
(void)frags;
INFO("the seed contributed " << (rules.nameFragmentCount - fragCount) << " name fragments beyond the floor");
CHECK(rules.nameFragmentCount == fragCount);
std::printf("[floor] %zu families, %zu fragments — generated from the seed\n", floorCount, fragCount);
}
// The property the floor exists for, asserted against the gate rather than
// against the generator: a rules file that names the three required families and
// nothing else must still block everything the shipped seed blocks.
//
// This is what §S21's hand-written floor did NOT do. It carried 4 of the seed's
// 22 values, so this same document left Denuvo, GameGuard, Xigncode3, mhyprot,
// FACEIT, ESEA, PunkBuster, EAC's directories and services, BattlEye's
// directories, Vanguard's service and the whole fuzzy tier unmatched.
TEST_CASE("a minimal rules file cannot shrink the blocklist", "[rules][floor][failclosed]") {
const std::string minimal = R"({"anticheat": {
"modules": [
{ "family": "Easy Anti-Cheat", "match": "exact", "values": ["zzzz-not-real.dll"] },
{ "family": "BattlEye", "match": "exact", "values": ["zzzz-also-not.dll"] }
],
"drivers": [ { "family": "Riot Vanguard", "match": "exact", "values": ["zzzz-nothing.sys"] } ],
"directories": [], "services": [], "files": [],
"blockedExecutables": [], "blockedStoreIds": []
}})";
Rules rules;
REQUIRE(ParseRules(minimal.c_str(), minimal.size(), rules) == ParseResult::kOk);
struct Case {
Group group;
const char* observed;
const char* family;
};
// One per group, and every one of these was unmatched under the old floor.
static constexpr Case kCases[] = {
{Group::kModules, "denuvo64.dll", "Denuvo Anti-Cheat"},
{Group::kModules, "GameGuard.des", "nProtect GameGuard"},
{Group::kModules, "xhunter1.sys", "Xigncode3"},
{Group::kModules, "PnkBstrA.exe", "PunkBuster"},
{Group::kModules, "faceitclient.dll", "FACEIT"},
{Group::kDrivers, "\\SystemRoot\\system32\\drivers\\mhyprot3.sys", "mihoyo protect"},
{Group::kDirectories, "EasyAntiCheat", "Easy Anti-Cheat"},
{Group::kDirectories, "BattlEye", "BattlEye"},
{Group::kServices, "vgc", "Riot Vanguard"},
{Group::kFiles, "x3.xem", "Xigncode3"},
};
for (const auto& c : kCases) {
const Family* hit = MatchName(rules, c.group, c.observed);
INFO("'" << c.observed << "' should still match " << c.family);
REQUIRE(hit != nullptr);
CHECK(std::string(hit->name) == c.family);
}
// The fuzzy tier survives a file with no `heuristic` block at all — §S19(d)'s
// hole, closed by the floor rather than by a new refusal.
CHECK(HasSuspiciousFragment(rules, "SomeAntiTamper64.dll"));
CHECK(HasSuspiciousFragment(rules, "xprotect.dll"));
CHECK_FALSE(HasSuspiciousFragment(rules, "d3d11.dll"));
}
TEST_CASE("the shipped seed is inside the guard's parse budget", "[rules][seed][budget]") {
@@ -277,12 +319,21 @@ TEST_CASE("the file holds exactly kMaxFamilies families, and not one more", "[ru
// Derived from the header constant rather than restated, for the same reason
// every other bound here is: this test went red the moment the floor landed,
// which is exactly what it exists to do.
constexpr std::size_t kFixtureFamilies = 6;
constexpr std::size_t kFileBudget = kMaxFamilies - kFloorFamilyCount;
Rules rules;
// MEASURED, not computed. Two things now stand between "kMaxFamilies" and
// "how many more this document may carry": the generated floor occupies slots
// before the file is read, and a file family identical to a floor entry is
// deduplicated rather than stored. Arithmetic over kFixtureFamilies would
// have to model both and would go stale the next time the seed changes — so
// the baseline is taken from the parser itself.
Rules rules;
Doc baseline;
REQUIRE(ParseDoc(Build(baseline), rules) == ParseResult::kOk);
const std::size_t used = rules.familyCount;
REQUIRE(used < kMaxFamilies);
const std::size_t room = kMaxFamilies - used;
Doc ok;
ok.extraModules = ExtraFamilies(kFileBudget - kFixtureFamilies);
ok.extraModules = ExtraFamilies(room);
REQUIRE(ParseDoc(Build(ok), rules) == ParseResult::kOk);
CHECK(rules.familyCount == kMaxFamilies);
@@ -290,7 +341,7 @@ TEST_CASE("the file holds exactly kMaxFamilies families, and not one more", "[ru
// because "this file is bigger than we can hold" and "this file is not the
// shape we require" are different problems for whoever has to fix them.
Doc over;
over.extraModules = ExtraFamilies(kFileBudget - kFixtureFamilies + 1);
over.extraModules = ExtraFamilies(room + 1);
CHECK(ParseDoc(Build(over), rules) == ParseResult::kTooLarge);
}
@@ -322,12 +373,20 @@ TEST_CASE("a heuristic array holds its cap, and not one more", "[rules][bounds]"
return s + "]";
};
// Same measured baseline as the family cap: the floor's fragments are already
// in the array before the file is read, and only the ones the file repeats
// are deduplicated. `list()` generates names the floor does not carry, so
// every one of them costs a slot.
Doc fragBase;
REQUIRE(ParseDoc(Build(fragBase), rules) == ParseResult::kOk);
const std::size_t fragRoom = kMaxNameFragments - rules.nameFragmentCount;
Doc okFrags;
okFrags.nameFragments = list("frag", kMaxNameFragments);
okFrags.nameFragments = list("frag", fragRoom);
CHECK(ParseDoc(Build(okFrags), rules) == ParseResult::kOk);
Doc overFrags;
overFrags.nameFragments = list("frag", kMaxNameFragments + 1);
overFrags.nameFragments = list("frag", fragRoom + 1);
CHECK(ParseDoc(Build(overFrags), rules) == ParseResult::kMalformed);
Doc okSigners;
@@ -14,7 +14,8 @@
add_executable(fl-probe-vklayer main.cpp
"${CMAKE_SOURCE_DIR}/FrameLedger.Injector/src/fl_ac_rules.cpp")
target_include_directories(fl-probe-vklayer PRIVATE "${CMAKE_SOURCE_DIR}/FrameLedger.Injector/include")
target_link_libraries(fl-probe-vklayer PRIVATE fl_native_flags fl_jsmn Shell32 Ole32)
target_link_libraries(fl-probe-vklayer PRIVATE fl_native_flags fl_jsmn Shell32 Ole32 fl_ac_floor)
add_dependencies(fl-probe-vklayer fl_ac_floor_gen)
target_compile_definitions(fl-probe-vklayer PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX
# The repository seed, installed to %LOCALAPPDATA% only when nothing is
# there and removed afterwards. The layer reads from the ONE product
+144
View File
@@ -0,0 +1,144 @@
#requires -Version 7.0
<#
.SYNOPSIS
Generates the guard's compiled-in blocklist floor from rules/detection-rules.json.
.DESCRIPTION
§S21 gave the guard a floor that a rules file may extend but never shrink. That
floor was hand-written and deliberately minimal — the three families
IsCompleteEnoughToGate already required — because a larger hand-written one
would have been a second copy of the blocklist, drifting from the data.
Measured 2026-08-04, that reasoning bought a floor covering 4 of the seed's 22
values, 2 of its 5 groups and none of its 5 name fragments. So §S21 closed
"a crafted rules file makes the guard allow everything" and left open
"a crafted rules file removes most of the blocklist" — Denuvo, GameGuard,
Xigncode3, mhyprot, FACEIT, ESEA, PunkBuster, EAC's directories and services,
BattlEye's directories, Vanguard's service, and the whole fuzzy tier.
That gap was tolerable while nothing delivered a rules file to any machine.
§S20's seeder is what turns it into a push channel, so the floor grows to the
whole shipped blocklist first.
GENERATING it is what makes that safe. The objection to a large floor was
drift, and a table derived from the data at build time cannot drift from it.
.NOTES
Emits into the BUILD directory, never the source tree: generated code in
src/native would be subject to clang-format (build.ps1 §clang-format excludes
`build`), and a generated file under version control is a copy that can be
edited independently — which is the thing this exists to prevent.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$RulesPath,
[Parameter(Mandatory)][string]$OutPath
)
$ErrorActionPreference = 'Stop'
if (-not (Test-Path -LiteralPath $RulesPath)) {
Write-Error "FLOOR GENERATION FAILED: no rules file at $RulesPath"
}
$rules = Get-Content -LiteralPath $RulesPath -Raw | ConvertFrom-Json
$ac = $rules.anticheat
if ($null -eq $ac) {
Write-Error "FLOOR GENERATION FAILED: $RulesPath has no `anticheat` block"
}
# The five family-bearing groups, in fl::guard::Group order. A group added to the
# schema and not to this list would silently not be floored, so the count is
# asserted against the enum on the C++ side.
$groups = [ordered]@{
modules = 'kModules'
drivers = 'kDrivers'
directories = 'kDirectories'
services = 'kServices'
files = 'kFiles'
}
function ConvertTo-CxxString([string]$s) {
# The schema constrains these to a conservative character set, but escaping is
# not where this script gets to assume. A value that needs anything beyond
# backslash/quote escaping is a value we do not understand, and refusing is
# cheaper than emitting source that compiles into the wrong token.
if ($s -notmatch '^[\x20-\x7E]+$') {
Write-Error "FLOOR GENERATION FAILED: value '$s' is not printable ASCII"
}
return '"' + ($s -replace '\\', '\\' -replace '"', '\"') + '"'
}
$rows = [System.Collections.Generic.List[string]]::new()
foreach ($g in $groups.Keys) {
foreach ($entry in @($ac.$g)) {
if ($null -eq $entry) { continue }
$match = if ($entry.PSObject.Properties.Name -contains 'match' -and $entry.match -eq 'prefix') {
'kPrefix'
}
else { 'kExact' }
$values = @($entry.values | ForEach-Object { ConvertTo-CxxString $_ })
if ($values.Count -eq 0) {
Write-Error "FLOOR GENERATION FAILED: family '$($entry.family)' in '$g' has no values"
}
$rows.Add((' {{{0}, Group::{1}, MatchKind::{2}, {{{3}}}, {4}}},' -f
(ConvertTo-CxxString $entry.family), $groups[$g], $match, ($values -join ', '), $values.Count))
}
}
# The fuzzy tier is floored too, and that is deliberate rather than incidental.
# §S19(d) records that a rules file with no `heuristic` block parses kOk and the
# tier silently stops existing, and proposed fixing it with a new ParseResult
# cause — which its own text says would make kRulesIncomplete's signal a lie and
# would drive layer.cpp to machine-wide inert passthrough. A floor needs neither:
# the tier cannot stop existing because the data never supplied it in the first
# place.
#
# trustedSigners is deliberately NOT floored. It is an ALLOW-widening list, so
# "data may only add" has the wrong polarity there: forcing entries in would be
# forcing suppressions in.
$fragments = @($ac.heuristic.nameFragments | ForEach-Object { ConvertTo-CxxString $_ })
if ($fragments.Count -eq 0) {
Write-Error 'FLOOR GENERATION FAILED: anticheat.heuristic.nameFragments is empty'
}
$header = @"
// GENERATED by tools/gen-ac-floor.ps1 from rules/detection-rules.json. DO NOT EDIT.
//
// The blocklist the guard carries inside the binary. A rules file may EXTEND it
// and can never shrink it (§S21). Generated rather than hand-written because the
// objection to a large floor was drift, and a table derived from the data at
// build time cannot drift from it.
//
// Source rules file: $([IO.Path]::GetFileName($RulesPath)), rulesVersion $($rules.rulesVersion)
#ifndef FL_AC_FLOOR_GENERATED_H
#define FL_AC_FLOOR_GENERATED_H
namespace fl::guard::generated {
inline constexpr Family kFloorFamilies[] = {
$($rows -join "`n")
};
inline constexpr const char* kFloorFragments[] = {
$(($fragments | ForEach-Object { " $_," }) -join "`n")
};
} // namespace fl::guard::generated
#endif // FL_AC_FLOOR_GENERATED_H
"@
$dir = Split-Path -Parent $OutPath
if ($dir -and -not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Force $dir | Out-Null }
# Write only on change, so an unchanged rules file does not force every target
# that compiles fl_ac_rules.cpp to rebuild.
$existing = if (Test-Path -LiteralPath $OutPath) { Get-Content -LiteralPath $OutPath -Raw } else { $null }
if ($existing -ne $header) {
Set-Content -LiteralPath $OutPath -Value $header -NoNewline -Encoding utf8
Write-Host "floor generated — $($rows.Count) families, $($fragments.Count) fragments -> $OutPath"
}
else {
Write-Host "floor unchanged — $($rows.Count) families, $($fragments.Count) fragments"
}
+23 -11
View File
@@ -407,14 +407,9 @@ function Get-HeaderConstant([string]$Name) {
$maxFamilies = Get-HeaderConstant 'kMaxFamilies'
$tokenBudget = Get-HeaderConstant 'kRulesTokenBudget'
# §S21. ParseRules seeds the compiled-in floor before it reads a byte of the
# file, so the budget available to THIS document is kMaxFamilies minus the floor.
# Read, never assumed: if the floor grows and this is not subtracted, a rules edit
# passes CI and then returns kTooLarge on every client — refuse-everything,
# published by a green build.
$floorFamilies = Get-HeaderConstant 'kFloorFamilyCount'
$maxFragments = Get-HeaderConstant 'kMaxNameFragments'
foreach ($c in @(@{ n = 'kMaxFamilies'; v = $maxFamilies }, @{ n = 'kRulesTokenBudget'; v = $tokenBudget },
@{ n = 'kFloorFamilyCount'; v = $floorFamilies })) {
@{ n = 'kMaxNameFragments'; v = $maxFragments })) {
if ($null -eq $c.v) {
Write-Host "RULES VALIDATION FAILED: could not read $($c.n) from fl_ac_rules.h" -ForegroundColor Red
Write-Host ' Either the constant was renamed or its form changed. Refusing rather than' -ForegroundColor Red
@@ -428,9 +423,23 @@ if (Test-Member $rules 'anticheat') {
foreach ($g in 'modules', 'drivers', 'directories', 'services', 'files') {
if (Test-Member $rules.anticheat $g) { $totalFamilies += @($rules.anticheat.$g).Count }
}
$fileBudget = $maxFamilies - $floorFamilies
if ($totalFamilies -gt $fileBudget) {
$errors.Add("$totalFamilies anticheat families across all groups exceeds the budget available to the FILE ($fileBudget = fl::guard::kMaxFamilies $maxFamilies - kFloorFamilyCount $floorFamilies) — ParseRules returns kTooLarge and the guard refuses EVERY title")
# §S21. The compiled-in floor is GENERATED from this file, so it holds exactly
# these families and ParseRules seeds them before reading a byte. A file family
# identical to a floor entry is then deduplicated — but a file that has DRIFTED
# from the shipped floor (an updated rules push against an older binary)
# duplicates none of it, and both copies have to fit.
#
# So the bound is 2x, not 1x. Getting this wrong does not fail here; it fails
# on every client as kTooLarge, which the guard turns into refuse-every-title.
if (($totalFamilies * 2) -gt $maxFamilies) {
$errors.Add("$totalFamilies anticheat families needs $($totalFamilies * 2) slots in the worst case (the generated floor plus a fully-drifted file) and fl::guard::kMaxFamilies is $maxFamilies — ParseRules returns kTooLarge and the guard refuses EVERY title")
}
$fragmentCount = 0
if ((Test-Member $rules.anticheat 'heuristic') -and (Test-Member $rules.anticheat.heuristic 'nameFragments')) {
$fragmentCount = @($rules.anticheat.heuristic.nameFragments).Count
}
if (($fragmentCount * 2) -gt $maxFragments) {
$errors.Add("$fragmentCount nameFragments needs $($fragmentCount * 2) slots in the worst case and fl::guard::kMaxNameFragments is $maxFragments — same failure mode as the family cap")
}
}
@@ -480,6 +489,9 @@ Write-Host "rules OK — schema v$($rules.schemaVersion), rules $($rules.rulesVe
# The families figure is against the FILE's budget, not kMaxFamilies: printing
# the raw capacity would overstate the headroom by the size of the §S21 floor,
# and this line exists to be read rather than to look reassuring.
Write-Host " capacity — $totalFamilies/$($maxFamilies - $floorFamilies) families (kMaxFamilies $maxFamilies less the $floorFamilies compiled-in floor), $tokenCount/$tokenBudget parse tokens" -ForegroundColor DarkGray
# Printed as the WORST case (floor + a fully-drifted file), not as the raw count.
# The raw count against kMaxFamilies would overstate the headroom by exactly the
# size of the floor, and this line exists to be read rather than to reassure.
Write-Host " capacity — $($totalFamilies * 2)/$maxFamilies family slots worst case, $($fragmentCount * 2)/$maxFragments fragment slots, $tokenCount/$tokenBudget parse tokens" -ForegroundColor DarkGray
Write-Host " fixtures — $($fixtureDirs.Count) corpus directories cover every engine and platform id" -ForegroundColor DarkGray
exit 0