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

safe from_ffi API may read from unaligned pointer or uninitialized memory #1

Open
JOE1994 opened this issue Jan 7, 2021 · 0 comments

Comments

@JOE1994
Copy link

JOE1994 commented Jan 7, 2021

Hello 🦀 ,
we (Rust group @sslab-gatech) found a memory-safety/soundness issue in this crate while scanning Rust code on crates.io for potential vulnerabilities.

Issue Description

unsafe impl<T, U> FromFFi<*mut U> for Option<T>
where
T: FromFFi<U> + std::fmt::Debug,
{
fn from_ffi(v: *mut U) -> FFiResult<Self> {
unsafe {
match v.as_mut() {
Some(ptr) => Ok(Some(T::from_ffi(std::ptr::read(ptr))?)),
None => Ok(None),
}
}
}
}

Currently, the from_ffi API is a public API.
It is possible to use it to invoke the following undefined behavior in safe Rust programs.

  • std::ptr::read() on unaligned pointer
  • read from uninitialized memory.

Example

In the following program, there is no guarantee that ptr is an aligned pointer.
When it is fed to from_ffi as input, it is possible to ptr::read() from an unaligned pointer
(which is specified as undefined behavior here).

Also, ptr points to memory outside of x, so that reading from ptr can potentially read from uninitialized memory.
(which is also specified as undefined behavior here)

fn main() {
    let mut x: i8 = 0x61;
    let a: i8 = 0x66;
    let uninit: MaybeUninit<i16> = MaybeUninit::uninit();

    let ptr = &mut x as *mut i8 as *mut i64;
    let b: FFiResult<Option<i64>> = FromFFi::<*mut i64>::from_ffi(ptr);
    let z: i64 = b.unwrap().unwrap();

    println!("0x{:X}, 0x{:X}", z, a);
}

Program Output

0x205606661, 0x66

Suggested Fix

The users of from_ffi API need to ensure by themselves that the pointer fed to from_ffi is an aligned pointer & points to initialized memory. The from_ffi API should be marked as unsafe API.

Thank you for checking out this issue 👍

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

1 participant