getrandom/backends/
use_file.rs

1//! Implementations that just need to read from a file
2use crate::Error;
3use core::{
4    ffi::{CStr, c_void},
5    mem::MaybeUninit,
6    sync::atomic::{AtomicI32, Ordering},
7};
8
9#[cfg(not(any(target_os = "android", target_os = "linux")))]
10pub use crate::util::{inner_u32, inner_u64};
11
12#[path = "../utils/sys_fill_exact.rs"]
13pub(super) mod utils;
14
15/// For all platforms, we use `/dev/urandom` rather than `/dev/random`.
16/// For more information see the linked man pages in lib.rs.
17///   - On Linux, "/dev/urandom is preferred and sufficient in all use cases".
18///   - On Redox, only /dev/urandom is provided.
19///   - On AIX, /dev/urandom will "provide cryptographically secure output".
20///   - On Haiku and QNX Neutrino they are identical.
21const FILE_PATH: &CStr = c"/dev/urandom";
22
23// File descriptor is a "nonnegative integer", so we can safely use negative sentinel values.
24const FD_UNINIT: libc::c_int = -1;
25const FD_ONGOING_INIT: libc::c_int = -2;
26
27// In theory `libc::c_int` could be something other than `i32`, but for the
28// targets we currently support that use `use_file`, it is always `i32`.
29// If/when we add support for a target where that isn't the case, we may
30// need to use a different atomic type or make other accommodations. The
31// compiler will let us know if/when that is the case, because the
32// `FD.store(fd)` would fail to compile.
33//
34// The opening of the file, by libc/libstd/etc. may write some unknown
35// state into in-process memory. (Such state may include some sanitizer
36// bookkeeping, or we might be operating in a unikernal-like environment
37// where all the "kernel" file descriptor bookkeeping is done in our
38// process.) `get_fd_locked` stores into FD using `Ordering::Release` to
39// ensure any such state is synchronized. `get_fd` loads from `FD` with
40// `Ordering::Acquire` to synchronize with it.
41static FD: AtomicI32 = AtomicI32::new(FD_UNINIT);
42
43#[inline]
44pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
45    let mut fd = FD.load(Ordering::Acquire);
46    if fd == FD_UNINIT || fd == FD_ONGOING_INIT {
47        fd = open_or_wait()?;
48    }
49    utils::sys_fill_exact(dest, |buf| unsafe {
50        libc::read(fd, buf.as_mut_ptr().cast::<c_void>(), buf.len())
51    })
52}
53
54/// Open a file in read-only mode.
55fn open_readonly(path: &CStr) -> Result<libc::c_int, Error> {
56    loop {
57        let fd = unsafe { libc::open(path.as_ptr(), libc::O_RDONLY | libc::O_CLOEXEC) };
58        if fd >= 0 {
59            return Ok(fd);
60        }
61        let errno = utils::get_errno();
62        // We should try again if open() was interrupted.
63        if errno != libc::EINTR {
64            return Err(Error::from_errno(errno));
65        }
66    }
67}
68
69#[cold]
70#[inline(never)]
71fn open_or_wait() -> Result<libc::c_int, Error> {
72    loop {
73        match FD.load(Ordering::Acquire) {
74            FD_UNINIT => {
75                let res = FD.compare_exchange_weak(
76                    FD_UNINIT,
77                    FD_ONGOING_INIT,
78                    Ordering::AcqRel,
79                    Ordering::Relaxed,
80                );
81                if res.is_ok() {
82                    break;
83                }
84            }
85            FD_ONGOING_INIT => sync::wait(),
86            fd => return Ok(fd),
87        }
88    }
89
90    let res = open_fd();
91    let val = match res {
92        Ok(fd) => fd,
93        Err(_) => FD_UNINIT,
94    };
95    FD.store(val, Ordering::Release);
96
97    // On non-Linux targets `wait` is just 1 ms sleep,
98    // so we don't need any explicit wake up in addition
99    // to updating value of `FD`.
100    #[cfg(any(target_os = "android", target_os = "linux"))]
101    sync::wake();
102
103    res
104}
105
106fn open_fd() -> Result<libc::c_int, Error> {
107    #[cfg(any(target_os = "android", target_os = "linux"))]
108    sync::wait_until_rng_ready()?;
109    let fd = open_readonly(FILE_PATH)?;
110    debug_assert!(fd >= 0);
111    Ok(fd)
112}
113
114#[cfg(not(any(target_os = "android", target_os = "linux")))]
115mod sync {
116    /// Sleep 1 ms before checking `FD` again.
117    ///
118    /// On non-Linux targets the critical section only opens file,
119    /// which should not block, so in the unlikely contended case,
120    /// we can sleep-wait for the opening operation to finish.
121    pub(super) fn wait() {
122        let rqtp = libc::timespec {
123            tv_sec: 0,
124            tv_nsec: 1_000_000,
125        };
126        let mut rmtp = libc::timespec {
127            tv_sec: 0,
128            tv_nsec: 0,
129        };
130        // We do not care if sleep gets interrupted, so the return value is ignored
131        unsafe {
132            libc::nanosleep(&rqtp, &mut rmtp);
133        }
134    }
135}
136
137#[cfg(any(target_os = "android", target_os = "linux"))]
138mod sync {
139    use super::{Error, FD, FD_ONGOING_INIT, open_readonly, utils};
140
141    /// Wait for atomic `FD` to change value from `FD_ONGOING_INIT` to something else.
142    ///
143    /// Futex syscall with `FUTEX_WAIT` op puts the current thread to sleep
144    /// until futex syscall with `FUTEX_WAKE` op gets executed for `FD`.
145    ///
146    /// For more information read: https://www.man7.org/linux/man-pages/man2/futex.2.html
147    pub(super) fn wait() {
148        let op = libc::FUTEX_WAIT | libc::FUTEX_PRIVATE_FLAG;
149        let timeout_ptr = core::ptr::null::<libc::timespec>();
150        let ret = unsafe { libc::syscall(libc::SYS_futex, &FD, op, FD_ONGOING_INIT, timeout_ptr) };
151        // FUTEX_WAIT should return either 0 or EAGAIN error
152        debug_assert!({
153            match ret {
154                0 => true,
155                -1 => utils::get_errno() == libc::EAGAIN,
156                _ => false,
157            }
158        });
159    }
160
161    /// Wake up all threads which wait for value of atomic `FD` to change.
162    pub(super) fn wake() {
163        let op = libc::FUTEX_WAKE | libc::FUTEX_PRIVATE_FLAG;
164        let ret = unsafe { libc::syscall(libc::SYS_futex, &FD, op, libc::INT_MAX) };
165        debug_assert!(ret >= 0);
166    }
167
168    // Polls /dev/random to make sure it is ok to read from /dev/urandom.
169    //
170    // Polling avoids draining the estimated entropy from /dev/random;
171    // short-lived processes reading even a single byte from /dev/random could
172    // be problematic if they are being executed faster than entropy is being
173    // collected.
174    //
175    // OTOH, reading a byte instead of polling is more compatible with
176    // sandboxes that disallow `poll()` but which allow reading /dev/random,
177    // e.g. sandboxes that assume that `poll()` is for network I/O. This way,
178    // fewer applications will have to insert pre-sandbox-initialization logic.
179    // Often (blocking) file I/O is not allowed in such early phases of an
180    // application for performance and/or security reasons.
181    //
182    // It is hard to write a sandbox policy to support `libc::poll()` because
183    // it may invoke the `poll`, `ppoll`, `ppoll_time64` (since Linux 5.1, with
184    // newer versions of glibc), and/or (rarely, and probably only on ancient
185    // systems) `select`. depending on the libc implementation (e.g. glibc vs
186    // musl), libc version, potentially the kernel version at runtime, and/or
187    // the target architecture.
188    //
189    // BoringSSL and libstd don't try to protect against insecure output from
190    // `/dev/urandom'; they don't open `/dev/random` at all.
191    //
192    // OpenSSL uses `libc::select()` unless the `dev/random` file descriptor
193    // is too large; if it is too large then it does what we do here.
194    //
195    // libsodium uses `libc::poll` similarly to this.
196    pub(super) fn wait_until_rng_ready() -> Result<(), Error> {
197        let fd = open_readonly(c"/dev/random")?;
198        let mut pfd = libc::pollfd {
199            fd,
200            events: libc::POLLIN,
201            revents: 0,
202        };
203
204        let res = loop {
205            // A negative timeout means an infinite timeout.
206            let res = unsafe { libc::poll(&mut pfd, 1, -1) };
207            if res >= 0 {
208                // We only used one fd, and cannot timeout.
209                debug_assert_eq!(res, 1);
210                break Ok(());
211            }
212            let errno = utils::get_errno();
213            // Assuming that `poll` is called correctly,
214            // on Linux it can return only EINTR and ENOMEM errors.
215            match errno {
216                libc::EINTR => continue,
217                _ => break Err(Error::from_errno(errno)),
218            }
219        };
220        unsafe { libc::close(fd) };
221        res
222    }
223}