mirror of
https://github.com/morluto/rea.git
synced 2026-12-02 19:57:58 +00:00
perf(pe): stream PE certificates over FileHandle (#13884)
* perf(pe): stream PE certificates over FileHandle * fix(pe): share certificate table admission across readers
This commit is contained in:
1 parent
a8ccf8b5b8
commit
eae4b4cd2e
3 files changed
+173
-52
No files matched your search
@@ -17,7 +17,10 @@ import {
|
||||
PeCertificateAsn1Failure,
|
||||
readAsn1,
|
||||
} from "./PeCertificateAsn1.js";
|
||||
import { parsePeCertificates } from "./PeCertificateParser.js";
|
||||
import {
|
||||
parsePeCertificates,
|
||||
parsePeCertificatesFromHandle,
|
||||
} from "./PeCertificateParser.js";
|
||||
|
||||
// Independent boundary examples: changing an allowance requires reviewing
|
||||
// both the admitted and rejected certificate shapes.
|
||||
@@ -76,6 +79,52 @@ it("reads PE32 and PE32+ PKCS#7 certificate tables", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("reads distant PE headers and certificates without reading the intervening image", async () => {
|
||||
const fixture = peCertificateFixture(true);
|
||||
const peAt = 0x4000;
|
||||
const headersEnd = peAt + 0x180;
|
||||
const tableAt = 2 * 1024 * 1024;
|
||||
const table = fixture.subarray(0x200);
|
||||
const bytes = Buffer.alloc(tableAt + table.length);
|
||||
fixture.copy(bytes, 0, 0, 0x80);
|
||||
fixture.copy(bytes, peAt, 0x80, 0x200);
|
||||
table.copy(bytes, tableAt);
|
||||
bytes.writeUInt32LE(peAt, 60);
|
||||
bytes.writeUInt32LE(headersEnd, peAt + 24 + 60);
|
||||
bytes.writeUInt32LE(tableAt, peAt + 24 + 112 + 4 * 8);
|
||||
|
||||
const buffered = parse(bytes);
|
||||
expect(buffered.entries).toHaveLength(1);
|
||||
expect(buffered.table?.location).toEqual({
|
||||
offset: tableAt,
|
||||
bytes: table.length,
|
||||
});
|
||||
const reads: { offset: number; length: number }[] = [];
|
||||
const streamed = await parsePeCertificatesFromHandle(
|
||||
{
|
||||
sha256: buffered.artifact.sha256,
|
||||
size: bytes.length,
|
||||
prefix: bytes.subarray(0, 4096),
|
||||
readRange: async (offset, length) => {
|
||||
reads.push({ offset, length });
|
||||
return bytes.subarray(offset, offset + length);
|
||||
},
|
||||
},
|
||||
buffered.artifact,
|
||||
defaults,
|
||||
);
|
||||
expect(streamed).toEqual(buffered);
|
||||
expect(reads.slice(0, -1).length).toBeGreaterThan(0);
|
||||
expect(
|
||||
reads
|
||||
.slice(0, -1)
|
||||
.every(
|
||||
({ offset, length }) => offset >= peAt && offset + length <= headersEnd,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(reads.at(-1)).toEqual({ offset: tableAt, length: table.length });
|
||||
});
|
||||
|
||||
it("reports unsigned attribute OIDs and incomplete nested coverage", () => {
|
||||
const types = [
|
||||
[1, 3, 6, 1, 4, 1, 311, 3, 3, 1],
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
artifactParseFailure,
|
||||
type StableArtifactHandle,
|
||||
} from "../../resources/index.js";
|
||||
import type {
|
||||
InspectPeCertificatesInput,
|
||||
@@ -14,7 +15,10 @@ import {
|
||||
PeCertificateAsn1Failure,
|
||||
readAsn1,
|
||||
} from "./PeCertificateAsn1.js";
|
||||
import { readPeImageHeaders } from "../../domain/pe/peImageHeaders.js";
|
||||
import {
|
||||
readPeImageHeaders,
|
||||
readPeImageHeadersAt,
|
||||
} from "../../domain/pe/peImageHeaders.js";
|
||||
import { sha256Hex } from "../../kernel/sha256Hex.js";
|
||||
|
||||
const fail = (message: string): never => {
|
||||
@@ -30,13 +34,29 @@ const readCertificateImageHeaders = (bytes: Buffer) => {
|
||||
}
|
||||
};
|
||||
|
||||
const requireRange = (bytes: Buffer, offset: number, length: number): void => {
|
||||
const readCertificateImageHeadersAt = async (handle: StableArtifactHandle) => {
|
||||
try {
|
||||
return await readPeImageHeadersAt(
|
||||
handle.prefix,
|
||||
handle.size,
|
||||
(offset, length) => handle.readRange(offset, length),
|
||||
);
|
||||
} catch (cause) {
|
||||
throw artifactParseFailure(cause, undefined);
|
||||
}
|
||||
};
|
||||
|
||||
const requireRange = (
|
||||
fileSize: number,
|
||||
offset: number,
|
||||
length: number,
|
||||
): void => {
|
||||
if (
|
||||
!Number.isSafeInteger(offset) ||
|
||||
!Number.isSafeInteger(length) ||
|
||||
offset < 0 ||
|
||||
length < 0 ||
|
||||
offset > bytes.length - length
|
||||
offset > fileSize - length
|
||||
)
|
||||
fail(
|
||||
`PE certificate range ${String(offset)} + ${String(length)} leaves the artifact.`,
|
||||
@@ -61,19 +81,36 @@ const ABSENT_LIMITATIONS = [
|
||||
"This workflow does not verify signatures, certificate chains, timestamps, or Authenticode digest coverage of image bytes.",
|
||||
] as const;
|
||||
|
||||
/** Decode IMAGE_DIRECTORY_ENTRY_SECURITY as a file-offset WIN_CERTIFICATE table. */
|
||||
export const parsePeCertificates = (
|
||||
bytes: Buffer,
|
||||
type CertificateHeaders = ReturnType<typeof readPeImageHeaders>;
|
||||
|
||||
const certificateTableRange = (
|
||||
headers: CertificateHeaders,
|
||||
fileSize: number,
|
||||
) => {
|
||||
const security = headers.dataDirectories[4];
|
||||
if (security === undefined || (security.address === 0 && security.size === 0))
|
||||
return null;
|
||||
const { address: tableOffset, size: tableSize } = security;
|
||||
if (tableSize === 0 || tableOffset < headers.headerSize)
|
||||
fail("PE certificate table offset overlaps headers or has zero size.");
|
||||
if (tableOffset % 8 !== 0)
|
||||
fail("PE certificate table offset must be aligned to eight bytes.");
|
||||
requireRange(fileSize, tableOffset, tableSize);
|
||||
return {
|
||||
tableOffset,
|
||||
tableSize,
|
||||
directoryAt: headers.optionalHeaderOffset + security.offset,
|
||||
};
|
||||
};
|
||||
|
||||
const parsePeCertificateTable = (
|
||||
{ machine, format }: CertificateHeaders,
|
||||
range: ReturnType<typeof certificateTableRange>,
|
||||
table: Buffer,
|
||||
artifact: PeCertificates["artifact"],
|
||||
input: InspectPeCertificatesInput,
|
||||
): PeCertificates => {
|
||||
const { machine, format, dataDirectories, headerSize, optionalHeaderOffset } =
|
||||
readCertificateImageHeaders(bytes);
|
||||
const security = dataDirectories[4];
|
||||
if (
|
||||
security === undefined ||
|
||||
(security.address === 0 && security.size === 0)
|
||||
) {
|
||||
if (range === null)
|
||||
return {
|
||||
artifact,
|
||||
format,
|
||||
@@ -83,16 +120,13 @@ export const parsePeCertificates = (
|
||||
coverage: { status: "complete", examined_entries: 0, certificates: 0 },
|
||||
limitations: [...ABSENT_LIMITATIONS],
|
||||
};
|
||||
}
|
||||
const tableOffset = security.address;
|
||||
const tableSize = security.size;
|
||||
const directoryAt = optionalHeaderOffset + security.offset;
|
||||
if (tableSize === 0 || tableOffset < headerSize)
|
||||
fail("PE certificate table offset overlaps headers or has zero size.");
|
||||
if (tableOffset % 8 !== 0)
|
||||
fail("PE certificate table offset must be aligned to eight bytes.");
|
||||
requireRange(bytes, tableOffset, tableSize);
|
||||
const table = bytes.subarray(tableOffset, tableOffset + tableSize);
|
||||
const { tableOffset, tableSize, directoryAt } = range;
|
||||
if (table.length !== tableSize)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
"PE certificate table ended before its admitted extent.",
|
||||
{ integrityCheck: "read-coverage" },
|
||||
);
|
||||
const entries: PeCertificates["entries"] = [];
|
||||
let at = 0;
|
||||
const reader = new BinaryReader(table, true, "pe-certificate-table");
|
||||
@@ -248,3 +282,36 @@ export const parsePeCertificates = (
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
/** Decode IMAGE_DIRECTORY_ENTRY_SECURITY as a file-offset WIN_CERTIFICATE table. */
|
||||
export const parsePeCertificates = (
|
||||
bytes: Buffer,
|
||||
artifact: PeCertificates["artifact"],
|
||||
input: InspectPeCertificatesInput,
|
||||
): PeCertificates => {
|
||||
const headers = readCertificateImageHeaders(bytes);
|
||||
const range = certificateTableRange(headers, bytes.length);
|
||||
const table =
|
||||
range === null
|
||||
? Buffer.alloc(0)
|
||||
: bytes.subarray(range.tableOffset, range.tableOffset + range.tableSize);
|
||||
return parsePeCertificateTable(headers, range, table, artifact, input);
|
||||
};
|
||||
|
||||
/**
|
||||
* Decode IMAGE_DIRECTORY_ENTRY_SECURITY from a verified random-access handle,
|
||||
* reading only the PE headers and the WIN_CERTIFICATE table range.
|
||||
*/
|
||||
export const parsePeCertificatesFromHandle = async (
|
||||
handle: StableArtifactHandle,
|
||||
artifact: PeCertificates["artifact"],
|
||||
input: InspectPeCertificatesInput,
|
||||
): Promise<PeCertificates> => {
|
||||
const headers = await readCertificateImageHeadersAt(handle);
|
||||
const range = certificateTableRange(headers, handle.size);
|
||||
const table =
|
||||
range === null
|
||||
? Buffer.alloc(0)
|
||||
: await handle.readRange(range.tableOffset, range.tableSize);
|
||||
return parsePeCertificateTable(headers, range, table, artifact, input);
|
||||
};
|
||||
@@ -5,8 +5,7 @@ import {
|
||||
projectStableArtifactFailure,
|
||||
projectArtifactCloseFailure,
|
||||
ArtifactReaderFailure,
|
||||
type StableArtifactSnapshot,
|
||||
readStableArtifact,
|
||||
withStableArtifactHandle,
|
||||
artifactFilePrimaryFacts,
|
||||
type ArtifactFilePrimaryFacts,
|
||||
ArtifactResourceScope,
|
||||
@@ -14,10 +13,7 @@ import {
|
||||
import type { PeCertificatesPort } from "../../ports/binaryDiagnostics/PeCertificatesPort.js";
|
||||
import type { ExecutionOptions } from "../../ports/AnalysisProvider.js";
|
||||
import { ArtifactOperationError } from "../../domain/artifactOperationError.js";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisResourceConstraintError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js";
|
||||
import {
|
||||
MAX_INSPECT_PE_CERTIFICATE_ENTRIES,
|
||||
MAX_INSPECT_PE_CERTIFICATE_FILE_BYTES,
|
||||
@@ -30,9 +26,10 @@ import {
|
||||
PeCertificateAsn1Failure,
|
||||
type PeCertificateDecodeAllowance,
|
||||
} from "./PeCertificateAsn1.js";
|
||||
import { parsePeCertificates } from "./PeCertificateParser.js";
|
||||
import { parsePeCertificatesFromHandle } from "./PeCertificateParser.js";
|
||||
|
||||
const OPERATION = "inspect_pe_certificates";
|
||||
const PE_HEADER_PREFIX_BYTES = 4096;
|
||||
|
||||
/** Portable parser over one bounded, identity-checked regular file. */
|
||||
export class PeCertificatesProvider implements PeCertificatesPort {
|
||||
@@ -52,30 +49,38 @@ export class PeCertificatesProvider implements PeCertificatesPort {
|
||||
}
|
||||
|
||||
async inspect(input: InspectPeCertificatesInput, options?: ExecutionOptions) {
|
||||
let snapshot: StableArtifactSnapshot | undefined;
|
||||
let observed:
|
||||
| { readonly sha256: string; readonly bytes: number }
|
||||
| undefined;
|
||||
try {
|
||||
return await this.#resources.run(async () => {
|
||||
snapshot = await readStableArtifact(
|
||||
return await this.#resources.run(async () =>
|
||||
withStableArtifactHandle(
|
||||
input.path,
|
||||
input.max_file_bytes,
|
||||
options?.signal,
|
||||
undefined,
|
||||
this.#resources,
|
||||
);
|
||||
return ok(
|
||||
parsePeCertificates(
|
||||
snapshot.bytes,
|
||||
{
|
||||
path: input.path,
|
||||
sha256: snapshot.sha256,
|
||||
bytes: snapshot.bytes.length,
|
||||
{
|
||||
retainBytes: (size) => Math.min(size, PE_HEADER_PREFIX_BYTES),
|
||||
signal: options?.signal,
|
||||
resourceScope: this.#resources,
|
||||
onIdentity: (identity) => {
|
||||
observed = identity;
|
||||
},
|
||||
input,
|
||||
),
|
||||
);
|
||||
});
|
||||
},
|
||||
async (handle) =>
|
||||
ok(
|
||||
await parsePeCertificatesFromHandle(
|
||||
handle,
|
||||
{
|
||||
path: input.path,
|
||||
sha256: handle.sha256,
|
||||
bytes: handle.size,
|
||||
},
|
||||
input,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (cause) {
|
||||
return err(peCertificatesFailure(cause, input, snapshot));
|
||||
return err(peCertificatesFailure(cause, input, observed));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -212,7 +217,7 @@ const peCertificatesFailurePrimary = (
|
||||
const peCertificatesFailure = (
|
||||
cause: unknown,
|
||||
input: InspectPeCertificatesInput,
|
||||
snapshot?: StableArtifactSnapshot,
|
||||
observed?: { readonly sha256: string; readonly bytes: number },
|
||||
) => {
|
||||
const primary = peCertificatesFailurePrimary(
|
||||
artifactFilePrimaryFacts(cause),
|
||||
@@ -224,6 +229,6 @@ const peCertificatesFailure = (
|
||||
input.path,
|
||||
PE_CERTIFICATES_PROVIDER.id,
|
||||
OPERATION,
|
||||
snapshot,
|
||||
observed,
|
||||
);
|
||||
};
|
||||
Reference in new issue
Block a user