Skip to content

Unsound usages of unsafe implementation about c_void #5

Description

@llooFlashooll

Hi, I am scanning this crate in the latest version using my own static analyzer tool.

Unsafe pointer conversion is found at:

pub unsafe fn vsprintf_raw<V>(format: *const c_char,
                              va_list: *mut V) -> Result<Vec<u8>> {
    let list_ptr = va_list  as *mut c_void;

    let mut buffer = Vec::new();
    buffer.extend([0u8; INITIAL_BUFFER_SIZE].iter().cloned());

    loop {
        let character_count = vsnprintf_wrapper(
            buffer.as_mut_ptr(), buffer.len(), format, list_ptr
        );

        // Check for errors.
        if character_count == -1 {
            // C does not require vsprintf to set errno, but POSIX does.
            //
            // Default handling will just generate an 'unknown' IO error
            // if no errno is set.
            return Err(Error::last_os_error());
        } else {
            assert!(character_count >= 0);
            let character_count = character_count as usize;

            let current_max = buffer.len() - 1;

            // Check if we had enough room in the buffer to fit everything.
            if character_count > current_max {
                let extra_space_required = character_count - current_max;

                // Reserve enough space and try again.
                buffer.extend(repeat(0).take(extra_space_required as usize));
                continue;
            } else { // We fit everything into the buffer.
                // Truncate the buffer up until the null terminator.
                buffer = buffer.into_iter()
                               .take_while(|&b| b != 0)
                               .collect();
                break;
            }
        }
    }

    Ok(buffer)
}

This unsound implementation would create memory issues such as overflow, underflow, or misalignment. The attacker can manipulate the argument va_list associated with the c_void pointer with an unexpected type or layout, which can lead to an out-of-bounds memory access bug. The c_void pointer is passed through the formatting FFI path (vsnprintf_wrapper), which can further corrupt the C/C++ code.

This would cause undefined behaviors in Rust. Adversaries can manipulate the associated argument to cause memory safety bugs. I am reporting this issue for your attention.

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