syd 3.41.7

rock-solid application kernel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//
// Syd: rock-solid application kernel
// src/rng.rs: OS Random Number Generator (RNG) interface
//
// Copyright (c) 2023, 2024, 2025 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

//! Set of functions to manage the OS Random Number Generator (RNG)

use std::{
    ops::RangeInclusive,
    os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd, RawFd},
};

use libc::{c_int, dup3, GRND_RANDOM};
use nix::{
    errno::Errno,
    fcntl::{OFlag, ResolveFlag},
    sys::resource::{getrlimit, Resource},
    unistd::{close, UnlinkatFlags},
    NixPath,
};

use crate::{
    cookie::safe_unlinkat,
    fs::{is_active_fd, retry_on_eintr, safe_open},
    log::{now, Tm},
    path::{XPath, XPathBuf, PATH_MAX},
};

/// RAII guard that disables pthread cancellation for the current thread
/// and restores the previous state on drop. Uses pthread_setcancelstate(3).
#[must_use = "hold the guard to keep cancellation disabled"]
pub struct CancelGuard(c_int);

const _PTHREAD_CANCEL_ENABLE: c_int = 0;
const PTHREAD_CANCEL_DISABLE: c_int = 1;

// Libc crate does not define this symbol explicitly yet.
extern "C" {
    fn pthread_setcancelstate(state: c_int, oldstate: *mut c_int) -> c_int;
}

impl CancelGuard {
    /// Acquire the guard by disabling pthread cancellation for this thread.
    ///
    /// Returns a guard that will restore the previous state when dropped.
    pub fn acquire() -> Result<Self, Errno> {
        let mut old: c_int = 0;

        // SAFETY: We call pthread_setcancelstate(3) for the current thread.
        // - PTHREAD_CANCEL_DISABLE is a valid constant.
        // - Second arg is a valid, writable pointer to store the previous state.
        // - This does not move or alias Rust values; it only flips the thread-local flag.
        let err = unsafe { pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &raw mut old) };

        // POSIX returns error code directly (not via errno).
        if err == 0 {
            Ok(Self(old))
        } else {
            Err(Errno::from_raw(err))
        }
    }
}

impl Drop for CancelGuard {
    fn drop(&mut self) {
        // SAFETY: Restore the exact state captured at construction
        // for the current thread. The second parameter can be NULL
        // when we don't care about the previous value.
        unsafe {
            pthread_setcancelstate(self.0, std::ptr::null_mut());
        }
    }
}

/// Public trait for unsigned integers that support uniform sampling without widening.
pub trait RandUint: Copy + Ord {
    /// Additive zero.
    const ZERO: Self;
    /// Additive one.
    const ONE: Self;
    /// Maximum value.
    const MAX: Self;

    /// Draw a uniformly random value of this type using the OS RNG for exactly this width.
    fn rand_from_os() -> Result<Self, Errno>;

    /// Checked add returning None on overflow.
    fn checked_add(self, rhs: Self) -> Option<Self>;
    /// Checked sub returning None on underflow.
    fn checked_sub(self, rhs: Self) -> Option<Self>;
    /// Checked mul returning None on overflow.
    fn checked_mul(self, rhs: Self) -> Option<Self>;

    /// Euclidean division returning None if rhs is zero.
    fn div_euclid_opt(self, rhs: Self) -> Option<Self>;
}

macro_rules! impl_rand_uint {
    ($($t:ty),* $(,)?) => {$(
        impl RandUint for $t {
            const ZERO: Self = 0;
            const ONE: Self = 1;
            const MAX: Self = <$t>::MAX;

            #[inline]
            fn rand_from_os() -> Result<Self, Errno> {
                // Read exactly size_of::<$t>() bytes, and interpret in native endian.
                let mut buf = [0u8; { std::mem::size_of::<$t>() }];
                fillrandom(&mut buf)?;
                Ok(<$t>::from_ne_bytes(buf))
            }

            #[inline] fn checked_add(self, rhs: Self) -> Option<Self> { self.checked_add(rhs) }
            #[inline] fn checked_sub(self, rhs: Self) -> Option<Self> { self.checked_sub(rhs) }
            #[inline] fn checked_mul(self, rhs: Self) -> Option<Self> { self.checked_mul(rhs) }

            #[inline]
            fn div_euclid_opt(self, rhs: Self) -> Option<Self> {
                if rhs == 0 { None } else { Some(self.div_euclid(rhs)) }
            }
        }
    )*};
}
impl_rand_uint!(u8, u16, u32, u64, u128, usize);

