Files
reverse-engineering-anything/tests/boundary/filesystem/asarSignedAfterPacking.test.ts
T
Beqa 4edb2c08ee fix(artifacts): explain ASAR PE signed-after-packing mismatches (#14702)
* fix(artifacts): explain ASAR PE signed-after-packing mismatches

When an unpacked PE companion fails ASAR integrity only because Authenticode
was applied after packing, record a verifiable signing_explanation on the
SHA-256 contradiction and error details instead of an opaque untrusted
mismatch. Bytes stay observed-untrusted; any other mutation remains an
unexplained contradiction.

Fixes #7212

* fix(artifacts): address signed-after-packing Greptile review

Catch ParseFailureError so unreadable PKCS#7 keeps the digest explanation,
share WIN_CERTIFICATE structural walks, index signer lookups, charge optional
reads to acquisition budgets with reported skips, preserve mismatch details
through cleanup failures, and inherit the shared MCP test deadline.

* fix(pe): walk WIN_CERTIFICATE entries lazily under max_entries

Convert the certificate-table walker into a generator so inspection stops at
the entry budget without materializing every range, and reconstruction can
validate structure with constant memory.
2026-11-26 10:31:54 -05:00

309 lines
11 KiB
TypeScript

import { createHash } from "node:crypto";
import { Readable } from "node:stream";
import { expect, it, vi } from "vitest";
import { AsarArtifactReader } from "../../../src/artifacts/AsarArtifactReader.js";
import {
ArtifactEntryContentUnavailable,
ArtifactReaderFailure,
type ArtifactReader,
} from "../../../src/resources/index.js";
import { scanReader } from "../../../src/artifacts/inventory/scanReader.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { createSignedAfterPackingAsarAddon } from "../../fixtures/signedAfterPackingAsarAddon.js";
import { createStrippedAsarAddon } from "../../fixtures/strippedAsarAddon.js";
import { analyzeJavaScriptApplication } from "../../support/javascriptApplicationScope.js";
it("classifies an unpacked PE signed after packing without trusting the bytes", async () => {
const { archive, addon, declaredSha256, observedSha256 } =
await createSignedAfterPackingAsarAddon();
const rejected = await analyzeJavaScriptApplication({ input_path: archive });
if (rejected.ok) throw new Error("Expected strict integrity failure");
expect(projectAnalysisError(rejected.error)).toMatchObject({
code: "artifact_integrity_mismatch",
details: {
logical_path: addon,
declared_sha256: declaredSha256,
calculated_sha256: observedSha256,
unpacked: true,
signing_explanation: {
kind: "signed-after-packing",
platform: "pe-authenticode",
unsigned_sha256: declaredSha256,
signer_subjects: [expect.stringContaining("commonName=REA Fixture")],
signer_subjects_complete: true,
},
},
});
const continued = await analyzeJavaScriptApplication({
input_path: archive,
integrity_policy: "record-and-continue",
});
if (!continued.ok) throw new Error("Expected explicit continuation");
const result = javascriptApplicationAnalysisResultSchema.parse(
continued.value.normalized_result,
);
const contradiction = result.integrity_contradictions.find(
({ logical_path }) => logical_path === addon,
);
expect(contradiction).toMatchObject({
logical_path: addon,
declared_sha256: declaredSha256,
observed_sha256: observedSha256,
trust: "observed-untrusted",
signing_explanation: {
kind: "signed-after-packing",
platform: "pe-authenticode",
unsigned_sha256: declaredSha256,
},
});
expect(contradiction?.limitations[0]).toContain("signed-after-packing");
expect(result.limitations).toEqual(
expect.arrayContaining([expect.stringContaining(addon)]),
);
});
it("keeps an ordinary unpacked mismatch unexplained", async () => {
const { archive, addon } = await createStrippedAsarAddon();
const continued = await analyzeJavaScriptApplication({
input_path: archive,
integrity_policy: "record-and-continue",
});
if (!continued.ok) throw new Error("Expected explicit continuation");
const result = javascriptApplicationAnalysisResultSchema.parse(
continued.value.normalized_result,
);
const contradiction = result.integrity_contradictions.find(
({ logical_path }) => logical_path === addon,
);
expect(contradiction).toMatchObject({
logical_path: addon,
trust: "observed-untrusted",
});
expect(contradiction).not.toHaveProperty("signing_explanation");
});
it("does not attach signing facts from a different same-sized second read", async () => {
const { archive, addon, signed } = await createSignedAfterPackingAsarAddon();
const first = Buffer.from(signed);
first[0x100] = (first[0x100] ?? 0) ^ 1;
const reader = new AsarArtifactReader(archive);
const open = reader.open.bind(reader);
let reads = 0;
vi.spyOn(reader, "open").mockImplementation(async (entry, signal) => {
if (entry.path !== addon) return open(entry, signal);
reads += 1;
return Readable.from([reads === 1 ? first : signed]);
});
try {
const result = await scanReader(
reader,
[],
undefined,
"record-and-continue",
);
const mismatch = result.pendingContradictions.find(
({ occurrence }) => occurrence.logical_path === addon,
);
expect(reads).toBe(2);
expect(mismatch?.integrity).toMatchObject({
observed_sha256: createHash("sha256").update(first).digest("hex"),
});
expect(mismatch?.signingExplanation).toBeUndefined();
} finally {
await reader.close();
}
});
it.each(["fail", "record-and-continue"] as const)(
"retains the first mismatch under %s when the explanation read is unavailable",
async (policy) => {
const { archive, addon, observedSha256 } =
await createSignedAfterPackingAsarAddon();
const reader = new AsarArtifactReader(archive);
const open = reader.open.bind(reader);
let reads = 0;
vi.spyOn(reader, "open").mockImplementation(async (entry, signal) => {
if (entry.path === addon && ++reads === 2)
throw new ArtifactEntryContentUnavailable(
"gone",
"companion unavailable",
);
return open(entry, signal);
});
try {
if (policy === "fail")
await expect(
scanReader(reader, [], undefined, policy),
).rejects.toMatchObject({
reason: "integrity",
cause: { limitation: "companion unavailable" },
});
else {
const result = await scanReader(reader, [], undefined, policy);
expect(result.pendingContradictions).toHaveLength(1);
expect(result.pendingContradictions[0]?.integrity).toMatchObject({
observed_sha256: observedSha256,
});
expect(
result.occurrences.find(({ logical_path }) => logical_path === addon)
?.limitations,
).toContain("Signing explanation unavailable: companion unavailable");
expect(
result.pendingContradictions[0]?.signingExplanation,
).toBeUndefined();
}
} finally {
await reader.close();
}
},
);
it("retains cleanup failure when cancellation arrives during the optional second read", async () => {
const { archive, addon } = await createSignedAfterPackingAsarAddon();
const reader = new AsarArtifactReader(archive);
const open = reader.open.bind(reader);
const controller = new AbortController();
const reason = new Error("stop during explanation");
let reads = 0;
vi.spyOn(reader, "open").mockImplementation(async (entry, signal) => {
if (entry.path === addon && ++reads === 2) {
controller.abort(reason);
throw ArtifactReaderFailure.withCleanup(
new ArtifactEntryContentUnavailable("gone", "companion unavailable"),
{ reason: "close failed", resources: ["companion handle"] },
);
}
return open(entry, signal);
});
try {
await expect(
scanReader(reader, [], controller.signal, "record-and-continue"),
).rejects.toMatchObject({
reason: "cancelled",
cancellation: { reason },
cleanup: { reason: "close failed", resources: ["companion handle"] },
});
} finally {
await reader.close();
}
});
it("retains the first mismatch when the optional read encounters an I/O failure", async () => {
const { archive, addon, observedSha256 } =
await createSignedAfterPackingAsarAddon();
const reader = new AsarArtifactReader(archive);
const open = reader.open.bind(reader);
let reads = 0;
vi.spyOn(reader, "open").mockImplementation(async (entry, signal) => {
if (entry.path === addon && ++reads === 2)
throw new ArtifactReaderFailure("io", "companion read failed");
return open(entry, signal);
});
try {
const result = await scanReader(
reader,
[],
undefined,
"record-and-continue",
);
expect(result.pendingContradictions[0]?.integrity).toMatchObject({
observed_sha256: observedSha256,
});
expect(
result.occurrences.find(({ logical_path }) => logical_path === addon)
?.limitations,
).toContain("Signing explanation unavailable: companion read failed");
} finally {
await reader.close();
}
});
it("preserves the first mismatch digest pair when explanation cleanup also fails", async () => {
const { archive, addon, declaredSha256, observedSha256 } =
await createSignedAfterPackingAsarAddon();
const reader = new AsarArtifactReader(archive);
const open = reader.open.bind(reader);
let reads = 0;
vi.spyOn(reader, "open").mockImplementation(async (entry, signal) => {
if (entry.path === addon && ++reads === 2)
throw ArtifactReaderFailure.withCleanup(
new ArtifactEntryContentUnavailable("gone", "companion unavailable"),
{ reason: "close failed", resources: ["companion handle"] },
);
return open(entry, signal);
});
try {
await expect(
scanReader(reader, [], undefined, "fail"),
).rejects.toMatchObject({
reason: "integrity",
integrityCheck: "declared-digest",
details: {
logicalPath: addon,
declaredSha256,
calculatedSha256: observedSha256,
},
cleanup: { reason: "close failed", resources: ["companion handle"] },
});
} finally {
await reader.close();
}
});
it("skips the signing explanation when the acquisition byte budget is exhausted", async () => {
const { signed, original, addon } = await createSignedAfterPackingAsarAddon();
const declaredSha256 = createHash("sha256").update(original).digest("hex");
const observedSha256 = createHash("sha256").update(signed).digest("hex");
let opens = 0;
const reader: ArtifactReader = {
format: "asar",
async *entries(_signal, options) {
yield {
path: addon,
kind: "file",
declaredSize: signed.length,
compressedSize: null,
executable: false,
encrypted: false,
byteOffset: null,
declaredIntegrity: { algorithm: "sha256", digest: declaredSha256 },
unpacked: true,
limitations: [],
adapterKey: addon,
};
options?.onCoverage?.({ status: "complete", limitations: [] });
},
async open() {
opens += 1;
return Readable.from([signed]);
},
provenance: () => [],
async close() {},
};
const result = await scanReader(
reader,
[reader],
undefined,
"record-and-continue",
undefined,
// First read consumes the whole allowance; the optional second read must skip.
{ maximumEntries: 10, maximumBytes: signed.length },
);
expect(opens).toBe(1);
expect(result.pendingContradictions[0]?.integrity).toMatchObject({
observed_sha256: observedSha256,
});
expect(result.pendingContradictions[0]?.signingExplanation).toBeUndefined();
expect(result.occurrences[0]?.limitations).toEqual(
expect.arrayContaining([
expect.stringMatching(
/Signing explanation skipped:.*reconstruction allowance/,
),
]),
);
});