sfmt icon indicating copy to clipboard operation
sfmt copied to clipboard

Potential unsoundness in `SFMT::pop64`

Open shinmao opened this issue 2 years ago • 1 comments

The source of unsoundness

Hi, we are the PhD researchers from SunLab. We found that pop64 might have unsound implementation. https://github.com/rust-math/sfmt/blob/7767d230942c7ad6f8ffbeb6733a935f2e3718b1/src/lib.rs#L81-L89 At line 85, p is aligned to 4 bytes as u32, but it was cast to u64 with stronger alignment requirement. Misaligned pointer dereference could lead to undefined behavior in safe function.

To reproduce the bug

use sfmt::SFMT;
use rand_core::{SeedableRng, RngCore};

fn main() {
    let sd: [u8; 4] = [10; 4];
    let mut smt = SFMT::from_seed(sd);
    let tmp = smt.next_u64();
    let tmp1 = smt.next_u64();
    let tmp1_addr = tmp1 as *mut u64 as usize;
    println!("{:x}", tmp1_addr);
    assert!(tmp1_addr % std::mem::align_of::<u64>() == 0);
}

to run with cargo run

thread 'main' panicked at 'assertion failed: tmp1_addr % std::mem::align_of::<u64>() == 0', src/main.rs:12:5

shinmao avatar Aug 26 '23 22:08 shinmao

This is also found at https://asan.saethlin.dev/ub?crate=sfmt&version=0.7.0

riking avatar Feb 27 '24 22:02 riking