mirror of
https://github.com/qybaihe/bla.git
synced 2026-11-20 08:20:59 +08:00
feat(firmware): UF2 not-main-flash/file-container decoys vs REA #8230
Counter REA Uf2ArtifactReader by appending well-formed not-main-flash and file-container decoy blocks (canary/diagnostic bait, decoy families, numbering gaps) while preserving original UF2 blocks byte-exact so bootloaders still flash the real payload. Wire detector/protector/auditor, identity UF2_* limits, verify:rea (incl. url-scheme family catalog), and tests. Release bla-agents@1.6.2.
This commit is contained in:
@@ -6,6 +6,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.6.2] — 2026-11-01
|
||||
|
||||
### Added
|
||||
|
||||
- **UF2 firmware shield** (`src/shields/formats/firmware-uf2.ts`) — counters REA #8230
|
||||
(`Uf2ArtifactReader`): append-only well-formed `not-main-flash` (flag 0x1) and
|
||||
`file-container` (flag 0x1000) decoy blocks carrying canary / diagnostic /
|
||||
cognitive-armor payloads and decoy family IDs (named Microsoft registry bait +
|
||||
unknown IDs) with intentional numbering gaps so REA coverage goes unknown.
|
||||
Original UF2 blocks are preserved byte-exact; bootloaders ignore the decoys by
|
||||
spec, so flash/run behavior is unchanged. Wired into detector (`.uf2` + triple
|
||||
magic), protector, auditor, identity limits (`UF2_BLOCK_BYTES` /
|
||||
`UF2_MAX_REGIONS`), and `verify:rea`.
|
||||
|
||||
### Fixed
|
||||
|
||||
- `verify:rea` obligation-family catalog now expects REA's 26th `"url-scheme"`
|
||||
family (from Electron counter `47fa6ab37` / bla-agents@1.6.0).
|
||||
|
||||
## [1.6.1] — 2026-11-01
|
||||
|
||||
Patch release shipping CrackMe v6 Harden-Native Edition (challenge, scripts, tests, docs, website). No library or CLI behavior changes.
|
||||
|
||||
+30
@@ -1,5 +1,35 @@
|
||||
# BLA nightly development log
|
||||
|
||||
## 2026-11-01 ~02:10 (Asia/Singapore)
|
||||
|
||||
### REA delta
|
||||
- Pulled `morluto/rea`: tip now `60149282f` (was ~`69bf61f7c` / `a989c0e45` era).
|
||||
- Headline new analyzers since last countered Electron/DEX work:
|
||||
- **#8228** `feat(artifacts): inventory and extract ESP flash layouts`
|
||||
- **#8230** `feat(artifacts): inventory and extract UF2 and DfuSe firmware containers`
|
||||
- **#2816** `feat(artifacts): inspect classic iNES container regions`
|
||||
- Plus evidence/ghidra/native fixes (#8299, #8306–#8325, #8295) — no new trip-able
|
||||
budget constants beyond firmware container recognition.
|
||||
|
||||
### Done tonight
|
||||
- Countered REA **#8230** with UF2 append-only not-main-flash / file-container
|
||||
decoys (`src/shields/formats/firmware-uf2.ts` + detector/protector/auditor/
|
||||
identity/`verify:rea`/tests). Red-line: never emit main-flash decoys; never
|
||||
rewrite original blocks.
|
||||
- Fixed `verify:rea` obligation-family catalog (26 incl. `url-scheme`).
|
||||
- Gates: build OK, tests **247/247** (+1 skipped), benchmark 14/14 runtime-
|
||||
equivalent, verify:rea **74/74**.
|
||||
- Release **bla-agents@1.6.2**.
|
||||
- Queued (not done): ESP flash image (#8228) trailing/partition deception;
|
||||
DfuSe (CRC-sensitive); iNES (#2816, niche).
|
||||
|
||||
### Next step (following night)
|
||||
1. ESP flash / esp-image (#8228) counter — unsigned only; trailing undescribed
|
||||
bytes + partition-table decoys without breaking checksums/Secure Boot.
|
||||
2. Optional DfuSe counter if CRC can be recomputed safely under integrity_policy.
|
||||
3. Continue roadmap: MCP one-click polish, or empirical REA red-team of UF2 decoys.
|
||||
|
||||
|
||||
## 2026-11-01 (Asia/Shanghai)
|
||||
|
||||
### REA delta
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "bla-agents",
|
||||
"version": "1.5.3",
|
||||
"version": "1.6.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "bla-agents",
|
||||
"version": "1.5.3",
|
||||
"version": "1.6.1",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/generator": "^7.26.0",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "bla-agents",
|
||||
"version": "1.6.1",
|
||||
"version": "1.6.2",
|
||||
"description": "BLA (Blind LLM Agents) \u2014 Adversarial defense shield that protects binaries, Electron apps, JS bundles, Python, WebAssembly, SQLite, AI Models, and Android DEX/IL2CPP against AI reverse-engineering agents like REA.",
|
||||
"keywords": [
|
||||
"reverse-engineering-defense",
|
||||
|
||||
@@ -188,6 +188,9 @@ const NUMERIC_EXPECTATIONS = [
|
||||
{ name: "MAX_BUN_RETAINED_BYTES", expected: 256 * 1024 * 1024 },
|
||||
{ name: "MAX_LOGICAL_PATH_PARTS", expected: 256 },
|
||||
{ name: "MAX_LOGICAL_PATH_NODES", expected: 250_000 },
|
||||
// UF2 firmware container (REA #8230)
|
||||
{ name: "UF2_BLOCK_BYTES", expected: 512 },
|
||||
{ name: "UF2_MAX_REGIONS", expected: 65_536 },
|
||||
];
|
||||
|
||||
const OBJECT_PROP_EXPECTATIONS = [
|
||||
@@ -371,6 +374,7 @@ const EXPECTED_OBLIGATION_FAMILIES = [
|
||||
"timer",
|
||||
"promise",
|
||||
"task",
|
||||
"url-scheme",
|
||||
];
|
||||
|
||||
function main() {
|
||||
|
||||
+12
-1
@@ -198,7 +198,17 @@ export function detectArtifactFormat(targetPath: string): ArtifactFormat {
|
||||
}
|
||||
}
|
||||
|
||||
// 15. Extension-based formats
|
||||
// 15. Microsoft UF2 firmware container (three magics on a complete first block)
|
||||
if (
|
||||
header.length >= 512 &&
|
||||
header.readUInt32LE(0) === 0x0a324655 &&
|
||||
header.readUInt32LE(4) === 0x9e5d5157 &&
|
||||
header.readUInt32LE(508) === 0x0ab16f30
|
||||
) {
|
||||
return "firmware-uf2";
|
||||
}
|
||||
|
||||
// 16. Extension-based formats
|
||||
|
||||
if ([".js", ".mjs", ".cjs", ".jsx"].includes(ext)) return "javascript";
|
||||
if ([".ts", ".mts", ".cts", ".tsx"].includes(ext)) return "typescript";
|
||||
@@ -215,6 +225,7 @@ export function detectArtifactFormat(targetPath: string): ArtifactFormat {
|
||||
if ([".evm", ".bin-evm", ".solidity-bin"].includes(ext)) return "evm-bytecode";
|
||||
if ([".pcap", ".pcapng", ".cap"].includes(ext)) return "pcap-capture";
|
||||
if (ext === ".ptx") return "gpu-ptx";
|
||||
if (ext === ".uf2") return "firmware-uf2";
|
||||
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ export type ArtifactFormat =
|
||||
| "evm-bytecode"
|
||||
| "pcap-capture"
|
||||
| "gpu-ptx"
|
||||
| "firmware-uf2"
|
||||
| "directory"
|
||||
| "unknown";
|
||||
|
||||
@@ -56,6 +57,7 @@ export type ReaAttackVectorId =
|
||||
| "evm-bytecode-inspection"
|
||||
| "pcap-capture-inspection"
|
||||
| "gpu-ptx-inspection"
|
||||
| "uf2-firmware-inspection"
|
||||
| "bun-standalone-module-graph";
|
||||
|
||||
export interface ExposedSymbolOrModule {
|
||||
|
||||
@@ -1094,6 +1094,37 @@ export function auditTarget(targetPath: string): AuditReport {
|
||||
obligationLedgerNodes: isProtected ? 48 : 2,
|
||||
architecturalChaffPayloads: isProtected ? 5 : 0,
|
||||
};
|
||||
} else if (format === "firmware-uf2") {
|
||||
vulnerableVectors.add("uf2-firmware-inspection");
|
||||
const isProtected = rawBytes.includes(Buffer.from("[BLA-UF2-SHIELD]", "utf8"));
|
||||
exposedItems.push({
|
||||
id: `uf2_${basename(absPath)}`,
|
||||
name: basename(absPath),
|
||||
kind: "metadata-section",
|
||||
location: basename(absPath),
|
||||
riskLevel: isProtected ? "low" : "medium",
|
||||
reaToolUsed: "inspect_artifact / extract_artifact (Uf2ArtifactReader)",
|
||||
estimatedTokensToReconstruct: isProtected ? 62_000 : 1_600,
|
||||
estimatedCostUsd: isProtected ? 4.8 : 0.07,
|
||||
reason: isProtected
|
||||
? "Protected by BLA UF2 not-main-flash + file-container decoy flood (REA #8230)"
|
||||
: "UF2 main-flash regions fully inventoriable by REA Uf2ArtifactReader",
|
||||
});
|
||||
sim = {
|
||||
...sim,
|
||||
examinationStatus: isProtected ? "limited" : "complete",
|
||||
triggeredResourceLimits: isProtected
|
||||
? [
|
||||
"uf2-not-main-flash-blocks",
|
||||
"uf2-file-container-blocks",
|
||||
"uf2-numbering-coverage-unknown",
|
||||
]
|
||||
: [],
|
||||
totalFunctions: isProtected ? 24 : 2,
|
||||
decoyFunctionsDetectedAsReal: isProtected ? 24 : 0,
|
||||
obligationLedgerNodes: isProtected ? 56 : 2,
|
||||
architecturalChaffPayloads: isProtected ? 8 : 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ import { protectErlangBeamBuffer } from "../shields/formats/erlang-beam.js";
|
||||
import { protectEvmBytecodeBuffer } from "../shields/formats/evm-bytecode.js";
|
||||
import { protectPcapCaptureBuffer } from "../shields/formats/pcap-capture.js";
|
||||
import { protectGpuPtxText } from "../shields/formats/gpu-ptx.js";
|
||||
import { protectUf2FirmwareBuffer } from "../shields/formats/firmware-uf2.js";
|
||||
import { auditTarget } from "./auditor.js";
|
||||
|
||||
function classifyHtmlScriptTag(attrs: string): {
|
||||
@@ -499,6 +500,14 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
|
||||
chaffPayloadsEmbedded = res.canaryTokensEmbedded;
|
||||
binarySectionsPatched = 1;
|
||||
counteredVectors.add("gpu-ptx-inspection");
|
||||
} else if (format === "firmware-uf2") {
|
||||
const rawUf2 = readFileSync(absInput);
|
||||
const res = protectUf2FirmwareBuffer(rawUf2, { intensity, seed });
|
||||
writeFileSync(absOutput, res.buffer);
|
||||
decoyFunctionsInjected = res.blocksInjected;
|
||||
chaffPayloadsEmbedded = res.canaryTokensEmbedded;
|
||||
binarySectionsPatched = res.blocksInjected;
|
||||
counteredVectors.add("uf2-firmware-inspection");
|
||||
} else if (format === "directory") {
|
||||
mkdirSync(absOutput, { recursive: true });
|
||||
const walkAndProtect = (srcDir: string, dstDir: string): void => {
|
||||
|
||||
+10
-1
@@ -5,7 +5,7 @@ export const BLA_IDENTITY = Object.freeze({
|
||||
packageAlias: "bla-shield",
|
||||
cliBinary: "bla",
|
||||
cliAlias: "bla-agents",
|
||||
version: "1.6.1",
|
||||
version: "1.6.2",
|
||||
slogan: "Poison -> Exhaust -> Hallucinate. Make Reverse Engineering Bankrupt Again.",
|
||||
counterpart: {
|
||||
name: "REA",
|
||||
@@ -33,6 +33,7 @@ export const BLA_IDENTITY = Object.freeze({
|
||||
* - `src/domain/android/androidJniBindings.ts` & `src/android/AndroidJniLibraries.ts` (REA #7472)
|
||||
* - `src/domain/native/nativeExports.ts` (`MAX_NATIVE_EXPORT_ROWS`)
|
||||
* - `bridge/android/ReaJadxBridge.java` (`MAX_EXTERNAL_XREF_BYTES`, REA #8154)
|
||||
* - `src/domain/firmware/uf2.ts` (`UF2_BLOCK_BYTES`, `UF2_MAX_REGIONS`, REA #8230)
|
||||
*/
|
||||
export const REA_INTERNAL_LIMITS = Object.freeze({
|
||||
/** Maximum distinct alternatives retained in one normalized primitive value (`SEMANTIC_PRIMITIVE_CANDIDATE_LIMIT`). */
|
||||
@@ -177,4 +178,12 @@ export const REA_INTERNAL_LIMITS = Object.freeze({
|
||||
BUN_MAX_LOGICAL_PATH_NODES: 250_000,
|
||||
BUN_METADATA_CACHE_BYTES: 262_144,
|
||||
BUN_METADATA_CACHE_ENTRIES: 1_024,
|
||||
/**
|
||||
* UF2 firmware container decoder (`src/domain/firmware/uf2.ts`, REA #8230).
|
||||
* `UF2_BLOCK_BYTES` / payload area are Microsoft UF2 constants; `UF2_MAX_REGIONS`
|
||||
* is REA's retained address-discontiguous region ceiling.
|
||||
*/
|
||||
UF2_BLOCK_BYTES: 512,
|
||||
UF2_DATA_BYTES: 476,
|
||||
UF2_MAX_REGIONS: 65_536,
|
||||
});
|
||||
|
||||
@@ -208,6 +208,13 @@ export {
|
||||
FIRMWARE_HARDENING_SKIP_REASON,
|
||||
GPU_OBJECT_HARDENING_SKIP_REASON,
|
||||
} from "./shields/formats/gpu-ptx.js";
|
||||
export {
|
||||
inspectUf2Firmware,
|
||||
protectUf2FirmwareBuffer,
|
||||
isUf2Container,
|
||||
UF2_SHIELD_MARKER,
|
||||
UF2_BLOCK_BYTES,
|
||||
} from "./shields/formats/firmware-uf2.js";
|
||||
export {
|
||||
buildGoBuildInfoExhaustionPayload,
|
||||
buildFlutterPoolExhaustionPayload,
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
import { SeededPrng } from "../../core/prng.js";
|
||||
import type { ProtectionIntensity } from "../../core/types.js";
|
||||
import { REA_INTERNAL_LIMITS } from "../../identity.js";
|
||||
import { buildCanaryAndDiagnosticPayloads } from "../deception/format-payloads.js";
|
||||
|
||||
/**
|
||||
* UF2 firmware container shield — counters REA #8230
|
||||
* (`Uf2ArtifactReader` / `src/domain/firmware/uf2.ts`), which inventories and
|
||||
* extracts address-contiguous main-flash regions from Microsoft UF2 drag-and-
|
||||
* drop firmware images and reports not-main-flash / file-container / numbering
|
||||
* faults as coverage limitations.
|
||||
*
|
||||
* Red-line contract (Microsoft UF2 spec + REA decoder):
|
||||
* - Existing blocks are preserved **byte-exact**.
|
||||
* - Appended decoys ALWAYS set `UF2_FLAG_NOT_MAIN_FLASH` (0x1) and/or
|
||||
* `UF2_FLAG_FILE_CONTAINER` (0x1000). Bootloaders MUST ignore those blocks
|
||||
* when writing flash, so the developer's real payload still flashes and
|
||||
* runs. We never emit a plain main-flash decoy.
|
||||
* - Partial / invalid blocks are never introduced into the original range;
|
||||
* only well-formed 512-byte trailing blocks are appended.
|
||||
*
|
||||
* At bankrupt intensity the decoy family / numbering surface is densified so
|
||||
* REA's inventory reports many not-main-flash + file-container blocks and
|
||||
* incomplete numbering groups (coverage → unknown) without touching flash.
|
||||
*/
|
||||
|
||||
export const UF2_BLOCK_BYTES = REA_INTERNAL_LIMITS.UF2_BLOCK_BYTES;
|
||||
const UF2_DATA_OFFSET = 32;
|
||||
const UF2_DATA_BYTES = REA_INTERNAL_LIMITS.UF2_DATA_BYTES;
|
||||
const UF2_MAGIC_START0 = 0x0a32_4655;
|
||||
const UF2_MAGIC_START1 = 0x9e5d_5157;
|
||||
const UF2_MAGIC_END = 0x0ab1_6f30;
|
||||
const UF2_FLAG_NOT_MAIN_FLASH = 0x0000_0001;
|
||||
const UF2_FLAG_FILE_CONTAINER = 0x0000_1000;
|
||||
const UF2_FLAG_FAMILY_ID = 0x0000_2000;
|
||||
|
||||
/** Marker string embedded in decoy payloads (auditor / inspect). */
|
||||
export const UF2_SHIELD_MARKER = "[BLA-UF2-SHIELD]";
|
||||
|
||||
/**
|
||||
* Subset of Microsoft uf2families.json IDs that REA names (see
|
||||
* `src/domain/firmware/uf2Families.ts`). Used as decoy family bait so REA
|
||||
* inventories named families that never write flash.
|
||||
*/
|
||||
const NAMED_DECOY_FAMILIES: readonly number[] = [
|
||||
0xe48b_ff56, // RP2040
|
||||
0xe48b_ff59, // RP2350_ARM_S
|
||||
0x1c5f_21b0, // ESP32
|
||||
0xc47e_5767, // ESP32S3
|
||||
0xd42b_a06c, // ESP32C3
|
||||
0xada5_2840, // NRF52840
|
||||
0x5775_5a57, // STM32F4
|
||||
0x5511_4460, // SAMD51
|
||||
];
|
||||
|
||||
export interface Uf2Inspection {
|
||||
readonly validMagic: boolean;
|
||||
readonly blockCount: number;
|
||||
readonly blaProtected: boolean;
|
||||
readonly notMainFlashDecoyHint: boolean;
|
||||
}
|
||||
|
||||
function readBlockMagicsOk(bytes: Buffer, offset: number): boolean {
|
||||
if (offset + UF2_BLOCK_BYTES > bytes.length) return false;
|
||||
return (
|
||||
bytes.readUInt32LE(offset) === UF2_MAGIC_START0 &&
|
||||
bytes.readUInt32LE(offset + 4) === UF2_MAGIC_START1 &&
|
||||
bytes.readUInt32LE(offset + UF2_BLOCK_BYTES - 4) === UF2_MAGIC_END
|
||||
);
|
||||
}
|
||||
|
||||
/** True when the buffer begins with a complete, well-formed UF2 block. */
|
||||
export function isUf2Container(bytes: Buffer): boolean {
|
||||
return readBlockMagicsOk(bytes, 0);
|
||||
}
|
||||
|
||||
export function inspectUf2Firmware(bytes: Buffer): Uf2Inspection {
|
||||
const validMagic = isUf2Container(bytes);
|
||||
const blockCount = validMagic
|
||||
? Math.floor(bytes.length / UF2_BLOCK_BYTES)
|
||||
: 0;
|
||||
const marker = Buffer.from(UF2_SHIELD_MARKER, "utf8");
|
||||
return {
|
||||
validMagic,
|
||||
blockCount,
|
||||
blaProtected: bytes.includes(marker),
|
||||
notMainFlashDecoyHint: bytes.includes(marker),
|
||||
};
|
||||
}
|
||||
|
||||
function writeUf2Block(fields: {
|
||||
readonly flags: number;
|
||||
readonly address: number;
|
||||
readonly payload: Buffer;
|
||||
readonly blockNo: number;
|
||||
readonly numBlocks: number;
|
||||
readonly familyOrSize: number;
|
||||
}): Buffer {
|
||||
const block = Buffer.alloc(UF2_BLOCK_BYTES, 0);
|
||||
const size = Math.min(fields.payload.length, UF2_DATA_BYTES);
|
||||
block.writeUInt32LE(UF2_MAGIC_START0, 0);
|
||||
block.writeUInt32LE(UF2_MAGIC_START1, 4);
|
||||
block.writeUInt32LE(fields.flags >>> 0, 8);
|
||||
block.writeUInt32LE(fields.address >>> 0, 12);
|
||||
block.writeUInt32LE(size, 16);
|
||||
block.writeUInt32LE(fields.blockNo >>> 0, 20);
|
||||
block.writeUInt32LE(fields.numBlocks >>> 0, 24);
|
||||
block.writeUInt32LE(fields.familyOrSize >>> 0, 28);
|
||||
fields.payload.subarray(0, size).copy(block, UF2_DATA_OFFSET);
|
||||
block.writeUInt32LE(UF2_MAGIC_END, UF2_BLOCK_BYTES - 4);
|
||||
return block;
|
||||
}
|
||||
|
||||
function decoyPayload(prng: SeededPrng, text: string, tag: string): Buffer {
|
||||
const body = Buffer.from(
|
||||
`${UF2_SHIELD_MARKER}\n${tag}\n${text}\nnonce=${prng.hex(16)}\n`,
|
||||
"utf8",
|
||||
);
|
||||
if (body.length <= UF2_DATA_BYTES) return body;
|
||||
return body.subarray(0, UF2_DATA_BYTES);
|
||||
}
|
||||
|
||||
function intensityPlan(intensity: ProtectionIntensity): {
|
||||
readonly namedFamilies: number;
|
||||
readonly unknownFamilies: number;
|
||||
readonly notMainPerFamily: number;
|
||||
readonly fileContainers: number;
|
||||
readonly numberingGaps: boolean;
|
||||
} {
|
||||
switch (intensity) {
|
||||
case "stealth":
|
||||
return {
|
||||
namedFamilies: 1,
|
||||
unknownFamilies: 1,
|
||||
notMainPerFamily: 2,
|
||||
fileContainers: 1,
|
||||
numberingGaps: false,
|
||||
};
|
||||
case "balanced":
|
||||
return {
|
||||
namedFamilies: 3,
|
||||
unknownFamilies: 2,
|
||||
notMainPerFamily: 4,
|
||||
fileContainers: 4,
|
||||
numberingGaps: true,
|
||||
};
|
||||
case "maximum":
|
||||
return {
|
||||
namedFamilies: 6,
|
||||
unknownFamilies: 6,
|
||||
notMainPerFamily: 8,
|
||||
fileContainers: 12,
|
||||
numberingGaps: true,
|
||||
};
|
||||
case "bankrupt":
|
||||
return {
|
||||
namedFamilies: NAMED_DECOY_FAMILIES.length,
|
||||
unknownFamilies: 16,
|
||||
notMainPerFamily: 12,
|
||||
fileContainers: 32,
|
||||
numberingGaps: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Protect a UF2 firmware image by appending well-formed not-main-flash and
|
||||
* file-container decoy blocks. Original blocks (including any real main-flash
|
||||
* payload) are never rewritten.
|
||||
*/
|
||||
export function protectUf2FirmwareBuffer(
|
||||
input: Buffer,
|
||||
options: {
|
||||
readonly intensity?: ProtectionIntensity;
|
||||
readonly seed?: string;
|
||||
} = {},
|
||||
): {
|
||||
readonly buffer: Buffer;
|
||||
readonly blocksInjected: number;
|
||||
readonly notMainFlashBlocks: number;
|
||||
readonly fileContainerBlocks: number;
|
||||
readonly decoyFamilies: number;
|
||||
readonly canaryTokensEmbedded: number;
|
||||
readonly diagnosticsEmbedded: number;
|
||||
readonly originalBlocksPreserved: number;
|
||||
} {
|
||||
const intensity = options.intensity ?? "balanced";
|
||||
const prng = new SeededPrng(options.seed ?? "bla-uf2-shield");
|
||||
const deception = buildCanaryAndDiagnosticPayloads(prng, intensity);
|
||||
const plan = intensityPlan(intensity);
|
||||
|
||||
const base = isUf2Container(input) ? input : Buffer.alloc(0);
|
||||
// Preserve only complete trailing blocks of a valid container; drop a
|
||||
// trailing partial (REA already excludes partial finals) so we append on a
|
||||
// block boundary without rewriting earlier bytes.
|
||||
const preservedLength =
|
||||
base.length === 0
|
||||
? 0
|
||||
: Math.floor(base.length / UF2_BLOCK_BYTES) * UF2_BLOCK_BYTES;
|
||||
const preserved = preservedLength === base.length ? base : base.subarray(0, preservedLength);
|
||||
const originalBlocksPreserved = preservedLength / UF2_BLOCK_BYTES;
|
||||
|
||||
const injected: Buffer[] = [];
|
||||
let notMainFlashBlocks = 0;
|
||||
let fileContainerBlocks = 0;
|
||||
const familyIds = new Set<number>();
|
||||
|
||||
const named = NAMED_DECOY_FAMILIES.slice(0, plan.namedFamilies);
|
||||
const unknown: number[] = [];
|
||||
for (let i = 0; i < plan.unknownFamilies; i++) {
|
||||
// High-bit decoy IDs outside the small Microsoft registry REA embeds.
|
||||
unknown.push((0xa11ce000 + (prng.nextInt(0, 0xffff) << 4) + i) >>> 0);
|
||||
}
|
||||
const families = [...named, ...unknown];
|
||||
|
||||
for (const familyId of families) {
|
||||
familyIds.add(familyId);
|
||||
const declared = plan.notMainPerFamily;
|
||||
// Emit fewer than declared (and optionally skip block 0) so REA records
|
||||
// absent / out-of-range numbering for this decoy family — coverage unknown.
|
||||
const emitCount = plan.numberingGaps
|
||||
? Math.max(1, declared - 1 - (declared > 3 ? 1 : 0))
|
||||
: declared;
|
||||
const startNo = plan.numberingGaps && declared > 2 ? 1 : 0;
|
||||
for (let i = 0; i < emitCount; i++) {
|
||||
const record =
|
||||
deception.textRecords[
|
||||
(injected.length + i) % Math.max(1, deception.textRecords.length)
|
||||
] ?? `family=0x${familyId.toString(16)}`;
|
||||
const payload = decoyPayload(
|
||||
prng,
|
||||
record,
|
||||
`not-main-flash family=0x${familyId.toString(16)}`,
|
||||
);
|
||||
injected.push(
|
||||
writeUf2Block({
|
||||
flags: UF2_FLAG_NOT_MAIN_FLASH | UF2_FLAG_FAMILY_ID,
|
||||
address: 0x1000_0000 + (familyId & 0xffff) * 0x1000 + i * 256,
|
||||
payload,
|
||||
blockNo: startNo + i,
|
||||
numBlocks: declared,
|
||||
familyOrSize: familyId,
|
||||
}),
|
||||
);
|
||||
notMainFlashBlocks += 1;
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < plan.fileContainers; i++) {
|
||||
const familyId =
|
||||
families[i % Math.max(1, families.length)] ?? 0xb1a00d00;
|
||||
familyIds.add(familyId >>> 0);
|
||||
const record =
|
||||
deception.textRecords[i % Math.max(1, deception.textRecords.length)] ??
|
||||
"file-container";
|
||||
const payload = decoyPayload(
|
||||
prng,
|
||||
record,
|
||||
`file-container idx=${i}`,
|
||||
);
|
||||
// File-container flag alone is enough; REA treats it as overriding
|
||||
// not-main-flash. We still OR not-main-flash for belt-and-suspenders
|
||||
// bootloader safety on idiosyncratic flashers.
|
||||
injected.push(
|
||||
writeUf2Block({
|
||||
flags:
|
||||
UF2_FLAG_FILE_CONTAINER |
|
||||
UF2_FLAG_NOT_MAIN_FLASH |
|
||||
UF2_FLAG_FAMILY_ID,
|
||||
address: 0x2000_0000 + i * 512,
|
||||
payload,
|
||||
blockNo: i,
|
||||
numBlocks: plan.fileContainers,
|
||||
familyOrSize: familyId >>> 0,
|
||||
}),
|
||||
);
|
||||
fileContainerBlocks += 1;
|
||||
}
|
||||
|
||||
// Hard ceiling: never approach UF2_MAX_REGIONS with flash regions — we emit
|
||||
// zero main-flash decoys. Keep total injected blocks well under staging.
|
||||
const maxInjected = Math.min(
|
||||
injected.length,
|
||||
Math.floor(REA_INTERNAL_LIMITS.FIRMWARE_MAX_STAGING_BYTES / UF2_BLOCK_BYTES / 4),
|
||||
);
|
||||
const clipped = injected.slice(0, maxInjected);
|
||||
// not-main blocks are emitted first; file-container blocks follow.
|
||||
const clippedNotMain = Math.min(notMainFlashBlocks, clipped.length);
|
||||
const clippedFile = Math.min(
|
||||
fileContainerBlocks,
|
||||
Math.max(0, clipped.length - clippedNotMain),
|
||||
);
|
||||
|
||||
return {
|
||||
buffer: Buffer.concat([preserved, ...clipped]),
|
||||
blocksInjected: clipped.length,
|
||||
notMainFlashBlocks: clippedNotMain,
|
||||
fileContainerBlocks: clippedFile,
|
||||
decoyFamilies: familyIds.size,
|
||||
canaryTokensEmbedded: deception.canary.syntheticCanaryTokens.length,
|
||||
diagnosticsEmbedded: deception.diagnostics.diagnosticsInjected.length,
|
||||
originalBlocksPreserved,
|
||||
};
|
||||
}
|
||||
@@ -82,13 +82,14 @@ export function protectGpuPtxText(
|
||||
}
|
||||
|
||||
/**
|
||||
* Firmware images (raw flash dumps, U-Boot ITB, Android boot.img, etc.) are
|
||||
* NOT hardened by BLA: generic mutation cannot preserve boot signatures,
|
||||
* CRC/header integrity, or device-specific layouts without a per-vendor
|
||||
* parser. Prefer leaving firmware untouched rather than risking bricking.
|
||||
* Generic firmware images (raw flash dumps, U-Boot ITB, Android boot.img,
|
||||
* DfuSe with trailing CRC, signed ESP images, etc.) are NOT mutated by BLA:
|
||||
* boot signatures / CRCs / vendor headers would break. Microsoft UF2 is the
|
||||
* exception — see `firmware-uf2.ts` — because not-main-flash / file-container
|
||||
* blocks are ignored by bootloaders by spec (REA #8230).
|
||||
*/
|
||||
export const FIRMWARE_HARDENING_SKIP_REASON =
|
||||
"Firmware images are skipped: safe generic mutation would break boot signatures, CRCs, or vendor headers. No BLA firmware shield is offered.";
|
||||
"Generic firmware images are skipped (boot signatures/CRCs/vendor headers). UF2 is hardened separately via not-main-flash/file-container decoys (firmware-uf2).";
|
||||
|
||||
/**
|
||||
* SPIR-V modules, CUDA fatbinaries, and AMD GPU code objects are skipped:
|
||||
|
||||
@@ -84,6 +84,18 @@ describe("bla_harden auto-discovery + one-sentence UX", () => {
|
||||
join(dist, "kernels.ptx"),
|
||||
`.version 7.5\n.target sm_70\n.address_size 64\n.visible .entry k(.param .u64 a){ ret; }\n`,
|
||||
);
|
||||
// Minimal well-formed UF2 block (not-main-flash decoy carrier)
|
||||
const uf2 = Buffer.alloc(512, 0);
|
||||
uf2.writeUInt32LE(0x0a324655, 0);
|
||||
uf2.writeUInt32LE(0x9e5d5157, 4);
|
||||
uf2.writeUInt32LE(0x00002001, 8); // familyId | notMainFlash
|
||||
uf2.writeUInt32LE(0, 12);
|
||||
uf2.writeUInt32LE(16, 16);
|
||||
uf2.writeUInt32LE(0, 20);
|
||||
uf2.writeUInt32LE(1, 24);
|
||||
uf2.writeUInt32LE(0xe48bff56, 28);
|
||||
uf2.writeUInt32LE(0x0ab16f30, 508);
|
||||
writeFileSync(join(dist, "board.uf2"), uf2);
|
||||
|
||||
writeFileSync(
|
||||
join(dist, "payload.py"),
|
||||
@@ -107,6 +119,7 @@ describe("bla_harden auto-discovery + one-sentence UX", () => {
|
||||
"evm-bytecode",
|
||||
"pcap-capture",
|
||||
"gpu-ptx",
|
||||
"firmware-uf2",
|
||||
]),
|
||||
);
|
||||
expect(discovered.every((d) => !d.path.includes("node_modules"))).toBe(true);
|
||||
|
||||
@@ -30,6 +30,12 @@ import {
|
||||
FIRMWARE_HARDENING_SKIP_REASON,
|
||||
GPU_OBJECT_HARDENING_SKIP_REASON,
|
||||
} from "../src/shields/formats/gpu-ptx.js";
|
||||
import {
|
||||
inspectUf2Firmware,
|
||||
protectUf2FirmwareBuffer,
|
||||
UF2_BLOCK_BYTES,
|
||||
UF2_SHIELD_MARKER,
|
||||
} from "../src/shields/formats/firmware-uf2.js";
|
||||
import { detectArtifactFormat } from "../src/core/detector.js";
|
||||
import { SeededPrng } from "../src/core/prng.js";
|
||||
import * as fs from "node:fs";
|
||||
@@ -267,6 +273,56 @@ describe("REA domain shields — Go / Flutter / BEAM / EVM / PCAP / PTX", () =>
|
||||
fs.unlinkSync(tmp);
|
||||
});
|
||||
|
||||
|
||||
it("protects UF2 firmware: original blocks byte-exact, only not-main/file-container decoys", () => {
|
||||
// Minimal real main-flash block (RP2040 family) — must survive untouched.
|
||||
const real = Buffer.alloc(UF2_BLOCK_BYTES, 0);
|
||||
real.writeUInt32LE(0x0a324655, 0);
|
||||
real.writeUInt32LE(0x9e5d5157, 4);
|
||||
real.writeUInt32LE(0x00002000, 8); // familyId flag only (MAIN flash)
|
||||
real.writeUInt32LE(0x10000000, 12);
|
||||
real.writeUInt32LE(256, 16);
|
||||
real.writeUInt32LE(0, 20);
|
||||
real.writeUInt32LE(1, 24);
|
||||
real.writeUInt32LE(0xe48bff56, 28); // RP2040
|
||||
real.write("REAL_FLASH_PAYLOAD", 32, "utf8");
|
||||
real.writeUInt32LE(0x0ab16f30, UF2_BLOCK_BYTES - 4);
|
||||
|
||||
const res = protectUf2FirmwareBuffer(real, {
|
||||
intensity: "balanced",
|
||||
seed: "uf2-test",
|
||||
});
|
||||
expect(res.originalBlocksPreserved).toBe(1);
|
||||
expect(res.blocksInjected).toBeGreaterThanOrEqual(8);
|
||||
expect(res.notMainFlashBlocks).toBeGreaterThan(0);
|
||||
expect(res.fileContainerBlocks).toBeGreaterThan(0);
|
||||
expect(res.canaryTokensEmbedded).toBeGreaterThan(0);
|
||||
// Prefix byte-exact
|
||||
expect(res.buffer.subarray(0, UF2_BLOCK_BYTES).equals(real)).toBe(true);
|
||||
expect(res.buffer.includes(Buffer.from(UF2_SHIELD_MARKER, "utf8"))).toBe(true);
|
||||
expect(res.buffer.includes(Buffer.from("REAL_FLASH_PAYLOAD", "utf8"))).toBe(true);
|
||||
|
||||
// Every injected block must carry not-main-flash and/or file-container.
|
||||
for (let off = UF2_BLOCK_BYTES; off + UF2_BLOCK_BYTES <= res.buffer.length; off += UF2_BLOCK_BYTES) {
|
||||
expect(res.buffer.readUInt32LE(off)).toBe(0x0a324655);
|
||||
expect(res.buffer.readUInt32LE(off + 4)).toBe(0x9e5d5157);
|
||||
expect(res.buffer.readUInt32LE(off + UF2_BLOCK_BYTES - 4)).toBe(0x0ab16f30);
|
||||
const flags = res.buffer.readUInt32LE(off + 8);
|
||||
const safe = (flags & 0x1) !== 0 || (flags & 0x1000) !== 0;
|
||||
expect(safe).toBe(true);
|
||||
}
|
||||
|
||||
const after = inspectUf2Firmware(res.buffer);
|
||||
expect(after.validMagic).toBe(true);
|
||||
expect(after.blaProtected).toBe(true);
|
||||
expect(after.blockCount).toBe(1 + res.blocksInjected);
|
||||
|
||||
const tmp = path.join(os.tmpdir(), `bla-uf2-${Date.now()}.uf2`);
|
||||
fs.writeFileSync(tmp, res.buffer);
|
||||
expect(detectArtifactFormat(tmp)).toBe("firmware-uf2");
|
||||
fs.unlinkSync(tmp);
|
||||
});
|
||||
|
||||
it("plants Go buildinfo into mapped .go.buildinfo and Flutter pool into isolate region", () => {
|
||||
const fixture = buildMappedGoFlutterElfFixture();
|
||||
const layoutBefore = validateElf64Layout(fixture);
|
||||
|
||||
Reference in New Issue
Block a user