Files
reverse-engineering-anything/src/go/GoStringLiterals.ts
T

704 lines
21 KiB
TypeScript

import {
lastAtOrBelow,
type FileMapping,
} from "../domain/virtualFileMapping.js";
import { isUtf8 } from "node:buffer";
import {
GO_ANALYSIS_BUDGET_DEFAULTS,
type GoAnalysisBudgets,
type GoStringBudgetKey,
type GoStringLiteral,
type GoStringLiterals,
} from "../domain/go/goBinary.js";
import {
BinaryFormatFailure,
BinaryMappingFailure,
BinaryReader,
createFileMappingIndex,
imageFileMappings,
type BinaryContainer,
type FileMappingIndex,
type LoadRegion,
} from "../domain/binaryContainer.js";
import type { ByteSource } from "../domain/byteSource.js";
const STREAM_CHUNK_BYTES = 64 * 1024;
const TARGET_PAGE_BYTES = 4096;
const TARGET_CACHE_PAGES = 8;
const MAX_REJECTED_SLICE_CACHE = 4096;
const PE_MEM_READ = 0x40000000;
const PE_MEM_EXECUTE = 0x20000000;
const PE_MEM_DISCARDABLE = 0x02000000;
const PE_CNT_CODE = 0x00000020;
const PE_CNT_INITIALIZED_DATA = 0x00000040;
const MACHO_ATTR_INSTRUCTIONS = 0x80000400;
const MACHO_ATTR_DEBUG = 0x02000000;
const DISALLOWED_GO_STRING_CODE_POINT =
/(?![\t\n\r\u200c\u200d])[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}]/u;
interface CandidateLiteral {
readonly offset: number;
readonly bytes: number;
firstHeaderOffset: number;
referenceCount: number;
}
interface HeaderScanSpan {
readonly startOffset: number;
readonly endOffset: number;
}
type StringScanRead = {
readonly offset: number;
readonly length: number;
readonly kind: "header" | "target";
};
/** Read exactly the admitted header and candidate ranges from the file. */
export const recoverGoStringLiteralsFromReader = async (
source: ByteSource,
container: BinaryContainer,
budgets: GoAnalysisBudgets = GO_ANALYSIS_BUDGET_DEFAULTS,
checkActive?: () => void,
): Promise<GoStringLiterals> => {
const steps = recoverGoStringLiteralSteps(
source.size,
container,
budgets,
checkActive,
);
const pages = new Map<number, Buffer>();
let previousPage: number | undefined;
let consecutiveTargets = 0;
let readAheadCredit = 0;
const read = async (
offset: number,
length: number,
label: string,
): Promise<Buffer> => {
const bytes =
source.prefix !== undefined && offset + length <= source.prefix.length
? source.prefix.subarray(offset, offset + length)
: await source.readRange(offset, length);
if (bytes.length !== length)
throw new BinaryFormatFailure(
"truncated",
`${label} range is outside the file`,
{ format: container.format, offset },
);
return bytes;
};
const readTarget = async ({
offset,
length,
}: StringScanRead): Promise<Buffer> => {
const pageOffset = offset - (offset % TARGET_PAGE_BYTES);
consecutiveTargets =
pageOffset === previousPage ? consecutiveTargets + 1 : 1;
previousPage = pageOffset;
const relative = offset - pageOffset;
const pageLength = Math.min(TARGET_PAGE_BYTES, source.size - pageOffset);
if (relative + length <= pageLength) {
const cached = pages.get(pageOffset);
if (cached !== undefined) {
pages.delete(pageOffset);
pages.set(pageOffset, cached);
return cached.subarray(relative, relative + length);
}
// Admit extra I/O only after observing locality. The total extra bytes
// can never exceed the header bytes read, even if every page is evicted.
const extra = pageLength - length;
if (consecutiveTargets >= 3 && readAheadCredit >= extra) {
readAheadCredit -= extra;
const bytes = await read(pageOffset, pageLength, "Go string literal");
if (pages.size === TARGET_CACHE_PAGES) {
const oldest = pages.keys().next();
if (!oldest.done) pages.delete(oldest.value);
}
pages.set(pageOffset, bytes);
return bytes.subarray(relative, relative + length);
}
}
return read(offset, length, "Go string literal");
};
let step = steps.next();
while (!step.done) {
const request = step.value;
if (request.kind === "header") {
const chunk = await read(
request.offset,
request.length,
"Go string header span",
);
readAheadCredit += chunk.length;
step = steps.next(chunk);
} else {
step = steps.next(await readTarget(request));
}
}
return step.value;
};
function* recoverGoStringLiteralSteps(
fileSize: number,
container: BinaryContainer,
budgets: GoAnalysisBudgets,
checkActive: (() => void) | undefined,
): Generator<StringScanRead, GoStringLiterals, Buffer> {
const limitsReached = new Set<GoStringBudgetKey>();
const maxItems = budgets.max_string_literals;
checkActive?.();
const index = createFileMappingIndex(
imageFileMappings(container),
container.zero_fills,
);
checkActive?.();
const readableRegions = createReadableLoadRegionIndex(
container.load_regions,
checkActive,
);
const targets = selectTargetSpans(
fileSize,
container,
index,
readableRegions,
checkActive,
);
const headerSpans = selectHeaderScanSpans(
fileSize,
container,
index,
readableRegions,
checkActive,
);
if (targets.length === 0 || headerSpans.length === 0)
return {
evidence_kind: "inferred",
items: [],
discovered_count: 0,
aggregate_bytes: 0,
max_items: maxItems,
truncated: false,
};
const { bits } = container;
const little = container.byte_order === "little";
const wordBytes = bits === 64 ? 8 : 4;
const firstTarget = targets[0] as FileMapping;
const lastTarget = targets[targets.length - 1] as FileMapping;
const minTargetAddr = firstTarget.address;
const maxTargetEnd = lastTarget.address + BigInt(lastTarget.size);
const targetEnds = targets.map((t) => t.address + BigInt(t.size));
const accepted = new Map<string, CandidateLiteral>();
const rejected = new Set<string>();
const candidates: CandidateLiteral[] = [];
let remainingBudget = budgets.max_string_header_scan_bytes;
let budgetTruncated = false;
let steps = 0;
outer: for (const { startOffset, endOffset } of headerSpans) {
if (remainingBudget < wordBytes * 2) {
budgetTruncated = true;
limitsReached.add("max_string_header_scan_bytes");
break;
}
const chunkLimit = STREAM_CHUNK_BYTES;
let cursor = startOffset;
let word0: bigint | undefined;
while (cursor < endOffset) {
checkActive?.();
const admittedBytes = remainingBudget - (remainingBudget % wordBytes);
if (admittedBytes < wordBytes) {
budgetTruncated = true;
limitsReached.add("max_string_header_scan_bytes");
break outer;
}
const chunkLen = Math.min(chunkLimit, endOffset - cursor, admittedBytes);
const chunk = yield {
offset: cursor,
length: chunkLen,
kind: "header",
};
const chunkReader = new BinaryReader(chunk, little, container.format);
let rel = 0;
if (word0 === undefined) {
word0 = chunkReader.word(0, bits);
remainingBudget -= wordBytes;
rel = wordBytes;
}
for (; rel + wordBytes <= chunkLen; rel += wordBytes) {
if ((++steps & 0xffff) === 0) checkActive?.();
if (remainingBudget < wordBytes) {
budgetTruncated = true;
limitsReached.add("max_string_header_scan_bytes");
break outer;
}
remainingBudget -= wordBytes;
const word1 = chunkReader.word(rel, bits);
const headerOffset = cursor + rel - wordBytes;
const ptr = word0;
const rawLen = word1;
word0 = word1;
if (rawLen < 1n) continue;
if (ptr < minTargetAddr || ptr >= maxTargetEnd) continue;
const targetIndex = lastSpanAtOrBelow(targets, ptr);
if (targetIndex < 0) continue;
const target = targets[targetIndex] as FileMapping;
if (ptr + rawLen > targetEnds[targetIndex]!) continue;
const byteLen = Number(rawLen);
const sliceOffset = target.offset + Number(ptr - target.address);
if (
headerOffset < sliceOffset + byteLen &&
sliceOffset < headerOffset + wordBytes * 2
)
continue;
if (byteLen > budgets.max_string_literal_bytes) {
limitsReached.add("max_string_literal_bytes");
budgetTruncated = true;
continue;
}
const key = `${String(sliceOffset)}:${String(byteLen)}`;
const existing = accepted.get(key);
if (existing !== undefined) {
existing.referenceCount += 1;
if (headerOffset < existing.firstHeaderOffset)
existing.firstHeaderOffset = headerOffset;
continue;
}
if (rejected.has(key)) continue;
if (remainingBudget < byteLen) {
limitsReached.add("max_string_header_scan_bytes");
budgetTruncated = true;
break outer;
}
remainingBudget -= byteLen;
const slice = yield {
offset: sliceOffset,
length: byteLen,
kind: "target",
};
if (!isPrintableGoUtf8(slice)) {
if (rejected.size >= MAX_REJECTED_SLICE_CACHE) rejected.clear();
rejected.add(key);
continue;
}
if (candidates.length >= budgets.max_string_candidates) {
limitsReached.add("max_string_candidates");
budgetTruncated = true;
break outer;
}
const entry: CandidateLiteral = {
offset: sliceOffset,
bytes: byteLen,
firstHeaderOffset: headerOffset,
referenceCount: 1,
};
accepted.set(key, entry);
candidates.push(entry);
}
cursor += chunkLen;
}
}
checkActive?.();
candidates.sort(
(left, right) => left.offset - right.offset || left.bytes - right.bytes,
);
const items: GoStringLiteral[] = [];
let aggregateBytes = 0;
let outputTruncated = false;
for (const candidate of candidates) {
if (
items.length >= maxItems ||
aggregateBytes + candidate.bytes > budgets.max_string_bytes
) {
limitsReached.add(
items.length >= maxItems ? "max_string_literals" : "max_string_bytes",
);
outputTruncated = true;
break;
}
const slice = yield {
offset: candidate.offset,
length: candidate.bytes,
kind: "target",
};
items.push({
value: slice.toString("utf8"),
location: { offset: candidate.offset, bytes: candidate.bytes },
first_header_offset: candidate.firstHeaderOffset,
reference_count: candidate.referenceCount,
});
aggregateBytes += candidate.bytes;
}
return {
evidence_kind: "inferred",
items,
discovered_count: candidates.length,
aggregate_bytes: aggregateBytes,
max_items: maxItems,
truncated: budgetTruncated || outputTruncated,
...(limitsReached.size === 0 ? {} : { limits_reached: [...limitsReached] }),
};
}
const isPrintableGoUtf8 = (slice: Buffer): boolean => {
let hasNonAscii = false;
for (let i = 0; i < slice.length; i += 1) {
const byte = slice[i]!;
if (byte >= 0x80) {
hasNonAscii = true;
continue;
}
if (
(byte < 0x20 && byte !== 0x09 && byte !== 0x0a && byte !== 0x0d) ||
byte === 0x7f
)
return false;
}
if (!hasNonAscii) return true;
if (!isUtf8(slice)) return false;
return !DISALLOWED_GO_STRING_CODE_POINT.test(slice.toString("utf8"));
};
const admitMappedSpan = (
fileSize: number,
container: BinaryContainer,
index: FileMappingIndex,
address: bigint,
offset: number,
size: number,
): FileMapping | null => {
if (
size <= 0 ||
offset < 0 ||
offset > fileSize ||
size > fileSize - offset ||
address < 0n ||
address + BigInt(size) > 1n << BigInt(container.bits)
)
return null;
try {
return index.offset(address, size) === offset
? { address, offset, size }
: null;
} catch (cause) {
if (cause instanceof BinaryMappingFailure) return null;
throw cause;
}
};
interface ReadableLoadRegionIndex {
readonly contains: (address: bigint, size: number) => boolean;
}
const createReadableLoadRegionIndex = (
loadRegions: readonly LoadRegion[] | undefined,
checkActive?: () => void,
): ReadableLoadRegionIndex => {
if (loadRegions === undefined || loadRegions.length === 0)
return { contains: () => false };
const raw: { start: bigint; end: bigint }[] = [];
let steps = 0;
for (const region of loadRegions) {
if ((++steps & 0x3ff) === 0) checkActive?.();
if (!region.read || region.mapping.size <= 0) continue;
raw.push({
start: region.mapping.address,
end: region.mapping.address + BigInt(region.mapping.size),
});
}
if (raw.length === 0) return { contains: () => false };
checkActive?.();
raw.sort((left, right) =>
left.start < right.start
? -1
: left.start > right.start
? 1
: left.end < right.end
? -1
: left.end > right.end
? 1
: 0,
);
const starts: bigint[] = [];
const ends: bigint[] = [];
let currentStart = (raw[0] as (typeof raw)[number]).start;
let currentEnd = (raw[0] as (typeof raw)[number]).end;
for (let index = 1; index < raw.length; index += 1) {
if ((index & 0x3ff) === 0) checkActive?.();
const span = raw[index] as (typeof raw)[number];
if (span.start <= currentEnd) {
if (span.end > currentEnd) currentEnd = span.end;
continue;
}
starts.push(currentStart);
ends.push(currentEnd);
currentStart = span.start;
currentEnd = span.end;
}
starts.push(currentStart);
ends.push(currentEnd);
return {
contains: (address, size) => {
if (size <= 0) return false;
const index = lastAtOrBelow(starts, address);
return index >= 0 && address + BigInt(size) <= (ends[index] as bigint);
},
};
};
/**
* Retain read-only non-executable mapped spans without merging distinct sections,
* so `[ptr, ptr + len)` cannot cross section boundaries.
*/
const selectTargetSpans = (
fileSize: number,
container: BinaryContainer,
index: FileMappingIndex,
readableRegions: ReadableLoadRegionIndex,
checkActive?: () => void,
): readonly FileMapping[] => {
const raw: FileMapping[] = [];
let steps = 0;
if (container.sections.length > 0) {
for (const section of container.sections) {
if ((++steps & 0x3ff) === 0) checkActive?.();
if (!section.read_only) continue;
if (
section.format === "pe" &&
(section.characteristics & PE_MEM_DISCARDABLE) !== 0
)
continue;
if (
section.format === "macho" &&
(section.segment_unmapped ||
(section.flags & MACHO_ATTR_DEBUG) !== 0 ||
!readableRegions.contains(section.address, section.size))
)
continue;
const address =
section.format === "pe"
? (container.image_base ?? 0n) + BigInt(section.virtual_address)
: section.address;
const admitted = admitMappedSpan(
fileSize,
container,
index,
address,
section.offset,
section.size,
);
if (admitted !== null) raw.push(admitted);
}
} else {
for (const region of container.load_regions ?? []) {
if ((++steps & 0x3ff) === 0) checkActive?.();
if (!region.read || region.write || region.execute) continue;
const admitted = admitMappedSpan(
fileSize,
container,
index,
region.mapping.address,
region.mapping.offset,
region.mapping.size,
);
if (admitted !== null) raw.push(admitted);
}
}
raw.sort((left, right) =>
left.address < right.address
? -1
: left.address > right.address
? 1
: right.size - left.size,
);
const nonContained: FileMapping[] = [];
let maxEnd = -1n;
for (const span of raw) {
if ((++steps & 0x3ff) === 0) checkActive?.();
const end = span.address + BigInt(span.size);
if (end <= maxEnd) continue;
nonContained.push(span);
maxEnd = end;
}
return nonContained;
};
/** Select non-executable initialized data spans that may store static `(ptr, len)` pairs. */
const selectHeaderScanSpans = (
fileSize: number,
container: BinaryContainer,
index: FileMappingIndex,
readableRegions: ReadableLoadRegionIndex,
checkActive?: () => void,
): readonly HeaderScanSpan[] => {
const spans: FileMapping[] = [];
let steps = 0;
const push = (address: bigint, offset: number, size: number): void => {
const admitted = admitMappedSpan(
fileSize,
container,
index,
address,
offset,
size,
);
if (admitted !== null) spans.push(admitted);
};
for (const section of container.sections) {
if ((++steps & 0x3ff) === 0) checkActive?.();
if (!section.file_backed || section.compressed) continue;
if (section.format === "elf") {
if (
section.type !== 1 ||
(section.flags & 2n) === 0n ||
(section.flags & 4n) !== 0n
)
continue;
push(section.address, section.offset, section.size);
continue;
}
if (section.format === "macho") {
if (
section.segment_unmapped ||
(section.flags & MACHO_ATTR_INSTRUCTIONS) !== 0 ||
(section.flags & MACHO_ATTR_DEBUG) !== 0 ||
!readableRegions.contains(section.address, section.size)
)
continue;
push(section.address, section.offset, section.size);
continue;
}
if (
(section.characteristics & PE_MEM_READ) === 0 ||
(section.characteristics & PE_MEM_EXECUTE) !== 0 ||
(section.characteristics & PE_CNT_CODE) !== 0 ||
(section.characteristics & PE_MEM_DISCARDABLE) !== 0 ||
(section.characteristics & PE_CNT_INITIALIZED_DATA) === 0 ||
container.image_base === undefined
)
continue;
push(
container.image_base + BigInt(section.virtual_address),
section.offset,
section.size,
);
}
if (container.sections.length === 0) {
for (const region of container.load_regions ?? []) {
if ((++steps & 0x3ff) === 0) checkActive?.();
if (!region.read || region.execute) continue;
push(region.mapping.address, region.mapping.offset, region.mapping.size);
}
} else if (
container.format === "elf" &&
container.section_names_limitation !== undefined
) {
for (const region of container.load_regions ?? []) {
if ((++steps & 0x3ff) === 0) checkActive?.();
if (!region.read || !region.write || region.execute) continue;
push(region.mapping.address, region.mapping.offset, region.mapping.size);
}
}
return normalizeHeaderScanSpans(
spans,
container.bits === 64 ? 8 : 4,
checkActive,
);
};
/**
* Align candidate header spans to pointer-word boundaries, merge overlapping
* same-phase intervals so physical headers are never counted twice, and sort
* in ascending file-offset order so `first_header_offset` is minimal.
*/
const normalizeHeaderScanSpans = (
spans: readonly FileMapping[],
wordBytes: 4 | 8,
checkActive?: () => void,
): readonly HeaderScanSpan[] => {
const wordWidth = BigInt(wordBytes);
const aligned: {
startOffset: number;
endOffset: number;
readonly phase: number;
}[] = [];
let steps = 0;
for (const span of spans) {
if ((++steps & 0x3ff) === 0) checkActive?.();
const misalign = Number(
(wordWidth - (span.address % wordWidth)) % wordWidth,
);
const startOffset = span.offset + misalign;
const spanEnd = span.offset + span.size;
if (spanEnd - startOffset < wordBytes * 2) continue;
const endOffset =
startOffset + Math.floor((spanEnd - startOffset) / wordBytes) * wordBytes;
aligned.push({
startOffset,
endOffset,
phase: startOffset % wordBytes,
});
}
if (aligned.length === 0) return [];
aligned.sort(
(left, right) =>
left.phase - right.phase ||
left.startOffset - right.startOffset ||
right.endOffset - left.endOffset,
);
const merged: HeaderScanSpan[] = [];
let current = aligned[0] as (typeof aligned)[number];
for (let index = 1; index < aligned.length; index += 1) {
if ((++steps & 0x3ff) === 0) checkActive?.();
const next = aligned[index] as (typeof aligned)[number];
if (next.phase === current.phase && next.startOffset < current.endOffset) {
if (next.endOffset > current.endOffset)
current = { ...current, endOffset: next.endOffset };
continue;
}
merged.push({
startOffset: current.startOffset,
endOffset: current.endOffset,
});
current = next;
}
merged.push({
startOffset: current.startOffset,
endOffset: current.endOffset,
});
merged.sort(
(left, right) =>
left.startOffset - right.startOffset || left.endOffset - right.endOffset,
);
return merged;
};
const lastSpanAtOrBelow = (
sorted: readonly FileMapping[],
address: bigint,
): number => {
let low = 0;
let high = sorted.length;
while (low < high) {
const middle = (low + high) >>> 1;
if ((sorted[middle] as FileMapping).address <= address) low = middle + 1;
else high = middle;
}
return low - 1;
};