From 4edb2c08eea80eeff05b0de8b592e9a76e554dd8 Mon Sep 17 00:00:00 2001 From: Beqa <91750923+BeqaKs@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:31:54 +0400 Subject: [PATCH] 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. --- docs/error-contract.schema.json | 38 ++- docs/reference/mcp-contracts.md | 19 ++ scripts/lib/module-layers.mjs | 7 + .../JavaScriptArtifactGraphBuilder.ts | 8 +- src/artifacts/inventory/scanCanonical.ts | 7 +- src/artifacts/inventory/scanReader.ts | 220 ++++++++++++- src/domain/analysisErrorPresentation.ts | 13 +- src/domain/analysisErrorProjectionSchema.ts | 3 + src/domain/artifactGraph.ts | 7 +- src/domain/artifactInspection.ts | 5 +- src/domain/artifactIntegrity.ts | 33 +- src/native/pe/PeCertificateAsn1.ts | 11 +- src/native/pe/PeCertificateParser.test.ts | 48 ++- src/native/pe/PeCertificateParser.ts | 163 +++++++-- src/native/pe/PeCertificates.fixture.ts | 65 ++-- src/native/pe/PeUnsignedDigest.test.ts | 155 +++++++++ src/native/pe/PeUnsignedDigest.ts | 175 ++++++++++ .../filesystem/asarSignedAfterPacking.test.ts | 308 ++++++++++++++++++ .../mcp/asarUnpackedExtractionMcp.test.ts | 45 +++ tests/fixtures/signedAfterPackingAsarAddon.ts | 43 +++ 20 files changed, 1297 insertions(+), 76 deletions(-) create mode 100644 src/native/pe/PeUnsignedDigest.test.ts create mode 100644 src/native/pe/PeUnsignedDigest.ts create mode 100644 tests/boundary/filesystem/asarSignedAfterPacking.test.ts create mode 100644 tests/fixtures/signedAfterPackingAsarAddon.ts diff --git a/docs/error-contract.schema.json b/docs/error-contract.schema.json index 00842466808..aed6718305e 100644 --- a/docs/error-contract.schema.json +++ b/docs/error-contract.schema.json @@ -836,7 +836,43 @@ "logical_path": { "type": "string" }, "declared_sha256": { "type": ["string", "null"] }, "calculated_sha256": { "type": ["string", "null"] }, - "unpacked": { "type": "boolean" } + "unpacked": { "type": "boolean" }, + "signing_explanation": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "signed-after-packing" + }, + "platform": { + "type": "string", + "const": "pe-authenticode" + }, + "unsigned_sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "certificate_table_bytes": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "signer_subjects": { + "type": "array", + "items": { "type": "string" } + }, + "signer_subjects_complete": { "type": "boolean" } + }, + "required": [ + "kind", + "platform", + "unsigned_sha256", + "certificate_table_bytes", + "signer_subjects", + "signer_subjects_complete" + ], + "additionalProperties": false + } }, "required": [ "logical_path", diff --git a/docs/reference/mcp-contracts.md b/docs/reference/mcp-contracts.md index 07cc12a6a7f..7c9445b810f 100644 --- a/docs/reference/mcp-contracts.md +++ b/docs/reference/mcp-contracts.md @@ -2163,6 +2163,25 @@ does not check unpacked companions against those hashes at runtime. Integrity failures for such entries name this cause and the operation to rerun with `record-and-continue`; REA does not exempt unpacked entries silently. +When an unpacked PE companion already mismatches and removing +`IMAGE_DIRECTORY_ENTRY_SECURITY` (plus zeroing the security directory and PE +checksum) restores the declared SHA-256, the contradiction records a +`signing_explanation` with `kind: "signed-after-packing"`, `platform: +"pe-authenticode"`, the unsigned digest, certificate-table size, and signer +subjects when PKCS#7 decoding supplies a unique issuer-and-serial match. Exact +encoded issuer identity is required; unmatched or ambiguous signers are not +named. `signer_subjects_complete: false` indicates unresolved signers, incomplete +certificate coverage, a decoding limit, or unreadable PKCS#7. The optional +reconstruction buffers the companion in memory and is capped at 67108864 bytes +(representation bound for one PE rebuild); inventory acquisition +`maximumBytes` also bounds the second read. When either budget refuses the +companion, the contradiction stays unexplained and a limitation names the +effective ceiling. This does not verify a signature or certificate chain. +Observed bytes stay `observed-untrusted` and `hash_status` remains `mismatched`; +the explanation is additive evidence, not a trust upgrade. Mach-O +code-signature growth is not classified yet. A mismatch that does not restore +the declared digest stays an ordinary unexplained contradiction. + ## Schema advertisement Advertised input and output schemas contain no reachable recursive references. diff --git a/scripts/lib/module-layers.mjs b/scripts/lib/module-layers.mjs index ff4725646d9..93a2b1eb36f 100644 --- a/scripts/lib/module-layers.mjs +++ b/scripts/lib/module-layers.mjs @@ -431,6 +431,13 @@ const isEntryFile = (unit, target) => * still is. Keep the list short and say why. */ export const PROVIDER_DEPENDENCIES = Object.freeze([ + Object.freeze({ + from: "artifacts", + to: "native", + files: Object.freeze(["pe/PeUnsignedDigest.ts"]), + reason: + "ASAR inventory explains PE Authenticode signed-after-packing integrity mismatches", + }), Object.freeze({ from: "artifacts", to: "uefi", diff --git a/src/application/javascript/JavaScriptArtifactGraphBuilder.ts b/src/application/javascript/JavaScriptArtifactGraphBuilder.ts index d4a2167d825..c73247638c4 100644 --- a/src/application/javascript/JavaScriptArtifactGraphBuilder.ts +++ b/src/application/javascript/JavaScriptArtifactGraphBuilder.ts @@ -435,9 +435,11 @@ const graphLimitations = ( ]), ...context.snapshot.limitations, ...emptyInputLimitations(context), - ...context.snapshot.integrity_contradictions.map( - ({ logical_path: path }) => - `Artifact integrity metadata contradicts observed bytes at ${path}; the observed bytes are untrusted.`, + ...context.snapshot.integrity_contradictions.map((contradiction) => + "signing_explanation" in contradiction && + contradiction.signing_explanation !== undefined + ? `Artifact integrity metadata contradicts observed bytes at ${contradiction.logical_path}; removing the Authenticode certificate table restores the declared SHA-256 (signed after packing), but the observed bytes remain untrusted.` + : `Artifact integrity metadata contradicts observed bytes at ${contradiction.logical_path}; the observed bytes are untrusted.`, ), ...selfReferenceOmissions( relationshipOmissions.selfImports, diff --git a/src/artifacts/inventory/scanCanonical.ts b/src/artifacts/inventory/scanCanonical.ts index a1a5b375830..4eeaa9dd087 100644 --- a/src/artifacts/inventory/scanCanonical.ts +++ b/src/artifacts/inventory/scanCanonical.ts @@ -604,8 +604,13 @@ const buildIntegrityContradictions = ( unpacked: contradiction.unpacked, trust: "observed-untrusted", provenance: "container-integrity-metadata-versus-observed-bytes", + ...(contradiction.signingExplanation === undefined + ? {} + : { signing_explanation: contradiction.signingExplanation }), limitations: [ - "Observed bytes contradict declared integrity metadata and cannot support equivalence.", + contradiction.signingExplanation === undefined + ? "Observed bytes contradict declared integrity metadata and cannot support equivalence." + : "Observed bytes contradict declared integrity metadata; stripping IMAGE_DIRECTORY_ENTRY_SECURITY restores the declared SHA-256 (signed-after-packing). Bytes remain observed-untrusted and cannot support equivalence.", ], }; }); diff --git a/src/artifacts/inventory/scanReader.ts b/src/artifacts/inventory/scanReader.ts index 86629f3ff7f..61d903e55ab 100644 --- a/src/artifacts/inventory/scanReader.ts +++ b/src/artifacts/inventory/scanReader.ts @@ -5,6 +5,7 @@ import { artifactIntegrityDetails, type ArtifactContainerIntegrityPair, type ArtifactIntegrityPair, + type SignedAfterPackingExplanation, } from "../../domain/artifactIntegrity.js"; import { isAbsolute } from "node:path"; import { createHash, type Hash } from "node:crypto"; @@ -21,6 +22,7 @@ import { abortIfNeeded, DirectoryArtifactEntryAccessDenied, DirectoryArtifactReader, + streamChunkToBuffer, } from "../../resources/index.js"; import { ArtifactTraversalObservation, @@ -51,12 +53,18 @@ import { DirectoryTreeDigestBuilder, type DirectoryRootDigest, } from "../../domain/directoryTreeDigest.js"; +import { + explainPeSignedAfterPacking, + MAX_SIGNED_AFTER_PACKING_PE_BYTES, + signedAfterPackingBudgetLimitation, +} from "../../native/pe/PeUnsignedDigest.js"; export interface PendingIntegrityContradiction { readonly occurrence: MutableOccurrence; readonly integrity: ArtifactIntegrityPair; readonly entryKind: "file" | "slice"; readonly unpacked: boolean; + readonly signingExplanation?: SignedAfterPackingExplanation; } const emptyScan = (): { @@ -344,6 +352,9 @@ const visitArtifactEntries = async ( | { readonly node: ArtifactNode; readonly mismatched: boolean; + readonly signingExplanation: + | SignedAfterPackingExplanation + | undefined; readonly classification: ReturnType; } | undefined; @@ -392,7 +403,9 @@ const visitArtifactEntries = async ( : "verified"; if (digested.mismatched) occurrence.limitations.push( - "Declared integrity metadata contradicts observed bytes.", + digested.signingExplanation === undefined + ? "Declared integrity metadata contradicts observed bytes." + : "Declared integrity metadata contradicts observed bytes; Authenticode signing after packing restores the declared SHA-256 when IMAGE_DIRECTORY_ENTRY_SECURITY is stripped. Bytes remain observed-untrusted.", ); } context.occurrences.push(occurrence); @@ -479,6 +492,7 @@ const digestArtifactEntry = async ( | { readonly node: ArtifactNode; readonly mismatched: boolean; + readonly signingExplanation: SignedAfterPackingExplanation | undefined; readonly classification: ReturnType; } | undefined @@ -527,21 +541,6 @@ const digestArtifactEntry = async ( { integrityCheck: "declared-digest" }, ); const mismatched = claim !== null && claim.digest !== observed; - if (mismatched && claim !== null && observed !== undefined) { - if (context.integrity === "fail") - throw new ArtifactReaderFailure( - "integrity", - `Artifact integrity metadata disagrees with content: ${logicalPath}`, - { integrityCheck: "declared-digest" }, - artifactIntegrityDetails(logicalPath, claim, observed, entry.unpacked), - ); - context.pendingContradictions.push({ - occurrence, - integrity: artifactIntegrityPair(claim, observed), - entryKind: entry.kind, - unpacked: entry.unpacked, - }); - } const sliceHeader = entry.kind === "slice" ? classifyArtifactHeader(digest, digest.bytes) @@ -555,6 +554,117 @@ const digestArtifactEntry = async ( contentArchitecture: sliceHeader.architecture, } : classifyArtifactContent(logicalPath, digest, digest.bytes); + let signingExplanation: SignedAfterPackingExplanation | undefined; + let explanationFailure: unknown; + if ( + mismatched && + claim !== null && + observed !== undefined && + entry.unpacked && + claim.algorithm === "sha256" && + classified.contentFormat === "pe" + ) { + const mismatchDetails = artifactIntegrityDetails( + logicalPath, + claim, + observed, + entry.unpacked, + ); + try { + const attempt = await explainUnpackedPeSignedAfterPacking({ + reader: currentReader, + entry, + observedBytes: digest.bytes, + observedSha256: digest.sha256, + declaredSha256: claim.digest, + signal: context.signal, + context, + }); + if (attempt.status === "explained") + signingExplanation = attempt.explanation; + else if (attempt.status === "skipped") + occurrence.limitations.push(attempt.limitation); + } catch (cause: unknown) { + if ( + cause instanceof ArtifactReaderFailure && + (cause.cleanup !== undefined || (cause.cleanupLeases?.length ?? 0) > 0) + ) { + const cleanup = ArtifactReaderFailure.cleanupObservation( + cause, + `signing explanation for ${logicalPath}`, + ); + if (context.signal?.aborted === true) + throw ArtifactReaderFailure.withCleanup( + new ArtifactReaderFailure( + "cancelled", + "Artifact inventory cancelled", + { cause: context.signal.reason }, + ), + cleanup, + cause.partialObservation, + cause.cleanupLeases, + ); + // Keep the first mismatch digest pair when the optional read's cleanup + // also fails; completed observations must survive later cleanup. + throw ArtifactReaderFailure.withCleanup( + new ArtifactReaderFailure( + "integrity", + `Artifact integrity metadata disagrees with content: ${logicalPath}`, + { + integrityCheck: "declared-digest", + cause, + }, + mismatchDetails, + ), + cleanup, + cause.partialObservation, + cause.cleanupLeases, + ); + } + abortIfNeeded(context.signal); + if ( + !(cause instanceof ArtifactEntryContentUnavailable) && + !(cause instanceof DirectoryArtifactEntryAccessDenied) && + !( + cause instanceof ArtifactReaderFailure && + (cause.reason === "io" || cause.reason === "unavailable") + ) + ) + throw cause; + if (cause.cancellation !== undefined) throw cause; + explanationFailure = cause; + occurrence.limitations.push( + `Signing explanation unavailable: ${cause instanceof ArtifactEntryContentUnavailable ? cause.limitation : cause.message}`, + ); + } + } + if (mismatched && claim !== null && observed !== undefined) { + if (context.integrity === "fail") + throw new ArtifactReaderFailure( + "integrity", + `Artifact integrity metadata disagrees with content: ${logicalPath}`, + { + integrityCheck: "declared-digest", + ...(explanationFailure === undefined + ? {} + : { cause: explanationFailure }), + }, + artifactIntegrityDetails( + logicalPath, + claim, + observed, + entry.unpacked, + signingExplanation, + ), + ); + context.pendingContradictions.push({ + occurrence, + integrity: artifactIntegrityPair(claim, observed), + entryKind: entry.kind, + unpacked: entry.unpacked, + ...(signingExplanation === undefined ? {} : { signingExplanation }), + }); + } return { node: createArtifactNode({ sha256: digest.sha256, @@ -564,10 +674,88 @@ const digestArtifactEntry = async ( contentState: "embedded", }), mismatched, + signingExplanation, classification: classified, }; }; +type SigningExplanationAttempt = + | { + readonly status: "explained"; + readonly explanation: SignedAfterPackingExplanation; + } + | { readonly status: "unexplained" } + | { readonly status: "skipped"; readonly limitation: string }; + +const explainUnpackedPeSignedAfterPacking = async (input: { + readonly reader: ArtifactReader; + readonly entry: ArtifactEntry; + readonly observedBytes: number; + readonly observedSha256: string; + readonly declaredSha256: string; + readonly signal: AbortSignal | undefined; + readonly context: ScanContext; +}): Promise => { + const { + reader, + entry, + observedBytes, + observedSha256, + declaredSha256, + signal, + context, + } = input; + if (!Number.isSafeInteger(observedBytes) || observedBytes <= 0) + return { status: "unexplained" }; + const remainingAcquisition = + context.acquisitionLimits === undefined + ? undefined + : context.acquisitionLimits.maximumBytes - context.bytesRead; + const budget = Math.min( + MAX_SIGNED_AFTER_PACKING_PE_BYTES, + remainingAcquisition ?? MAX_SIGNED_AFTER_PACKING_PE_BYTES, + ); + if (observedBytes > budget) + return { + status: "skipped", + limitation: signedAfterPackingBudgetLimitation(observedBytes, budget), + }; + const stream = await reader.open(entry, signal); + const chunks: Buffer[] = []; + const hash = createHash("sha256"); + let total = 0; + for await (const raw of stream) { + abortIfNeeded(signal); + const chunk = streamChunkToBuffer(raw); + if ( + context.acquisitionLimits !== undefined && + chunk.length > context.acquisitionLimits.maximumBytes - context.bytesRead + ) + return { + status: "skipped", + limitation: signedAfterPackingBudgetLimitation( + observedBytes, + context.acquisitionLimits.maximumBytes, + ), + }; + total += chunk.length; + if (total > observedBytes) return { status: "unexplained" }; + if (context.acquisitionLimits !== undefined) + context.bytesRead += chunk.length; + hash.update(chunk); + chunks.push(chunk); + } + if (total !== observedBytes || hash.digest("hex") !== observedSha256) + return { status: "unexplained" }; + const explanation = explainPeSignedAfterPacking( + Buffer.concat(chunks, total), + declaredSha256, + ); + return explanation === null + ? { status: "unexplained" } + : { status: "explained", explanation }; +}; + const isExpandableAsar = (entry: ArtifactEntry, logicalPath: string): boolean => entry.kind === "file" && logicalPath.toLowerCase().endsWith(".asar") && diff --git a/src/domain/analysisErrorPresentation.ts b/src/domain/analysisErrorPresentation.ts index f0c2bb1a850..d5fd06f33aa 100644 --- a/src/domain/analysisErrorPresentation.ts +++ b/src/domain/analysisErrorPresentation.ts @@ -600,11 +600,14 @@ const artifactMessage = ({ INTEGRITY_POLICY_OPERATIONS.has(operation) ) return `${ - details?.unpacked === true && - "calculatedSha256" in details && - details.calculatedSha256 !== null - ? `Declared ASAR integrity for unpacked entry ${details.logicalPath} contradicts its companion file; packaging tools commonly sign or strip unpacked native binaries after writing the archive.` - : "Artifact bytes contradict declared integrity." + "signingExplanation" in details && + details.signingExplanation?.kind === "signed-after-packing" + ? `Declared ASAR integrity for unpacked entry ${details.logicalPath} contradicts its companion file because Authenticode appears to have been applied after packing (stripping IMAGE_DIRECTORY_ENTRY_SECURITY restores the declared SHA-256).` + : details.unpacked === true && + "calculatedSha256" in details && + details.calculatedSha256 !== null + ? `Declared ASAR integrity for unpacked entry ${details.logicalPath} contradicts its companion file; packaging tools commonly sign or strip unpacked native binaries after writing the archive.` + : "Artifact bytes contradict declared integrity." } If expected, rerun ${operation === "inventory_artifact" ? "inspect_artifact" : operation} with integrity_policy=record-and-continue to retain observed bytes as untrusted; otherwise get a fresh copy.`; if (reason === "integrity") return "Artifact is invalid or has changed. Get a fresh copy and try again."; diff --git a/src/domain/analysisErrorProjectionSchema.ts b/src/domain/analysisErrorProjectionSchema.ts index 3863869587c..166cdc33b8f 100644 --- a/src/domain/analysisErrorProjectionSchema.ts +++ b/src/domain/analysisErrorProjectionSchema.ts @@ -1,6 +1,7 @@ import { z } from "zod"; import { analysisErrorRecoverySchema } from "./analysisErrorRecovery.js"; +import { signedAfterPackingExplanationSchema } from "./artifactIntegrity.js"; import { jsonValueSchema } from "./jsonValue.js"; import type { AnalysisErrorProjection } from "./analysisErrorProjection.js"; @@ -69,6 +70,8 @@ export const analysisErrorProjectionSchema = z.discriminatedUnion("code", [ declared_sha256: z.string().nullable(), calculated_sha256: z.string().nullable(), unpacked: z.boolean(), + signing_explanation: + signedAfterPackingExplanationSchema.exactOptional(), }) .catchall(jsonValueSchema), z diff --git a/src/domain/artifactGraph.ts b/src/domain/artifactGraph.ts index a97fe21a150..b72fb4d411c 100644 --- a/src/domain/artifactGraph.ts +++ b/src/domain/artifactGraph.ts @@ -5,6 +5,7 @@ import { artifactIntegrityClaimSchema, artifactSha256PairSchema, artifactMd5PairSchema, + signedAfterPackingExplanationSchema, } from "./artifactIntegrity.js"; import { artifactFormatMetadataSchema } from "./artifactFormatMetadata.js"; import { z } from "zod"; @@ -244,7 +245,11 @@ const integrityContradictionBaseSchema = z.object({ }); export const integrityContradictionSchema = z.union([ - integrityContradictionBaseSchema.extend(artifactSha256PairSchema.shape), + integrityContradictionBaseSchema.extend({ + ...artifactSha256PairSchema.shape, + /** Present when PE Authenticode stripping restores the declared SHA-256. */ + signing_explanation: signedAfterPackingExplanationSchema.exactOptional(), + }), integrityContradictionBaseSchema.extend(artifactMd5PairSchema.shape), integrityContradictionBaseSchema.extend(artifactDfuCrc32PairSchema.shape), integrityContradictionBaseSchema.extend(artifactCrc32PairSchema.shape), diff --git a/src/domain/artifactInspection.ts b/src/domain/artifactInspection.ts index 7daadcf46db..14b1add39a3 100644 --- a/src/domain/artifactInspection.ts +++ b/src/domain/artifactInspection.ts @@ -375,7 +375,10 @@ const contradictions = ( statement: value.logical_path === "." ? "The container's declared integrity contradicts its observed bytes." - : `Declared integrity for ${value.logical_path} contradicts observed bytes.`, + : "signing_explanation" in value && + value.signing_explanation !== undefined + ? `Declared integrity for ${value.logical_path} contradicts observed bytes; removing the Authenticode certificate table restores the declared SHA-256.` + : `Declared integrity for ${value.logical_path} contradicts observed bytes.`, occurrence_id: value.occurrence_id, ...artifactIntegrityPairOf(value), evidence_id: evidenceId, diff --git a/src/domain/artifactIntegrity.ts b/src/domain/artifactIntegrity.ts index 73e5c483d93..8d751d28772 100644 --- a/src/domain/artifactIntegrity.ts +++ b/src/domain/artifactIntegrity.ts @@ -81,6 +81,28 @@ export const artifactIntegrityPairOf = ( }; }; +/** + * Verifiable explanation when stripping Authenticode restores an ASAR-declared + * SHA-256. Observed companion bytes remain untrusted; this does not attest the + * signature or treat the entry as matching for equivalence. + */ +export const signedAfterPackingExplanationSchema = z.strictObject({ + kind: z.literal("signed-after-packing"), + platform: z.literal("pe-authenticode"), + unsigned_sha256: sha256, + certificate_table_bytes: z + .number() + .int() + .nonnegative() + .max(Number.MAX_SAFE_INTEGER), + signer_subjects: z.array(z.string()), + /** False when a signer identity or certificate table could not be resolved. */ + signer_subjects_complete: z.boolean(), +}); +export type SignedAfterPackingExplanation = z.infer< + typeof signedAfterPackingExplanationSchema +>; + export type ArtifactIntegrityDetails = { readonly logicalPath: string; readonly unpacked: boolean; @@ -88,6 +110,7 @@ export type ArtifactIntegrityDetails = { | { readonly declaredSha256: string | null; readonly calculatedSha256: string | null; + readonly signingExplanation?: SignedAfterPackingExplanation; } | { readonly algorithm: "md5"; @@ -107,6 +130,7 @@ export const artifactIntegrityDetails = ( claim: ArtifactIntegrityClaim | null, observed: string | null, unpacked: boolean, + signingExplanation?: SignedAfterPackingExplanation, ): ArtifactIntegrityDetails => ({ logicalPath, unpacked, @@ -116,7 +140,11 @@ export const artifactIntegrityDetails = ( declaredMd5: claim.digest, calculatedMd5: observed, } - : { declaredSha256: claim?.digest ?? null, calculatedSha256: observed }), + : { + declaredSha256: claim?.digest ?? null, + calculatedSha256: observed, + ...(signingExplanation === undefined ? {} : { signingExplanation }), + }), }); /** Error details for a container checksum that disagrees with its own bytes. */ @@ -136,6 +164,9 @@ const projectedDigests = (details: ArtifactIntegrityDetails) => { return { declared_sha256: details.declaredSha256, calculated_sha256: details.calculatedSha256, + ...(details.signingExplanation === undefined + ? {} + : { signing_explanation: details.signingExplanation }), }; return details.algorithm === "md5" ? { diff --git a/src/native/pe/PeCertificateAsn1.ts b/src/native/pe/PeCertificateAsn1.ts index fdb52b5622a..6ec7e0f2b28 100644 --- a/src/native/pe/PeCertificateAsn1.ts +++ b/src/native/pe/PeCertificateAsn1.ts @@ -105,7 +105,7 @@ const MAX_OID_ARC_BYTES = 32; // One PKCS#7 payload shares this ceiling. Real issuer and subject names are // far smaller; the cap stops one wide string from occupying the file budget. -const MAX_DECODED_NAME_BYTES = 65_536; +export const MAX_DECODED_NAME_BYTES = 65_536; interface DecodedNameBudget { remaining: number; @@ -317,6 +317,8 @@ const decodeName = ( ): { readonly text: string; readonly attributes: readonly Attribute[]; + readonly start: number; + readonly end: number; } => { const attributes: Attribute[] = []; for (const [rdnIndex, rdn] of sequence(node, "Name").entries()) { @@ -361,7 +363,12 @@ const decodeName = ( openAttributes.push(`${key}=${attribute.value}`); } finishRdn(); - return { text: renderedRdns.join(", "), attributes }; + return { + text: renderedRdns.join(", "), + attributes, + start: node.start, + end: node.end, + }; }; // RFC 5280 4.1.2.5 and X.690 11.7-11.8: UTC with seconds, a final "Z", and diff --git a/src/native/pe/PeCertificateParser.test.ts b/src/native/pe/PeCertificateParser.test.ts index 8ae05952de8..295923e8790 100644 --- a/src/native/pe/PeCertificateParser.test.ts +++ b/src/native/pe/PeCertificateParser.test.ts @@ -1017,10 +1017,9 @@ it("distinguishes an empty RDNSequence from an empty RDN", () => { const certificate = readAsn1( namedCertificate(directoryName(der(0x0c, Buffer.from("Issuer"))), derSeq()), ); - expect(parseCertificate(certificate).subject).toEqual({ - text: "", - attributes: [], - }); + const { subject } = parseCertificate(certificate); + expect(subject.text).toBe(""); + expect(subject.attributes).toEqual([]); }); it.each(["signature", "public-key", "issuer-id", "subject-id"] as const)( @@ -1582,3 +1581,44 @@ it.each([ }); }, ); + +it("stops at max_entries lazily without materializing the rest of the table", async () => { + // Two well-formed 8-byte WIN_CERTIFICATE entries. With max_entries=1 the + // lazy walk must refuse on capacity after the first entry instead of + // retaining an array of every range up front. + const entry = Buffer.alloc(8); + entry.writeUInt32LE(8, 0); + entry.writeUInt16LE(0x0200, 4); + entry.writeUInt16LE(0x0001, 6); + const table = Buffer.concat([entry, entry]); + const headerBytes = 0x200; + const bytes = Buffer.alloc(headerBytes + table.length); + bytes.writeUInt16LE(0x5a4d, 0); + bytes.writeUInt32LE(0x80, 60); + bytes.writeUInt32LE(0x4550, 0x80); + bytes.writeUInt16LE(0x14c, 0x84); + bytes.writeUInt16LE(1, 0x86); + bytes.writeUInt16LE(224, 0x94); + bytes.writeUInt16LE(0x10b, 0x98); + bytes.writeUInt32LE(headerBytes, 0x98 + 60); + bytes.writeUInt32LE(16, 0x98 + 92); + const directoryAt = 0x98 + 96 + 4 * 8; + bytes.writeUInt32LE(headerBytes, directoryAt); + bytes.writeUInt32LE(table.length, directoryAt + 4); + table.copy(bytes, headerBytes); + + const limited = inspectPeCertificatesInputSchema.parse({ + path: "/artifacts/app.exe", + max_entries: 1, + }); + await expect(parsePeCertificateFixture(bytes, limited)).rejects.toMatchObject( + { + name: "ArtifactReaderFailure", + reason: "limit", + }, + ); + + const report = await parse(bytes); + expect(report.coverage.examined_entries).toBe(2); + expect(report.entries).toHaveLength(2); +}); diff --git a/src/native/pe/PeCertificateParser.ts b/src/native/pe/PeCertificateParser.ts index 56438ed3227..8f9b608f9de 100644 --- a/src/native/pe/PeCertificateParser.ts +++ b/src/native/pe/PeCertificateParser.ts @@ -21,6 +21,7 @@ import { readAsn1, } from "./PeCertificateAsn1.js"; import { + readPeImage, readPeImageFromReader, type PeImage, } from "../../domain/native/peImage.js"; @@ -69,6 +70,51 @@ const requireRange = ( const align8 = (value: number): number => Math.ceil(value / 8) * 8; +/** Index key for an Authenticode signer: encoded issuer Name bytes plus serial. */ +const issuerSerialKey = (issuer: Buffer, serialHex: string): string => + `${serialHex}:${issuer.toString("hex")}`; + +/** + * One WIN_CERTIFICATE inside IMAGE_DIRECTORY_ENTRY_SECURITY. Offsets are relative + * to the certificate table start; `next` is the 8-byte-aligned successor offset. + */ +export interface WinCertificateEntryRange { + readonly at: number; + readonly length: number; + readonly entryEnd: number; + readonly next: number; +} + +/** + * Lazily walk every WIN_CERTIFICATE entry for structural bounds and alignment. + * Throws {@link ParseFailureError} when the table is malformed or truncated so + * callers can enforce entry limits without materializing the full table first. + */ +export function* readWinCertificateEntryRanges( + table: Buffer, +): Generator { + const reader = new BinaryReader(table, true, FORMAT); + let at = 0; + while (at < table.length) { + // Alignment padding sits inside the gap before the next 8-byte boundary. + // Bytes that remain after that boundary are a short header, including + // zeros at the start of the table. + if (table.length - at < 8) + failTruncated("WIN_CERTIFICATE header is truncated."); + const length = reader.u32(at); + if (length < 8) + fail("WIN_CERTIFICATE dwLength is shorter than its header."); + const entryEnd = at + length; + if (entryEnd > table.length) + fail("WIN_CERTIFICATE dwLength exceeds the certificate table."); + const next = align8(entryEnd); + if (next > table.length) + failTruncated("WIN_CERTIFICATE alignment padding is truncated."); + yield { at, length, entryEnd, next }; + at = next; + } +} + const LIMITATIONS = [ "This workflow does not verify signatures, certificate chains, timestamps, or Authenticode digest coverage of image bytes.", "PKCS#7 fields are decoded structurally; cryptographic validity remains unobserved.", @@ -85,7 +131,19 @@ const ABSENT_LIMITATIONS = [ "This workflow does not verify signatures, certificate chains, timestamps, or Authenticode digest coverage of image bytes.", ] as const; -const certificateTableRange = (image: PeImage, fileSize: number) => { +/** + * Locate IMAGE_DIRECTORY_ENTRY_SECURITY in a PE image. Returns null when the + * directory is absent; throws {@link ParseFailureError} when it is present but + * structurally invalid. + */ +export const certificateTableRange = ( + image: PeImage, + fileSize: number, +): { + readonly tableOffset: number; + readonly tableSize: number; + readonly directoryAt: number; +} | null => { const security = image.pe_data_directories[4]; if (security === undefined || (security.address === 0 && security.size === 0)) return null; @@ -108,6 +166,7 @@ const parsePeCertificateTable = ( table: Buffer, artifact: PeCertificates["artifact"], input: InspectPeCertificatesInput, + onSignerSubject?: (subject: string | undefined) => void, ): PeCertificates => { const format = image.bits === 64 ? "pe32-plus" : "pe32"; const machine = image.pe_machine; @@ -133,33 +192,18 @@ const parsePeCertificateTable = ( { integrityCheck: "read-coverage" }, ); const entries: PeCertificates["entries"] = []; - let at = 0; const reader = new BinaryReader(table, true, FORMAT); let examined = 0; let teletexStringCompatibilityUsed = false; let unsignedAttributesPresent = false; - while (at < table.length) { - // Alignment padding sits inside the gap before the next 8-byte boundary. - // Bytes that remain after that boundary are a short header, including - // zeros at the start of the table. - if (table.length - at < 8) - failTruncated("WIN_CERTIFICATE header is truncated."); - const length = reader.u32(at); - if (length < 8) - fail("WIN_CERTIFICATE dwLength is shorter than its header."); - const entryEnd = at + length; - if (entryEnd > table.length) - fail("WIN_CERTIFICATE dwLength exceeds the certificate table."); - const next = align8(entryEnd); - if (next > table.length) - failTruncated("WIN_CERTIFICATE alignment padding is truncated."); - examined += 1; - if (examined > input.max_entries) + for (const { at, length, entryEnd } of readWinCertificateEntryRanges(table)) { + if (examined >= input.max_entries) throw new ArtifactReaderFailure( "limit", `PE certificate table exceeds the ${String(input.max_entries)}-entry budget.`, { boundary: "capacity" }, ); + examined += 1; const revision = reader.u16(at + 4); const certificateType = reader.u16(at + 6); const entryPayload = table.subarray(at + 8, entryEnd); @@ -182,6 +226,45 @@ const parsePeCertificateTable = ( fail("WIN_CERTIFICATE has invalid PKCS#7 alignment padding."); payload = entryPayload.subarray(0, root.end); const parsed = parsePkcs7SignedData(root); + if (onSignerSubject !== undefined) { + const byIssuerSerial = new Map< + string, + { readonly subject: string; count: number } + >(); + for (const certificate of parsed.certificates) { + if (certificate.serial_hex === null) continue; + const key = issuerSerialKey( + payload.subarray( + certificate.issuer.start, + certificate.issuer.end, + ), + certificate.serial_hex, + ); + const existing = byIssuerSerial.get(key); + byIssuerSerial.set(key, { + subject: certificate.subject.text, + count: (existing?.count ?? 0) + 1, + }); + } + for (const signer of parsed.signers) { + const issuer = signer.issuer; + if (issuer === null || signer.serial_hex === null) { + onSignerSubject(undefined); + continue; + } + const match = byIssuerSerial.get( + issuerSerialKey( + payload.subarray(issuer.start, issuer.end), + signer.serial_hex, + ), + ); + onSignerSubject( + match !== undefined && match.count === 1 + ? match.subject + : undefined, + ); + } + } teletexStringCompatibilityUsed ||= parsed.teletexStringCompatibilityUsed; unsignedAttributesPresent ||= parsed.signers.some( @@ -269,7 +352,6 @@ const parsePeCertificateTable = ( }, pkcs7, }); - at = next; } const certificates = entries.reduce( (count, entry) => count + (entry.pkcs7?.certificates.length ?? 0), @@ -307,6 +389,7 @@ export const parsePeCertificatesFromHandle = async ( handle: StableArtifactHandle, artifact: PeCertificates["artifact"], input: InspectPeCertificatesInput, + onSignerSubject?: (subject: string | undefined) => void, ): Promise => { const image = await readCertificateImageAt(handle); const range = certificateTableRange(image, handle.size); @@ -314,5 +397,43 @@ export const parsePeCertificatesFromHandle = async ( range === null ? Buffer.alloc(0) : await handle.readRange(range.tableOffset, range.tableSize); - return parsePeCertificateTable(image, range, table, artifact, input); + return parsePeCertificateTable( + image, + range, + table, + artifact, + input, + onSignerSubject, + ); +}; + +/** + * Decode IMAGE_DIRECTORY_ENTRY_SECURITY from already-buffered PE bytes. Used by + * the ASAR signed-after-packing explanation path after a mismatch. + */ +export const parsePeCertificatesFromBytes = ( + bytes: Buffer, + artifact: PeCertificates["artifact"], + input: InspectPeCertificatesInput, + onSignerSubject?: (subject: string | undefined) => void, +): PeCertificates => { + let image: PeImage; + try { + image = readPeImage(bytes, "headers"); + } catch (cause) { + throw artifactParseFailure(cause, undefined); + } + const range = certificateTableRange(image, bytes.length); + const table = + range === null + ? Buffer.alloc(0) + : bytes.subarray(range.tableOffset, range.tableOffset + range.tableSize); + return parsePeCertificateTable( + image, + range, + table, + artifact, + input, + onSignerSubject, + ); }; diff --git a/src/native/pe/PeCertificates.fixture.ts b/src/native/pe/PeCertificates.fixture.ts index ed2f2d8d815..86f3af750e0 100644 --- a/src/native/pe/PeCertificates.fixture.ts +++ b/src/native/pe/PeCertificates.fixture.ts @@ -3,9 +3,15 @@ const concat = (...parts: Buffer[]): Buffer => Buffer.concat(parts); const encodeLength = (length: number): Buffer => { if (length < 0x80) return Buffer.from([length]); if (length <= 0xff) return Buffer.from([0x81, length]); - const bytes = Buffer.alloc(3); - bytes[0] = 0x82; - bytes.writeUInt16BE(length, 1); + if (length <= 0xffff) { + const bytes = Buffer.alloc(3); + bytes[0] = 0x82; + bytes.writeUInt16BE(length, 1); + return bytes; + } + const bytes = Buffer.alloc(4); + bytes[0] = 0x83; + bytes.writeUIntBE(length, 1, 3); return bytes; }; @@ -75,27 +81,35 @@ export const pkcs7SignedDataFixture = ( Buffer > > = {}, + /** Extra certificate sharing the signer serial, for ambiguous-match fixtures. */ + extraCertificateName?: string, ): Buffer => { const serial = Buffer.from([0x11, 0x22, 0x33, 0x44]); const subject = name(commonName, organization); - const tbs = seq( - context(0, integer(2)), - integer(serial), - algorithm(SHA256_RSA), + const certificateOf = (issuer: Buffer, owner: Buffer) => + seq( + seq( + context(0, integer(2)), + integer(serial), + algorithm(SHA256_RSA), + issuer, + seq(utc("250101000000Z"), utc("260101000000Z")), + owner, + seq(algorithm(RSA), bitString(Buffer.from("pubkey"))), + context( + 3, + fields.extensions ?? + seq( + seq(oid([2, 5, 29, 14]), octet(Buffer.from([0x04, 0x01, 0xaa]))), + ), + ), + ), + algorithm(SHA256_RSA), + bitString(Buffer.from("signature")), + ); + const certificate = certificateOf( fields.issuer ?? subject, - seq(utc("250101000000Z"), utc("260101000000Z")), fields.subject ?? subject, - seq(algorithm(RSA), bitString(Buffer.from("pubkey"))), - context( - 3, - fields.extensions ?? - seq(seq(oid([2, 5, 29, 14]), octet(Buffer.from([0x04, 0x01, 0xaa])))), - ), - ); - const certificate = seq( - tbs, - algorithm(SHA256_RSA), - bitString(Buffer.from("signature")), ); const signer = seq( integer(1), @@ -125,7 +139,18 @@ export const pkcs7SignedDataFixture = ( integer(1), set(algorithm(SHA256)), seq(DATA), - context(0, certificate), + context( + 0, + extraCertificateName === undefined + ? certificate + : concat( + certificateOf( + name(extraCertificateName, organization), + name(extraCertificateName, organization), + ), + certificate, + ), + ), set(signer), ); return seq(SIGNED_DATA, context(0, signedData)); diff --git a/src/native/pe/PeUnsignedDigest.test.ts b/src/native/pe/PeUnsignedDigest.test.ts new file mode 100644 index 00000000000..e135d0d6de9 --- /dev/null +++ b/src/native/pe/PeUnsignedDigest.test.ts @@ -0,0 +1,155 @@ +import { createHash } from "node:crypto"; +import { expect, it } from "vitest"; + +import { + peCertificateFixture, + peWithoutCertificateTableFixture, + pkcs7SignedDataFixture, +} from "./PeCertificates.fixture.js"; +import { parsePeCertificatesFromBytes } from "./PeCertificateParser.js"; +import { MAX_DECODED_NAME_BYTES } from "./PeCertificateAsn1.js"; +import { + explainPeSignedAfterPacking, + rebuildPeBytesWithoutCertificateTable, +} from "./PeUnsignedDigest.js"; + +const digest = (bytes: Buffer): string => + createHash("sha256").update(bytes).digest("hex"); + +const securityDirectoryAt = (plus: boolean): number => + 0x98 + (plus ? 112 : 96) + 4 * 8; + +const unsignedFixture = (plus: boolean): Buffer => { + const bytes = peWithoutCertificateTableFixture(plus); + bytes.writeUInt32LE(16, 0x98 + (plus ? 108 : 92)); + return bytes; +}; + +it.each([false, true])( + "restores the pre-signing PE%s digest when only Authenticode overlay differs", + (plus) => { + const signed = peCertificateFixture(plus, pkcs7SignedDataFixture()); + signed.writeUInt32LE(0x89abcdef, 0x98 + 64); + const unsigned = unsignedFixture(plus); + expect(rebuildPeBytesWithoutCertificateTable(signed)?.bytes).toEqual( + unsigned, + ); + expect(unsigned.readUInt32LE(0x98 + 64)).toBe(0); + expect(unsigned.readUInt32LE(securityDirectoryAt(plus))).toBe(0); + expect(unsigned.readUInt32LE(securityDirectoryAt(plus) + 4)).toBe(0); + const explained = explainPeSignedAfterPacking(signed, digest(unsigned)); + expect(explained).toMatchObject({ + kind: "signed-after-packing", + platform: "pe-authenticode", + unsigned_sha256: digest(unsigned), + certificate_table_bytes: signed.length - unsigned.length, + signer_subjects: [expect.stringContaining("commonName=REA Fixture")], + signer_subjects_complete: true, + }); + }, +); + +it.each([ + [ + "different issuer", + "Other Issuer", + [expect.stringContaining("commonName=REA Fixture")], + true, + ], + ["ambiguous duplicate", "REA Fixture", [], false], +] as const)( + "does not select a wrong signer for a shared serial: %s", + (_case, extra, expected, complete) => { + const signed = peCertificateFixture( + false, + pkcs7SignedDataFixture( + "REA Fixture", + "REA Tests", + undefined, + undefined, + {}, + extra, + ), + ); + expect( + explainPeSignedAfterPacking(signed, digest(unsignedFixture(false))), + ).toMatchObject({ + signer_subjects: expected, + signer_subjects_complete: complete, + }); + }, +); + +it("keeps the digest explanation when signer decoding exceeds its allowance", () => { + const signed = peCertificateFixture( + false, + pkcs7SignedDataFixture("A".repeat(40_000)), + ); + expect(() => + parsePeCertificatesFromBytes( + signed, + { path: "/fixture", sha256: digest(signed), bytes: signed.length }, + { path: "/fixture", max_file_bytes: signed.length, max_entries: 64 }, + ), + ).toThrow( + expect.objectContaining({ + exhausted: { allowance: "decoded-text", limit: MAX_DECODED_NAME_BYTES }, + }), + ); + expect( + explainPeSignedAfterPacking(signed, digest(unsignedFixture(false))), + ).toMatchObject({ + kind: "signed-after-packing", + signer_subjects_complete: false, + }); +}); + +it("keeps the digest explanation when PKCS#7 parsing raises ParseFailureError", () => { + const signed = peCertificateFixture(false, pkcs7SignedDataFixture()); + // Corrupt CMS content while leaving the WIN_CERTIFICATE header intact so + // reconstruction still restores the declared digest. + signed[0x210] = (signed[0x210] ?? 0) ^ 0xff; + expect(() => + parsePeCertificatesFromBytes( + signed, + { path: "/fixture", sha256: digest(signed), bytes: signed.length }, + { path: "/fixture", max_file_bytes: signed.length, max_entries: 64 }, + ), + ).toThrow( + expect.objectContaining({ + name: "ParseFailureError", + }), + ); + expect( + explainPeSignedAfterPacking(signed, digest(unsignedFixture(false))), + ).toMatchObject({ + kind: "signed-after-packing", + unsigned_sha256: digest(unsignedFixture(false)), + signer_subjects_complete: false, + }); +}); + +it("keeps a real content mismatch unexplained", () => { + const signed = peCertificateFixture(); + signed.writeUInt32LE(0x11111111, 0x98 + 64); + const unsigned = unsignedFixture(false); + unsigned[0x100] = (unsigned[0x100] ?? 0) ^ 0xff; + expect(explainPeSignedAfterPacking(signed, digest(unsigned))).toBeNull(); +}); + +it("does not explain an image without a security directory", () => { + const bytes = peWithoutCertificateTableFixture(); + expect(explainPeSignedAfterPacking(bytes, digest(bytes))).toBeNull(); +}); + +it("does not explain when the certificate table is not the sole appended delta", () => { + const signed = peCertificateFixture(); + signed.writeUInt32LE(0x22222222, 0x98 + 64); + const withTrailer = Buffer.concat([signed, Buffer.from("trailer")]); + const unsigned = Buffer.alloc(0x200); + signed.copy(unsigned, 0, 0, 0x200); + unsigned.writeUInt32LE(0, 0x98 + 64); + unsigned.writeUInt32LE(0, securityDirectoryAt(false)); + unsigned.writeUInt32LE(0, securityDirectoryAt(false) + 4); + expect(explainPeSignedAfterPacking(withTrailer, digest(unsigned))).toBeNull(); +}); diff --git a/src/native/pe/PeUnsignedDigest.ts b/src/native/pe/PeUnsignedDigest.ts new file mode 100644 index 00000000000..239187f0c93 --- /dev/null +++ b/src/native/pe/PeUnsignedDigest.ts @@ -0,0 +1,175 @@ +import type { SignedAfterPackingExplanation } from "../../domain/artifactIntegrity.js"; +import { BinaryFormatFailure } from "../../domain/binaryContainer.js"; +import { ParseFailureError } from "../../domain/parseFailure.js"; +import { readPeImage } from "../../domain/native/peImage.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; +import { ArtifactReaderFailure } from "../../resources/index.js"; +import { PeCertificateAsn1Failure } from "./PeCertificateAsn1.js"; +import { + certificateTableRange, + parsePeCertificatesFromBytes, + readWinCertificateEntryRanges, +} from "./PeCertificateParser.js"; + +/** + * Bound for the optional in-memory PE reconstruction used only after an + * unpacked integrity mismatch. Authenticode rebuild needs the whole image as + * one buffer; this representation ceiling is fixed for the release. + */ +export const MAX_SIGNED_AFTER_PACKING_PE_BYTES = 67_108_864; + +const CHECKSUM_OPTIONAL_HEADER_OFFSET = 64; + +/** + * Confirm every WIN_CERTIFICATE entry is 8-byte aligned and in-bounds before + * trusting the security directory's Size as a removable overlay. + */ +const certificateTableIsWellFormed = (table: Buffer): boolean => { + try { + for (const _entry of readWinCertificateEntryRanges(table)) { + // Consuming the generator verifies every entry header, length, and + // 8-byte alignment bound without retaining an array of all entries. + } + return true; + } catch (cause) { + if (cause instanceof ParseFailureError) return false; + throw cause; + } +}; + +/** + * Rebuild PE file bytes as they would appear before Authenticode appended + * IMAGE_DIRECTORY_ENTRY_SECURITY: remove that table's exact file range, zero the + * security directory, and zero IMAGE_OPTIONAL_HEADER.CheckSum. + * + * Returns null when the image has no usable security directory or the range is + * invalid. Does not claim the result is Authenticode-valid; it is only a + * deterministic byte reconstruction for digest comparison. + */ +export const rebuildPeBytesWithoutCertificateTable = ( + bytes: Buffer, +): { + readonly bytes: Buffer; + readonly certificateTableBytes: number; +} | null => { + let image: ReturnType; + try { + image = readPeImage(bytes, "headers"); + } catch (cause) { + if (cause instanceof BinaryFormatFailure) return null; + throw cause; + } + let range: ReturnType; + try { + range = certificateTableRange(image, bytes.length); + } catch (cause) { + if (cause instanceof ParseFailureError) return null; + throw cause; + } + if (range === null) return null; + const { tableOffset, tableSize, directoryAt } = range; + if (directoryAt + 8 > tableOffset) return null; + if ( + !certificateTableIsWellFormed( + bytes.subarray(tableOffset, tableOffset + tableSize), + ) + ) + return null; + const rebuilt = Buffer.allocUnsafe(bytes.length - tableSize); + bytes.copy(rebuilt, 0, 0, tableOffset); + bytes.copy(rebuilt, tableOffset, tableOffset + tableSize); + rebuilt.writeUInt32LE( + 0, + image.pe_optional_header_file_offset + CHECKSUM_OPTIONAL_HEADER_OFFSET, + ); + rebuilt.writeUInt32LE(0, directoryAt); + rebuilt.writeUInt32LE(0, directoryAt + 4); + return { bytes: rebuilt, certificateTableBytes: tableSize }; +}; + +const signerSubjectsFromCertificateTable = ( + bytes: Buffer, +): { + readonly subjects: string[]; + readonly complete: boolean; +} => { + const subjects: string[] = []; + const seen = new Set(); + let complete = true; + try { + const report = parsePeCertificatesFromBytes( + bytes, + { + path: "", + sha256: sha256Hex(bytes), + bytes: bytes.length, + }, + { + path: "/asar-unpacked-pe", + max_file_bytes: bytes.length, + max_entries: 64, + }, + (subject) => { + if (subject === undefined) { + complete = false; + return; + } + if (!seen.has(subject)) { + seen.add(subject); + subjects.push(subject); + } + }, + ); + if ( + report.coverage.status !== "complete" || + report.entries.some(({ pkcs7 }) => pkcs7 === null) + ) + complete = false; + return { subjects, complete }; + } catch (cause) { + if ( + cause instanceof ArtifactReaderFailure || + cause instanceof PeCertificateAsn1Failure || + cause instanceof BinaryFormatFailure || + cause instanceof ParseFailureError + ) + return { subjects, complete: false }; + throw cause; + } +}; + +/** + * When an unpacked PE's observed SHA-256 disagrees with the ASAR claim, check + * whether removing Authenticode restores the declared digest. Match is exact; + * any other mutation stays an unexplained mismatch. + * + * Returns null when reconstruction does not restore the claim. Callers must + * apply {@link MAX_SIGNED_AFTER_PACKING_PE_BYTES} (and any acquisition budget) + * before buffering bytes and report when that skip happens. + */ +export const explainPeSignedAfterPacking = ( + bytes: Buffer, + declaredSha256: string, +): SignedAfterPackingExplanation | null => { + if (bytes.length > MAX_SIGNED_AFTER_PACKING_PE_BYTES) return null; + const rebuilt = rebuildPeBytesWithoutCertificateTable(bytes); + if (rebuilt === null) return null; + const unsignedSha256 = sha256Hex(rebuilt.bytes); + if (unsignedSha256 !== declaredSha256) return null; + const signers = signerSubjectsFromCertificateTable(bytes); + return { + kind: "signed-after-packing", + platform: "pe-authenticode", + unsigned_sha256: unsignedSha256, + certificate_table_bytes: rebuilt.certificateTableBytes, + signer_subjects: signers.subjects, + signer_subjects_complete: signers.complete, + }; +}; + +/** Limitation text when the optional PE reconstruction budget refuses the companion. */ +export const signedAfterPackingBudgetLimitation = ( + observedBytes: number, + maximumBytes: number, +): string => + `Signing explanation skipped: PE companion of ${String(observedBytes)} bytes exceeds the ${String(maximumBytes)}-byte signed-after-packing reconstruction allowance.`; diff --git a/tests/boundary/filesystem/asarSignedAfterPacking.test.ts b/tests/boundary/filesystem/asarSignedAfterPacking.test.ts new file mode 100644 index 00000000000..ede4e453aef --- /dev/null +++ b/tests/boundary/filesystem/asarSignedAfterPacking.test.ts @@ -0,0 +1,308 @@ +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/, + ), + ]), + ); +}); diff --git a/tests/boundary/mcp/asarUnpackedExtractionMcp.test.ts b/tests/boundary/mcp/asarUnpackedExtractionMcp.test.ts index 1fd5a52fbad..99943a1fdd6 100644 --- a/tests/boundary/mcp/asarUnpackedExtractionMcp.test.ts +++ b/tests/boundary/mcp/asarUnpackedExtractionMcp.test.ts @@ -5,11 +5,56 @@ import { expect, onTestFinished } from "vitest"; import { artifactExtractionResultSchema } from "../../../src/domain/artifactGraph.js"; import { parseEvidence } from "../../../src/domain/evidence.js"; +import { advertisedMcpToolSchemas } from "../../fixtures/advertisedMcpTool.js"; import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; +import { createSignedAfterPackingAsarAddon } from "../../fixtures/signedAfterPackingAsarAddon.js"; import { createStrippedAsarAddon } from "../../fixtures/strippedAsarAddon.js"; import { openArtifactTarget } from "../../support/mcp/artifactSession.js"; import { mcpTest } from "../../support/mcp/mcpFixture.js"; +mcpTest( + "publishes signed companion evidence through the advertised JavaScript analysis schema", + async ({ mcp }) => { + const { archive, addon, declaredSha256 } = + await createSignedAfterPackingAsarAddon(); + const client = await openArtifactTarget(mcp, onTestFinished, archive); + const schemas = await advertisedMcpToolSchemas( + client, + "analyze_javascript_application", + ); + const response = await client.callTool({ + name: "analyze_javascript_application", + arguments: { + input_path: archive, + integrity_policy: "record-and-continue", + }, + }); + expect(response.isError, JSON.stringify(response)).not.toBe(true); + expect( + schemas.ajv.validate(schemas.outputSchema, response.structuredContent), + JSON.stringify(schemas.ajv.errors), + ).toBe(true); + expect(response.structuredContent).toMatchObject({ + normalized_result: { + integrity_contradictions: expect.arrayContaining([ + expect.objectContaining({ + logical_path: addon, + signing_explanation: expect.objectContaining({ + kind: "signed-after-packing", + platform: "pe-authenticode", + unsigned_sha256: declaredSha256, + signer_subjects: [ + expect.stringContaining("commonName=REA Fixture"), + ], + signer_subjects_complete: true, + }), + }), + ]), + }, + }); + }, +); + mcpTest( "distinguishes rewritten and missing companions across extraction retries", async ({ mcp }) => { diff --git a/tests/fixtures/signedAfterPackingAsarAddon.ts b/tests/fixtures/signedAfterPackingAsarAddon.ts new file mode 100644 index 00000000000..aa44d3e775c --- /dev/null +++ b/tests/fixtures/signedAfterPackingAsarAddon.ts @@ -0,0 +1,43 @@ +import { createHash } from "node:crypto"; +import { mkdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { createPackageWithOptions } from "@electron/asar"; + +import { + peCertificateFixture, + peWithoutCertificateTableFixture, + pkcs7SignedDataFixture, +} from "../../src/native/pe/PeCertificates.fixture.js"; +import { createTestTempDirectory } from "./temporaryDirectory.js"; + +/** ASAR whose unpacked PE companion was Authenticode-signed after packing. */ +export const createSignedAfterPackingAsarAddon = async () => { + const root = await createTestTempDirectory("rea-signed-after-packing-asar-"); + const source = join(root, "source"); + const archive = join(root, "app.asar"); + const addon = "node_modules/device/binding.node"; + const addonPath = join(source, "node_modules", "device", "binding.node"); + const signed = peCertificateFixture(false, pkcs7SignedDataFixture()); + signed.writeUInt32LE(0xfeedface, 0x98 + 64); + const original = peWithoutCertificateTableFixture(); + // This fixture has an available (but empty) security directory before signing. + original.writeUInt32LE(16, 0x98 + 92); + await mkdir(join(source, "node_modules", "device"), { recursive: true }); + await writeFile(join(source, "main.js"), "module.exports = 'observed';\n"); + await writeFile(addonPath, original); + await createPackageWithOptions(source, archive, { unpack: "*.node" }); + await writeFile( + join(`${archive}.unpacked`, "node_modules", "device", "binding.node"), + signed, + ); + return { + root, + archive, + addon, + original, + signed, + declaredSha256: createHash("sha256").update(original).digest("hex"), + observedSha256: createHash("sha256").update(signed).digest("hex"), + }; +};