Skip to content

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

Open
@JOE1994

Description

@JOE1994

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 👍

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions