Repository navigation
[Linux] Prefer getrandom(2) over /dev/urandom; keep /proc/self/statm open - #394
dylan-conway wants to merge 4 commits into
Conversation
…open Two small changes so a JSC embedder can start inside a filesystem sandbox that hides /dev and /proc without crashing, and with fewer syscalls on a GC path. RandomDevice / bmalloc CryptoRandom: On Linux, probe getrandom(GRND_NONBLOCK) once. If the pool is already initialized, use getrandom for all subsequent reads and never open /dev/urandom (no path access, no fd held for the process lifetime). If the probe returns anything else -- EAGAIN (pool not yet ready, where /dev/urandom would have returned without blocking), ENOSYS (kernel < 3.17) or EPERM (seccomp) -- fall back to the existing /dev/urandom code unchanged, so behaviour is identical wherever getrandom is not a strict improvement. The urandom fd is now opened O_CLOEXEC. currentProcessMemoryStatus(): This is reached from Heap::proportionalHeapSize via memoryFootprint() after collections. Open /proc/self/statm once and pread() it instead of fopen/fgets/fclose per call, matching what LinuxMemory in AvailableMemory.cpp already does for memoryStatus(). If the open fails the function keeps returning zeros as before, but now costs nothing on later calls. As with LinuxMemory, the cached fd is bound to the opening pid; JSCOnly never runs JSC in a fork()-without-exec child.
|
Warning Review limit reachedYour included review limit has been reached. You’re in a promotional period — use the checkbox below to run this review for free:
On-demand reviews are free for the next 30 days. After that, they cost $0.25 per reviewed file. How can I continue?Run this review now using the option above, or comment You can also wait for the limit to reset (next review available in 1 minute), then comment An organization admin can change what happens after included review limits in Billing. How do review limits work?CodeRabbit enforces per-developer PR review limits within each organization. For paid Pro and Pro+ reviews, CodeRabbit uses a developer's included PR review attempts over the past 7 days to set the current hourly allowance. At typical activity levels, the full plan allowance applies. Higher sustained activity can lower the allowance until earlier attempts leave the 7-day window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (7)
WalkthroughChangesLinux entropy source selection
Process memory status collection
🚥 Pre-merge checks | ✅ 3 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (3 passed)
Comment |
There was a problem hiding this comment.
I reviewed this PR and didn't find any bugs. Because it modifies the cryptographic randomness sources in both WTF and bmalloc (and the author notes it wasn't built locally), a human look would still be worthwhile.
What was reviewed:
- Verified
m_fddefaults to-1in RandomDevice.h so the early-return path is sound; destructor now guardsclose(). - Checked the getrandom probe/fallback: EAGAIN/ENOSYS/EPERM all fall through to the unchanged
/dev/urandompath, and the read loop's existing EINTR/EAGAIN handling covers the blockinggetrandomcall. - Confirmed the
statmopen-once +preadpattern matches the existingLinuxMemoryprecedent inAvailableMemory.cpp; buffer is null-terminated with a byte reserved.
Extended reasoning...
Overview
Three Linux-only changes: (1) WTF::RandomDevice and (2) bmalloc::ARC4RandomNumberGenerator::stir now probe getrandom(2) with GRND_NONBLOCK at init and use it for all subsequent reads if the kernel entropy pool is initialized, falling back to the existing /dev/urandom path otherwise. (3) currentProcessMemoryStatus() switches from per-call fopen/fgets/fclose to a once-opened fd + pread, mirroring LinuxMemory::footprint() in AvailableMemory.cpp. All open() calls gain O_CLOEXEC.
Security risks
The first two changes touch the seeding path for cryptographic randomness — RandomDevice backs WTF::cryptographicallyRandomValues() and ARC4RandomNumberGenerator seeds bmalloc's CSPRNG. getrandom(2) without GRND_RANDOM draws from the same pool as /dev/urandom, so entropy quality is unchanged. The probe only commits to getrandom when it successfully returns 1 byte (pool initialized), and the pool cannot become uninitialized afterward, so subsequent blocking getrandom calls won't hang. The fallback path is byte-identical to the old code plus O_CLOEXEC. I don't see a way this weakens randomness, but any change to a CSPRNG seed source deserves a second set of eyes.
Level of scrutiny
High — this is security-critical infrastructure (crypto RNG seeding) even though the diff is small and mechanically straightforward. The author also notes "Not built locally", so CI is the first compile check.
Other factors
The statm change is a low-risk performance/robustness improvement with direct upstream precedent in the same tree. The fork-without-exec caveat is explicitly called out and matches what upstream already accepts for memoryStatus(). The #if guarding is careful (SYS_getrandom presence checked, GRND_NONBLOCK fallback-defined), and non-Linux platforms are unaffected by preprocessor construction.
Preview Builds
|
The option defaults to true, which keeps the behaviour of the previous commit: WTF::RandomDevice reads getrandom(2) and opens /dev/urandom only when the syscall is unavailable. Setting it to false (BUN_JSC_useGetrandom=0 in bun) makes the device open /dev/urandom as before. The device chooses its source when it is constructed, on the first request for randomness, so JSC::initialize() pushes the option into WTF right after Options::initialize() and before ExecutableAllocator::initialize(), which can be that first request. bmalloc's CryptoRandom is used before any option is parsed and is not covered by the option.
There was a problem hiding this comment.
I reviewed this PR and didn't find any bugs. Because it changes the OS entropy source for both WTF::RandomDevice and bmalloc's CryptoRandom (security-sensitive CSPRNG seeding), a human look would still be worthwhile.
What was reviewed:
- getrandom(2) probe/fallback logic in both RandomDevice and CryptoRandom — the
GRND_NONBLOCKprobe correctly falls through to/dev/urandomonEAGAIN/ENOSYS/EPERM, and them_fd < 0sentinel is only reachable when the probe succeeded. currentProcessMemoryStatuscached-fd +preadrewrite — buffer is explicitly NUL-terminated atlength, EINTR is retried, and open failure latches to the same zero-return behaviour as before.setUseGetrandomordering inJSC::initialize— placed afterOptions::initialize()and beforeExecutableAllocator::initialize(); no-op on non-Linux viaUNUSED_PARAM.
Extended reasoning...
Overview
This PR makes three related Linux-only changes across WTF, bmalloc, and JSC:
WTF::RandomDeviceandbmalloc::ARC4RandomNumberGenerator::stirnow probegetrandom(2)withGRND_NONBLOCKat construction/first-stir time. If the probe returns 1 byte, subsequent reads use the syscall directly (no fd, no filesystem dependency); otherwise they fall back to the existingopen("/dev/urandom")path, which now also getsO_CLOEXEC.WTF::currentProcessMemoryStatusswitches from per-callfopen/fgets/fcloseon/proc/self/statmto a one-timeopen+ per-callpreadat offset 0, mirroring the existing pattern inAvailableMemory.cpp.- A new
Options::useGetrandom(default true) is plumbed throughRandomDevice::setUseGetrandominJSC::initialize, letting users force the old/dev/urandombehaviour.
Security risks
The core of this PR is a change to how cryptographic randomness is sourced. getrandom(2) draws from the same kernel CSPRNG pool as /dev/urandom and is the modern recommended interface (used by glibc's getentropy, OpenSSL, BoringSSL, etc.), so the change is sound in principle. The probe-then-commit design is careful: the constructor only commits to getrandom after a successful non-blocking read proves the pool is initialized, so the later flag-0 reads in cryptographicallyRandomValues won't block indefinitely at early boot. The m_fd < 0 / fd < 0 sentinel meaning "use getrandom" is only reachable when RANDOM_DEVICE_USE_GETRANDOM/CRYPTO_RANDOM_USE_GETRANDOM is compiled in and the probe succeeded — in the fallback branch, open failure still hits crashUnableToOpenURandom() / RELEASE_BASSERT, so there's no path where m_fd == -1 silently degrades to a bad read. That said, any change to CSPRNG seeding is inherently security-sensitive and merits a second pair of eyes.
Level of scrutiny
High. Even though the diff is modest and the logic reads correctly, this touches the entropy source that seeds JSC's and bmalloc's random number generators (used for ASLR-adjacent decisions, StructureID randomization, hash seeds, etc.). The PR description also notes the initial change was "not built locally" and the JSC option wiring was "left to CI", so a maintainer confirming the CI matrix passed on all Linux variants (glibc/musl, x64/arm64) is worthwhile.
Other factors
- The
currentProcessMemoryStatuschange is a straightforward performance improvement with an acknowledged fork-without-exec caveat that already applies toLinuxMemoryin the same codebase; no concerns there. - The new
setUseGetrandomstatic uses a relaxed atomicbool, which is fine for a write-once-before-first-read configuration flag; the setter is defined on all platforms (no-op viaUNUSED_PARAMwhere getrandom isn't compiled in), so there's no link/ODR issue on macOS/Windows. - No prior human or bot reviews to consider beyond automated summaries.
bmalloc's ARC4 generator picked its OS source once, in a function-local once_flag inside stir(), and Gigacage stirs it during WTF::initialize(), before any option exists. The source is now generator state under its mutex: chooseSource() runs before the first stir and again from setCryptoRandomUsesGetrandom(), switching between getrandom(2) and an open /dev/urandom in either direction, so the option governs every stir after JSC::initialize(). WTF::RandomDevice::setUseGetrandom() forwards to it, so JSC still makes one call.
There was a problem hiding this comment.
I reviewed this PR and didn't find any bugs. Because it changes the OS entropy source for both WTF's and bmalloc's cryptographic RNGs, adds a new WTF→bmalloc configuration hook, and threads an option through JSC::initialize() ordering, a human look would still be worthwhile.
Checked: the GRND_NONBLOCK probe falls through to the existing /dev/urandom path on EAGAIN/ENOSYS/EPERM, so no new blocking or crash on old kernels/seccomp.
Checked: m_fd < 0 is only reachable when the probe succeeded (constructor crashes otherwise), so cryptographicallyRandomValues can't hit getrandom with an uninitialized pool.
Checked: setUseGetrandom/setCryptoRandomUsesGetrandom compile to no-ops on non-Linux; the unconditional <bmalloc/CryptoRandom.h> include is the only new cross-layer surface there.
Checked: pread into buffer[128] reads at most 127 and NUL-terminates, matching the old fgets bound.
Extended reasoning...
Overview
This PR touches seven files across three layers to make JSC start cleanly inside Linux filesystem sandboxes that hide /dev and /proc:
- bmalloc (
CryptoRandom.{h,cpp}): the ARC4 generator's entropy source moves from a function-localstd::once_flag-guarded fd into per-generator state (m_fd,m_sourceChosen,m_usesGetrandom) with a newchooseSource()that probesgetrandom(2)and can switch directions. A new exportedsetCryptoRandomUsesGetrandom(bool)reconfigures it under the generator's mutex. - WTF (
RandomDevice.{h,cpp}): the constructor probesgetrandom(GRND_NONBLOCK)before opening/dev/urandom; if the probe returns 1,m_fdstays −1 and reads use the syscall. A new staticsetUseGetrandom(bool)writes an atomic flag and forwards to bmalloc.O_CLOEXECis added to the fallback open. - WTF (
linux/CurrentProcessMemoryStatus.cpp):fopen/fgets/fcloseper call is replaced with a one-timeopen(O_RDONLY|O_CLOEXEC)cached in a static, thenpread()at offset 0. - JSC (
OptionsList.h,InitializeThreading.cpp): a newuseGetrandombool option (default true) is pushed into WTF right afterOptions::initialize()and beforeExecutableAllocator::initialize().
Security risks
This is squarely security-sensitive: it changes how the process obtains cryptographic randomness. The design is conservative — getrandom(2) and /dev/urandom draw from the same kernel pool, the probe uses GRND_NONBLOCK so it never blocks at boot, and any probe failure falls through to the pre-existing /dev/urandom code unchanged. The read loop still crashes on errors other than EAGAIN/EINTR, so it stays fail-closed. I did not find a path where randomness is silently degraded or where an uninitialized pool is read via the syscall (the only way m_fd stays −1 past construction is a probe that returned exactly 1). Still, changes to CSPRNG seeding warrant a second pair of eyes.
Level of scrutiny
High. Beyond the crypto surface, the PR:
- Adds a new dependency edge:
RandomDevice.cppnow unconditionally includes<bmalloc/CryptoRandom.h>and calls into bmalloc from WTF on every platform (a no-op off Linux, but a build-graph change). - Relies on initialization ordering in
JSC::initialize()— the setter must land afterOptions::initialize()but before the firstRandomDeviceconstruction, and the PR description acknowledges Gigacage's stir insideWTF::initialize()predates any option parsing. - Replaces a
std::once_flagstatic with mutable per-instance state in bmalloc's generator, protected by the existingStaticPerProcessmutex.
None of these are simple mechanical edits.
Other factors
The author notes the original portion was "not built locally" and the JSC side is "left to CI"; a preview build exists for an earlier commit (458db1d2) but the current head (83df2b7c) added the option plumbing afterward. The /proc/self/statm change carries the same fork-without-exec caveat the description calls out for AvailableMemory.cpp. Given the security surface and cross-layer plumbing, deferring to a human reviewer.
|
I ran the prebuilt Method: Linux x64, glibc 2.41. A seccomp user-notification supervisor answers
On main the release backtrace is Not checked: Bun built against this branch. With |
|
Replaced by #749, which keeps the getrandom(2) change with /dev/urandom as the fallback and drops |
Two small Linux-only changes so JSC can start inside a filesystem sandbox that hides
/devand/procwithout crashing, and does less work on a GC path. No behaviour change on macOS/Windows/FreeBSD.WTF::RandomDeviceandbmalloc::ARC4RandomNumberGenerator::stirToday both open
/dev/urandomat startup andCRASH()/RELEASE_BASSERTif that fails, then keep the fd for the life of the process.Now, on Linux, each probes
getrandom(…, GRND_NONBLOCK)once:getrandomfor every subsequent read. No path is touched and no fd is held.EAGAIN(pool not yet initialized, where a/dev/urandomread would have returned immediately),ENOSYS(kernel < 3.17),EPERM(seccomp) → fall through to the existing/dev/urandomcode, unchanged.So the only observable difference is on systems where
getrandomalready works and would return the same bytes from the same pool: one fewer open file and no dependency on/dev. The fallbackopen()gainsO_CLOEXEC.WTF::currentProcessMemoryStatus()Reached from
Heap::proportionalHeapSize→memoryFootprint()(becauseUSE(BUN_JSC_ADDITIONS)turns onUSE_MEMORY_FOOTPRINT_API), i.e. after collections. It didfopen("/proc/self/statm")+fgets+fcloseon every call. It now opens the file once (O_RDONLY|O_CLOEXEC) andpread()s at offset 0, which is exactly whatLinuxMemoryinAvailableMemory.cppalready does formemoryStatus(). If the open fails it latches and keeps returning zeros as before, at zero cost.Same caveat as
LinuxMemory: the cached fd is bound to the pid that opened it, so afork()-without-execchild would read the parent's numbers. JSCOnly never runs JSC in such a child (every fork is followed by exec), and upstream already accepted this trade-off formemoryStatus()on the same path.Not built locally.
Options::useGetrandom(added 2026-08-21, with main merged in)A JSC option that selects the source above. It defaults to true:
WTF::RandomDevicereadsgetrandom(2)and opens/dev/urandomonly when the syscall is unavailable, as described above.useGetrandom=false(BUN_JSC_useGetrandom=0in bun) makes the device open/dev/urandomas it did before this change.WTF::RandomDevicechooses its source when it is constructed, on the first request for randomness, soJSC::initialize()pushes the option into WTF (RandomDevice::setUseGetrandom) right afterOptions::initialize()and beforeExecutableAllocator::initialize(), which can be that first request. That setter also forwards to bmalloc (setCryptoRandomUsesGetrandom): the ARC4 generator's source is now generator state under its mutex, chosen before the first stir and re-chosen by the setter in either direction, so the option governs every stir afterJSC::initialize(). The one stir Gigacage triggers insideWTF::initialize()happens before any option is parsed and always uses the default (getrandom, then/dev/urandom); bmalloc re-stirs only after 1.6 MB of output, so in practice that first stir is the only one. Both setters are no-ops on platforms other than Linux.Evidence for the sandbox case: Sentry BUN-4NQQ is a 1.4.0 Linux aarch64
bun runthat aborted inRandomDevice::RandomDevice()duringJSC::VM::VM(symbolized against the right build in oven-sh/bun#39801's notes), so/dev/urandombeing unavailable does happen to users.Verified:
RandomDevice.cpp,OSRandomSource.cppand bmalloc'sCryptoRandom.cppcompile warning-free (-Wall -Wextra) with clang 21 against the tree, each in both theSYS_getrandomand the no-getrandom configuration. The JSC side (one option entry and one call) is left to CI.