feat(native): inspect offline ELF layout through pwntools (#1037)

* feat(native): inspect offline ELF layout through pwntools

* fix(build): prepare offline ELF verification on clean runners

* fix(native): preserve snapshot acquisition cancellation

* fix(native): handle sectionless ELF and retain decoder diagnostics

* test(native): verify malformed symbol table entry sizes

* fix(native): respect inherited limits and unused segment fields

* fix(native): preserve packed relocations and decoder launch constraints

* fix(native): validate symbol spans and preserve resource failures

* fix(native): preserve diagnostic completeness and memory failures

* fix(native): guard bridge imports against allocation failures

* fix(native): validate relocation symbol and section references

* fix(native): retain diagnostics through compounded cleanup failures

* fix(native): preserve unresolved relocation section references

* fix(native): bound linkage evidence and preserve CPU signal diagnostics

* fix(native): preserve file-size resource failure evidence

* fix(native): retain opaque linkage names and late cancellation output

* test(native): make CPU-limit fixture robust across runners

* fix(native): verify resource failure branches before interpreting exits

* fix(native): validate declared ELF string references

* fix(native): validate section-name table before decoding

* fix(native): enforce canonical ELF name-table escapes
This commit is contained in:
Ysopwnable
2026-10-08 14:22:08 +08:00
committed by GitHub
parent 8d5c88f17c
commit 4fc6565b0f
59 changed files with 5068 additions and 45 deletions
+362
View File
@@ -0,0 +1,362 @@
import { expect, it } from "vitest";
import { binaryLayoutSchema, type BinaryLayout } from "./binaryLayout.js";
const report = () => ({
artifact: { path: "/fixture.elf", sha256: "a".repeat(64), bytes: 128 },
format: "elf",
architecture: { machine: "EM_X86_64", bits: 64, byte_order: "little" },
image_type: "ET_EXEC",
entry_point: {
reported_value: "0x20000000000001",
meaning: "linked-virtual-address",
execution_status: "unknown",
},
runtime_load_base: null,
sections: [
{
index: 0,
name: {
display: "opaque",
bytes_base64: "b3BhcXVl",
location: { offset: "0x40", bytes: "0x7" },
unknown_reason: null,
},
name_offset: "0x0",
type: "SHT_NOBITS",
header_location: { offset: "0x0", bytes: "0x40" },
address: "0x20000000000001",
offset: "0xffffffffffffffff",
size: "0x2000",
alignment: "0x1",
flags: "0x3",
link: 0,
info: 0,
entry_size: "0x0",
file_backing: "none",
},
],
segments: [],
symbols: [],
relocations: [],
packed_relative_relocations: [],
relocation_inventory_completeness: "unknown",
linkage: {
needed_libraries: [],
interpreters: [],
got: [],
plt: [],
convenience_maps_completeness: "unknown",
runtime_library_paths: null,
},
mitigations: {
evidence_kind: "inferred",
position_independent: false,
nx_indicator: null,
executable_stack_indicator: false,
stack_canary_indicator: false,
relro: null,
},
diagnostics: { stdout: "", stderr: "", truncated: false },
limitations: [],
});
it("retains high linked values and NOBITS without inventing file backing", () => {
const value = binaryLayoutSchema.parse(report());
expect(value.entry_point.reported_value).toBe("0x20000000000001");
expect(value.sections[0]?.offset).toBe("0xffffffffffffffff");
expect(value.runtime_load_base).toBeNull();
});
it.each([
"file-backed-outside",
"header-outside",
"wrong-index",
"noncanonical-base64",
"wrong-machine",
"outside-elf64",
])("rejects a malformed source representation: %s", (problem) => {
const value = report();
const section = value.sections[0];
if (section === undefined) throw new Error("section missing");
if (problem === "file-backed-outside") section.file_backing = "file";
if (problem === "header-outside") section.header_location.offset = "0x80";
if (problem === "wrong-index") section.index = 1;
if (problem === "wrong-machine") value.architecture.machine = "EM_AARCH64";
if (problem === "outside-elf64")
value.entry_point.reported_value = "0x10000000000000000";
if (problem === "noncanonical-base64") section.name.bytes_base64 = "AR==";
expect(binaryLayoutSchema.safeParse(value).success).toBe(false);
});
it.each([
["PT_NULL", "0xffffffffffffffff", "none", null, true],
["PT_LOAD", "0x0", "none", { read: true, write: true, execute: false }, true],
[
"PT_LOAD",
"0x1",
"file",
{ read: true, write: false, execute: false },
false,
],
["PT_NULL", "0x1", "file", null, false],
[
"PT_NULL",
"0x1",
"none",
{ read: false, write: false, execute: false },
false,
],
[
"PT_LOAD",
"0x1",
"none",
{ read: true, write: false, execute: false },
false,
],
])(
"validates actual segment backing/meaning for %s size %s",
(type, fileSize, backing, permissions, valid) => {
const value = {
...report(),
segments: [
{
index: 0,
type,
header_location: { offset: "0x0", bytes: "0x38" },
offset: "0xffffffffffffffff",
file_size: fileSize,
memory_size: fileSize,
virtual_address: "0x0",
physical_address: "0x0",
alignment: "0x0",
flags: "0x0",
file_backing: backing,
permissions,
},
],
};
expect(binaryLayoutSchema.safeParse(value).success).toBe(valid);
},
);
it.each([
["ET_EXEC", "0x0", "absent", true],
["ET_DYN", "0x0", "linked-virtual-address", false],
["ET_REL", "0x0", "not-applicable", true],
["ET_EXEC", "0x1", "absent", false],
])(
"validates actual entry meaning: %s %s %s",
(imageType, entry, meaning, valid) => {
expect(
binaryLayoutSchema.safeParse({
...report(),
image_type: imageType,
entry_point: {
reported_value: entry,
meaning,
execution_status: "unknown",
},
}).success,
).toBe(valid);
},
);
it.each([
"valid",
"byte-length",
"section-identity",
"decoded-order",
"noncanonical-bytes",
])(
"retains original packed bytes and derived offset provenance: %s",
(problem) => {
const value = report();
const section = value.sections[0];
if (section === undefined) throw new Error("section missing");
section.type = "SHT_RELR";
section.file_backing = "file";
section.offset = "0x60";
section.size = "0x8";
const table = {
section_index: 0,
location: { offset: "0x60", bytes: "0x8" },
encoded_bytes_base64: "AAAAAAAAAAA=",
entries: [{ decoded_index: 0, reported_offset: "0x20000000000001" }],
offset_meaning: "linked-virtual-address",
evidence_kind: "derived",
entry_source_locations: null,
addends: null,
};
if (problem === "byte-length") table.location.bytes = "0x7";
if (problem === "section-identity") table.section_index = 1;
if (problem === "decoded-order")
table.entries[0] = { decoded_index: 1, reported_offset: "0x0" };
if (problem === "noncanonical-bytes") table.encoded_bytes_base64 = "AB==";
expect(
binaryLayoutSchema.safeParse({
...value,
packed_relative_relocations: [table],
}).success,
).toBe(problem === "valid");
},
);
it.each([
"valid",
"zero-symbol",
"zero-without-table",
"missing-table",
"wrong-table-kind",
"missing-symbol",
"symbol-outside-table",
"positive-without-table",
"owner-link-mismatch",
"wrong-meaning",
"valid-section-target",
"missing-target",
"wrong-target-owner",
"wrong-target-offset",
"undefined-target",
"inactive-target",
"false-resolved-zero-target",
"wrong-unknown-target",
"missing-string-table",
"wrong-string-table-kind",
])("validates relocation symbol reference semantics: %s", (problem) => {
const value = binaryLayoutSchema.parse(report());
value.artifact.bytes = 512;
const base = value.sections[0];
if (base === undefined) throw new Error("section missing");
value.sections.push(
{
...base,
index: 1,
type: "SHT_SYMTAB",
link: 3,
header_location: { offset: "0x40", bytes: "0x40" },
offset: "0x100",
size: "0x30",
entry_size: "0x18",
file_backing: "file",
},
{
...base,
index: 2,
type: "SHT_RELA",
header_location: { offset: "0x80", bytes: "0x40" },
offset: "0x130",
size: "0x18",
entry_size: "0x18",
link: 1,
file_backing: "file",
},
{
...base,
index: 3,
type: "SHT_STRTAB",
offset: "0x40",
size: "0x7",
file_backing: "file",
},
);
value.symbols.push({
table_index: 1,
entry_index: 1,
name: base.name,
name_offset: "0x0",
location: { offset: "0x118", bytes: "0x18" },
value: "0x0",
value_meaning: "undefined",
size: "0x0",
binding: "STB_GLOBAL",
type: "STT_NOTYPE",
visibility: "STV_DEFAULT",
section_index: "SHN_UNDEF",
});
const relocation: BinaryLayout["relocations"][number] = {
section_index: 2,
entry_index: 0,
reported_offset: "0x0",
target: { kind: "linked-virtual-address", address: "0x0" },
location: { offset: "0x130", bytes: "0x18" },
type: 1,
symbol_table_index: 1,
symbol_index: 1,
symbol_reference_meaning: "symbol-table-entry",
addend: "0",
};
const table = value.sections[1];
const owner = value.sections[2];
if (table === undefined || owner === undefined)
throw new Error("table or relocation owner missing");
if (problem.startsWith("zero")) {
relocation.symbol_index = 0;
relocation.symbol_reference_meaning = "zero-symbol-value";
}
if (problem === "zero-without-table" || problem === "positive-without-table")
owner.link = relocation.symbol_table_index = 0;
if (problem === "missing-table")
owner.link = relocation.symbol_table_index = 99;
if (problem === "wrong-table-kind") table.type = "SHT_PROGBITS";
if (problem === "missing-string-table") table.link = 99;
if (problem === "wrong-string-table-kind") table.link = 0;
if (problem === "missing-symbol") value.symbols = [];
if (problem === "symbol-outside-table") table.size = "0x18";
if (problem === "owner-link-mismatch") owner.link = 0;
if (problem === "wrong-meaning")
relocation.symbol_reference_meaning = "zero-symbol-value";
if (problem.includes("target")) {
value.image_type = "ET_REL";
value.entry_point.meaning = "not-applicable";
owner.info = 1;
relocation.target = {
kind: "section-offset",
section_index:
problem === "missing-target"
? 99
: problem === "wrong-target-owner"
? 2
: 1,
offset: problem === "wrong-target-offset" ? "0x1" : "0x0",
};
if (problem === "missing-target") owner.info = 99;
if (problem === "false-resolved-zero-target") {
owner.info = 0;
relocation.target.section_index = 0;
}
if (
["undefined-target", "inactive-target", "wrong-unknown-target"].includes(
problem,
)
) {
if (problem === "inactive-target")
value.sections.push({ ...base, index: 4, type: "SHT_NULL" });
owner.info =
problem === "undefined-target"
? 0
: problem === "inactive-target"
? 4
: 1;
relocation.target = {
kind: "unknown-section",
reported_section_index: owner.info,
offset: "0x0",
unknown_reason:
problem === "undefined-target"
? "undefined-section-reference"
: "inactive-section-header",
};
}
}
value.relocations.push(relocation);
expect(binaryLayoutSchema.safeParse(value).success).toBe(
[
"valid",
"zero-symbol",
"zero-without-table",
"valid-section-target",
"undefined-target",
"inactive-target",
].includes(problem),
);
});
+443
View File
@@ -0,0 +1,443 @@
import { z } from "zod";
const unsignedHex = z.string().regex(/^0x(?:0|[1-9a-f][0-9a-f]{0,15})$/);
const index = z.number().int().nonnegative();
const scalar = z.union([z.string(), z.number().int()]);
const range = z.strictObject({ offset: unsignedHex, bytes: unsignedHex });
const canonicalBase64 = z
.string()
.regex(
/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/][AQgw]==|[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=)?$/,
);
const name = z.strictObject({
display: z.string(),
bytes_base64: canonicalBase64.nullable(),
location: range.nullable(),
unknown_reason: z.string().nullable(),
});
/** Explicit local object selection, independent of an active disassembler target. */
export const inspectBinaryLayoutInputSchema = z.strictObject({
path: z
.string()
.min(1)
.describe("Absolute filesystem path to the selected binary"),
});
/** File and linked-image evidence; numeric ELF values never pass through unsafe JSON numbers. */
const binaryLayoutObjectSchema = z.strictObject({
artifact: z.strictObject({
path: z.string().min(1),
sha256: z.string().regex(/^[a-f0-9]{64}$/),
bytes: index,
}),
format: z.literal("elf"),
architecture: z.strictObject({
machine: z.literal("EM_X86_64"),
bits: z.literal(64),
byte_order: z.literal("little"),
}),
image_type: z.enum(["ET_EXEC", "ET_DYN", "ET_REL"]),
entry_point: z.strictObject({
reported_value: unsignedHex,
meaning: z.enum(["linked-virtual-address", "not-applicable", "absent"]),
execution_status: z.literal("unknown"),
}),
runtime_load_base: z.null(),
sections: z.array(
z.strictObject({
index,
name,
name_offset: unsignedHex,
type: scalar,
header_location: range,
address: unsignedHex,
offset: unsignedHex,
size: unsignedHex,
alignment: unsignedHex,
flags: unsignedHex,
link: index,
info: index,
entry_size: unsignedHex,
file_backing: z.enum(["file", "none"]),
}),
),
segments: z.array(
z.strictObject({
index,
type: scalar,
header_location: range,
offset: unsignedHex,
file_size: unsignedHex,
memory_size: unsignedHex,
virtual_address: unsignedHex,
physical_address: unsignedHex,
alignment: unsignedHex,
flags: unsignedHex,
file_backing: z.enum(["file", "none"]),
permissions: z
.strictObject({
read: z.boolean(),
write: z.boolean(),
execute: z.boolean(),
})
.nullable(),
}),
),
symbols: z.array(
z.strictObject({
table_index: index,
entry_index: index,
name,
name_offset: unsignedHex,
location: range,
value: unsignedHex,
value_meaning: z.enum([
"undefined",
"alignment",
"absolute-value",
"no-address",
"unknown-section-index",
"section-offset",
"tls-offset",
"linked-virtual-address",
]),
size: unsignedHex,
binding: scalar,
type: scalar,
visibility: scalar,
section_index: scalar,
}),
),
relocations: z.array(
z.strictObject({
section_index: index,
entry_index: index,
reported_offset: unsignedHex,
target: z.discriminatedUnion("kind", [
z.strictObject({
kind: z.literal("section-offset"),
section_index: index,
offset: unsignedHex,
}),
z.strictObject({
kind: z.literal("linked-virtual-address"),
address: unsignedHex,
}),
z.strictObject({
kind: z.literal("unknown-section"),
reported_section_index: index,
offset: unsignedHex,
unknown_reason: z.enum([
"undefined-section-reference",
"inactive-section-header",
]),
}),
]),
location: range,
type: index,
symbol_table_index: index,
symbol_index: index,
symbol_reference_meaning: z.enum([
"zero-symbol-value",
"symbol-table-entry",
]),
addend: z
.string()
.regex(/^-?(?:0|[1-9][0-9]{0,18})$/)
.nullable(),
}),
),
packed_relative_relocations: z.array(
z.strictObject({
section_index: index,
location: range,
encoded_bytes_base64: canonicalBase64,
entries: z.array(
z.strictObject({ decoded_index: index, reported_offset: unsignedHex }),
),
offset_meaning: z.enum(["linked-virtual-address", "unknown"]),
evidence_kind: z.literal("derived"),
entry_source_locations: z.null(),
addends: z.null(),
}),
),
relocation_inventory_completeness: z.literal("unknown"),
linkage: z.strictObject({
needed_libraries: z.array(name),
interpreters: z.array(name),
got: z.array(
z.strictObject({ display_name: z.string(), address: unsignedHex }),
),
plt: z.array(
z.strictObject({ display_name: z.string(), address: unsignedHex }),
),
convenience_maps_completeness: z.literal("unknown"),
runtime_library_paths: z.null(),
}),
mitigations: z.strictObject({
evidence_kind: z.literal("inferred"),
position_independent: z.boolean(),
nx_indicator: z.boolean().nullable(),
executable_stack_indicator: z.boolean(),
stack_canary_indicator: z.boolean(),
relro: z.enum(["Partial", "Full"]).nullable(),
}),
diagnostics: z.strictObject({
stdout: z.string(),
stderr: z.string(),
truncated: z.boolean(),
}),
limitations: z.array(z.string()),
});
/** Decoder payload excludes the artifact identity observed by the owning process boundary. */
export const binaryLayoutPayloadSchema = binaryLayoutObjectSchema.omit({
artifact: true,
diagnostics: true,
});
/** Check source ranges again at the public boundary, independently of upstream parsing. */
export const binaryLayoutSchema = binaryLayoutObjectSchema.superRefine(
(value, context) => {
const size = BigInt(value.artifact.bytes);
const check = (
offset: string,
length: string,
path: (string | number)[],
): void => {
const start = BigInt(offset);
const bytes = BigInt(length);
if (start > size || bytes > size - start)
context.addIssue({
code: "custom",
path,
message:
"Reported file-backed range lies outside the selected artifact.",
});
};
const checkLocation = (
where: z.infer<typeof range>,
path: (string | number)[],
): void => check(where.offset, where.bytes, path);
const checkName = (
reported: z.infer<typeof name>,
path: (string | number)[],
): void => {
if (reported.location !== null)
checkLocation(reported.location, [...path, "location"]);
};
const expectedEntryMeaning =
value.image_type === "ET_REL"
? "not-applicable"
: value.entry_point.reported_value === "0x0"
? "absent"
: "linked-virtual-address";
if (value.entry_point.meaning !== expectedEntryMeaning)
context.addIssue({
code: "custom",
path: ["entry_point", "meaning"],
message:
"Entry meaning must distinguish zero/unused fields from an actual linked address.",
});
for (const [index, section] of value.sections.entries()) {
if (
(section.type === "SHT_SYMTAB" || section.type === "SHT_DYNSYM") &&
value.sections[section.link]?.type !== "SHT_STRTAB"
)
context.addIssue({
code: "custom",
path: ["sections", index, "link"],
message:
"Symbol tables must link to an existing string-table section.",
});
if (section.index !== index)
context.addIssue({
code: "custom",
path: ["sections", index, "index"],
message:
"Complete section order must preserve original producer indices.",
});
checkLocation(section.header_location, [
"sections",
index,
"header_location",
]);
checkName(section.name, ["sections", index, "name"]);
if (section.file_backing === "file")
check(section.offset, section.size, ["sections", index]);
}
for (const [index, segment] of value.segments.entries()) {
if (segment.index !== index)
context.addIssue({
code: "custom",
path: ["segments", index, "index"],
message:
"Complete segment order must preserve original producer indices.",
});
checkLocation(segment.header_location, [
"segments",
index,
"header_location",
]);
const hasFileBytes =
segment.type !== "PT_NULL" && BigInt(segment.file_size) !== 0n;
if (segment.file_backing !== (hasFileBytes ? "file" : "none"))
context.addIssue({
code: "custom",
path: ["segments", index, "file_backing"],
message:
"File backing must follow the reported segment type and file size.",
});
if ((segment.type === "PT_NULL") !== (segment.permissions === null))
context.addIssue({
code: "custom",
path: ["segments", index, "permissions"],
message:
"Unused PT_NULL flags have no permission meaning; other segment flags retain their interpretation.",
});
if (hasFileBytes)
check(segment.offset, segment.file_size, ["segments", index]);
}
for (const [index, symbol] of value.symbols.entries()) {
checkLocation(symbol.location, ["symbols", index, "location"]);
checkName(symbol.name, ["symbols", index, "name"]);
}
for (const [index, relocation] of value.relocations.entries())
checkLocation(relocation.location, ["relocations", index, "location"]);
validateRelocationReferences(value, context);
validatePackedRelativeTables(value, context, checkLocation);
for (const facet of ["needed_libraries", "interpreters"] as const)
for (const [index, reported] of value.linkage[facet].entries())
checkName(reported, ["linkage", facet, index]);
},
);
export type InspectBinaryLayoutInput = z.infer<
typeof inspectBinaryLayoutInputSchema
>;
export type BinaryLayout = z.infer<typeof binaryLayoutSchema>;
const validateRelocationReferences = (
value: z.output<typeof binaryLayoutObjectSchema>,
context: z.RefinementCtx,
): void => {
const symbols = new Set(
value.symbols.map(
(symbol) => `${symbol.table_index}:${symbol.entry_index}`,
),
);
for (const [index, relocation] of value.relocations.entries()) {
const owner = value.sections[relocation.section_index];
const target = relocation.target;
const targetMatches =
value.image_type === "ET_REL"
? target.kind === "section-offset"
? target.section_index !== 0 &&
target.section_index === owner?.info &&
value.sections[target.section_index] !== undefined &&
value.sections[target.section_index]?.type !== "SHT_NULL" &&
target.offset === relocation.reported_offset
: target.kind === "unknown-section" &&
target.reported_section_index === owner?.info &&
target.offset === relocation.reported_offset &&
(target.reported_section_index === 0
? target.unknown_reason === "undefined-section-reference"
: value.sections[target.reported_section_index]?.type ===
"SHT_NULL" &&
target.unknown_reason === "inactive-section-header")
: target.kind === "linked-virtual-address" &&
target.address === relocation.reported_offset;
if (!targetMatches)
context.addIssue({
code: "custom",
path: ["relocations", index, "target"],
message:
"Relocation target must preserve its reported offset and owner reference; SHN_UNDEF and inactive headers remain unknown rather than resolved sections.",
});
const table = value.sections[relocation.symbol_table_index];
const tableExists =
relocation.symbol_table_index !== 0 &&
(table?.type === "SHT_SYMTAB" || table?.type === "SHT_DYNSYM");
const positiveReferenceExists =
tableExists &&
BigInt(table.entry_size) >= 24n &&
BigInt(relocation.symbol_index) <
BigInt(table.size) / BigInt(table.entry_size) &&
symbols.has(
`${relocation.symbol_table_index}:${relocation.symbol_index}`,
);
if (
(owner?.type !== "SHT_REL" && owner?.type !== "SHT_RELA") ||
owner.link !== relocation.symbol_table_index ||
(relocation.symbol_table_index !== 0 && !tableExists) ||
(relocation.symbol_index !== 0 && !positiveReferenceExists) ||
relocation.symbol_reference_meaning !==
(relocation.symbol_index === 0
? "zero-symbol-value"
: "symbol-table-entry")
)
context.addIssue({
code: "custom",
path: ["relocations", index],
message:
"Relocation must preserve its REL/RELA owner and resolve positive symbol indices through the linked symbol table; index zero uses a zero symbol value.",
});
}
};
const validatePackedRelativeTables = (
value: z.output<typeof binaryLayoutObjectSchema>,
context: z.RefinementCtx,
checkLocation: (
location: z.output<typeof range>,
path: (string | number)[],
) => void,
): void => {
for (const [
tableIndex,
table,
] of value.packed_relative_relocations.entries()) {
checkLocation(table.location, [
"packed_relative_relocations",
tableIndex,
"location",
]);
const encodedBytes =
(table.encoded_bytes_base64.length * 3) / 4 -
(table.encoded_bytes_base64.endsWith("==")
? 2
: table.encoded_bytes_base64.endsWith("=")
? 1
: 0);
if (
!Number.isInteger(encodedBytes) ||
BigInt(encodedBytes) !== BigInt(table.location.bytes)
)
context.addIssue({
code: "custom",
path: ["packed_relative_relocations", tableIndex],
message:
"Complete packed table bytes must match its original file range.",
});
const section = value.sections[table.section_index];
if (
section?.type !== "SHT_RELR" ||
section.offset !== table.location.offset ||
section.size !== table.location.bytes
)
context.addIssue({
code: "custom",
path: ["packed_relative_relocations", tableIndex, "section_index"],
message:
"Packed relative evidence must retain its original RELR section identity and range.",
});
for (const [decoded, entry] of table.entries.entries())
if (entry.decoded_index !== decoded)
context.addIssue({
code: "custom",
path: ["packed_relative_relocations", tableIndex, "entries", decoded],
message: "Decoded offsets must preserve upstream iterator order.",
});
}
};