-
Notifications
You must be signed in to change notification settings - Fork 62
Harden Bubblewrap version probing #723
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Gudge (MGudgin)
wants to merge
1
commit into
main
Choose a base branch
from
user/gudge/bwrap-probe-hardening
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| // Copyright (c) Microsoft Corporation. | ||
| // Licensed under the MIT License. | ||
|
|
||
| import { spawn } from 'node:child_process'; | ||
|
|
||
| // Strip NODE_OPTIONS so a host's loader/inspector/require flags cannot | ||
| // interfere with the helper's minimal, trusted `bwrap --version` probe. | ||
| const spawnEnv = { ...process.env }; | ||
| delete spawnEnv.NODE_OPTIONS; | ||
|
|
||
| const helperPath = process.argv[2]; | ||
| const timeoutMs = Number(process.argv[3]); | ||
| const outputLimit = process.argv[4]; | ||
| let resultWritten = false; | ||
| let resultFlushed = false; | ||
| let shuttingDown = false; | ||
| let helperClosed = false; | ||
| let output = ''; | ||
| const hold = setInterval(() => {}, 0x3fffffff); | ||
|
|
||
| function terminateHelper(): void { | ||
| if (shuttingDown) return; | ||
| shuttingDown = true; | ||
| const pid = helperProcess.pid; | ||
| if (pid && !helperClosed) { | ||
| try { | ||
| process.kill(pid, 'SIGKILL'); | ||
| } catch { | ||
| // The helper may already have exited. | ||
| } | ||
| } | ||
| } | ||
|
|
||
| function terminateOwnedGroup(): void { | ||
| try { | ||
| process.kill(-process.pid, 'SIGKILL'); | ||
| } catch { | ||
| process.exit(1); | ||
| } | ||
| } | ||
|
|
||
| function finishIfReady(): void { | ||
| if (!helperClosed || !resultFlushed) return; | ||
| clearTimeout(watchdog); | ||
| clearInterval(hold); | ||
| // The anchor is still the unreaped group leader. The helper has already | ||
| // been reaped, so terminating the owned group cannot target a recycled ID. | ||
| terminateOwnedGroup(); | ||
| } | ||
|
|
||
| const watchdog = setTimeout(() => { | ||
| terminateHelper(); | ||
| setTimeout(terminateOwnedGroup, 500).unref(); | ||
| }, timeoutMs + 1000); | ||
| watchdog.unref(); | ||
|
|
||
| process.on('SIGTERM', () => { | ||
| terminateHelper(); | ||
| }); | ||
|
|
||
| function emitFailure(detail: string): void { | ||
| if (resultWritten) return; | ||
| resultWritten = true; | ||
| process.stdout.write(`${JSON.stringify({ kind: 'spawnError', detail })}\n`, () => { | ||
| resultFlushed = true; | ||
| finishIfReady(); | ||
| }); | ||
| } | ||
|
|
||
| const helperProcess = spawn( | ||
| process.execPath, | ||
| [helperPath, String(timeoutMs), outputLimit], | ||
| { detached: false, stdio: ['ignore', 'pipe', 'ignore'], env: spawnEnv }, | ||
| ); | ||
| helperProcess.stdout.setEncoding('utf8'); | ||
| helperProcess.stdout.on('data', (chunk: string) => { | ||
| output += chunk; | ||
| const newline = output.indexOf('\n'); | ||
| if (!resultWritten && newline !== -1) { | ||
| resultWritten = true; | ||
| process.stdout.write(output.slice(0, newline + 1), () => { | ||
| resultFlushed = true; | ||
| finishIfReady(); | ||
| }); | ||
| terminateHelper(); | ||
| } | ||
| }); | ||
| helperProcess.on('error', (error) => emitFailure(error.message)); | ||
| helperProcess.on('close', () => { | ||
| helperClosed = true; | ||
| emitFailure('probe helper exited without a result'); | ||
| finishIfReady(); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| // Copyright (c) Microsoft Corporation. | ||
| // Licensed under the MIT License. | ||
|
|
||
| import { spawn, ChildProcessByStdio } from 'node:child_process'; | ||
| import * as fs from 'node:fs/promises'; | ||
| import * as path from 'node:path'; | ||
| import { Readable } from 'node:stream'; | ||
|
|
||
| type HelperResult = | ||
| | { kind: 'completed'; status: number | null; signal: NodeJS.Signals | null; stdout: string; stderr: string } | ||
| | { kind: 'notFound' } | ||
| | { kind: 'timeout' } | ||
| | { kind: 'overflow' } | ||
| | { kind: 'spawnError'; detail: string }; | ||
|
|
||
| const timeoutMs = Number(process.argv[2]); | ||
| const outputLimit = Number(process.argv[3]); | ||
| let child: ChildProcessByStdio<null, Readable, Readable> | undefined; | ||
| let finished = false; | ||
| let classifyingSpawnError = false; | ||
| let timer: NodeJS.Timeout | undefined; | ||
| let stdoutLength = 0; | ||
| let stderrLength = 0; | ||
| const stdoutChunks: Buffer[] = []; | ||
| const stderrChunks: Buffer[] = []; | ||
| const hold = setInterval(() => {}, 0x3fffffff); | ||
|
|
||
| setTimeout(() => { | ||
| if (child) { | ||
| try { | ||
| child.kill('SIGKILL'); | ||
| } catch { | ||
| // The child may already have exited. | ||
| } | ||
| } | ||
| process.exit(1); | ||
| }, timeoutMs + 1000).unref(); | ||
|
|
||
| function capture(chunks: Buffer[], chunk: Buffer, currentLength: number): number { | ||
| const remaining = Math.max(0, outputLimit - currentLength); | ||
| if (remaining > 0) chunks.push(chunk.subarray(0, remaining)); | ||
| return currentLength + chunk.length; | ||
| } | ||
|
|
||
| function emit(result: HelperResult): void { | ||
| if (finished) return; | ||
| finished = true; | ||
| if (timer) clearTimeout(timer); | ||
| process.stdout.write(`${JSON.stringify(result)}\n`); | ||
| } | ||
|
|
||
| async function handleSpawnError(error: NodeJS.ErrnoException): Promise<void> { | ||
| if (error.code !== 'ENOENT') { | ||
| emit({ kind: 'spawnError', detail: error.message }); | ||
| return; | ||
| } | ||
| for (const entry of (process.env.PATH ?? '').split(path.delimiter)) { | ||
| const candidate = path.join(entry, 'bwrap'); | ||
| try { | ||
| if ((await fs.stat(candidate)).isFile()) { | ||
| emit({ | ||
| kind: 'spawnError', | ||
| detail: `${candidate} was found but could not be executed; check for a missing interpreter or loader`, | ||
| }); | ||
| return; | ||
| } | ||
| } catch (statError) { | ||
| const error = statError as NodeJS.ErrnoException; | ||
| if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') { | ||
| emit({ kind: 'spawnError', detail: `failed to inspect ${candidate}: ${error.message}` }); | ||
| return; | ||
| } | ||
| } | ||
| } | ||
| emit({ kind: 'notFound' }); | ||
| } | ||
|
|
||
| try { | ||
| child = spawn('bwrap', ['--version'], { | ||
| detached: false, | ||
| stdio: ['ignore', 'pipe', 'pipe'], | ||
| }); | ||
| } catch (error) { | ||
| void handleSpawnError(error as NodeJS.ErrnoException); | ||
| } | ||
|
|
||
| if (child) { | ||
| child.stdout.on('data', (chunk: Buffer) => { | ||
| stdoutLength = capture(stdoutChunks, chunk, stdoutLength); | ||
| if (stdoutLength > outputLimit) emit({ kind: 'overflow' }); | ||
| }); | ||
| child.stderr.on('data', (chunk: Buffer) => { | ||
| stderrLength = capture(stderrChunks, chunk, stderrLength); | ||
| if (stderrLength > outputLimit) emit({ kind: 'overflow' }); | ||
| }); | ||
| child.on('error', (error: NodeJS.ErrnoException) => { | ||
| classifyingSpawnError = true; | ||
| void handleSpawnError(error); | ||
| }); | ||
| child.on('close', (status, signal) => { | ||
| if (classifyingSpawnError) return; | ||
| emit({ | ||
| kind: 'completed', | ||
| status, | ||
| signal, | ||
| stdout: Buffer.concat(stdoutChunks).toString('utf8'), | ||
| stderr: Buffer.concat(stderrChunks).toString('utf8'), | ||
| }); | ||
| }); | ||
| timer = setTimeout(() => emit({ kind: 'timeout' }), timeoutMs); | ||
| } | ||
|
|
||
| void hold; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| // Copyright (c) Microsoft Corporation. | ||
| // Licensed under the MIT License. | ||
|
|
||
| import { spawn, ChildProcessByStdio } from 'node:child_process'; | ||
| import { Readable } from 'node:stream'; | ||
| import { workerData } from 'node:worker_threads'; | ||
|
|
||
| // Strip NODE_OPTIONS so a host's loader/inspector/require flags cannot | ||
| // interfere with the anchor's minimal, trusted probe supervision. | ||
| const spawnEnv = { ...process.env }; | ||
| delete spawnEnv.NODE_OPTIONS; | ||
|
|
||
| interface ProbeWorkerData { | ||
| shared: SharedArrayBuffer; | ||
| anchorPath: string; | ||
| helperPath: string; | ||
| probeTimeoutMs: number; | ||
| publishTimeoutMs: number; | ||
| outputLimit: number; | ||
| } | ||
|
|
||
| const data = workerData as ProbeWorkerData; | ||
| const header = new Int32Array(data.shared, 0, 3); | ||
| const payload = new Uint8Array(data.shared, 12); | ||
| let anchor: ChildProcessByStdio<null, Readable, null> | undefined; | ||
| let output = ''; | ||
| let finished = false; | ||
| let anchorExited = false; | ||
| let anchorClosed = false; | ||
| let completionRequested = false; | ||
| let pendingResult: unknown; | ||
| let timeout: NodeJS.Timeout | undefined; | ||
|
|
||
| function stopAnchor(): void { | ||
| const pid = anchor?.pid; | ||
| if (!pid || anchorExited) return; | ||
| try { | ||
| process.kill(pid, 'SIGTERM'); | ||
| } catch { | ||
| // The process may have exited between the ownership check and the signal. | ||
| } | ||
| } | ||
|
|
||
| function publish(result: unknown): void { | ||
| if (finished) return; | ||
| finished = true; | ||
| if (timeout) clearTimeout(timeout); | ||
| let encoded = Buffer.from(JSON.stringify(result)); | ||
| if (encoded.length > payload.length) { | ||
| encoded = Buffer.from(JSON.stringify({ | ||
| kind: 'spawnError', | ||
| detail: 'probe helper result exceeded its bound', | ||
| })); | ||
| } | ||
| payload.set(encoded); | ||
| Atomics.store(header, 1, encoded.length); | ||
| if (Atomics.compareExchange(header, 0, 0, 1) === 0) { | ||
| Atomics.notify(header, 0); | ||
| } | ||
| } | ||
|
|
||
| function completeAfterCleanup(result: unknown, stop = false): void { | ||
| if (finished || completionRequested) return; | ||
| completionRequested = true; | ||
| pendingResult = result; | ||
| if (stop) stopAnchor(); | ||
| if (anchorClosed) publish(pendingResult); | ||
| } | ||
|
|
||
| if (Atomics.load(header, 0) === 0) { | ||
| try { | ||
| const spawnedAnchor = spawn( | ||
| process.execPath, | ||
| [ | ||
| data.anchorPath, | ||
| data.helperPath, | ||
| String(data.probeTimeoutMs), | ||
| String(data.outputLimit), | ||
| ], | ||
| { detached: true, stdio: ['ignore', 'pipe', 'ignore'], env: spawnEnv }, | ||
| ); | ||
| anchor = spawnedAnchor; | ||
| const anchorPid = spawnedAnchor.pid; | ||
| if (anchorPid === undefined) { | ||
| completeAfterCleanup({ | ||
| kind: 'spawnError', | ||
| detail: 'probe anchor did not receive a process id', | ||
| }); | ||
| } else { | ||
| Atomics.store(header, 2, anchorPid); | ||
| } | ||
| if (Atomics.load(header, 0) !== 0) { | ||
| stopAnchor(); | ||
| } | ||
| spawnedAnchor.stdout.setEncoding('utf8'); | ||
| spawnedAnchor.stdout.on('data', (chunk: string) => { | ||
| output += chunk; | ||
| const newline = output.indexOf('\n'); | ||
| if (newline !== -1) { | ||
| try { | ||
| completeAfterCleanup(JSON.parse(output.slice(0, newline))); | ||
| } catch (error) { | ||
| const detail = error instanceof Error ? error.message : String(error); | ||
| completeAfterCleanup( | ||
| { kind: 'spawnError', detail: `invalid probe helper result: ${detail}` }, | ||
| true, | ||
| ); | ||
| } | ||
| } | ||
| }); | ||
| spawnedAnchor.on('error', (error) => { | ||
| completeAfterCleanup({ kind: 'spawnError', detail: error.message }, true); | ||
| }); | ||
| spawnedAnchor.on('exit', () => { | ||
| anchorExited = true; | ||
| }); | ||
| spawnedAnchor.on('close', () => { | ||
| anchorClosed = true; | ||
| publish( | ||
| completionRequested | ||
| ? pendingResult | ||
| : { kind: 'spawnError', detail: 'probe helper exited without a result' }, | ||
| ); | ||
| }); | ||
| // Ask the anchor to stop inside the caller's budget. Publication waits for | ||
| // close so the result cannot escape before group teardown and reaping. | ||
| timeout = setTimeout( | ||
| () => completeAfterCleanup({ kind: 'timeout' }, true), | ||
| data.publishTimeoutMs, | ||
| ); | ||
| } catch (error) { | ||
| const detail = error instanceof Error ? error.message : String(error); | ||
| publish({ kind: 'spawnError', detail }); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.