feat(artifacts): inspect PE resource identities and payload ranges (#1482)

* feat(artifacts): inspect PE resource identities and payload ranges

* fix(artifacts): reject header payloads overlapping PE sections

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
Thang Luu
2026-10-10 23:02:06 +08:00
committed by GitHub
co-authored by morluto
parent f6009d0077
commit 905e4866c4
26 changed files with 1694 additions and 3 deletions
+143
View File
@@ -0,0 +1,143 @@
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
export const peFailure = (message: string): never => {
throw new ArtifactReaderFailure("format", message);
};
export const requirePeRange = (
bytes: Buffer,
offset: number,
length: number,
): void => {
if (
!Number.isSafeInteger(offset) ||
!Number.isSafeInteger(length) ||
offset < 0 ||
length < 0 ||
offset > bytes.length - length
)
peFailure(
`PE range ${String(offset)} + ${String(length)} leaves the artifact.`,
);
};
interface Section {
readonly rva: number;
readonly virtualSize: number;
readonly offset: number;
readonly size: number;
}
/** Header admission and unambiguous file-backed RVA mapping, independent of section names. */
export const readPeResourceLayout = (bytes: Buffer) => {
requirePeRange(bytes, 0, 64);
if (bytes.readUInt16LE(0) !== 0x5a4d) peFailure("Expected an MZ PE image.");
const pe = bytes.readUInt32LE(60);
requirePeRange(bytes, pe, 24);
if (bytes.readUInt32LE(pe) !== 0x4550) peFailure("Expected a PE signature.");
const sectionCount = bytes.readUInt16LE(pe + 6);
const optionalSize = bytes.readUInt16LE(pe + 20);
const optional = pe + 24;
requirePeRange(bytes, optional, optionalSize);
if (optionalSize < 64) peFailure("Truncated PE optional header.");
const magic = bytes.readUInt16LE(optional);
if (magic !== 0x10b && magic !== 0x20b)
peFailure("Unsupported PE optional header magic.");
const countAt = magic === 0x10b ? 92 : 108;
const directoriesAt = countAt + 4;
if (optionalSize < directoriesAt)
peFailure("Truncated PE data directory count.");
const directoryCount = bytes.readUInt32LE(optional + countAt);
if (directoryCount > Math.floor((optionalSize - directoriesAt) / 8))
peFailure("PE directory count exceeds its optional header.");
const headerSize = bytes.readUInt32LE(optional + 60);
const table = optional + optionalSize;
requirePeRange(bytes, table, sectionCount * 40);
if (headerSize < table + sectionCount * 40 || headerSize > bytes.length)
peFailure("Invalid PE SizeOfHeaders.");
const sections: Section[] = [];
for (let index = 0; index < sectionCount; index++) {
const at = table + index * 40;
const section = {
rva: bytes.readUInt32LE(at + 12),
virtualSize: bytes.readUInt32LE(at + 8),
offset: bytes.readUInt32LE(at + 20),
size: bytes.readUInt32LE(at + 16),
};
if (section.rva + Math.max(section.virtualSize, section.size) > 0x100000000)
peFailure("PE section RVA range overflows.");
if (section.size > 0) {
requirePeRange(bytes, section.offset, section.size);
if (section.offset < headerSize)
peFailure("PE section raw bytes overlap headers.");
}
sections.push(section);
}
const backed = sections
.filter(({ size }) => size > 0)
.sort((left, right) => left.offset - right.offset);
for (let index = 1; index < backed.length; index++) {
const previous = backed[index - 1];
const current = backed[index];
if (
previous !== undefined &&
current !== undefined &&
current.offset < previous.offset + previous.size
)
peFailure("PE sections have overlapping raw file ranges.");
}
const map = (rva: number, size: number): number => {
if (rva + size > 0x100000000) peFailure("Resource RVA range overflows.");
const candidates = sections.filter(
(section) =>
rva >= section.rva &&
rva - section.rva < Math.max(section.size, section.virtualSize),
);
if (rva < headerSize) {
if (
sections.some(
(section) =>
section.rva < rva + size &&
section.rva + Math.max(section.size, section.virtualSize) > rva,
) ||
size > headerSize - rva
)
peFailure("Ambiguous resource header RVA mapping.");
requirePeRange(bytes, rva, size);
return rva;
}
if (candidates.length !== 1)
peFailure("Resource RVA has missing or overlapping section mappings.");
const section = candidates[0];
if (section === undefined) return peFailure("Missing resource section.");
const within = rva - section.rva;
if (within > section.size || size > section.size - within)
peFailure("Resource range is not entirely file-backed in one section.");
// A second section starting inside the requested interval is ambiguous too.
if (
sections.some(
(other) =>
other !== section &&
other.rva < rva + size &&
other.rva + Math.max(other.size, other.virtualSize) > rva,
)
)
peFailure("Resource interval intersects overlapping virtual sections.");
const offset = section.offset + within;
requirePeRange(bytes, offset, size);
return offset;
};
const directoryAt = optional + directoriesAt + 16;
const rva = directoryCount > 2 ? bytes.readUInt32LE(directoryAt) : 0;
const size = directoryCount > 2 ? bytes.readUInt32LE(directoryAt + 4) : 0;
if ((rva === 0) !== (size === 0))
peFailure("Inconsistent PE resource directory RVA/size.");
return {
format: magic === 0x10b ? ("pe32" as const) : ("pe32-plus" as const),
machine: bytes.readUInt16LE(pe + 4),
directoryAt,
rva,
size,
map,
};
};
+261
View File
@@ -0,0 +1,261 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import {
inspectPeResourcesInputSchema,
peResourcesSchema,
} from "../../domain/native/peResources.js";
import { parsePeResources } from "./PeResourceParser.js";
import { peResourceFixture } from "./PeResources.fixture.js";
const parse = (bytes: Buffer, maxEntries = 4096, signal?: AbortSignal) =>
parsePeResources(
bytes,
{
path: "/fixtures/example.exe",
bytes: bytes.length,
sha256: createHash("sha256").update(bytes).digest("hex"),
},
inspectPeResourcesInputSchema.parse({
path: "/fixtures/example.exe",
max_entries: maxEntries,
}),
signal,
);
describe("portable PE resource parsing", () => {
it.each([false, true])(
"preserves original identities, ranges, hashes and icon candidates (PE32+ = %s)",
async (plus) => {
const { bytes } = peResourceFixture(plus);
const result = peResourcesSchema.parse(await parse(bytes));
expect(result.format).toBe(plus ? "pe32-plus" : "pe32");
expect(result.coverage).toMatchObject({
status: "complete",
resources: 5,
});
expect(
result.resources.map(({ type, name, language }) => [
type,
name,
language,
]),
).toContainEqual([
{ kind: "id", id: 10 },
{ kind: "id", id: 7 },
{ kind: "id", id: 1041 },
]);
const named = result.resources.find(({ name }) => name.kind === "name");
expect(named?.name).toMatchObject({
kind: "name",
name: "7",
utf16le_hex: "3700",
});
for (const resource of result.resources) {
const { offset, bytes: size } = resource.payload.location;
expect(resource.payload.rva - offset).toBe(0x1c00);
expect(resource.payload.sha256).toBe(
createHash("sha256")
.update(bytes.subarray(offset, offset + size))
.digest("hex"),
);
}
expect(result.icon_groups[0]?.images).toMatchObject([
{
resource_id: 1,
candidate_resource_indices: [0, 1],
same_language_resource_index: 0,
size_matches: true,
},
{
resource_id: 99,
candidate_resource_indices: [],
same_language_resource_index: null,
size_matches: null,
},
]);
},
);
it("distinguishes an absent resource directory from a present empty tree", async () => {
const fixture = peResourceFixture(false, []);
expect(await parse(fixture.bytes)).toMatchObject({
directory: { rva: 0x2000 },
resources: [],
coverage: { resources: 0, examined_entries: 0 },
});
fixture.bytes.fill(0, fixture.directoryAt, fixture.directoryAt + 8);
expect(await parse(fixture.bytes)).toMatchObject({
directory: null,
resources: [],
});
});
it.each([
[
"truncated directory",
(fixture: ReturnType<typeof peResourceFixture>) =>
fixture.bytes.writeUInt32LE(17, fixture.directoryAt + 4),
],
[
"cycle",
(fixture: ReturnType<typeof peResourceFixture>) =>
fixture.bytes.writeUInt32LE(
0x80000000,
(fixture.entryOffsets[0] ?? 0) + 4,
),
],
[
"bad payload RVA",
(fixture: ReturnType<typeof peResourceFixture>) =>
fixture.bytes.writeUInt32LE(0xfffffff0, fixture.dataOffsets[0]),
],
[
"overlapping payloads",
(fixture: ReturnType<typeof peResourceFixture>) =>
fixture.bytes.writeUInt32LE(
fixture.bytes.readUInt32LE(fixture.dataOffsets[0]) + 1,
fixture.dataOffsets[1],
),
],
[
"bad named counts",
(fixture: ReturnType<typeof peResourceFixture>) =>
fixture.bytes.writeUInt16LE(1, 0x400 + 12),
],
[
"truncated data entry",
(fixture: ReturnType<typeof peResourceFixture>) =>
fixture.bytes.writeUInt32LE(
0x7fffffff,
(fixture.entryOffsets.at(-1) ?? 0) + 4,
),
],
])("rejects %s without partial success", async (_name, mutate) => {
const fixture = peResourceFixture();
mutate(fixture);
await expect(parse(fixture.bytes)).rejects.toMatchObject({
reason: "format",
});
});
});
describe("PE header admission and bounded traversal", () => {
it.each([
[
"truncated DOS header",
(fixture: ReturnType<typeof peResourceFixture>) =>
fixture.bytes.subarray(0, 63),
],
[
"invalid optional magic",
(fixture: ReturnType<typeof peResourceFixture>) => {
fixture.bytes.writeUInt16LE(0, 0x98);
return fixture.bytes;
},
],
[
"unbacked virtual payload",
(fixture: ReturnType<typeof peResourceFixture>) => {
fixture.bytes.writeUInt32LE(0x10000, fixture.sectionAt + 8);
fixture.bytes.writeUInt32LE(0x8000, fixture.dataOffsets[0]);
return fixture.bytes;
},
],
[
"duplicate sibling IDs",
(fixture: ReturnType<typeof peResourceFixture>) => {
fixture.bytes.writeUInt32LE(
fixture.bytes.readUInt32LE(fixture.entryOffsets[0]),
(fixture.entryOffsets[0] ?? 0) + 8,
);
return fixture.bytes;
},
],
[
"section beginning inside a header-backed payload",
(fixture: ReturnType<typeof peResourceFixture>) => {
fixture.bytes.writeUInt32LE(0x100, fixture.dataOffsets[0]);
fixture.bytes.writeUInt32LE(4, (fixture.dataOffsets[0] ?? 0) + 4);
fixture.bytes.writeUInt16LE(2, 0x86);
const section = fixture.sectionAt + 40;
fixture.bytes.writeUInt32LE(4, section + 8);
fixture.bytes.writeUInt32LE(0x102, section + 12);
fixture.bytes.writeUInt32LE(4, section + 16);
const rawOffset = fixture.bytes.length;
fixture.bytes = Buffer.concat([fixture.bytes, Buffer.alloc(4)]);
fixture.bytes.writeUInt32LE(rawOffset, section + 20);
return fixture.bytes;
},
],
[
"overlapping virtual sections",
(fixture: ReturnType<typeof peResourceFixture>) => {
fixture.bytes.writeUInt16LE(2, 0x86);
fixture.bytes.copy(
fixture.bytes,
fixture.sectionAt + 40,
fixture.sectionAt,
fixture.sectionAt + 40,
);
fixture.bytes.writeUInt32LE(0, fixture.sectionAt + 40 + 16);
return fixture.bytes;
},
],
[
"malformed icon group",
(fixture: ReturnType<typeof peResourceFixture>) => {
const data = fixture.dataOffsets.at(-1) ?? 0;
const offset = fixture.bytes.readUInt32LE(data) - 0x1c00;
fixture.bytes.writeUInt16LE(3, offset + 4);
return fixture.bytes;
},
],
])("rejects %s", async (_name, mutate) => {
await expect(parse(mutate(peResourceFixture()))).rejects.toMatchObject({
reason: "format",
});
});
it("keeps icon size mismatch and unresolved language distinct", async () => {
const fixture = peResourceFixture();
const data = fixture.dataOffsets.at(-1) ?? 0;
const payload = fixture.bytes.readUInt32LE(data) - 0x1c00;
fixture.bytes.writeUInt32LE(123, payload + 14);
let report = await parse(fixture.bytes);
expect(report.icon_groups[0]?.images[0]).toMatchObject({
same_language_resource_index: 0,
size_matches: false,
});
const languageEntry = report.resources[4]?.entry_locations[2]?.offset ?? 0;
fixture.bytes.writeUInt32LE(2057, languageEntry);
report = await parse(fixture.bytes);
expect(report.icon_groups[0]?.images[0]).toMatchObject({
candidate_resource_indices: [0, 1],
same_language_resource_index: null,
size_matches: null,
});
});
it("preserves exact shared payload ranges and hashes", async () => {
const fixture = peResourceFixture();
fixture.bytes.writeUInt32LE(
fixture.bytes.readUInt32LE(fixture.dataOffsets[0]),
fixture.dataOffsets[1],
);
const result = await parse(fixture.bytes);
expect(result.resources[0]?.payload).toEqual(result.resources[1]?.payload);
});
it("enforces entry budgets before traversing large tables", async () => {
await expect(parse(peResourceFixture().bytes, 1)).rejects.toMatchObject({
reason: "limit",
});
});
it("allows cancellation while traversing resource entries", async () => {
const controller = new AbortController();
const parsing = parse(peResourceFixture().bytes, 4096, controller.signal);
controller.abort();
await expect(parsing).rejects.toThrow();
});
});
+315
View File
@@ -0,0 +1,315 @@
import { createHash } from "node:crypto";
import { setImmediate } from "node:timers/promises";
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
import type {
InspectPeResourcesInput,
PeResourceIdentity,
PeResources,
} from "../../domain/native/peResources.js";
import {
peFailure,
readPeResourceLayout,
requirePeRange,
} from "./PeResourceLayout.js";
type Range = { offset: number; bytes: number };
type OccupiedRange = Range & {
kind: "directory" | "name" | "data-entry" | "payload";
};
const METADATA_BYTES = 8 * 1024 * 1024;
const limit = (message: string): never => {
throw new ArtifactReaderFailure("limit", message);
};
const identityKey = (id: PeResourceIdentity): string =>
id.kind === "id" ? `id:${String(id.id)}` : `name:${id.utf16le_hex}`;
/** Decode the conventional type/name/language tree; never infer payload meaning or runtime loading. */
export const parsePeResources = async (
bytes: Buffer,
artifact: PeResources["artifact"],
input: InspectPeResourcesInput,
signal?: AbortSignal,
): Promise<PeResources> => {
signal?.throwIfAborted();
const layout = readPeResourceLayout(bytes);
const directories: PeResources["directories"] = [];
const resources: PeResources["resources"] = [];
const occupied: OccupiedRange[] = [];
const names = new Map<number, PeResourceIdentity>();
let examined = 0;
let metadataBytes = 0;
const account = (value: unknown): void => {
metadataBytes += Buffer.byteLength(JSON.stringify(value));
if (metadataBytes > METADATA_BYTES)
limit(
"PE resource metadata exceeds the 8 MiB complete-result allocation budget.",
);
};
const root = layout.size === 0 ? 0 : layout.map(layout.rva, layout.size);
const relative = (at: number, length: number): number => {
if (at > layout.size - length || at < 0)
peFailure(
"Resource directory offset leaves the declared resource interval.",
);
requirePeRange(bytes, root + at, length);
return root + at;
};
const recordRange = (
offset: number,
size: number,
kind: OccupiedRange["kind"],
): Range => {
const range = { offset, bytes: size };
if (size > 0) occupied.push({ ...range, kind });
return range;
};
const readIdentity = (encoded: number): PeResourceIdentity => {
if ((encoded & 0x80000000) === 0) return { kind: "id", id: encoded };
const at = encoded & 0x7fffffff;
const previous = names.get(at);
if (previous !== undefined) return previous;
if (at % 2 !== 0) peFailure("Unaligned PE resource name.");
const start = relative(at, 2);
const length = bytes.readUInt16LE(start) * 2;
relative(at, 2 + length);
const raw = bytes.subarray(start + 2, start + 2 + length);
const value: PeResourceIdentity = {
kind: "name",
name: raw.toString("utf16le"),
utf16le_hex: raw.toString("hex"),
location: recordRange(start, 2 + length, "name"),
};
names.set(at, value);
account(value);
return value;
};
const visit = async (
at: number,
path: PeResourceIdentity[],
entryLocations: Range[],
ancestors: ReadonlySet<number>,
): Promise<void> => {
if (ancestors.has(at)) peFailure("Cyclic PE resource directory.");
if (at % 4 !== 0) peFailure("Unaligned PE resource directory.");
const header = relative(at, 16);
const named = bytes.readUInt16LE(header + 12);
const ids = bytes.readUInt16LE(header + 14);
const count = named + ids;
if (count > input.max_entries - examined)
limit(
"PE resource directory entry budget exceeded; no partial inventory was returned.",
);
examined += count;
relative(at, 16 + 8 * count);
const directory = {
location: recordRange(header, 16 + 8 * count, "directory"),
characteristics: bytes.readUInt32LE(header),
timestamp: bytes.readUInt32LE(header + 4),
major_version: bytes.readUInt16LE(header + 8),
minor_version: bytes.readUInt16LE(header + 10),
named_entries: named,
id_entries: ids,
};
directories.push(directory);
account(directory);
const keys = new Set<string>();
const nested = new Set([...ancestors, at]);
for (let index = 0; index < count; index++) {
if (index % 128 === 0) {
await setImmediate();
signal?.throwIfAborted();
}
const entry = header + 16 + index * 8;
const encoded = bytes.readUInt32LE(entry);
if (((encoded & 0x80000000) !== 0) !== index < named)
peFailure(
"Resource name/ID entry counts disagree with encoded identities.",
);
const identity = readIdentity(encoded);
const key = identityKey(identity);
if (keys.has(key))
peFailure("Duplicate identity within a resource directory.");
keys.add(key);
const next = [...path, identity];
const locations = [...entryLocations, { offset: entry, bytes: 8 }];
const target = bytes.readUInt32LE(entry + 4);
const offset = target & 0x7fffffff;
if ((target & 0x80000000) !== 0) {
if (next.length >= 3)
peFailure(
"Unsupported resource tree deeper than type/name/language.",
);
await visit(offset, next, locations, nested);
} else {
if (next.length !== 3)
peFailure(
"Unsupported resource leaf outside the type/name/language profile.",
);
const data = relative(offset, 16);
if (offset % 4 !== 0) peFailure("Unaligned resource data entry.");
const rva = bytes.readUInt32LE(data);
const size = bytes.readUInt32LE(data + 4);
const payloadOffset = layout.map(rva, size);
const [type, name, language] = next;
if (type === undefined || name === undefined || language === undefined)
return peFailure("Incomplete resource identity.");
const resource = {
index: resources.length,
type,
name,
language,
entry_locations: locations,
data_entry_location: recordRange(data, 16, "data-entry"),
code_page: bytes.readUInt32LE(data + 8),
reserved: bytes.readUInt32LE(data + 12),
payload: {
rva,
location: recordRange(payloadOffset, size, "payload"),
sha256: "0".repeat(64),
},
};
resources.push(resource);
account(resource);
}
}
};
if (layout.size > 0) await visit(0, [], [], new Set());
rejectOverlappingRanges(occupied);
const hashes = new Map<string, string>();
for (const resource of resources) {
const range = resource.payload.location;
const key = `${String(range.offset)}:${String(range.bytes)}`;
let digest = hashes.get(key);
if (digest === undefined) {
const hash = createHash("sha256");
for (let offset = 0; offset < range.bytes; offset += 1048576) {
await setImmediate();
signal?.throwIfAborted();
hash.update(
bytes.subarray(
range.offset + offset,
range.offset + Math.min(range.bytes, offset + 1048576),
),
);
}
digest = hash.digest("hex");
hashes.set(key, digest);
}
resource.payload.sha256 = digest;
}
const iconGroups = readIconGroups(bytes, resources, account);
const report: PeResources = {
artifact,
format: layout.format,
machine: layout.machine,
directory:
layout.size === 0
? null
: {
rva: layout.rva,
location: { offset: root, bytes: layout.size },
data_directory_location: { offset: layout.directoryAt, bytes: 8 },
},
directories,
resources,
icon_groups: iconGroups,
coverage: {
status: "complete",
examined_entries: examined,
resources: resources.length,
},
limitations: [
"Static PE32/PE32+ type/name/language resource inventory; payloads other than RT_GROUP_ICON remain opaque.",
"Icon candidates are resource-table relationships. Language fallback, image decoding and actual shell/window loading are not observed.",
"Exact shared byte ranges are retained; non-identical overlapping resource structures or payloads are rejected.",
],
};
signal?.throwIfAborted();
if (Buffer.byteLength(JSON.stringify(report)) > METADATA_BYTES)
limit("PE resource result exceeds the 8 MiB allocation budget.");
return report;
};
const rejectOverlappingRanges = (ranges: OccupiedRange[]): void => {
ranges.sort(
(left, right) => left.offset - right.offset || right.bytes - left.bytes,
);
let previous: OccupiedRange | undefined;
for (const current of ranges) {
if (
previous !== undefined &&
current.offset < previous.offset + previous.bytes &&
(current.offset !== previous.offset ||
current.bytes !== previous.bytes ||
current.kind !== previous.kind)
)
peFailure("Non-identical resource byte ranges overlap.");
previous = current;
}
};
const readIconGroups = (
bytes: Buffer,
resources: PeResources["resources"],
account: (value: unknown) => void,
): PeResources["icon_groups"] => {
const imagesById = new Map<number, PeResources["resources"]>();
for (const resource of resources) {
if (
resource.type.kind !== "id" ||
resource.type.id !== 3 ||
resource.name.kind !== "id"
)
continue;
const candidates = imagesById.get(resource.name.id) ?? [];
candidates.push(resource);
imagesById.set(resource.name.id, candidates);
}
return resources
.filter(
(resource) => resource.type.kind === "id" && resource.type.id === 14,
)
.map((group) => {
const { offset, bytes: size } = group.payload.location;
if (
size < 6 ||
bytes.readUInt16LE(offset) !== 0 ||
bytes.readUInt16LE(offset + 2) !== 1
)
peFailure("Malformed RT_GROUP_ICON header.");
const count = bytes.readUInt16LE(offset + 4);
if (size !== 6 + count * 14)
peFailure("RT_GROUP_ICON length does not match its image count.");
const images: PeResources["icon_groups"][number]["images"] = [];
for (let index = 0; index < count; index++) {
const at = offset + 6 + index * 14;
const id = bytes.readUInt16LE(at + 12);
const candidates = imagesById.get(id) ?? [];
const exact = candidates.find(
(resource) =>
identityKey(resource.language) === identityKey(group.language),
);
const declaredBytes = bytes.readUInt32LE(at + 8);
const image = {
location: { offset: at, bytes: 14 },
width: bytes[at] ?? 0,
height: bytes[at + 1] ?? 0,
color_count: bytes[at + 2] ?? 0,
reserved: bytes[at + 3] ?? 0,
planes: bytes.readUInt16LE(at + 4),
bit_count: bytes.readUInt16LE(at + 6),
declared_bytes: declaredBytes,
resource_id: id,
candidate_resource_indices: candidates.map(({ index }) => index),
same_language_resource_index: exact?.index ?? null,
size_matches:
exact === undefined
? null
: exact.payload.location.bytes === declaredBytes,
};
account(image);
images.push(image);
}
return { resource_index: group.index, images };
});
};
+148
View File
@@ -0,0 +1,148 @@
interface Resource {
readonly type: number | string;
readonly name: number | string;
readonly language: number | string;
readonly payload: Buffer;
}
interface Tree {
readonly children: Map<
string,
{ identity: number | string; value: Tree | Resource }
>;
}
const iconGroup = (): Buffer => {
const bytes = Buffer.alloc(34);
bytes.writeUInt16LE(1, 2);
bytes.writeUInt16LE(2, 4);
for (const [index, id] of [1, 99].entries()) {
const at = 6 + index * 14;
bytes[at] = 16;
bytes[at + 1] = 16;
bytes.writeUInt16LE(1, at + 4);
bytes.writeUInt16LE(32, at + 6);
bytes.writeUInt32LE(4, at + 8);
bytes.writeUInt16LE(id, at + 12);
}
return bytes;
};
/** Hand-authored PE resource bytes, independent of the production decoder. */
export const peResourceFixture = (
plus = false,
resources: readonly Resource[] = [
{ type: 3, name: 1, language: 1033, payload: Buffer.from("ICON") },
{ type: 3, name: 1, language: 1041, payload: Buffer.from("JAPN") },
{ type: 10, name: "7", language: 1033, payload: Buffer.from("Hello") },
{ type: 10, name: 7, language: 1041, payload: Buffer.from("World") },
{ type: 14, name: 42, language: 1033, payload: iconGroup() },
],
) => {
const tree: Tree = { children: new Map() };
for (const resource of resources) {
let parent = tree;
for (const [depth, identity] of [
resource.type,
resource.name,
resource.language,
].entries()) {
const key = `${typeof identity}:${String(identity)}`;
let child = parent.children.get(key);
if (child === undefined) {
child = {
identity,
value: depth === 2 ? resource : { children: new Map() },
};
parent.children.set(key, child);
}
if ("children" in child.value) parent = child.value;
}
}
const section = Buffer.alloc(65536);
let cursor = 0;
const allocate = (size: number, alignment = 4): number => {
cursor = Math.ceil(cursor / alignment) * alignment;
const at = cursor;
cursor += size;
return at;
};
const leaves: { dataAt: number; resource: Resource }[] = [];
const entryOffsets: number[] = [];
const directories: number[] = [];
const emit = (node: Tree): number => {
const children = [...node.children.values()].sort((left, right) =>
typeof left.identity === typeof right.identity
? typeof left.identity === "number" &&
typeof right.identity === "number"
? left.identity - right.identity
: String(left.identity).localeCompare(String(right.identity))
: typeof left.identity === "string"
? -1
: 1,
);
const at = allocate(16 + children.length * 8);
directories.push(at);
const named = children.filter(
({ identity }) => typeof identity === "string",
).length;
section.writeUInt16LE(named, at + 12);
section.writeUInt16LE(children.length - named, at + 14);
children.forEach(({ identity, value }, index) => {
const entry = at + 16 + index * 8;
entryOffsets.push(entry);
if (typeof identity === "string") {
const encoded = Buffer.from(identity, "utf16le");
const nameAt = allocate(encoded.length + 2, 2);
section.writeUInt16LE(encoded.length / 2, nameAt);
encoded.copy(section, nameAt + 2);
section.writeUInt32LE(0x80000000 + nameAt, entry);
} else section.writeUInt32LE(identity, entry);
if ("children" in value)
section.writeUInt32LE(0x80000000 + emit(value), entry + 4);
else {
const dataAt = allocate(16);
section.writeUInt32LE(dataAt, entry + 4);
leaves.push({ dataAt, resource: value });
}
});
return at;
};
emit(tree);
for (const { dataAt, resource } of leaves) {
const payloadAt = allocate(resource.payload.length);
resource.payload.copy(section, payloadAt);
section.writeUInt32LE(0x2000 + payloadAt, dataAt);
section.writeUInt32LE(resource.payload.length, dataAt + 4);
section.writeUInt32LE(65001, dataAt + 8);
}
const rawSize = Math.ceil(cursor / 512) * 512;
const bytes = Buffer.alloc(0x400 + rawSize);
bytes.writeUInt16LE(0x5a4d, 0);
bytes.writeUInt32LE(0x80, 60);
bytes.writeUInt32LE(0x4550, 0x80);
bytes.writeUInt16LE(plus ? 0x8664 : 0x14c, 0x84);
bytes.writeUInt16LE(1, 0x86);
const optionalSize = plus ? 240 : 224;
bytes.writeUInt16LE(optionalSize, 0x94);
bytes.writeUInt16LE(plus ? 0x20b : 0x10b, 0x98);
bytes.writeUInt32LE(0x400, 0x98 + 60);
bytes.writeUInt32LE(16, 0x98 + (plus ? 108 : 92));
const directoryAt = 0x98 + (plus ? 112 : 96) + 16;
bytes.writeUInt32LE(0x2000, directoryAt);
bytes.writeUInt32LE(cursor, directoryAt + 4);
const sectionAt = 0x98 + optionalSize;
bytes.write(".rsrc", sectionAt, "ascii");
bytes.writeUInt32LE(cursor, sectionAt + 8);
bytes.writeUInt32LE(0x2000, sectionAt + 12);
bytes.writeUInt32LE(rawSize, sectionAt + 16);
bytes.writeUInt32LE(0x400, sectionAt + 20);
section.copy(bytes, 0x400, 0, rawSize);
return {
bytes,
directoryAt,
sectionAt,
entryOffsets: entryOffsets.map((at) => at + 0x400),
directoryOffsets: directories.map((at) => at + 0x400),
dataOffsets: leaves.map(({ dataAt }) => dataAt + 0x400),
};
};
+83
View File
@@ -0,0 +1,83 @@
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
import type { PeResourcesPort } from "../../application/binaryDiagnostics/PeResourcesPort.js";
import type { ExecutionOptions } from "../../application/AnalysisProvider.js";
import { ArtifactOperationError } from "../../domain/artifactOperationError.js";
import {
AnalysisAccessDeniedError,
AnalysisCancelledError,
AnalysisResourceConstraintError,
} from "../../domain/analysisErrorCore.js";
import type { InspectPeResourcesInput } from "../../domain/native/peResources.js";
import { err, ok } from "../../domain/result.js";
import { PE_RESOURCES_PROVIDER } from "../../application/InvestigationProviders.js";
import { parsePeResources } from "./PeResourceParser.js";
/** Portable parser over one bounded, identity-checked regular file. */
export class PeResourcesProvider implements PeResourcesPort {
readonly identity = PE_RESOURCES_PROVIDER;
async inspect(input: InspectPeResourcesInput, options?: ExecutionOptions) {
try {
const snapshot = await readStableArtifact(
input.path,
input.max_file_bytes,
options?.signal,
);
return ok(
await parsePeResources(
snapshot.bytes,
{
path: input.path,
sha256: snapshot.sha256,
bytes: snapshot.bytes.length,
},
input,
options?.signal,
),
);
} catch (cause) {
if (options?.signal?.aborted)
return err(
new AnalysisCancelledError("inspect_pe_resources", { cause }),
);
if (cause instanceof ArtifactReaderFailure && cause.reason === "limit")
return err(
new AnalysisResourceConstraintError(
"inspect_pe_resources",
"memory",
cause.message,
{
max_file_bytes: input.max_file_bytes,
max_entries: input.max_entries,
},
{ cause },
),
);
if (
cause instanceof Error &&
"code" in cause &&
(cause.code === "EACCES" || cause.code === "EPERM")
)
return err(
new AnalysisAccessDeniedError(
"inspect_pe_resources",
input.path,
cause.code,
{ cause },
),
);
return err(
new ArtifactOperationError(
"inspect_pe_resources",
cause instanceof ArtifactReaderFailure ? cause.reason : "io",
undefined,
cause instanceof Error
? cause.message
: "PE artifact inspection failed.",
{ cause },
),
);
}
}
}