Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unsound type casting in cast_slice #328

Open
shinmao opened this issue Jun 28, 2023 · 3 comments
Open

Unsound type casting in cast_slice #328

shinmao opened this issue Jun 28, 2023 · 3 comments

Comments

@shinmao
Copy link

shinmao commented Jun 28, 2023

The source of unsoundness

rendy/core/src/casts.rs

Lines 16 to 20 in 8e3054a

pub fn cast_slice<T>(slice: &[T]) -> &[u8] {
let len = std::mem::size_of::<T>() * slice.len();
let ptr = slice.as_ptr();
unsafe { std::slice::from_raw_parts(ptr as _, len) }
}

cast_slice would cast any type to byte slice which is unsound. e.g., If type T contains padding bytes, read the returned byte slice would lead to uninitialized memory read. Similar issue could happen in cast_vec.

To reproduce the bug

use rendy_core::cast_slice;

#[derive(Copy, Clone, Debug)]
pub struct A {
    a: i8,
    b: i32,
    c: i8,
}

fn main() {
    let int_array: [i32; 10] = [2; 10];
    let int_byte = cast_slice(&int_array);
    println!("{:?}", int_byte);     // it's ok to read it because i32 won't contain padding bytes

    let sa = A { a: 10, b: 11, c: 12 };
    let xsa = [sa; 10];
    let xsa_byte = cast_slice(&xsa);
    println!("{:?}", xsa_byte);   // it is dangerous to read it because struct A here contains padding bytes
}

run it with Miri

error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory

It is unsound to have UB happen in safe code.

Ideas about fixing the bug

Here I suggest to apply a trait bound such as Pod which could limit the type to be casted to byte slice.

@zakarumych
Copy link
Member

NoUninit would be enough.

@shinmao
Copy link
Author

shinmao commented Jun 28, 2023

@zakarumych Yup to solve uninitialized bytes issues specifically.

@shinmao
Copy link
Author

shinmao commented Jul 7, 2023

@zakarumych would you like me to post it to rustsec advisories?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants