posixutils-rs icon indicating copy to clipboard operation
posixutils-rs copied to clipboard

Unsoundness in open_at function

Open lwz23 opened this issue 11 months ago • 1 comments

Describe the bug The open_at function uses unsafe operations with a raw pointer (*const libc::c_char) to convert it into a CStr. However, the function does not validate the pointer's validity or ensure the string is null-terminated. This may lead to Undefined Behavior (UB) if the pointer is null, invalid, or not properly null-terminated. https://github.com/rustcoreutils/posixutils-rs/blob/895c4fab108f5f25dd2b8112168e0e5f9511f567/ftw/src/dir.rs#L79

pub fn open_at(
        dir_file_descriptor: &FileDescriptor,
        filename: *const libc::c_char,
    ) -> Result<Self, Error> {
        let file_descriptor = FileDescriptor::open_at(
            dir_file_descriptor,
            unsafe { CStr::from_ptr(filename) },
            libc::O_RDONLY,
        )
        .map_err(|e| Error::new(e, ErrorKind::Open))?;
        let dir = OwnedDir::new(file_descriptor).map_err(|e| Error::new(e, ErrorKind::OpenDir))?;
        Ok(dir)
    }

To Reproduce Steps to reproduce the behavior: Call the open_at function with a null pointer:

let dir_fd = FileDescriptor::new(...); // Assume this is valid
let null_ptr: *const libc::c_char = std::ptr::null();
let result = open_at(&dir_fd, null_ptr); // UB: Null pointer

Expected behavior The function should validate the input pointer to ensure it is non-null and points to a valid, null-terminated C string. It should gracefully handle invalid inputs and return an error instead of causing a crash or Undefined Behavior. Additional context Expected behavior includes: Validating that the filename pointer is not null before dereferencing it. Ensuring the memory pointed to by filename is null-terminated. Safely handling errors, such as invalid pointers or invalid C strings, by returning appropriate error messages instead of invoking UB.

lwz23 avatar Nov 27 '24 08:11 lwz23