fix(formats): fail closed instead of synthesizing containers from invalid input

The PCAP, BEAM and Apple-plist shields replaced a malformed input with a
freshly generated container instead of refusing it. On an empty or truncated
file that means the user's artifact is silently swapped for synthetic bytes
that were never derived from it, and the protection claim becomes
meaningless. The repo already treats this as a bug class (see the closed
safetensors PR: reject malformed input rather than fabricate weights) and
the directory-protection contract is explicitly fail-closed.

Throw on invalid/truncated input for those three shields, keep the existing
happy paths (a real 24-byte pcap header, a valid FOR1/BEAM form, bplist or
XML <plist>), and add malformed-input contract tests that also lock in the
"never lose the original bytes" invariant for PTX and managed assemblies.
The pcap fixtures in rea-domain-shields now start from a real global header
instead of an empty buffer.
This commit is contained in:
DeryFerd
2026-11-08 22:32:46 +07:00
parent 8cf27e34cc
commit 1ae02ea2a3
5 changed files with 130 additions and 51 deletions
+7 -1
View File
@@ -158,7 +158,13 @@ export function protectApplePlistBuffer(
exceedsBinaryPlistNestingDepth: true,
};
}
const xmlRes = protectAppleXmlPlist(rawBuffer.toString("utf8"), options);
const xmlSource = rawBuffer.toString("utf8");
if (!xmlSource.includes("<plist")) {
throw new Error(
"Invalid Apple property list: expected a binary 'bplist00' header or an XML <plist> document; refusing to synthesize a replacement plist.",
);
}
const xmlRes = protectAppleXmlPlist(xmlSource, options);
return {
buffer: Buffer.from(xmlRes.xmlPlist, "utf8"),
triggersBudgetAbort: xmlRes.triggersInternalSubsetBudgetAbort,
+9 -32
View File
@@ -250,38 +250,15 @@ export function protectErlangBeamBuffer(
const deception = buildCanaryAndDiagnosticPayloads(prng, intensity);
const parsed = parseBeamChunks(input);
const baseChunks: BeamChunkView[] = parsed.valid
? parsed.chunks.map((c) => ({ name: c.name, payload: Buffer.from(c.payload) }))
: [
{
name: "AtU8",
payload: (() => {
// Minimal valid module atoms so ExpT can reference indices.
const names = ["bla_beam_module", "module_info", "start"];
const parts: Buffer[] = [u32be(names.length)];
for (const name of names) {
const enc = Buffer.from(name, "utf8");
parts.push(Buffer.from([enc.length]), enc);
}
return Buffer.concat(parts);
})(),
},
{
name: "Code",
payload: Buffer.concat([
u32be(16),
u32be(0),
u32be(169),
u32be(4),
u32be(2),
Buffer.from("code"),
]),
},
{
name: "ExpT",
payload: Buffer.concat([u32be(1), u32be(2), u32be(0), u32be(1)]),
},
];
if (!parsed.valid) {
throw new Error(
"Invalid or truncated BEAM module: expected an IFF FOR1/BEAM container; refusing to synthesize a replacement module.",
);
}
const baseChunks: BeamChunkView[] = parsed.chunks.map((c) => ({
name: c.name,
payload: Buffer.from(c.payload),
}));
// Expand non-compact AtU8 in place (keep original atom indices).
let atomsInjected = 0;
+8 -16
View File
@@ -17,18 +17,6 @@ export interface PcapInspection {
readonly blaProtected: boolean;
}
function buildGlobalHeader(): Buffer {
const hdr = Buffer.alloc(24);
hdr.writeUInt32LE(PCAP_MAGIC_LE, 0);
hdr.writeUInt16LE(2, 4);
hdr.writeUInt16LE(4, 6);
hdr.writeInt32LE(0, 8);
hdr.writeUInt32LE(0, 12);
hdr.writeUInt32LE(65535, 16);
hdr.writeUInt32LE(1, 20); // Ethernet
return hdr;
}
function ipv4Checksum(ipHeader: Buffer): number {
let sum = 0;
for (let i = 0; i < 20; i += 2) {
@@ -198,13 +186,17 @@ export function protectPcapCaptureBuffer(
const prng = new SeededPrng(options.seed ?? "bla-pcap-shield");
const deception = buildCanaryAndDiagnosticPayloads(prng, intensity);
const base =
const hasGlobalHeader =
input.length >= 24 &&
(input.readUInt32LE(0) === PCAP_MAGIC_LE ||
input.readUInt32BE(0) === PCAP_MAGIC_LE ||
input.readUInt32LE(0) === 0xa1b23c4d)
? input
: buildGlobalHeader();
input.readUInt32LE(0) === 0xa1b23c4d);
if (!hasGlobalHeader) {
throw new Error(
"Invalid or truncated libpcap capture: expected a 24-byte global header with the pcap magic; refusing to synthesize a replacement capture.",
);
}
const base = input;
const httpPackets =
intensity === "bankrupt" ? 96 : intensity === "maximum" ? 24 : 4;
+93
View File
@@ -0,0 +1,93 @@
import { describe, expect, it } from "vitest";
import { inspectErlangBeam, protectErlangBeamBuffer } from "../src/shields/formats/erlang-beam.js";
import { inspectPcapCapture, protectPcapCaptureBuffer } from "../src/shields/formats/pcap-capture.js";
import { protectApplePlistBuffer } from "../src/shields/formats/apple-plist.js";
import { protectDotnetManagedBuffer } from "../src/shields/formats/dotnet-managed.js";
import { protectGpuPtxText } from "../src/shields/formats/gpu-ptx.js";
const u32 = (n: number): Buffer => {
const b = Buffer.alloc(4);
b.writeUInt32BE(n >>> 0);
return b;
};
const chunk = (name: string, payload: Buffer): Buffer =>
Buffer.concat([Buffer.from(name, "latin1"), u32(payload.length), payload]);
function buildMinimalBeam(): Buffer {
const atoms = ["demo_mod", "module_info"];
const atomBody = Buffer.concat([
u32(atoms.length),
...atoms.map((a) => Buffer.concat([Buffer.from([a.length]), Buffer.from(a, "utf8")])),
]);
const code = Buffer.concat([u32(16), u32(0), u32(169), u32(4), u32(2), Buffer.from("code")]);
const form = Buffer.concat([
Buffer.from("BEAM", "latin1"),
chunk("AtU8", atomBody),
chunk("Code", code),
]);
return Buffer.concat([Buffer.from("FOR1", "latin1"), u32(form.length), form]);
}
function buildMinimalPcapHeader(): Buffer {
const hdr = Buffer.alloc(24);
hdr.writeUInt32LE(0xa1b2c3d4, 0);
hdr.writeUInt16LE(2, 4);
hdr.writeUInt16LE(4, 6);
hdr.writeUInt32LE(65535, 16);
hdr.writeUInt32LE(1, 20);
return hdr;
}
describe("parser shields fail closed on malformed input", () => {
it("refuses to synthesize a replacement libpcap capture", () => {
expect(() => protectPcapCaptureBuffer(Buffer.alloc(0), {})).toThrow(/libpcap capture/);
expect(() =>
protectPcapCaptureBuffer(Buffer.from([0xd4, 0xc3, 0xb2, 0xa1, 2, 0, 4, 0]), {}),
).toThrow(/libpcap capture/);
});
it("preserves the original libpcap global header and existing bytes", () => {
const header = buildMinimalPcapHeader();
const out = protectPcapCaptureBuffer(header, { intensity: "balanced", seed: "pcap-contract" });
expect(out.buffer.subarray(0, header.length).equals(header)).toBe(true);
expect(out.buffer.length).toBeGreaterThan(header.length);
expect(inspectPcapCapture(out.buffer).validMagic).toBe(true);
});
it("refuses to synthesize a replacement BEAM module", () => {
expect(() => protectErlangBeamBuffer(Buffer.alloc(0), {})).toThrow(/BEAM module/);
expect(() => protectErlangBeamBuffer(Buffer.from("FOR1xxxxNOPE"), {})).toThrow(/BEAM module/);
});
it("keeps original BEAM atoms and chunks when the container is valid", () => {
const raw = buildMinimalBeam();
expect(inspectErlangBeam(raw).validMagic).toBe(true);
const out = protectErlangBeamBuffer(raw, { intensity: "balanced", seed: "beam-contract" });
expect(inspectErlangBeam(out.buffer).validMagic).toBe(true);
expect(out.buffer.toString("utf8")).toContain("demo_mod");
expect(out.buffer.length).toBeGreaterThan(raw.length);
});
it("refuses to synthesize a replacement Apple plist", () => {
expect(() => protectApplePlistBuffer(Buffer.alloc(0))).toThrow(/Apple property list/);
expect(() => protectApplePlistBuffer(Buffer.from("not a plist at all"))).toThrow(
/Apple property list/,
);
});
it("appends to a binary plist without losing the original bytes", () => {
const raw = Buffer.from("bplist00", "latin1");
const out = protectApplePlistBuffer(raw, { intensity: "balanced", seed: "plist-contract" });
expect(out.buffer.subarray(0, raw.length).equals(raw)).toBe(true);
});
it("never loses PTX or managed-assembly input bytes", () => {
const ptx = "hello world";
expect(protectGpuPtxText(ptx, { intensity: "balanced" }).text.startsWith(ptx)).toBe(true);
const managed = Buffer.from([0x4d, 0x5a]);
const out = protectDotnetManagedBuffer(managed, { intensity: "balanced" });
expect(out.buffer.subarray(0, managed.length).equals(managed)).toBe(true);
});
});
+13 -2
View File
@@ -30,6 +30,17 @@ import {
FIRMWARE_HARDENING_SKIP_REASON,
GPU_OBJECT_HARDENING_SKIP_REASON,
} from "../src/shields/formats/gpu-ptx.js";
/** A classic 24-byte libpcap global header with no packets. */
function pcapGlobalHeader(): Buffer {
const hdr = Buffer.alloc(24);
hdr.writeUInt32LE(0xa1b2c3d4, 0);
hdr.writeUInt16LE(2, 4);
hdr.writeUInt16LE(4, 6);
hdr.writeUInt32LE(65535, 16);
hdr.writeUInt32LE(1, 20);
return hdr;
}
import {
inspectUf2Firmware,
protectUf2FirmwareBuffer,
@@ -232,7 +243,7 @@ describe("REA domain shields — Go / Flutter / BEAM / EVM / PCAP / PTX", () =>
});
it("protects PCAP captures: magic preserved, decoy packets + canaries present", () => {
const res = protectPcapCaptureBuffer(Buffer.alloc(0), {
const res = protectPcapCaptureBuffer(pcapGlobalHeader(), {
intensity: "balanced",
seed: "pcap-test",
});
@@ -454,7 +465,7 @@ describe("REA domain shields — Go / Flutter / BEAM / EVM / PCAP / PTX", () =>
});
it("bankrupt PCAP decoys estimate past TSHARK_JSON_MAX_BYTES while staying valid libpcap", () => {
const res = protectPcapCaptureBuffer(Buffer.alloc(0), {
const res = protectPcapCaptureBuffer(pcapGlobalHeader(), {
intensity: "bankrupt",
seed: "pcap-bankrupt",
});