| 1 |
// GStreamer |
| 2 |
// |
| 3 |
// Copyright (C) 2015-2023 Sebastian Dröge <[email protected]> |
| 4 |
// |
| 5 |
// This Source Code Form is subject to the terms of the Mozilla Public License, v2.0. |
| 6 |
// If a copy of the MPL was not distributed with this file, You can obtain one at |
| 7 |
// <https://mozilla.org/MPL/2.0/>. |
| 8 |
// |
| 9 |
// SPDX-License-Identifier: MPL-2.0 |
| 10 |
|
| 11 |
#[cfg(unix)] |
| 12 |
mod unix { |
| 13 |
use std::io; |
| 14 |
|
| 15 |
#[cfg(target_os = "linux")] |
| 16 |
/// Try using the getrandom syscall on Linux. |
| 17 |
pub fn getrandom() -> io::Result<[u8; 8]> { |
| 18 |
use std::io::Read; |
| 19 |
|
| 20 |
use crate::ffi::unix::linux::*; |
| 21 |
|
| 22 |
// Depends on us knowing the syscall number |
| 23 |
if SYS_getrandom == 0 { |
| 24 |
// FIXME: Use Unsupported once we can depend on 1.53 |
| 25 |
return Err(io::Error::from(io::ErrorKind::NotFound)); |
| 26 |
} |
| 27 |
|
| 28 |
struct GetRandom; |
| 29 |
|
| 30 |
impl Read for GetRandom { |
| 31 |
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { |
| 32 |
// SAFETY: `getrandom` syscall fills up to the requested amount of bytes of |
| 33 |
// the provided memory and returns the number of bytes or a negative value |
| 34 |
// on errors. |
| 35 |
unsafe { |
| 36 |
let res = syscall(SYS_getrandom, buf.as_mut_ptr(), buf.len(), 0u32); |
| 37 |
if res < 0 { |
| 38 |
Err(std::io::Error::last_os_error()) |
| 39 |
} else { |
| 40 |
Ok(res as usize) |
| 41 |
} |
| 42 |
} |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
let mut r = [0u8; 8]; |
| 47 |
GetRandom.read_exact(&mut r)?; |
| 48 |
|
| 49 |
Ok(r) |
| 50 |
} |
| 51 |
|
| 52 |
/// Try reading random numbers from /dev/urandom. |
| 53 |
pub fn dev_urandom() -> io::Result<[u8; 8]> { |
| 54 |
use crate::ffi::unix::*; |
| 55 |
use std::{io::Read, os::raw::c_int}; |
| 56 |
|
| 57 |
struct Fd(c_int); |
| 58 |
|
| 59 |
impl Drop for Fd { |
| 60 |
fn drop(&mut self) { |
| 61 |
// SAFETY: The fd is valid by construction below and closed by this at |
| 62 |
// most once. |
| 63 |
unsafe { |
| 64 |
// Return value is intentionally ignored as there's nothing that |
| 65 |
// can be done on errors anyway. |
| 66 |
let _ = close(self.0); |
| 67 |
} |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
impl Read for Fd { |
| 72 |
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { |
| 73 |
// SAFETY: read() requires a valid fd and a mutable buffer with the given size. |
| 74 |
// The fd is valid by construction as is the buffer. |
| 75 |
// |
| 76 |
// read() will return the number of bytes read or a negative value on errors. |
| 77 |
let res = unsafe { read(self.0, buf.as_mut_ptr(), buf.len()) }; |
| 78 |
if res < 0 { |
| 79 |
Err(std::io::Error::last_os_error()) |
| 80 |
} else { |
| 81 |
Ok(res as usize) |
| 82 |
} |
| 83 |
} |
| 84 |
} |
| 85 |
|
| 86 |
let mut fd = loop { |
| 87 |
// SAFETY: open() requires a NUL-terminated file path and will |
| 88 |
// return an integer in any case. A negative value is an invalid fd |
| 89 |
// and signals an error. On EINTR, opening can be retried. |
| 90 |
let fd = unsafe { open(b"/dev/urandom\0".as_ptr(), O_RDONLY) }; |
| 91 |
if fd < 0 { |
| 92 |
let err = std::io::Error::last_os_error(); |
| 93 |
if err.kind() == std::io::ErrorKind::Interrupted { |
| 94 |
continue; |
| 95 |
} |
| 96 |
|
| 97 |
return Err(err); |
| 98 |
} |
| 99 |
|
| 100 |
break Fd(fd); |
| 101 |
}; |
| 102 |
|
| 103 |
let mut r = [0u8; 8]; |
| 104 |
fd.read_exact(&mut r)?; |
| 105 |
|
| 106 |
Ok(r) |
| 107 |
} |
| 108 |
|
| 109 |
#[cfg(test)] |
| 110 |
mod test { |
| 111 |
#[test] |
| 112 |
fn test_dev_urandom() { |
| 113 |
match super::dev_urandom() { |
| 114 |
Ok(n) => { |
| 115 |
assert_ne!(n, [0u8; 8]); |
| 116 |
} |
| 117 |
Err(err) if err.kind() != std::io::ErrorKind::NotFound => { |
| 118 |
panic!("{}", err); |
| 119 |
} |
| 120 |
_ => (), |
| 121 |
} |
| 122 |
} |
| 123 |
|
| 124 |
#[cfg(target_os = "linux")] |
| 125 |
#[test] |
| 126 |
fn test_getrandom() { |
| 127 |
match super::getrandom() { |
| 128 |
Ok(n) => { |
| 129 |
assert_ne!(n, [0u8; 8]); |
| 130 |
} |
| 131 |
// FIXME: Use Unsupported once we can depend on 1.53 |
| 132 |
Err(err) if err.kind() != std::io::ErrorKind::NotFound => { |
| 133 |
panic!("{}", err); |
| 134 |
} |
| 135 |
_ => (), |
| 136 |
} |
| 137 |
} |
| 138 |
} |
| 139 |
} |
| 140 |
|
| 141 |
#[cfg(windows)] |
| 142 |
mod windows { |
| 143 |
use std::io; |
| 144 |
|
| 145 |
/// Call BCryptGenRandom(), which is available since Windows Vista. |
| 146 |
pub fn bcrypt_gen_random() -> io::Result<[u8; 8]> { |
| 147 |
// SAFETY: BCryptGenRandom() fills the provided memory with the requested number of bytes |
| 148 |
// and returns 0 on success. In that case, all memory was written and is initialized now. |
| 149 |
unsafe { |
| 150 |
use std::{mem, ptr}; |
| 151 |
|
| 152 |
use crate::ffi::windows::*; |
| 153 |
|
| 154 |
let mut r = mem::MaybeUninit::<[u8; 8]>::uninit(); |
| 155 |
let res = BCryptGenRandom( |
| 156 |
ptr::null_mut(), |
| 157 |
r.as_mut_ptr() as *mut u8, |
| 158 |
8, |
| 159 |
BCRYPT_USE_SYSTEM_PREFERRED_RNG, |
| 160 |
); |
| 161 |
if res == 0 { |
| 162 |
Ok(r.assume_init()) |
| 163 |
} else { |
| 164 |
Err(io::Error::from_raw_os_error(res as i32)) |
| 165 |
} |
| 166 |
} |
| 167 |
} |
| 168 |
|
| 169 |
#[cfg(test)] |
| 170 |
mod test { |
| 171 |
#[test] |
| 172 |
fn test_bcrypt_gen_random() { |
| 173 |
let n = super::bcrypt_gen_random().unwrap(); |
| 174 |
assert_ne!(n, [0u8; 8]); |
| 175 |
} |
| 176 |
} |
| 177 |
} |
| 178 |
|
| 179 |
/// As fallback use a combination of the process ID and the current system time. |
| 180 |
fn fallback_rand() -> [u8; 8] { |
| 181 |
let now = std::time::SystemTime::now() |
| 182 |
.duration_since(std::time::SystemTime::UNIX_EPOCH) |
| 183 |
.unwrap() |
| 184 |
.as_nanos() |
| 185 |
.to_be_bytes(); |
| 186 |
let pid = std::process::id().to_be_bytes(); |
| 187 |
[ |
| 188 |
now[0] ^ now[15] ^ pid[0], |
| 189 |
now[1] ^ now[14] ^ pid[1], |
| 190 |
now[2] ^ now[13] ^ pid[2], |
| 191 |
now[3] ^ now[12] ^ pid[3], |
| 192 |
now[4] ^ now[11] ^ pid[0], |
| 193 |
now[5] ^ now[10] ^ pid[1], |
| 194 |
now[6] ^ now[9] ^ pid[2], |
| 195 |
now[7] ^ now[8] ^ pid[3], |
| 196 |
] |
| 197 |
} |
| 198 |
|
| 199 |
/// Returns a random'ish 64 bit value. |
| 200 |
pub fn rand() -> [u8; 8] { |
| 201 |
#[cfg(unix)] |
| 202 |
{ |
| 203 |
// Try getrandom syscall or otherwise first on Linux |
| 204 |
#[cfg(target_os = "linux")] |
| 205 |
{ |
| 206 |
if let Ok(r) = unix::getrandom() { |
| 207 |
return r; |
| 208 |
} |
| 209 |
} |
| 210 |
|
| 211 |
if let Ok(r) = unix::dev_urandom() { |
| 212 |
return r; |
| 213 |
} |
| 214 |
} |
| 215 |
#[cfg(windows)] |
| 216 |
{ |
| 217 |
if let Ok(r) = windows::bcrypt_gen_random() { |
| 218 |
return r; |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
fallback_rand() |
| 223 |
} |
| 224 |
|
| 225 |
#[cfg(test)] |
| 226 |
mod test { |
| 227 |
// While not a very useful test for randomness, we're mostly interested here |
| 228 |
// in whether the memory is initialized correctly and nothing crashes because |
| 229 |
// of the usage of unsafe code above. If the memory was not initialized fully |
| 230 |
// then this test would fail in e.g. valgrind. |
| 231 |
// |
| 232 |
// Technically, all zeroes could be returned as a valid random number but that's |
| 233 |
// extremely unlikely and more likely a bug in the code above. |
| 234 |
|
| 235 |
#[test] |
| 236 |
fn test_rand() { |
| 237 |
let n = super::rand(); |
| 238 |
assert_ne!(n, [0u8; 8]); |
| 239 |
} |
| 240 |
|
| 241 |
#[test] |
| 242 |
fn test_fallback_rand() { |
| 243 |
let n = super::fallback_rand(); |
| 244 |
assert_ne!(n, [0u8; 8]); |
| 245 |
} |
| 246 |
} |