/// Return a uniform random unsigned integer in the inclusive range,
/// using OS randomness with rejection sampling.
pub fn randint<T>(range: RangeInclusive<T>) -> Result<T, Errno>
where
    T: RandUint,
{
    let (lo, hi) = range.into_inner();

    // Reject inverted or one-point ranges as invalid input.
    if lo >= hi {
        return Err(Errno::EINVAL);
    }

    // Full-domain path returns raw OS bytes for exact type width.
    if lo == T::ZERO && hi == T::MAX {
        return T::rand_from_os();
    }

    // Compute span = (hi - lo) + 1 with checked ops to avoid overflow.
    let span = hi
        .checked_sub(lo)
        .ok_or(Errno::EOVERFLOW)?
        .checked_add(T::ONE)
        .ok_or(Errno::EOVERFLOW)?;

    // Compute accept_top = floor(MAX / span) * span,
    // using only checked ops and Euclidean division.
    let k = T::MAX.div_euclid_opt(span).ok_or(Errno::EOVERFLOW)?;
    let accept_top = k.checked_mul(span).ok_or(Errno::EOVERFLOW)?;

    // Draw until r < accept_top so the mapping is unbiased.
    loop {
        let r = T::rand_from_os()?;
        if r < accept_top {
            // Compute off = r - floor(r / span) * span without remainder operators.
            let q = r.div_euclid_opt(span).ok_or(Errno::EOVERFLOW)?;
            let qspan = q.checked_mul(span).ok_or(Errno::EOVERFLOW)?;
            let off = r.checked_sub(qspan).ok_or(Errno::EOVERFLOW)?;
            let v = lo.checked_add(off).ok_or(Errno::EOVERFLOW)?;
            return Ok(v);
        }
    }
}

/// Return a random unprivileged port number using the OS RNG.
#[inline]
pub fn randport() -> Result<u16, Errno> {
    randint(1025u16..=0xFFFF)
}

/// Get secure bytes using the OS random number generator.
pub fn getrandom(size: usize) -> Result<Vec<u8>, Errno> {
    if size == 0 {
        // SAFETY:
        // Return EINVAL on zero length which is a common case of error.
        return Err(Errno::EINVAL);
    }

    let mut buf = Vec::new();
    if buf.try_reserve(size).is_err() {
        return Err(Errno::ENOMEM);
    }
    buf.resize(size, 0);

    fillrandom(&mut buf)?;
    Ok(buf)
}

/// Fill the given buffer using the OS random number generator.
pub fn fillrandom(buf: &mut [u8]) -> Result<(), Errno> {
    // SAFETY: Ensure buffer is not empty,
    // which is a common case of error.
    let siz = buf.len();
    if siz == 0 {
        return Err(Errno::EINVAL);
    }

    // Disable pthread cancellation within this critical section.
    // Restored automatically when guard is dropped.
    let guard = CancelGuard::acquire()?;

    let mut n = 0;
    while n < siz {
        let ptr = &mut buf[n..];
        let ptr = ptr.as_mut_ptr().cast();
        let siz = siz.checked_sub(n).ok_or(Errno::EOVERFLOW)?;

        n = n
            .checked_add(
                retry_on_eintr(|| {
                    // SAFETY: In libc we trust.
                    Errno::result(unsafe { libc::getrandom(ptr, siz, GRND_RANDOM) })
                })?
                .try_into()
                .or(Err(Errno::EINVAL))?,
            )
            .ok_or(Errno::EOVERFLOW)?;
    }

    // End of critical section.
    drop(guard);

    Ok(())
}

