From 115fff74826089184db809c3ed0bc9b61154509d Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 13 Sep 2026 21:44:41 +0000 Subject: [PATCH 1/9] bun_core: read /dev/urandom when getrandom(2) answers ENOSYS Linux older than 3.17 has no getrandom(2). os_entropy, the seed of fast_random(), panicked there with "getrandom failed: errno 38", so `bun build`, `Bun.build()`, `bun test --randomize` and package extraction in `bun install` aborted. On ENOSYS, read /dev/urandom instead, as BoringSSL does. README: state the same kernel floor as docs/installation.mdx. --- README.md | 2 +- src/bun_core/util.rs | 43 +++++++ test/regression/issue/27279.test.ts | 178 ++++++++++++++++++++++++++++ 3 files changed, 222 insertions(+), 1 deletion(-) create mode 100644 test/regression/issue/27279.test.ts diff --git a/README.md b/README.md index c507cc5dec62..fd81c44d1661 100644 --- a/README.md +++ b/README.md @@ -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. Bun runs on kernels as old as 3.10 (RHEL 7) with graceful degradation of newer syscalls. > **x64 users** — if you see "illegal instruction" or similar errors, check our [CPU requirements](https://bun.com/docs/installation#cpu-requirements) diff --git a/src/bun_core/util.rs b/src/bun_core/util.rs index b9a99746c8f7..4280fa6ebdf0 100644 --- a/src/bun_core/util.rs +++ b/src/bun_core/util.rs @@ -2665,6 +2665,9 @@ fn os_entropy(bytes: &mut [u8]) { if err == libc::EINTR { continue; } + if err == libc::ENOSYS { + return dev_urandom(&mut bytes[filled..]); + } panic!("getrandom failed: errno {err}"); } filled += rc as usize; @@ -2698,6 +2701,46 @@ fn os_entropy(bytes: &mut [u8]) { } } +/// Linux older than 3.17 has no getrandom(2) and answers ENOSYS. Read the same +/// pool through /dev/urandom, as BoringSSL does (`crypto/rand/urandom.cc`). +#[cfg(any(target_os = "linux", target_os = "android"))] +fn dev_urandom(bytes: &mut [u8]) { + let fd = loop { + // SAFETY: the path is a NUL-terminated literal. + let fd = unsafe { libc::open(c"/dev/urandom".as_ptr(), libc::O_RDONLY | libc::O_CLOEXEC) }; + if fd >= 0 { + break fd; + } + let err = crate::ffi::errno(); + if err != libc::EINTR { + panic!("getrandom is not available and /dev/urandom failed to open: errno {err}"); + } + }; + let mut filled = 0usize; + while filled < bytes.len() { + // SAFETY: writes at most len-filled bytes into the slice. + let rc = unsafe { + libc::read( + fd, + bytes.as_mut_ptr().add(filled).cast(), + bytes.len() - filled, + ) + }; + if rc > 0 { + filled += rc as usize; + } else if rc == 0 { + panic!("/dev/urandom returned EOF"); + } else { + let err = crate::ffi::errno(); + if err != libc::EINTR { + panic!("/dev/urandom read failed: errno {err}"); + } + } + } + // SAFETY: `fd` came from the open above and nothing else holds it. + unsafe { libc::close(fd) }; +} + // ── self_exe_path ───────────────────────────────────────────────────────── // Memoized into a process-lifetime // static buffer; thread-safe via `Once`. Returns a `&'static ZStr`. diff --git a/test/regression/issue/27279.test.ts b/test/regression/issue/27279.test.ts new file mode 100644 index 000000000000..c7a31f027a5e --- /dev/null +++ b/test/regression/issue/27279.test.ts @@ -0,0 +1,178 @@ +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. +describe.skipIf(!isLinux)("getrandom(2) answers ENOSYS", () => { + const ENOSYS = 38; + + // usage: block [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 +#include +#include +#include +#include +#include +#include +#include +#include + +#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; + }; + + const helperBin = tryBuild(); + + // 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[]) { + await using proc = Bun.spawn({ + cmd: [helperBin!, bunExe(), ...args], + env: bunEnv, + 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; + return { stdout, stderr, exitCode }; + } + + const cases: Array<{ + name: string; + args: string[]; + check: (out: { stdout: string; stderr: string }, dir: string) => Promise | void; + }> = [ + { + name: "bun build", + args: ["build", "./index.ts", "--outdir", "./out"], + check: async (_out, dir) => { + 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()).toBe("true true"); + }, + }, + { + name: "bun test --randomize", + args: ["test", "--randomize", "./seed.test.ts"], + check: out => { + expect(out.stderr).toContain("--seed="); + expect(out.stderr).toContain("1 pass"); + }, + }, + ]; + + for (const c of cases) { + test.concurrent(`${c.name} falls back to /dev/urandom`, async () => { + 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); });`, + }); + + const out = await runWithoutGetrandom(String(dir), c.args); + if (out == null) { + console.warn(`SKIP ${c.name}: seccomp not permitted in this environment`); + return; + } + + await c.check(out, String(dir)); + expect(out.exitCode).toBe(0); + }); + } +}); From f99793b28395e636bebb7d21444490af9f447b6e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 13 Sep 2026 22:00:19 +0000 Subject: [PATCH 2/9] test: report seccomp helper failures in 27279.test.ts, skip the compile off Linux - Compile the helper only on Linux. describe.skipIf still runs the callback on the other platforms. - Exit codes 78 and 127 of the helper throw with its stderr. - Each case asserts the exit code itself. `bun build` asserts it before it reads the output file, with the child's stderr as the message. --- test/regression/issue/27279.test.ts | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/test/regression/issue/27279.test.ts b/test/regression/issue/27279.test.ts index c7a31f027a5e..b8816f4b272b 100644 --- a/test/regression/issue/27279.test.ts +++ b/test/regression/issue/27279.test.ts @@ -103,7 +103,8 @@ int main(int argc, char **argv) { return bin; }; - const helperBin = tryBuild(); + // 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). @@ -117,18 +118,24 @@ int main(int argc, char **argv) { }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); if (exitCode === 77) return null; + // 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[]; - check: (out: { stdout: string; stderr: string }, dir: string) => Promise | void; + check: (out: { stdout: string; stderr: string; exitCode: number }, dir: string) => Promise | void; }> = [ { name: "bun build", args: ["build", "./index.ts", "--outdir", "./out"], - check: async (_out, dir) => { + 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"); }, }, @@ -140,7 +147,8 @@ int main(int argc, char **argv) { console.log(result.success, (await result.outputs[0].text()).includes("from-index"));`, ], check: out => { - expect(out.stdout.trim()).toBe("true true"); + expect(out.stdout.trim(), out.stderr).toBe("true true"); + expect(out.exitCode).toBe(0); }, }, { @@ -149,6 +157,7 @@ int main(int argc, char **argv) { check: out => { expect(out.stderr).toContain("--seed="); expect(out.stderr).toContain("1 pass"); + expect(out.exitCode).toBe(0); }, }, ]; @@ -172,7 +181,6 @@ int main(int argc, char **argv) { } await c.check(out, String(dir)); - expect(out.exitCode).toBe(0); }); } }); From 7accab46b8fb0d40c4dee4b3675a203d1ee0bc01 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 13 Sep 2026 22:03:13 +0000 Subject: [PATCH 3/9] bun_core: shorten the dev_urandom doc comment --- src/bun_core/util.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/bun_core/util.rs b/src/bun_core/util.rs index 4280fa6ebdf0..eb9c04d5f877 100644 --- a/src/bun_core/util.rs +++ b/src/bun_core/util.rs @@ -2701,8 +2701,7 @@ fn os_entropy(bytes: &mut [u8]) { } } -/// Linux older than 3.17 has no getrandom(2) and answers ENOSYS. Read the same -/// pool through /dev/urandom, as BoringSSL does (`crypto/rand/urandom.cc`). +/// getrandom(2) answers ENOSYS on Linux older than 3.17. #[cfg(any(target_os = "linux", target_os = "android"))] fn dev_urandom(bytes: &mut [u8]) { let fd = loop { From 7b460b646acd8e01ba3f9f5b5e6339ea8540cf52 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 13 Sep 2026 22:24:34 +0000 Subject: [PATCH 4/9] ci: retrigger From 2061ebcf84807f3a1b8cf132c53cd9374a7903ef Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 14 Sep 2026 06:02:45 +0000 Subject: [PATCH 5/9] test: cover bun install under the getrandom(2) ENOSYS filter More than half of the fast_random() call sites are in src/install. The new case installs a local tarball with a cold cache, so the extraction asks FileSystem::tmpname for a temporary directory name. --- test/regression/issue/27279.test.ts | 30 ++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/test/regression/issue/27279.test.ts b/test/regression/issue/27279.test.ts index b8816f4b272b..a55a34c42e32 100644 --- a/test/regression/issue/27279.test.ts +++ b/test/regression/issue/27279.test.ts @@ -108,10 +108,10 @@ int main(int argc, char **argv) { // 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[]) { + async function runWithoutGetrandom(cwd: string, args: string[], env: Record = {}) { await using proc = Bun.spawn({ cmd: [helperBin!, bunExe(), ...args], - env: bunEnv, + env: { ...bunEnv, ...env }, cwd, stdout: "pipe", stderr: "pipe", @@ -128,6 +128,8 @@ int main(int argc, char **argv) { const cases: Array<{ name: string; args: string[]; + files?: Record; + env?: (dir: string) => Record; check: (out: { stdout: string; stderr: string; exitCode: number }, dir: string) => Promise | void; }> = [ { @@ -160,6 +162,27 @@ int main(int argc, char **argv) { 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); + }, + }, ]; for (const c of cases) { @@ -172,9 +195,10 @@ int main(int argc, char **argv) { 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); + 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; From 20603c60c5b62bba2a9d42d8c17b43babbe659d8 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 24 Sep 2026 04:22:33 +0000 Subject: [PATCH 6/9] bun_core: seed fast_random() with getrandom::fill os_entropy on Linux and Android now calls the getrandom crate, which is already a workspace dependency for Bun.password. The crate reads /dev/urandom on a kernel that has no getrandom(2). This replaces the hand-written getrandom(2) loop and /dev/urandom reader, and their unsafe blocks. glibc 2.41+ answers the crate's zero-length probe from the vDSO with no syscall. Under a seccomp filter the crate then keeps the syscall path and returns the error. os_entropy reads /dev/urandom through std::fs in that case. README: link to the installation docs for older kernels, and state no kernel floor. --- Cargo.lock | 1 + README.md | 2 +- src/bun_core/Cargo.toml | 3 ++ src/bun_core/util.rs | 69 ++++------------------------- test/regression/issue/27279.test.ts | 6 +++ 5 files changed, 20 insertions(+), 61 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 20012ce3d0cf..5fa536f9b99e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -392,6 +392,7 @@ dependencies = [ "bun_wyhash", "bytemuck", "const_format", + "getrandom", "itoa", "libc", "strum", diff --git a/README.md b/README.md index fd81c44d1661..7aa79bb40dfb 100644 --- a/README.md +++ b/README.md @@ -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. Bun runs on kernels as old as 3.10 (RHEL 7) with graceful degradation of newer syscalls. +> **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) diff --git a/src/bun_core/Cargo.toml b/src/bun_core/Cargo.toml index b330270cf68c..752a9962a2da 100644 --- a/src/bun_core/Cargo.toml +++ b/src/bun_core/Cargo.toml @@ -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 diff --git a/src/bun_core/util.rs b/src/bun_core/util.rs index 54f94bfba089..6c66a7323f66 100644 --- a/src/bun_core/util.rs +++ b/src/bun_core/util.rs @@ -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 @@ -2648,27 +2648,15 @@ 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; - } - if err == libc::ENOSYS { - return dev_urandom(&mut bytes[filled..]); - } - panic!("getrandom failed: errno {err}"); + // The crate selects its own /dev/urandom fallback with a zero-length probe. glibc 2.41+ + // answers that probe from the vDSO, so a seccomp filter on the syscall still fails here. + if let Err(err) = getrandom::fill(bytes) { + 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"))] @@ -2699,45 +2687,6 @@ fn os_entropy(bytes: &mut [u8]) { } } -/// getrandom(2) answers ENOSYS on Linux older than 3.17. -#[cfg(any(target_os = "linux", target_os = "android"))] -fn dev_urandom(bytes: &mut [u8]) { - let fd = loop { - // SAFETY: the path is a NUL-terminated literal. - let fd = unsafe { libc::open(c"/dev/urandom".as_ptr(), libc::O_RDONLY | libc::O_CLOEXEC) }; - if fd >= 0 { - break fd; - } - let err = crate::ffi::errno(); - if err != libc::EINTR { - panic!("getrandom is not available and /dev/urandom failed to open: errno {err}"); - } - }; - let mut filled = 0usize; - while filled < bytes.len() { - // SAFETY: writes at most len-filled bytes into the slice. - let rc = unsafe { - libc::read( - fd, - bytes.as_mut_ptr().add(filled).cast(), - bytes.len() - filled, - ) - }; - if rc > 0 { - filled += rc as usize; - } else if rc == 0 { - panic!("/dev/urandom returned EOF"); - } else { - let err = crate::ffi::errno(); - if err != libc::EINTR { - panic!("/dev/urandom read failed: errno {err}"); - } - } - } - // SAFETY: `fd` came from the open above and nothing else holds it. - unsafe { libc::close(fd) }; -} - // ── self_exe_path ───────────────────────────────────────────────────────── // Memoized into a process-lifetime // static buffer; thread-safe via `Once`. Returns a `&'static ZStr`. diff --git a/test/regression/issue/27279.test.ts b/test/regression/issue/27279.test.ts index a55a34c42e32..0d4bda2ede83 100644 --- a/test/regression/issue/27279.test.ts +++ b/test/regression/issue/27279.test.ts @@ -15,6 +15,12 @@ import { join } from "node:path"; // // 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; From ca21f090c8f0efdaaaa5fddde864dc27ba074894 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 24 Sep 2026 04:27:07 +0000 Subject: [PATCH 7/9] bun_core: make the os_entropy comment one line --- src/bun_core/util.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/bun_core/util.rs b/src/bun_core/util.rs index 6c66a7323f66..a188611bf65b 100644 --- a/src/bun_core/util.rs +++ b/src/bun_core/util.rs @@ -2648,8 +2648,7 @@ pub fn is_writable(fd: Fd) -> Pollable { fn os_entropy(bytes: &mut [u8]) { #[cfg(any(target_os = "linux", target_os = "android"))] { - // The crate selects its own /dev/urandom fallback with a zero-length probe. glibc 2.41+ - // answers that probe from the vDSO, so a seccomp filter on the syscall still fails here. + // Under seccomp the crate never falls back: glibc 2.41+ answers its probe from the vDSO. if let Err(err) = getrandom::fill(bytes) { use std::io::Read; if let Err(io_err) = From 18534030f2de128727025611165636b5019383a2 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 24 Sep 2026 05:03:56 +0000 Subject: [PATCH 8/9] bun_core: read /dev/urandom directly when getrandom(2) answers ENOSYS or EPERM os_entropy keeps its getrandom(2) call. On ENOSYS (Linux older than 3.17) or EPERM (a seccomp filter) it reads /dev/urandom through std::fs. There is no new unsafe block and no new dependency. This replaces getrandom::fill. On a kernel with no getrandom(2) the crate polls /dev/random with no timeout before it reads /dev/urandom. Before Linux 5.6, /dev/random is readable only when the entropy estimate is 64 bits or more, so the seed of a non-cryptographic PRNG could wait there. BoringSSL and Rust std do not wait. test: the helper takes the errno, one EPERM case for `bun build`, and the cases are skipped (not passed) where the host has no cc or refuses the seccomp filter. --- Cargo.lock | 1 - src/bun_core/Cargo.toml | 3 - src/bun_core/util.rs | 37 +++++++--- test/regression/issue/27279.test.ts | 101 ++++++++++++++-------------- 4 files changed, 79 insertions(+), 63 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5fa536f9b99e..20012ce3d0cf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -392,7 +392,6 @@ dependencies = [ "bun_wyhash", "bytemuck", "const_format", - "getrandom", "itoa", "libc", "strum", diff --git a/src/bun_core/Cargo.toml b/src/bun_core/Cargo.toml index 752a9962a2da..b330270cf68c 100644 --- a/src/bun_core/Cargo.toml +++ b/src/bun_core/Cargo.toml @@ -30,6 +30,3 @@ 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 diff --git a/src/bun_core/util.rs b/src/bun_core/util.rs index a188611bf65b..f7ee0f1176ac 100644 --- a/src/bun_core/util.rs +++ b/src/bun_core/util.rs @@ -2639,7 +2639,7 @@ pub fn is_writable(fd: Fd) -> Pollable { } // ── os_entropy ──────────────────────────────────────────────────────────── -// Raw OS entropy source: the `getrandom` crate on Linux, getentropy on Darwin/BSD, +// Raw OS entropy source: getrandom(2) 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 @@ -2648,14 +2648,35 @@ pub fn is_writable(fd: Fd) -> Pollable { fn os_entropy(bytes: &mut [u8]) { #[cfg(any(target_os = "linux", target_os = "android"))] { - // Under seccomp the crate never falls back: glibc 2.41+ answers its probe from the vDSO. - if let Err(err) = getrandom::fill(bytes) { - 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})"); + 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; + } + // ENOSYS: Linux older than 3.17. EPERM: a seccomp filter. + if err == libc::ENOSYS || err == libc::EPERM { + use std::io::Read; + let rest = &mut bytes[filled..]; + if let Err(io_err) = + std::fs::File::open("/dev/urandom").and_then(|mut f| f.read_exact(rest)) + { + panic!("getrandom failed (errno {err}), /dev/urandom failed ({io_err})"); + } + return; + } + panic!("getrandom failed: errno {err}"); } + filled += rc as usize; } } #[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd"))] diff --git a/test/regression/issue/27279.test.ts b/test/regression/issue/27279.test.ts index 0d4bda2ede83..2f5d6891db5f 100644 --- a/test/regression/issue/27279.test.ts +++ b/test/regression/issue/27279.test.ts @@ -15,17 +15,13 @@ import { join } from "node:path"; // // 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 [args...] - // exit 77: the environment refuses the filter (skip). exit 78: the filter is +// A seccomp policy that does not know getrandom(2) answers EPERM. BoringSSL +// aborts on that errno, so only `bun build` has an EPERM case. +describe.skipIf(!isLinux)("getrandom(2) is not available", () => { + const errnos = { ENOSYS: 38, EPERM: 1 }; + + // usage: block [args...] + // exit 77: the environment refuses the filter. exit 78: the filter is // installed but getrandom still works, so the run would prove nothing. const helperSrc = ` #define _GNU_SOURCE @@ -35,6 +31,7 @@ describe.skipIf(!isLinux)("getrandom(2) answers ENOSYS", () => { #include #include #include +#include #include #include #include @@ -48,8 +45,9 @@ describe.skipIf(!isLinux)("getrandom(2) answers ENOSYS", () => { #endif int main(int argc, char **argv) { - if (argc < 2) return 2; + if (argc < 3) return 2; if (MY_AUDIT_ARCH == 0) return 77; + unsigned int err = (unsigned int)atoi(argv[1]); struct sock_filter filter[] = { BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, arch)), @@ -57,7 +55,7 @@ int main(int argc, char **argv) { 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_ERRNO | (err & SECCOMP_RET_DATA)), BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW), }; struct sock_fprog prog = { @@ -75,12 +73,12 @@ int main(int argc, char **argv) { } unsigned char probe; - if (syscall(__NR_getrandom, &probe, 1, 0) != -1 || errno != ${ENOSYS}) { + if (syscall(__NR_getrandom, &probe, 1, 0) != -1 || errno != (int)err) { fprintf(stderr, "getrandom is not blocked\\n"); return 78; } - execvp(argv[1], &argv[1]); + execvp(argv[2], &argv[2]); perror("execvp"); return 127; } @@ -111,44 +109,50 @@ int main(int argc, char **argv) { // describe.skipIf still runs this callback on the other platforms. const helperBin = isLinux ? tryBuild() : null; + // One run of the helper tells if this environment accepts the filter (exit 77 if not). + const canFilter = helperBin != null && spawnSync(helperBin, [String(errnos.ENOSYS), "true"]).status === 0; - // 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 = {}) { + // Runs `bun ...args` in `cwd` with getrandom(2) answering `errno`. + async function runWithoutGetrandom(errno: number, cwd: string, args: string[], env: Record = {}) { await using proc = Bun.spawn({ - cmd: [helperBin!, bunExe(), ...args], + cmd: [helperBin!, String(errno), 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; - // 78: the filter does not block getrandom. 127: execvp failed. - if (exitCode === 78 || exitCode === 127) { + // 77: the filter was refused. 78: it does not block getrandom. 127: execvp failed. + if (exitCode === 77 || exitCode === 78 || exitCode === 127) { throw new Error(`seccomp helper exited with code ${exitCode}:\n${stderr}`); } return { stdout, stderr, exitCode }; } + type Output = { stdout: string; stderr: string; exitCode: number }; + const bunBuild = { + name: "bun build", + args: ["build", "./index.ts", "--outdir", "./out"], + check: async (out: Output, dir: string) => { + // 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"); + }, + }; + const cases: Array<{ name: string; + errno: keyof typeof errnos; args: string[]; files?: Record; env?: (dir: string) => Record; - check: (out: { stdout: string; stderr: string; exitCode: number }, dir: string) => Promise | void; + check: (out: Output, dir: string) => Promise | 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"); - }, - }, + { ...bunBuild, errno: "ENOSYS" }, + { ...bunBuild, errno: "EPERM" }, { name: "Bun.build()", + errno: "ENOSYS", args: [ "-e", `const result = await Bun.build({ entrypoints: ["./index.ts"] }); @@ -161,6 +165,7 @@ int main(int argc, char **argv) { }, { name: "bun test --randomize", + errno: "ENOSYS", args: ["test", "--randomize", "./seed.test.ts"], check: out => { expect(out.stderr).toContain("--seed="); @@ -170,6 +175,7 @@ int main(int argc, char **argv) { }, { name: "bun install", + errno: "ENOSYS", args: ["install"], files: { "package.json": JSON.stringify({ @@ -192,25 +198,18 @@ int main(int argc, char **argv) { ]; for (const c of cases) { - test.concurrent(`${c.name} falls back to /dev/urandom`, async () => { - 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; - } + // Skipped where the host has no cc or kernel headers, or refuses the seccomp filter. + test + .skipIf(!canFilter) + .concurrent(`${c.name} reads /dev/urandom when getrandom(2) answers ${c.errno}`, async () => { + 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, + }); - await c.check(out, String(dir)); - }); + const out = await runWithoutGetrandom(errnos[c.errno], String(dir), c.args, c.env?.(String(dir))); + await c.check(out, String(dir)); + }); } }); From 77179c8b8ba26929db7e7d26b7a8a4237182030b Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 24 Sep 2026 05:58:04 +0000 Subject: [PATCH 9/9] bun_core: os_entropy on Linux no longer panics If getrandom(2) fails, os_entropy reads /dev/urandom. If that fails too, it seeds from the clock, the thread id and a stack address. The seed only feeds the non-cryptographic fast_random(), so a host with no entropy source does not have to abort. The errno of getrandom(2) no longer selects the path: every failure except EINTR takes the /dev/urandom read. --- src/bun_core/util.rs | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/src/bun_core/util.rs b/src/bun_core/util.rs index f7ee0f1176ac..22427bdfdaeb 100644 --- a/src/bun_core/util.rs +++ b/src/bun_core/util.rs @@ -2659,22 +2659,18 @@ fn os_entropy(bytes: &mut [u8]) { ) }; if rc < 0 { - let err = crate::ffi::errno(); - if err == libc::EINTR { + if crate::ffi::errno() == libc::EINTR { continue; } // ENOSYS: Linux older than 3.17. EPERM: a seccomp filter. - if err == libc::ENOSYS || err == libc::EPERM { - use std::io::Read; - let rest = &mut bytes[filled..]; - if let Err(io_err) = - std::fs::File::open("/dev/urandom").and_then(|mut f| f.read_exact(rest)) - { - panic!("getrandom failed (errno {err}), /dev/urandom failed ({io_err})"); - } - return; + use std::io::Read; + let rest = &mut bytes[filled..]; + let urandom = + std::fs::File::open("/dev/urandom").and_then(|mut f| f.read_exact(rest)); + if urandom.is_err() { + weak_entropy(rest); } - panic!("getrandom failed: errno {err}"); + return; } filled += rc as usize; } @@ -2707,6 +2703,20 @@ fn os_entropy(bytes: &mut [u8]) { } } +/// For a host with no OS entropy source. It is enough for the non-cryptographic `fast_random()`. +#[cfg(any(target_os = "linux", target_os = "android"))] +#[cold] +fn weak_entropy(bytes: &mut [u8]) { + let on_stack = 0u8; + let seed = (time::nano_timestamp() as u64) + ^ (crate::thread_id::current() as u64).rotate_left(32) + ^ (core::ptr::from_ref(&on_stack) as usize as u64); + let mut prng = rand::DefaultPrng::init(seed); + for chunk in bytes.chunks_mut(8) { + chunk.copy_from_slice(&prng.next_u64().to_ne_bytes()[..chunk.len()]); + } +} + // ── self_exe_path ───────────────────────────────────────────────────────── // Memoized into a process-lifetime // static buffer; thread-safe via `Once`. Returns a `&'static ZStr`.