grr icon indicating copy to clipboard operation
grr copied to clipboard

Soundness Issue: `as_u8_slice` creates a reference to uninitialized memory

Open lewismosciski opened this issue 2 months ago • 0 comments

Hello,

First, thank you for your work on the grr crate.

I believe I have identified a soundness issue in the as_u8_slice function. The function creates a &[u8] slice that can include uninitialized padding bytes from the source data. According to Rust's official guarantees, creating a safe reference to uninitialized memory is immediate Undefined Behavior (UB).

This makes any safe API that uses this function to view padded structs unsound.

https://github.com/msiglreith/grr/blob/02c831643ac714daf1988a9091676084ed37d7cd/src/lib.rs#L145-L148

POC:

use::grr::as_u8_slice;

struct PaddedStruct {
    _field1: u8,
    _field2: u32,
}

fn main() {
    let data = [PaddedStruct { _field1: 10, _field2: 20 }];
    let byte_slice = as_u8_slice(&data);
    println!("Byte slice: {:?}", byte_slice);
}

verified with miri:

cuu@ccuu-H3CDesk-D500t:~/Desktop/rust/test1$ cargo +nightly miri run
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.01s
     Running `/home/ccuu/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/bin/cargo-miri runner target/miri/x86_64-unknown-linux-gnu/debug/test1`
error: Undefined Behavior: reading memory at alloc131[0x5..0x6], but memory is uninitialized at [0x5..0x6], and this operation requires initialized memory
   --> /home/ccuu/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/fmt/num.rs:599:5
    |
599 |     impl_Display!(i8, u8, i16, u16, i32, u32, i64, u64, isize, usize; as u64 into display_u64);
    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Undefined Behavior occurred here
    |
    = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
    = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information

lewismosciski avatar Oct 15 '25 09:10 lewismosciski