/// Duplicate the file descriptor to a random fd.
///
/// Valid flags:
/// - O_EXCL: closes oldfd after successful duplication.
/// - All other flags are passed to dup3(2), ie O_CLOEXEC.
pub fn duprand(oldfd: RawFd, mut flags: OFlag) -> Result<RawFd, Errno> {
    let range_start = 7u64;
    let (range_end, _) = getrlimit(Resource::RLIMIT_NOFILE)?;
    #[expect(clippy::unnecessary_cast)]
    let range_end = range_end.saturating_sub(1) as u64;

    // SAFETY: Cap to a sane maximum because sufficiently big values
    // of the hard limit tend to return ENOMEM.
    let range_end = range_end.min(0x10000);
    if range_end <= range_start {
        return Err(Errno::EMFILE);
    }
    let range = range_start..=range_end;

    // Close old fd if O_EXCL is given,
    // pass the rest of the flags to dup3.
    let close_old = flags.contains(OFlag::O_EXCL);
    flags.remove(OFlag::O_EXCL);

    // SAFETY: To make this file descriptor harder to spot by an
    // attacker we duplicate it to a random fd number.
    for _ in range.clone() {
        #[expect(clippy::cast_possible_truncation)]
        let fd_rand = randint(range.clone())? as RawFd;

        // SAFETY: fd only used after validation.
        let fd_rand = unsafe { BorrowedFd::borrow_raw(fd_rand) };

        // Check if the slot is free.
        // This is arguably subject to race but since this is solely
        // used for fds at startup, we don't really care.
        if is_active_fd(fd_rand) {
            continue;
        }

        match retry_on_eintr(|| {
            // SAFETY: In libc we trust.
            Errno::result(unsafe { dup3(oldfd, fd_rand.as_raw_fd(), flags.bits()) })
        }) {
            Ok(_) => {
                if close_old {
                    let _ = close(oldfd);
                }
                return Ok(fd_rand.as_raw_fd());
            }
            Err(Errno::EMFILE) => return Err(Errno::EMFILE),
            Err(_) => {}
        }
    }

    Err(Errno::EBADF)
}

/// Create a unique temporary file in `dirfd` relative to `prefix`
/// unlink the file and return its file descriptor. Unlike libc's
/// mkstemp(3) function the template here does not have to end with any
/// number of `X` characters. The function appends an implementation
/// defined number of random characters after `prefix`. `prefix` must
/// not start with the `/` character and not be longer than `PATH_MAX`
/// characters long. It is OK for prefix to be empty.
/// If `dirfd` supports the `O_TMPFILE` operation, an unnamed temporary
/// file is created instead with `O_TMPFILE|O_EXCL`.
pub fn mkstempat<Fd: AsFd>(dirfd: Fd, prefix: &XPath) -> Result<OwnedFd, Errno> {
    const MAX_TCOUNT: usize = 8;
    const SUFFIX_LEN: usize = 128;
    const CHARSET: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    // Step 1: Attempt to use O_TMPFILE|O_EXCL which is safer.
    let mut flags = OFlag::O_TMPFILE | OFlag::O_EXCL | OFlag::O_RDWR;
    match safe_open(&dirfd, XPath::from_bytes(b"."), flags, ResolveFlag::empty()) {
        Ok(fd) => return Ok(fd),
        Err(Errno::EISDIR | Errno::ENOENT | Errno::EOPNOTSUPP) => {}
        Err(errno) => return Err(errno),
    }

    // Step 2: Fallback to random name generation.
    flags.remove(OFlag::O_TMPFILE);
    flags.insert(OFlag::O_CREAT);
    if prefix.is_absolute() {
        return Err(Errno::EINVAL);
    } else if prefix.len().saturating_sub(SUFFIX_LEN) > PATH_MAX {
        return Err(Errno::ENAMETOOLONG);
    }

    let mut attempts = 0;
    let mut rng_data = [0u8; SUFFIX_LEN];
    #[expect(clippy::arithmetic_side_effects)]
    loop {
        attempts += 1;
        if attempts > MAX_TCOUNT {
            // Too many collisions.
            return Err(Errno::EEXIST);
        }

        // Fill with random bytes.
        fillrandom(&mut rng_data)?;

        // Map bytes to characters.
        let mut base = XPathBuf::with_capacity(prefix.len() + SUFFIX_LEN);
        base.append_bytes(prefix.as_bytes());
        for &b in &rng_data {
            base.append_byte(CHARSET[(b as usize) % CHARSET.len()]);
        }

        match safe_open(&dirfd, &base, flags, ResolveFlag::empty()) {
            Ok(fd) => {
                safe_unlinkat(dirfd, &base, UnlinkatFlags::NoRemoveDir)?;
                return Ok(fd);
            }
            Err(Errno::EEXIST) => {
                // Try again with a new random sequence.
                continue;
            }
            Err(errno) => return Err(errno),
        }
    }
}

/// Generate a random Linux kernel version string.
pub fn rand_version() -> Result<String, Errno> {
    const VERMAGICS: &[&str] = &[
        "SMP",
        "SMP PREEMPT",
        "SMP PREEMPT_DYNAMIC",
        "SMP PREEMPT_RT",
    ];
    const MONTHS: &[&str] = &[
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
    ];
    const WKDAYS: &[&str] = &["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

    // Subtract a random number of seconds within ~last year.
    const TS_WINDOW: u64 = 366 * 86_400;
    let now = now();
    let offset: u64 = randint(0..=TS_WINDOW)?;
    let target: i64 = now
        .saturating_sub(offset)
        .try_into()
        .or(Err(Errno::EOVERFLOW))?;

    // Break down that instant.
    let tm = Tm::try_from(target)?;

    // Randomize build number and PREEMPT variant.
    let build_no = randint(1u8..=64)?;
    #[expect(clippy::arithmetic_side_effects)]
    let vermagic = VERMAGICS[randint(0usize..=(VERMAGICS.len() - 1))?];

    // Determine version month and day.
    #[expect(clippy::arithmetic_side_effects)]
    #[expect(clippy::cast_sign_loss)]
    let mon = MONTHS[(tm.month() - 1) as usize];
    #[expect(clippy::cast_sign_loss)]
    let wday = WKDAYS[tm.weekday() as usize];
    let mday = tm.day();
    let hh = tm.hour();
    let mm = tm.minute();
    let ss = tm.second();
    let year = tm.year();

    Ok(format!(
        "#{build_no} {vermagic} {wday} {mon} {mday:>2} {hh:02}:{mm:02}:{ss:02} UTC {year}",
    ))
}

#[cfg(test)]
mod tests {
    use std::fmt::Debug;

    use super::*;

    // Check basic API functions for sanity

    #[test]
    fn test_fillrandom() {
        assert_eq!(fillrandom(&mut []), Err(Errno::EINVAL));

        assert_eq!(fillrandom(&mut [0u8; 257]), Ok(()));
    }

    #[test]
    fn test_getrandom() {
        assert_eq!(getrandom(0), Err(Errno::EINVAL));

        let result = getrandom(257);
        assert!(result.is_ok(), "result:{result:?}");
    }

    // Test helpers

    fn draw<T: RandUint + Debug>(lo: T, hi: T) -> T {
        match randint::<T>(lo..=hi) {
            Ok(v) => v,
            Err(e) => panic!("randint failed for [{:?},{:?}] -> {:?}", lo, hi, e),
        }
    }

    fn sample<T: RandUint + Debug>(lo: T, hi: T, n: usize) -> Vec<T> {
        (0..n).map(|_| draw::<T>(lo, hi)).collect()
    }

    fn all_in_range<T: RandUint + Debug>(xs: &[T], lo: T, hi: T) -> bool {
        xs.iter().all(|&v| v >= lo && v <= hi)
    }

    // API checks

    #[test]
    fn test_randint_invalid_u8() {
        assert!(matches!(randint::<u8>(200..=100), Err(Errno::EINVAL)));
    }

    #[test]
    fn test_randint_invalid_u16() {
        assert!(matches!(randint::<u16>(5000..=4999), Err(Errno::EINVAL)));
    }

    #[test]
    fn test_randint_invalid_u32() {
        assert!(matches!(randint::<u32>(42..=41), Err(Errno::EINVAL)));
    }

    #[test]
    fn test_randint_invalid_u64() {
        assert!(matches!(randint::<u64>(999..=998), Err(Errno::EINVAL)));
    }

    #[test]
    fn test_randint_invalid_u128() {
        assert!(matches!(randint::<u128>(500..=499), Err(Errno::EINVAL)));
    }

    #[test]
    fn test_randint_invalid_usize() {
        assert!(matches!(randint::<usize>(100..=99), Err(Errno::EINVAL)));
    }

    #[test]
    fn test_randint_onepoint_u8() {
        assert!(matches!(randint::<u8>(77..=77), Err(Errno::EINVAL)));
    }

    #[test]
    fn test_randint_onepoint_u16() {
        assert!(matches!(randint::<u16>(31337..=31337), Err(Errno::EINVAL)));
    }

    #[test]
    fn test_randint_onepoint_u32() {
        assert!(matches!(
            randint::<u32>(1_000_000..=1_000_000),
            Err(Errno::EINVAL)
        ));
    }

    #[test]
    fn test_randint_onepoint_u64() {
        assert!(matches!(
            randint::<u64>(123456789..=123456789),
            Err(Errno::EINVAL)
        ));
    }

    #[test]
    fn test_randint_onepoint_u128() {
        assert!(matches!(randint::<u128>(999..=999), Err(Errno::EINVAL)));
    }

    #[test]
    fn test_randint_onepoint_usize() {
        assert!(matches!(randint::<usize>(4242..=4242), Err(Errno::EINVAL)));
    }

    #[test]
    fn test_randint_fulldomain_u8_inbounds() {
        let xs = sample::<u8>(u8::MIN, u8::MAX, 4096);
        assert!(all_in_range(&xs, u8::MIN, u8::MAX));
    }

    #[test]
    fn test_randint_fulldomain_u16_inbounds() {
        let xs = sample::<u16>(u16::MIN, u16::MAX, 2048);
        assert!(all_in_range(&xs, u16::MIN, u16::MAX));
    }

    #[test]
    fn test_randint_fulldomain_u32_inbounds() {
        let xs = sample::<u32>(u32::MIN, u32::MAX, 2048);
        assert!(all_in_range(&xs, u32::MIN, u32::MAX));
    }

    #[test]
    fn test_randint_fulldomain_u64_inbounds() {
        let xs = sample::<u64>(u64::MIN, u64::MAX, 1024);
        assert!(all_in_range(&xs, u64::MIN, u64::MAX));
    }

    #[test]
    fn test_randint_fulldomain_u128_inbounds() {
        let xs = sample::<u128>(u128::MIN, u128::MAX, 256);
        assert!(all_in_range(&xs, u128::MIN, u128::MAX));
    }

    #[test]
    fn test_randint_fulldomain_usize_inbounds() {
        let xs = sample::<usize>(usize::MIN, usize::MAX, 1024);
        assert!(all_in_range(&xs, usize::MIN, usize::MAX));
    }

    #[test]
    fn test_randint_u8_nearmax_inbounds() {
        let lo = u8::MAX.saturating_sub(15);
        let xs = sample::<u8>(lo, u8::MAX, 2000);
        assert!(all_in_range(&xs, lo, u8::MAX));
    }

    #[test]
    fn test_randint_u16_nearmax_inbounds() {
        let lo = u16::MAX.saturating_sub(1023);
        let xs = sample::<u16>(lo, u16::MAX, 4000);
        assert!(all_in_range(&xs, lo, u16::MAX));
    }

    #[test]
    fn test_randint_u32_nearmax_inbounds() {
        let lo = u32::MAX.saturating_sub(1000);
        let xs = sample::<u32>(lo, u32::MAX, 3000);
        assert!(all_in_range(&xs, lo, u32::MAX));
    }

    #[test]
    fn test_randint_u64_nearmax_inbounds() {
        let lo = u64::MAX.saturating_sub(1000);
        let xs = sample::<u64>(lo, u64::MAX, 3000);
        assert!(all_in_range(&xs, lo, u64::MAX));
    }

    #[test]
    fn test_randint_u128_nearmax_inbounds() {
        let lo = u128::MAX.saturating_sub(1000);
        let xs = sample::<u128>(lo, u128::MAX, 2000);
        assert!(all_in_range(&xs, lo, u128::MAX));
    }

    #[test]
    fn test_randint_usize_nearmax_inbounds() {
        let lo = usize::MAX.saturating_sub(1000);
        let xs = sample::<usize>(lo, usize::MAX, 3000);
        assert!(all_in_range(&xs, lo, usize::MAX));
    }
}