Repository navigation
Expand file tree
/
Copy pathRustBinaryImage.ts
More file actions
305 lines (289 loc) · 9.7 KB
/
Copy pathRustBinaryImage.ts
File metadata and controls
305 lines (289 loc) · 9.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import {
BinaryResourceFailure,
type ImageSection,
} from "../domain/binaryContainer.js";
import { malformedInput, unsupportedInput } from "../domain/parseFailure.js";
import { keyedBy, uniqueKeyed } from "../domain/keyedCollection.js";
import { readBinaryContainer } from "../domain/native/readBinaryContainer.js";
import type {
RustAuditableMetadata,
RustBinary,
} from "../domain/rust/rustBinary.js";
import {
DEFAULT_RUSTC_HASH_LIMIT,
rustcPartialCoverage,
rustDependencySectionName,
} from "../domain/rust/rustBinary.js";
import { RUST_PRODUCER_DEFAULTS } from "../domain/rust/rustResourceLimits.js";
import {
readAuditableSection,
RUST_AUDITABLE_FORMAT,
RustAuditableResourceFailure,
} from "./RustAuditableReader.js";
import { hasWasmPreamble, readRustWasmSections } from "./RustWasmImage.js";
const RUSTC_PREFIX = Buffer.from("/rustc/");
const HASH_BYTES = 40;
/** Container identity plus optional dependency metadata and inferred rustc commits. */
export interface RustBinaryImage {
readonly format: RustBinary["format"];
readonly architecture: string;
readonly bits: RustBinary["bits"];
readonly byte_order: RustBinary["byte_order"];
readonly auditable_metadata: RustAuditableMetadata | null;
readonly rustc_commit: RustBinary["rustc_commit"];
readonly section_names_limitation?: string;
}
interface FileSpan {
readonly offset: number;
readonly size: number;
}
/** The stored dependency stream and the PE padding allowance that may follow it. */
interface DependencySpan extends FileSpan {
readonly peFileAlignment?: number | undefined;
}
/** Container identity and the exact file spans that Rust metadata lookups read. */
interface RustImageLayout extends Pick<
RustBinaryImage,
"format" | "architecture" | "bits" | "byte_order" | "section_names_limitation"
> {
readonly section_name: RustAuditableMetadata["section_name"];
readonly dependency: DependencySpan | null;
/** Spans where rustc stores constant `/rustc/<hash>/` path strings. */
readonly compiler_strings: readonly FileSpan[];
}
/** Read dependency metadata from container sections without executing the image. */
export const readRustBinaryImage = (
bytes: Buffer,
maxRustcHashes = DEFAULT_RUSTC_HASH_LIMIT,
maxOutputBytes: number = RUST_PRODUCER_DEFAULTS.output_bytes,
): RustBinaryImage => {
const { section_name, dependency, compiler_strings, ...identity } =
hasWasmPreamble(bytes) ? wasmLayout(bytes) : nativeLayout(bytes);
return {
...identity,
auditable_metadata:
dependency === null
? null
: readAuditableSection(
section_name,
dependency.offset,
bytes.subarray(
dependency.offset,
dependency.offset + dependency.size,
),
{ maxOutputBytes, peFileAlignment: dependency.peFileAlignment },
),
rustc_commit: rustcCommit(
bytes,
compiler_strings,
maxRustcHashes,
maxOutputBytes,
),
};
};
const nativeLayout = (bytes: Buffer): RustImageLayout => {
const container = readContainer(bytes);
const section_name = rustDependencySectionName(container.format);
const dependency = dependencySection(section_name, container.sections);
return {
format: container.format,
architecture: container.architecture,
bits: container.bits,
byte_order: container.byte_order,
...(container.section_names_limitation === undefined
? {}
: { section_names_limitation: container.section_names_limitation }),
section_name,
dependency:
dependency === null
? null
: {
offset: dependency.offset,
size: dependency.size,
peFileAlignment:
dependency.format === "pe" &&
dependency.virtual_size === 0 &&
dependency.file_alignment > 0 &&
dependency.raw_size % dependency.file_alignment === 0
? dependency.file_alignment
: undefined,
},
compiler_strings: [
...container.sections.filter((section) => section.read_only),
...(container.format === "elf"
? (container.load_regions ?? [])
.filter((region) => region.read && !region.write && !region.execute)
.map(({ mapping }) => mapping)
: []),
],
};
};
/** WebAssembly fixes little-endian encoding but declares no container word size. */
const wasmLayout = (bytes: Buffer): RustImageLayout => {
const { dependency_sections, data_section } = readRustWasmSections(bytes);
if (dependency_sections.length > 1) throw duplicateDependencySection();
return {
format: "wasm",
architecture: "wasm",
bits: null,
byte_order: "little",
section_name: rustDependencySectionName("wasm"),
dependency: dependency_sections[0] ?? null,
compiler_strings: data_section === null ? [] : [data_section],
};
};
/** cargo-auditable writes one dependency section; a second leaves the list ambiguous. */
const duplicateDependencySection = () =>
malformedInput(
RUST_AUDITABLE_FORMAT,
"Image contains more than one dependency section",
);
const readContainer = (bytes: Buffer) => {
try {
return readBinaryContainer(bytes);
} catch (cause) {
// A container format failure is already a ParseFailureError; it keeps
// its own kind and facts instead of being restated as a Rust failure.
if (cause instanceof BinaryResourceFailure)
throw new RustAuditableResourceFailure(
{
resource: "memory",
reported_limits: { maximum_bytes: cause.maximum_bytes },
},
cause.message,
{
cause,
},
);
throw cause;
}
};
const dependencySection = (
expected: RustAuditableMetadata["section_name"],
sections: readonly ImageSection[],
): ImageSection | null => {
const selected = uniqueKeyed(
keyedBy(sections, ({ name }) => name),
expected,
);
if (!selected.ok) throw duplicateDependencySection();
const section = selected.value;
if (section === undefined) return null;
if (section.compressed)
throw unsupportedInput(
RUST_AUDITABLE_FORMAT,
"Compressed dependency sections are unsupported",
{ undecodedContent: true },
);
if (!section.file_backed)
throw malformedInput(
RUST_AUDITABLE_FORMAT,
"Dependency section is not file-backed",
);
return section;
};
const rustcCommit = (
bytes: Buffer,
spans: readonly FileSpan[],
maxHashes: number,
maxOutputBytes: number,
): RustBinaryImage["rustc_commit"] => {
const retention: RustcPathRetention = {
hashes: [],
seen: new Set(),
maxHashes,
maxBytes: maxOutputBytes,
bytes: 2,
reason: undefined,
};
// Overlapping section and ELF load ranges are scanned once, so total work
// stays bounded by the file size however many mappings reference a range.
for (const range of mergedFileRanges(spans)) {
collectHashes(bytes, range, retention);
if (retention.reason !== undefined) break;
}
return retention.hashes.length === 0
? null
: {
evidence_kind: "inferred",
hashes: retention.hashes,
...(retention.reason !== undefined
? {
coverage: rustcPartialCoverage(
retention.reason,
retention.reason === "report_bytes"
? maxOutputBytes
: maxHashes,
),
}
: {}),
};
};
/** One owner for compiler-path uniqueness, retained output and exhaustion. */
interface RustcPathRetention {
readonly hashes: { hash: string; file_offset: number }[];
readonly seen: Set<string>;
readonly maxHashes: number;
readonly maxBytes: number;
bytes: number;
reason: "max_rustc_hashes" | "report_bytes" | undefined;
}
const mergedFileRanges = (
ranges: readonly FileSpan[],
): { readonly offset: number; readonly end: number }[] => {
const sorted = ranges
.filter(({ size }) => size > 0)
.map(({ offset, size }) => ({ offset, end: offset + size }))
.sort((left, right) => left.offset - right.offset);
const merged: { offset: number; end: number }[] = [];
for (const range of sorted) {
const last = merged.at(-1);
if (last !== undefined && range.offset <= last.end)
last.end = Math.max(last.end, range.end);
else merged.push({ ...range });
}
return merged;
};
const collectHashes = (
bytes: Buffer,
range: { readonly offset: number; readonly end: number },
retention: RustcPathRetention,
): void => {
const region = bytes.subarray(range.offset, range.end);
let cursor = 0;
while (cursor < region.length) {
const at = region.indexOf(RUSTC_PREFIX, cursor);
if (at < 0) return;
const start = at + RUSTC_PREFIX.length;
const hash = hashAt(region, start);
if (hash !== null && !retention.seen.has(hash)) {
if (retention.seen.size >= retention.maxHashes) {
retention.reason = "max_rustc_hashes";
return;
}
const entry = { hash, file_offset: range.offset + at };
const entryBytes = Buffer.byteLength(JSON.stringify(entry)) + 1;
if (entryBytes > retention.maxBytes - retention.bytes) {
retention.reason = "report_bytes";
return;
}
retention.bytes += entryBytes;
retention.seen.add(hash);
retention.hashes.push(entry);
}
cursor = at + 1;
}
};
const hashAt = (region: Buffer, start: number): string | null => {
const end = start + HASH_BYTES;
// Windows builds join the remapped `/rustc/<hash>` prefix with `\`.
if (end >= region.length || (region[end] !== 0x2f && region[end] !== 0x5c))
return null;
for (let index = start; index < end; index += 1) {
const byte = region[index] ?? 0;
const hex =
(byte >= 0x30 && byte <= 0x39) || (byte >= 0x61 && byte <= 0x66);
if (!hex) return null;
}
return region.toString("latin1", start, end);
};