Skip to content

Unsoundness in UnicodeString::as_string_ext #59

@lwz23

Description

@lwz23

Description:
The UnicodeString::as_string_ext function in the provided implementation is unsound and can lead to undefined behavior (UB) when the buffer field is a null pointer. The function directly dereferences buffer without checking its validity, which violates Rust's memory safety guarantees. This may result in crashes or UB when the code is executed.

PoC

use std::os::raw::{c_ushort};
use wchar::wchar_t;

pub struct UnicodeString {
    pub length: c_ushort,
    pub maximum_length: c_ushort,
    pub buffer: *const wchar_t,
}

impl UnicodeString {
    pub fn as_string_ext(&self, extension: [wchar_t; 12]) -> String {
        unsafe {
            let str_slice = std::slice::from_raw_parts(self.buffer, self.length as usize);
            String::from_utf16_lossy(str_slice)
        }
    }
}

fn main() {
    // Constructing a UnicodeString with a null pointer as the buffer
    let a = UnicodeString {
        length: 0,
        maximum_length: 0,
        buffer: std::ptr::null(),
    };

    // Calling as_string_ext with a null buffer
    println!("{}", a.as_string_ext([0; 12]));
}

Result

thread 'main' panicked at core\src\panicking.rs:223:5:
unsafe precondition(s) violated: slice::from_raw_parts requires the pointer to be aligned and non-null, and the total size of the slice not to exceed `isize::MAX`
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread caused non-unwinding panic. aborting.
error: process didn't exit successfully: `target\debug\lwz.exe` (exit code: 0xc0000409, STATUS_STACK_BUFFER_OVERRUN)

The function does not validate the buffer pointer before using it in the std::slice::from_raw_parts call. This is unsafe and violates Rust’s safety guarantees.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions