Files
reverse-engineering-anything/tests/boundary/process/windowsNativeArtifactVerifier.test.ts
608378c311 fix(windows): reject native addons with unusable delay-import tables (#15216)
* fix: deepen verified coverage for PR #14258

* fix(windows): recognize GNU delay-import terminator placement

* fix(windows): validate complete delay-import address tables

* fix(windows): validate delay-load descriptor targets

* fix(windows): validate delay-import function names

* fix(windows): bound delay imports to the dedicated IAT section

* test(windows): cover delay-import verifier refusals

* test(windows): cover nonzero delay-import padding

* fix(windows): require readable delay-import descriptors

* test(windows): accept read-only delay import names

* fix(windows): validate initial delay loader state

---------

Co-authored-by: ShuaixinHuang <ShuaixinHuang@users.noreply.github.com>
Co-authored-by: ShuaixinHuang <197200901+ShuaixinHuang@users.noreply.github.com>
Co-authored-by: Vincent Koc <vincentkoc@ieee.org>
2026-11-30 19:18:16 +08:00

401 lines
15 KiB
TypeScript

import { createHash } from "node:crypto";
import { access, copyFile, mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname, join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { parse } from "@babel/parser";
import { expect } from "vitest";
import { processTest } from "../../support/process/processFixture.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { windowsNativeArtifactFixture } from "../../fixtures/windowsNativeArtifact.js";
const repository = fileURLToPath(new URL("../../..", import.meta.url));
/** Copy the selected entry's relative ESM graph; package dependencies stay absent. */
const copyModuleGraph = async (root: string, entry: string): Promise<void> => {
const pending = [join(repository, entry)];
const copied = new Set<string>();
while (pending.length > 0) {
const source = pending.pop();
if (source === undefined || copied.has(source)) continue;
copied.add(source);
const output = join(root, relative(repository, source));
const text = await readFile(source, "utf8");
await mkdir(dirname(output), { recursive: true });
await copyFile(source, output);
for (const node of parse(text, {
sourceType: "module",
plugins: ["typescript"],
}).program.body) {
if (
node.type !== "ImportDeclaration" &&
node.type !== "ExportNamedDeclaration" &&
node.type !== "ExportAllDeclaration"
)
continue;
const specifier = node.source?.value;
if (!specifier?.startsWith(".")) continue;
let dependency = resolve(dirname(source), specifier);
try {
await access(dependency);
} catch (cause) {
if (
cause instanceof Error &&
"code" in cause &&
cause.code === "ENOENT" &&
dependency.endsWith(".js") &&
source.endsWith(".ts")
)
dependency = dependency.slice(0, -3) + ".ts";
else throw cause;
}
pending.push(dependency);
}
}
};
const delayImportFixture = () => {
const { bytes: identity, manifest } = windowsNativeArtifactFixture();
const optional = 88;
const directory = optional + 112 + 13 * 8;
const section = optional + 240;
const descriptors = 512;
const delaySection = section + 40;
const delaySlots = descriptors + 192;
const bytes = Buffer.alloc(delaySlots + 32);
identity.copy(bytes);
bytes.writeUInt16LE(2, 70); // NumberOfSections
bytes.writeUInt16LE(240, 84); // SizeOfOptionalHeader
bytes.writeUInt32LE(16, optional + 108);
bytes.writeUInt32LE(0x1000, directory);
bytes.writeUInt32LE(64, directory + 4);
bytes.writeUInt32LE(192, section + 8); // VirtualSize
bytes.writeUInt32LE(0x1000, section + 12);
bytes.writeUInt32LE(192, section + 16); // SizeOfRawData
bytes.writeUInt32LE(descriptors, section + 20);
bytes.writeUInt32LE(0xc000_0040, section + 36);
bytes.writeUInt32LE(1, descriptors);
bytes.writeUInt32LE(0x10b0, descriptors + 4);
bytes.writeUInt32LE(0x10a0, descriptors + 8);
bytes.write("fixture.dll\0", descriptors + 176, "ascii");
bytes.write(".didat", delaySection, "ascii");
bytes.writeUInt32LE(32, delaySection + 8);
bytes.writeUInt32LE(0x2000, delaySection + 12);
bytes.writeUInt32LE(32, delaySection + 16);
bytes.writeUInt32LE(delaySlots, delaySection + 20);
bytes.writeUInt32LE(0xc000_0040, delaySection + 36);
bytes.writeUInt32LE(0x2000, descriptors + 12);
bytes.writeUInt32LE(0x1040, descriptors + 16);
bytes.write("One\0", descriptors + 106, "ascii");
bytes.writeBigUInt64LE(0x1068n, descriptors + 64);
bytes.writeBigUInt64LE((1n << 63n) | 2n, descriptors + 72);
bytes.writeBigUInt64LE(1n, delaySlots);
bytes.writeBigUInt64LE(2n, delaySlots + 8);
return {
bytes,
manifest,
directory,
section,
descriptors,
delaySection,
delaySlots,
};
};
for (const mode of ["preinstall source", "packed source-free"]) {
processTest(
`verifies native artifact identity from ${mode} without installed dependencies`,
async ({ processes }) => {
const root = await createTestTempDirectory(
"rea-native-artifact-verifier-",
);
await mkdir(join(root, "scripts"), { recursive: true });
await copyFile(
join(repository, "scripts/verify-windows-native-artifact.mjs"),
join(root, "scripts/verify-windows-native-artifact.mjs"),
);
if (mode === "preinstall source")
await copyModuleGraph(root, "scripts/lib/verifier-source-loader.mjs");
await copyModuleGraph(
root,
mode === "preinstall source"
? "src/domain/windowsNativeArtifact.ts"
: "dist/domain/windowsNativeArtifact.js",
);
await expect(access(join(root, "node_modules"))).rejects.toMatchObject({
code: "ENOENT",
});
if (mode === "packed source-free") {
await expect(access(join(root, "src"))).rejects.toMatchObject({
code: "ENOENT",
});
await expect(
access(join(root, "scripts/lib/verifier-source-loader.mjs")),
).rejects.toMatchObject({ code: "ENOENT" });
}
await writeFile(
join(root, "package.json"),
JSON.stringify({ type: "module", version: "1.0.0" }),
);
const artifactRoot = join(root, "native/windows/build");
await mkdir(artifactRoot, { recursive: true });
const {
bytes,
manifest,
directory,
section,
descriptors,
delaySection,
delaySlots,
} = delayImportFixture();
const manifestPath = join(artifactRoot, "manifest.json");
const writeArtifact = async (artifact = bytes) => {
manifest.artifactSha256 = createHash("sha256")
.update(artifact)
.digest("hex");
await writeFile(join(artifactRoot, manifest.artifact), artifact);
await writeFile(manifestPath, JSON.stringify(manifest));
};
await writeArtifact();
const run = () =>
processes.run(
process.execPath,
[join(root, "scripts/verify-windows-native-artifact.mjs")],
{ cwd: root },
);
const valid = await run();
expect(valid.exitCode, valid.stderr).toBe(0);
expect(JSON.parse(valid.stdout)).toEqual({
ok: true,
...manifest,
artifactBytes: bytes.length,
});
// A module handle can be backed by zero-filled writable image data.
bytes.writeUInt32LE(200, section + 8);
bytes.writeUInt32LE(0x10c0, descriptors + 8);
await writeArtifact();
expect((await run()).exitCode).toBe(0);
// A partially file-backed slot keeps its virtual tail zero-filled.
bytes.writeUInt32LE(0x10bc, descriptors + 8);
await writeArtifact();
expect((await run()).exitCode).toBe(0);
bytes[descriptors + 188] = 1;
await writeArtifact();
expect((await run()).stderr).toContain("nonzero initial value");
bytes[descriptors + 188] = 0;
bytes.writeUInt32LE(0x10c0, descriptors + 8);
bytes.writeUInt32LE(192, section + 8);
await writeArtifact();
expect((await run()).stderr).toContain(
"module handle outside writable PE data",
);
bytes.writeUInt32LE(0x10a0, descriptors + 8);
for (const handle of [1n, 1n << 56n]) {
bytes.writeBigUInt64LE(handle, descriptors + 160);
await writeArtifact();
expect((await run()).stderr).toContain("nonzero initial value");
}
bytes.writeBigUInt64LE(0n, descriptors + 160);
for (const fieldOffset of [20, 24, 28]) {
bytes.writeUInt32LE(1, descriptors + fieldOffset);
await writeArtifact();
expect((await run()).stderr).toContain(
"unsupported bound/unload/timestamp delay-import fields",
);
bytes.writeUInt32LE(0, descriptors + fieldOffset);
}
bytes.writeUInt32LE(0x10c0, descriptors + 4);
await writeArtifact();
expect((await run()).stderr).toContain(
"unreadable or unterminated delay-import DLL name",
);
bytes.writeUInt32LE(0x10b0, descriptors + 4);
bytes.writeUInt32LE(32, directory + 4);
await writeArtifact();
expect((await run()).exitCode).toBe(0);
bytes.writeUInt32LE(1, descriptors + 32);
await writeArtifact();
const unterminated = await run();
expect(unterminated.exitCode).not.toBe(0);
expect(unterminated.stderr).toContain(
"unterminated delay-import directory",
);
bytes.writeUInt32LE(0, descriptors + 32);
bytes.writeUInt32LE(64, directory + 4);
// A writable IAT cannot rescue a read-only module-handle slot.
bytes.writeUInt32LE(0x4000_0040, section + 36);
await writeArtifact();
expect((await run()).stderr).toContain(
"module handle outside writable PE data",
);
bytes.writeUInt32LE(0xc000_0040, section + 36);
// Read-only names are valid when both loader write locations stay writable.
const readOnlyNames = Buffer.alloc(bytes.length + 8);
bytes.copy(readOnlyNames);
readOnlyNames.writeUInt16LE(3, 70);
readOnlyNames.writeUInt32LE(0x4000_0040, section + 36);
const handleSection = section + 80;
readOnlyNames.write(".data", handleSection, "ascii");
readOnlyNames.writeUInt32LE(8, handleSection + 8);
readOnlyNames.writeUInt32LE(0x3000, handleSection + 12);
readOnlyNames.writeUInt32LE(8, handleSection + 16);
readOnlyNames.writeUInt32LE(bytes.length, handleSection + 20);
readOnlyNames.writeUInt32LE(0xc000_0040, handleSection + 36);
readOnlyNames.writeUInt32LE(0x3000, descriptors + 8);
await writeArtifact(readOnlyNames);
const validReadOnlyNames = await run();
expect(validReadOnlyNames.exitCode, validReadOnlyNames.stderr).toBe(0);
bytes.writeUInt32LE(40, delaySection + 8);
await writeArtifact();
expect((await run()).stderr).toContain("outside writable PE data");
bytes.writeUInt32LE(32, delaySection + 8);
bytes.writeUInt32LE(0x8000_0040, section + 36);
await writeArtifact();
const unreadableDirectory = await run();
expect(unreadableDirectory.exitCode).not.toBe(0);
expect(unreadableDirectory.stderr).toContain(
"unreadable delay-import directory",
);
bytes.writeUInt32LE(0xc000_0040, section + 36);
// Padding belongs to the checked section even after both tables end.
const padding = bytes.length - 1;
bytes[padding] = 1;
await writeArtifact();
const nonzeroPadding = await run();
expect(nonzeroPadding.exitCode).not.toBe(0);
expect(nonzeroPadding.stderr).toContain(
"inconsistent with its name table",
);
bytes[padding] = 0;
bytes.writeBigUInt64LE(0n, delaySlots + 8);
await writeArtifact();
expect((await run()).stderr).toContain(
"inconsistent with its name table",
);
bytes.writeBigUInt64LE(2n, delaySlots + 8);
bytes.writeUInt32LE(0x4000_0040, delaySection + 36);
await writeArtifact();
expect((await run()).stderr).toContain("outside writable PE data");
bytes.writeUInt32LE(0xc000_0040, delaySection + 36);
// Keep the package identity valid so the verifier reaches the table checks.
const originalName = bytes[descriptors + 106]!;
bytes[descriptors + 106] = 0;
await writeArtifact();
const emptyImportName = await run();
expect(emptyImportName.exitCode).not.toBe(0);
expect(emptyImportName.stderr).toContain(
"inconsistent with its name table",
);
bytes[descriptors + 106] = originalName;
bytes.writeUInt32LE(0x8000_0040, delaySection + 36);
await writeArtifact();
const unreadableIat = await run();
expect(unreadableIat.exitCode).not.toBe(0);
expect(unreadableIat.stderr).toContain(
"inconsistent with its name table",
);
bytes.writeUInt32LE(0xc000_0040, delaySection + 36);
bytes.fill(0, directory, directory + 8);
await writeArtifact();
const missingDirectory = await run();
expect(missingDirectory.exitCode).not.toBe(0);
expect(missingDirectory.stderr).toContain(
"no valid delay-import directory",
);
await writeFile(
manifestPath,
JSON.stringify({ ...manifest, extra: true }),
);
const invalid = await run();
expect(invalid.exitCode).not.toBe(0);
expect(invalid.stderr).toContain("missing or unknown fields");
},
);
}
processTest.skipIf(process.platform !== "linux")(
"repairs an invalid Node header cache with a verified download",
async ({ processes }) => {
const root = await createTestTempDirectory("rea-native-build-cache-");
const entry = "scripts/build-windows-native.mjs";
await copyModuleGraph(root, entry);
await copyModuleGraph(root, "src/domain/windowsNativeArtifact.ts");
await writeFile(join(root, "package.json"), '{"type":"module"}');
const cache = join(root, ".cache", "rea-windows-native");
const bin = join(root, "bin");
await mkdir(cache, { recursive: true });
await mkdir(bin);
const name = "node-v22.19.0-headers.tar.gz";
const archive = join(cache, name);
const validBytes = "verified header archive fixture";
const digest = createHash("sha256").update(validBytes).digest("hex");
await writeFile(archive, "interrupted download");
await writeFile(
join(bin, "x86_64-w64-mingw32-g++"),
"#!/bin/sh\nexit 0\n",
{
mode: 0o755,
},
);
// Stop at extraction so this test needs neither a real tarball nor MinGW.
await writeFile(
join(bin, "tar"),
'#!/bin/sh\nprintf "extraction received: " >&2\ncat "$2" >&2\nexit 1\n',
{ mode: 0o755 },
);
const preload = join(root, "registry-fixture.mjs");
await writeFile(
preload,
`globalThis.fetch = async (url) => {
if (url.endsWith("/SHASUMS256.txt")) return new Response(${JSON.stringify(`${digest} ${name}\n`)});
if (url.endsWith(${JSON.stringify(`/${name}`)})) return new Response(process.env.HEADER_DOWNLOAD);
throw new Error("Unexpected fetch: " + url);
};\n`,
);
const run = (download: string) =>
processes.run(
process.execPath,
["--import", preload, join(root, entry)],
{
cwd: root,
env: {
...process.env,
HOME: root,
PATH: `${bin}:${process.env.PATH ?? ""}`,
HEADER_DOWNLOAD: download,
},
},
);
const invalid = await run("bad upstream content");
expect(invalid.exitCode).not.toBe(0);
expect(invalid.stderr).toContain("SHA-256 mismatch");
expect(invalid.stderr).not.toContain("extraction received");
expect(await readFile(archive, "utf8")).toBe("interrupted download");
const repaired = await run(validBytes);
expect(repaired.stderr).toContain(`extraction received: ${validBytes}`);
expect(await readFile(archive, "utf8")).toBe(validBytes);
const cached = await run("bad upstream content");
expect(cached.stderr).toContain(`extraction received: ${validBytes}`);
},
);