Skip to content
Closed
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ bunx cowsay 'Hello, world!' # execute a package

Bun supports Linux (x64 & arm64), macOS (x64 & Apple Silicon), and Windows (x64 & arm64).

> **Linux users** — Kernel version 5.6 or higher is strongly recommended, but the minimum is 5.1.
> **Linux users** — Kernel version 5.6 or higher is strongly recommended. For older kernels, see the [installation docs](https://bun.com/docs/installation).

> **x64 users** — if you see "illegal instruction" or similar errors, check our [CPU requirements](https://bun.com/docs/installation#cpu-requirements)

Expand Down
3 changes: 3 additions & 0 deletions src/bun_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,6 @@ thiserror.workspace = true

[target.'cfg(windows)'.dependencies]
bun_windows_sys.workspace = true

[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies]
getrandom.workspace = true
26 changes: 8 additions & 18 deletions src/bun_core/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2639,7 +2639,7 @@ pub fn is_writable(fd: Fd) -> Pollable {
}

// ── os_entropy ────────────────────────────────────────────────────────────
// Raw OS entropy source: getrandom(2) on Linux, getentropy on Darwin/BSD,
// Raw OS entropy source: the `getrandom` crate on Linux, getentropy on Darwin/BSD,
// RtlGenRandom on Windows. bun_core sits below boringssl_sys in the crate
// graph so it cannot reach `RAND_bytes`; this is used only to seed
// `fast_random()`'s thread-local PRNG once per thread. Every other caller
Expand All @@ -2648,24 +2648,14 @@ pub fn is_writable(fd: Fd) -> Pollable {
fn os_entropy(bytes: &mut [u8]) {
#[cfg(any(target_os = "linux", target_os = "android"))]
{
let mut filled = 0usize;
while filled < bytes.len() {
// SAFETY: writes at most len-filled bytes into the slice.
let rc = unsafe {
libc::getrandom(
bytes.as_mut_ptr().add(filled).cast(),
bytes.len() - filled,
0,
)
};
if rc < 0 {
let err = crate::ffi::errno();
if err == libc::EINTR {
continue;
}
panic!("getrandom failed: errno {err}");
// Under seccomp the crate never falls back: glibc 2.41+ answers its probe from the vDSO.
if let Err(err) = getrandom::fill(bytes) {
Comment thread
robobun marked this conversation as resolved.
Resolved
use std::io::Read;
if let Err(io_err) =
std::fs::File::open("/dev/urandom").and_then(|mut f| f.read_exact(bytes))
{
panic!("getrandom failed ({err}), /dev/urandom failed ({io_err})");
}
filled += rc as usize;
}
}
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd"))]
Expand Down
216 changes: 216 additions & 0 deletions test/regression/issue/27279.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
import { describe, expect, test } from "bun:test";
import { bunEnv, bunExe, isLinux, tempDir, tempDirWithFiles } from "harness";
import { spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import { join } from "node:path";

// https://github.com/oven-sh/bun/issues/27279
//
// Linux older than 3.17 (Synology NAS, RHEL 7: kernel 3.10) has no
// getrandom(2). The syscall answers ENOSYS. BoringSSL, c-ares and highway fall
// back to /dev/urandom. The seed of `bun_core::fast_random()` has to do the
// same, or everything that draws from it aborts with
// "panic: getrandom failed: errno 38": `bun build`, `Bun.build()`,
// `bun test --randomize`, package extraction in `bun install`.
//
// This test installs a seccomp filter that makes getrandom(2) fail with ENOSYS,
// which is what such a kernel answers, and runs those entry points under it.
//
// A filter is not a full copy of an old kernel: glibc 2.41+ answers a
// zero-length getrandom() from the vDSO with no syscall. The getrandom crate
// probes with that call. So on glibc the crate fails under the filter and
// `os_entropy` reads /dev/urandom itself. On musl the crate takes its own
// fallback.
describe.skipIf(!isLinux)("getrandom(2) answers ENOSYS", () => {
const ENOSYS = 38;

// usage: block <cmd> [args...]
// exit 77: the environment refuses the filter (skip). exit 78: the filter is
// installed but getrandom still works, so the run would prove nothing.
const helperSrc = `
#define _GNU_SOURCE
#include <errno.h>
#include <linux/audit.h>
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <stddef.h>
#include <stdio.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <unistd.h>

#if defined(__x86_64__)
#define MY_AUDIT_ARCH AUDIT_ARCH_X86_64
#elif defined(__aarch64__)
#define MY_AUDIT_ARCH AUDIT_ARCH_AARCH64
#else
#define MY_AUDIT_ARCH 0
#endif

int main(int argc, char **argv) {
if (argc < 2) return 2;
if (MY_AUDIT_ARCH == 0) return 77;

struct sock_filter filter[] = {
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, arch)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, MY_AUDIT_ARCH, 1, 0),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_getrandom, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | (${ENOSYS} & SECCOMP_RET_DATA)),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
struct sock_fprog prog = {
.len = (unsigned short)(sizeof(filter) / sizeof(filter[0])),
.filter = filter,
};

if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) {
perror("prctl(PR_SET_NO_NEW_PRIVS)");
return 77;
}
if (syscall(__NR_seccomp, SECCOMP_SET_MODE_FILTER, 0, &prog) != 0) {
perror("seccomp");
return 77;
}

unsigned char probe;
if (syscall(__NR_getrandom, &probe, 1, 0) != -1 || errno != ${ENOSYS}) {
fprintf(stderr, "getrandom is not blocked\\n");
return 78;
}

execvp(argv[1], &argv[1]);
perror("execvp");
return 127;
}
`;

// Returns the binary path, or null if the host cannot build it (no cc, no
// kernel headers). Any other compile failure throws.
const tryBuild = (): string | null => {
const dir = tempDirWithFiles("getrandom-enosys-seccomp", {
"block_getrandom.c": helperSrc,
});
const src = join(dir, "block_getrandom.c");
const bin = join(dir, "block_getrandom");
const compile = spawnSync("cc", ["-O0", "-o", bin, src], { stdio: "pipe" });

if ((compile.error as NodeJS.ErrnoException | undefined)?.code === "ENOENT") return null;

if (compile.status !== 0) {
const stderr = compile.stderr?.toString() ?? "";
if (/linux\/(seccomp|filter|audit)\.h|sys\/prctl\.h/.test(stderr)) return null;
throw new Error(`failed to compile seccomp helper:\n${stderr}`);
}
if (!existsSync(bin)) {
throw new Error("seccomp helper compiled successfully but output binary is missing");
}
return bin;
};

// describe.skipIf still runs this callback on the other platforms.
const helperBin = isLinux ? tryBuild() : null;

// Runs `bun ...args` in `cwd` with getrandom(2) blocked. Returns null if the
// environment refuses the seccomp filter (skip).
async function runWithoutGetrandom(cwd: string, args: string[], env: Record<string, string> = {}) {
await using proc = Bun.spawn({
cmd: [helperBin!, bunExe(), ...args],
env: { ...bunEnv, ...env },
cwd,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
if (exitCode === 77) return null;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// 78: the filter does not block getrandom. 127: execvp failed.
if (exitCode === 78 || exitCode === 127) {
throw new Error(`seccomp helper exited with code ${exitCode}:\n${stderr}`);
}
return { stdout, stderr, exitCode };
}

const cases: Array<{
name: string;
args: string[];
files?: Record<string, string>;
env?: (dir: string) => Record<string, string>;
check: (out: { stdout: string; stderr: string; exitCode: number }, dir: string) => Promise<void> | void;
}> = [
{
name: "bun build",
args: ["build", "./index.ts", "--outdir", "./out"],
check: async (out, dir) => {
// The exit code goes first here: a build that failed wrote no file to read.
expect(out.exitCode, out.stderr).toBe(0);
expect(await Bun.file(join(dir, "out", "index.js")).text()).toContain("from-index");
},
},
{
name: "Bun.build()",
args: [
"-e",
`const result = await Bun.build({ entrypoints: ["./index.ts"] });
console.log(result.success, (await result.outputs[0].text()).includes("from-index"));`,
],
check: out => {
expect(out.stdout.trim(), out.stderr).toBe("true true");
expect(out.exitCode).toBe(0);
},
},
{
name: "bun test --randomize",
args: ["test", "--randomize", "./seed.test.ts"],
check: out => {
expect(out.stderr).toContain("--seed=");
expect(out.stderr).toContain("1 pass");
expect(out.exitCode).toBe(0);
},
},
{
name: "bun install",
args: ["install"],
files: {
"package.json": JSON.stringify({
name: "p",
version: "1.0.0",
dependencies: { bar: join(import.meta.dir, "..", "..", "cli", "install", "bar-0.0.2.tgz") },
}),
},
// A cold cache makes the install extract the tarball into a temporary directory.
env: dir => ({ BUN_INSTALL_CACHE_DIR: join(dir, ".cache") }),
check: async (out, dir) => {
expect(out.stdout, out.stderr).toContain("bar@");
expect(await Bun.file(join(dir, "node_modules", "bar", "package.json")).json()).toMatchObject({
name: "bar",
version: "0.0.2",
});
expect(out.exitCode).toBe(0);
},
},
];

Comment thread
robobun marked this conversation as resolved.
Resolved
for (const c of cases) {
test.concurrent(`${c.name} falls back to /dev/urandom`, async () => {
Comment thread
robobun marked this conversation as resolved.
Resolved
if (helperBin == null) {
console.warn(`SKIP ${c.name}: cc or seccomp headers not available`);
return;
}

using dir = tempDir("getrandom-enosys", {
"index.ts": `console.log("from-index");`,
"seed.test.ts": `import { test, expect } from "bun:test"; test("runs", () => { expect(1).toBe(1); });`,
...c.files,
});

const out = await runWithoutGetrandom(String(dir), c.args, c.env?.(String(dir)));
if (out == null) {
console.warn(`SKIP ${c.name}: seccomp not permitted in this environment`);
return;
}

await c.check(out, String(dir));
});
}
});
Loading