-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathpreflight.ts
More file actions
480 lines (458 loc) · 15.8 KB
/
Copy pathpreflight.ts
File metadata and controls
480 lines (458 loc) · 15.8 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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
import { createHash } from 'crypto';
import { createReadStream, constants, promises as fs } from 'fs';
import * as path from 'path';
import execa from 'execa';
import {
CLOUD_HYPERVISOR_RELEASE_VERSION,
type CloudHypervisorOptions,
} from '../types/runtime-options';
/**
* Fail-closed host and artifact validation for the Cloud Hypervisor v53.0
* runtime. Trust checks cover absolute paths, root/operator-owned
* non-writable regular files, trusted ancestor
* directories, digest pinning, PATH-resolved but ownership-verified host
* tools) so both VMM backends share the same fail-closed posture.
*
* Cloud Hypervisor has no jailer-equivalent process. AWF instead requires
* the pinned v1.10.0 virtiofsd sibling used for directory exports, while
* `src/cloud-hypervisor/launcher.ts` builds an equivalent
* network-namespace-join + privilege-drop + Landlock/seccomp launch using
* the `setpriv` tool resolved here, and `src/cloud-hypervisor/manager.ts`
* stages artifacts into a private, non-world-readable run directory.
*/
export interface CloudHypervisorPreflightDependencies {
platform: NodeJS.Platform;
arch: string;
uid: number;
access(filePath: string, mode: number): Promise<void>;
lstat(filePath: string): Promise<{
isFile(): boolean;
isSymbolicLink(): boolean;
mode: number;
uid: number;
}>;
runVersion(binaryPath: string): Promise<string>;
sha256(filePath: string): Promise<string>;
assertToolAvailable(tool: string): Promise<string>;
assertHostPolicy(): Promise<2>;
assertDockerInfrastructure(dockerBinaryPath: string): Promise<void>;
/** Resolves the group ID that owns `/dev/kvm`, so the launcher can retain
* exactly that supplementary group instead of the full operator group set. */
resolveKvmGid(): Promise<number>;
}
export type CloudHypervisorHostToolPaths = Readonly<{
ip: string;
nft: string;
sysctl: string;
mke2fs: string;
debugfs: string;
e2fsck: string;
rsync: string;
mount: string;
umount: string;
/**
* util-linux `setpriv`, used by the launcher to drop to the non-root
* operator uid/gid and clear capabilities/groups after joining the
* per-run network namespace (there is no jailer-equivalent process to do
* this for Cloud Hypervisor). See `src/cloud-hypervisor/launcher.ts`.
*/
setpriv: string;
}>;
const CLOUD_HYPERVISOR_HOST_TOOLS: (keyof CloudHypervisorHostToolPaths)[] = [
'ip', 'nft', 'sysctl', 'mke2fs', 'debugfs', 'e2fsck', 'rsync', 'mount', 'umount', 'setpriv',
];
const defaultDependencies: CloudHypervisorPreflightDependencies = {
platform: process.platform,
arch: process.arch,
uid: -1,
access: fs.access,
lstat: fs.lstat,
runVersion: async (binaryPath) => {
const result = await execa(binaryPath, ['--version'], {
reject: false,
timeout: 5_000,
stdio: ['ignore', 'pipe', 'pipe'],
});
if (result.exitCode !== 0) {
throw new Error(
`"${binaryPath} --version" exited with code ${result.exitCode}: ${result.stderr.trim()}`,
);
}
return `${result.stdout}\n${result.stderr}`.trim();
},
sha256: calculateSha256,
assertToolAvailable: async (tool) => {
const searchPath = process.env.PATH ?? '';
for (const directory of searchPath.split(path.delimiter)) {
if (!directory) continue;
try {
const candidate = path.join(directory, tool);
await assertTrustedHostTool(tool, candidate);
return candidate;
} catch {
// Continue searching the bounded host PATH.
}
}
throw new Error(`required trusted host tool "${tool}" was not found on PATH`);
},
assertHostPolicy: async () => {
if (process.getuid?.() !== 0) {
throw new Error(
'Cloud Hypervisor network setup requires root; invoke awf through sudo from a non-root account',
);
}
try {
await fs.access('/proc/sys/net/ipv4/ip_forward', constants.R_OK);
await fs.access('/proc/sys/net/ipv6/conf/all/disable_ipv6', constants.R_OK);
await fs.access('/proc/sys/kernel/seccomp/actions_avail', constants.R_OK);
} catch (error) {
throw new Error(
'host kernel policy does not expose required network namespace and seccomp controls: ' +
`${error instanceof Error ? error.message : String(error)}`,
);
}
try {
await fs.access('/sys/fs/cgroup/cgroup.controllers', constants.R_OK);
return 2;
} catch (error) {
// Cloud Hypervisor's launcher manages an explicit memory/CPU/PID
// cgroup for the launched process (see `src/cloud-hypervisor/launcher.ts`
// `CloudHypervisorCgroup`), which requires the cgroup v2 unified
// hierarchy's `cgroup.subtree_control` delegation model. A cgroup v1
// fallback would need separate per-controller mount points
// (`memory`, `cpu,cpuacct`, `pids`) that this launcher does not
// manage, so it is rejected explicitly rather than silently
// constructing a broken cgroup. GitHub-hosted Ubuntu runners (the
// only supported host) always run cgroup v2.
throw new Error(
'Cloud Hypervisor requires the cgroup v2 unified hierarchy ' +
'(/sys/fs/cgroup/cgroup.controllers); cgroup v1-only hosts are not supported: ' +
`${error instanceof Error ? error.message : String(error)}`,
);
}
},
assertDockerInfrastructure: async (dockerBinaryPath) => {
for (const args of [['info'], ['compose', 'version']] as const) {
const result = await execa(dockerBinaryPath, [...args], {
reject: false,
timeout: 10_000,
stdio: ['ignore', 'pipe', 'pipe'],
});
if (result.exitCode !== 0) {
throw new Error(
`${dockerBinaryPath} ${args.join(' ')} failed with code ${result.exitCode}: ${result.stderr.trim()}`,
);
}
}
},
resolveKvmGid: async () => {
const stat = await fs.stat('/dev/kvm');
return stat.gid;
},
};
/** @internal Exposed only for focused host-probe tests. */
export const cloudHypervisorPreflightTestHelpers = { defaultDependencies };
export interface CloudHypervisorPreflightResult {
version: string;
cloudHypervisorBinary: string;
virtiofsdBinary: string;
kernelPath: string;
rootfsPath: string;
supervisorPath: string;
tools: CloudHypervisorHostToolPaths;
cgroupVersion: 2;
/** Group ID that owns `/dev/kvm`, retained as the launcher's sole supplementary group. */
kvmGid: number;
}
async function assertTrustedHostTool(label: string, filePath: string): Promise<void> {
if (!path.isAbsolute(filePath)) {
throw new Error(`host tool "${label}" path must be absolute: ${filePath}`);
}
const { root } = path.parse(filePath);
const segments = filePath.slice(root.length).split('/').filter(Boolean);
let ancestor = root;
for (const segment of segments.slice(0, -1)) {
ancestor = path.join(ancestor, segment);
const stat = await fs.lstat(ancestor);
if (stat.isSymbolicLink() || (stat.mode & 0o022) !== 0 || stat.uid !== 0) {
throw new Error(`host tool "${label}" has an untrusted parent directory: ${ancestor}`);
}
}
const stat = await fs.lstat(filePath);
if (
stat.isSymbolicLink() ||
!stat.isFile() ||
(stat.mode & 0o022) !== 0 ||
stat.uid !== 0
) {
throw new Error(`host tool "${label}" must be a root-owned non-writable regular file: ${filePath}`);
}
await fs.access(filePath, constants.X_OK);
}
/**
* Parses a `cloud-hypervisor --version` output like `cloud-hypervisor v53.0`
* (also accepts the plain `v53.0`/`53.0` forms some builds emit).
*/
export function parseCloudHypervisorVersion(output: string): string {
const match = output.match(/\bv?(\d+\.\d+(?:\.\d+)?)\b/);
if (!match) {
throw new Error(`Could not parse Cloud Hypervisor version from: ${JSON.stringify(output)}`);
}
return match[1];
}
export const VIRTIOFSD_RELEASE_VERSION = '1.10.0';
export function parseVirtiofsdVersion(output: string): string {
const match = output.match(/(?:^|\s)v?(\d+\.\d+\.\d+)(?:\s|$)/);
if (!match) {
throw new Error(`Could not parse virtiofsd version from: ${JSON.stringify(output)}`);
}
return match[1];
}
export async function calculateSha256(filePath: string): Promise<string> {
const hash = createHash('sha256');
const stream = createReadStream(filePath);
for await (const chunk of stream) {
hash.update(chunk as Buffer);
}
return hash.digest('hex');
}
async function assertTrustedRegularFile(
label: string,
filePath: string,
accessMode: number,
dependencies: CloudHypervisorPreflightDependencies,
): Promise<void> {
if (!path.isAbsolute(filePath)) {
throw new Error(`${label} path must be absolute: ${filePath}`);
}
await assertTrustedAncestorChain(label, filePath, dependencies);
let stat;
try {
stat = await dependencies.lstat(filePath);
} catch (error) {
throw new Error(
`${label} is unavailable: ${filePath}: ${error instanceof Error ? error.message : String(error)}`,
);
}
if (stat.isSymbolicLink() || !stat.isFile()) {
throw new Error(`${label} must be a regular file and not a symbolic link: ${filePath}`);
}
if ((stat.mode & 0o022) !== 0) {
throw new Error(`${label} must not be group- or world-writable: ${filePath}`);
}
if (stat.uid !== 0 && stat.uid !== dependencies.uid) {
throw new Error(
`${label} must be owned by root or uid ${dependencies.uid}; found uid ${stat.uid}: ${filePath}`,
);
}
try {
await dependencies.access(filePath, accessMode);
} catch (error) {
throw new Error(
`${label} does not have the required host access: ${filePath}: ` +
`${error instanceof Error ? error.message : String(error)}`,
);
}
}
function parsePositiveUid(value: string | undefined): number | undefined {
if (!value || !/^[1-9]\d*$/.test(value)) return undefined;
return Number(value);
}
function resolveTrustedOperatorUid(): number {
return parsePositiveUid(process.env.SUDO_UID) ?? (process.getuid?.() ?? -1);
}
async function assertTrustedAncestorChain(
label: string,
filePath: string,
dependencies: CloudHypervisorPreflightDependencies,
): Promise<void> {
const { root } = path.parse(filePath);
const segments = filePath.slice(root.length).split('/').filter((segment) => segment.length > 0);
let ancestor = root;
for (const segment of segments.slice(0, -1)) {
ancestor = path.join(ancestor, segment);
const stat = await dependencies.lstat(ancestor);
if (stat.isSymbolicLink()) {
throw new Error(
`${label} parent directory must not be a symbolic link: ${ancestor}`,
);
}
if ((stat.mode & 0o022) !== 0) {
throw new Error(
`${label} parent directory must not be group- or world-writable: ${ancestor}`,
);
}
if (stat.uid !== 0 && stat.uid !== dependencies.uid) {
throw new Error(
`${label} parent directory must be owned by root or uid ${dependencies.uid}; ` +
`found uid ${stat.uid}: ${ancestor}`,
);
}
}
}
async function assertDigest(
label: string,
filePath: string,
expected: string | undefined,
dependencies: CloudHypervisorPreflightDependencies,
): Promise<void> {
if (!expected) return;
if (!/^[a-fA-F0-9]{64}$/.test(expected)) {
throw new Error(`${label} SHA-256 must contain exactly 64 hexadecimal characters`);
}
const actual = await dependencies.sha256(filePath);
if (actual.toLowerCase() !== expected.toLowerCase()) {
throw new Error(
`${label} SHA-256 mismatch: expected ${expected.toLowerCase()}, got ${actual.toLowerCase()}`,
);
}
}
/**
* Fail-closed host and artifact validation for Cloud Hypervisor v53.0.
*
* This checks Linux/KVM host requirements, trusted artifact
* ownership/permissions, pinned version, and pinned digests,
* adapted for Cloud Hypervisor's single-binary VMM (no jailer).
*/
export async function runCloudHypervisorPreflight(
config: CloudHypervisorOptions,
overrides: Partial<CloudHypervisorPreflightDependencies> = {},
): Promise<CloudHypervisorPreflightResult> {
const dependencies = {
...defaultDependencies,
...overrides,
uid: overrides.uid ?? resolveTrustedOperatorUid(),
};
if (dependencies.platform !== 'linux') {
throw new Error(`Cloud Hypervisor requires Linux with KVM; found ${dependencies.platform}`);
}
if (dependencies.arch !== 'x64') {
throw new Error(
`Cloud Hypervisor is supported only on x86_64 GitHub-hosted runners; found Node architecture ${dependencies.arch}`,
);
}
if (!config.kernelPath || !config.rootfsPath || !config.supervisorPath) {
throw new Error(
'Cloud Hypervisor requires guest kernel, rootfs, and supervisor artifact paths',
);
}
try {
await dependencies.access('/dev/kvm', constants.R_OK | constants.W_OK);
} catch (error) {
throw new Error(
'Cloud Hypervisor requires readable and writable /dev/kvm: ' +
`${error instanceof Error ? error.message : String(error)}`,
);
}
const kvmGid = await dependencies.resolveKvmGid();
const cgroupVersion = await dependencies.assertHostPolicy();
let dockerBinaryPath: string;
try {
dockerBinaryPath = await dependencies.assertToolAvailable('docker');
} catch (error) {
throw new Error(
'Cloud Hypervisor requires host tool "docker": ' +
`${error instanceof Error ? error.message : String(error)}`,
);
}
await dependencies.assertDockerInfrastructure(dockerBinaryPath);
await assertTrustedRegularFile(
'Cloud Hypervisor binary',
config.cloudHypervisorBinary,
constants.R_OK | constants.X_OK,
dependencies,
);
const virtiofsdBinary = path.join(path.dirname(config.cloudHypervisorBinary), 'virtiofsd');
await assertTrustedRegularFile(
'virtiofsd binary',
virtiofsdBinary,
constants.R_OK | constants.X_OK,
dependencies,
);
const tools = {} as Record<keyof CloudHypervisorHostToolPaths, string>;
for (const tool of CLOUD_HYPERVISOR_HOST_TOOLS) {
try {
tools[tool] = await dependencies.assertToolAvailable(tool);
} catch (error) {
throw new Error(
`Cloud Hypervisor requires host tool "${tool}": ` +
`${error instanceof Error ? error.message : String(error)}`,
);
}
}
await assertTrustedRegularFile(
'Cloud Hypervisor guest kernel',
config.kernelPath,
constants.R_OK,
dependencies,
);
await assertTrustedRegularFile(
'Cloud Hypervisor rootfs',
config.rootfsPath,
constants.R_OK,
dependencies,
);
await assertTrustedRegularFile(
'Cloud Hypervisor guest supervisor',
config.supervisorPath,
constants.R_OK,
dependencies,
);
await assertDigest(
'Cloud Hypervisor binary',
config.cloudHypervisorBinary,
config.sha256?.cloudHypervisor,
dependencies,
);
await assertDigest(
'virtiofsd binary',
virtiofsdBinary,
config.sha256?.virtiofsd,
dependencies,
);
const version = parseCloudHypervisorVersion(
await dependencies.runVersion(config.cloudHypervisorBinary),
);
if (version !== CLOUD_HYPERVISOR_RELEASE_VERSION) {
throw new Error(
`Cloud Hypervisor is pinned to v${CLOUD_HYPERVISOR_RELEASE_VERSION}; found v${version}`,
);
}
const virtiofsdVersion = parseVirtiofsdVersion(
await dependencies.runVersion(virtiofsdBinary),
);
if (virtiofsdVersion !== VIRTIOFSD_RELEASE_VERSION) {
throw new Error(
`virtiofsd is pinned to v${VIRTIOFSD_RELEASE_VERSION}; found v${virtiofsdVersion}`,
);
}
await assertDigest(
'Cloud Hypervisor guest kernel',
config.kernelPath,
config.sha256?.kernel,
dependencies,
);
await assertDigest(
'Cloud Hypervisor rootfs',
config.rootfsPath,
config.sha256?.rootfs,
dependencies,
);
await assertDigest(
'Cloud Hypervisor guest supervisor',
config.supervisorPath,
config.sha256?.supervisor,
dependencies,
);
return {
version,
cloudHypervisorBinary: config.cloudHypervisorBinary,
virtiofsdBinary,
kernelPath: config.kernelPath,
rootfsPath: config.rootfsPath,
supervisorPath: config.supervisorPath,
tools,
cgroupVersion,
kvmGid,
};
}