73 lines
3.1 KiB
JavaScript

import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const optionalPrintDlls = new Set([
'windows.data.pdf.dll',
'api-ms-win-core-winrt-l1-1-0.dll',
'prntvpt.dll',
'd2d1.dll',
]);
export function regularPeImports(exe) {
if (exe.readUInt16LE(0) !== 0x5a4d) throw Error('缺少 DOS PE 文件头');
const pe = exe.readUInt32LE(0x3c);
if (exe.readUInt32LE(pe) !== 0x4550) throw Error('缺少 PE 文件头');
const optional = pe + 24;
const optionalSize = exe.readUInt16LE(pe + 20);
const magic = exe.readUInt16LE(optional);
if (magic !== 0x10b && magic !== 0x20b) throw Error('未知的 PE 可选文件头类型');
const directories = optional + (magic === 0x20b ? 112 : 96);
if (directories + 16 > optional + optionalSize || exe.readUInt32LE(directories - 4) < 2) {
throw Error('缺少 PE 导入目录');
}
const importsRva = exe.readUInt32LE(directories + 8);
const importsSize = exe.readUInt32LE(directories + 12);
if (importsRva === 0 && importsSize === 0) return [];
const sectionCount = exe.readUInt16LE(pe + 6);
const firstSection = optional + optionalSize;
const sections = Array.from({ length: sectionCount }, (_, index) => {
const header = firstSection + index * 40;
return {
rva: exe.readUInt32LE(header + 12),
size: exe.readUInt32LE(header + 16),
offset: exe.readUInt32LE(header + 20),
};
});
const atRva = (rva, length) => {
const section = sections.find(({ rva: base, size }) => rva >= base && rva - base + length <= size);
if (!section || section.offset + section.size > exe.length) throw Error('PE 导入目录指向无效的文件区段');
const offset = section.offset + rva - section.rva;
return exe.subarray(offset, section.offset + section.size);
};
const table = atRva(importsRva, importsSize).subarray(0, importsSize);
const names = [];
for (let entry = 0; entry + 20 <= table.length; entry += 20) {
const descriptor = table.subarray(entry, entry + 20);
if (descriptor.every(byte => byte === 0)) return names;
const name = atRva(descriptor.readUInt32LE(12), 1);
const end = name.indexOf(0);
if (end <= 0) throw Error('PE 导入目录中的 DLL 名无效');
names.push(name.toString('ascii', 0, end).toLowerCase());
}
throw Error('PE 导入目录没有结束项');
}
export function assertSafePeImports(exe, label) {
const imports = regularPeImports(exe);
const blocked = [...new Set(imports.filter(dll => optionalPrintDlls.has(dll)))];
if (blocked.length) throw Error(`${label} 的 PE 常规导入表含有按需加载的 Windows 打印组件:${blocked.join(', ')}`);
return [...new Set(imports)].sort();
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const files = process.argv.slice(2);
if (!files.length) throw Error('请指定要核验常规导入表的 Windows EXE');
for (const file of files) {
const imports = assertSafePeImports(await readFile(file), path.basename(file));
console.log(JSON.stringify({ file, imports }));
}
}