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

Unsoundness in ptr_to_string may cause UB due to unsafe assumptions about pointer validity and string encoding #224

Open
lwz23 opened this issue Nov 27, 2024 · 1 comment

Comments

@lwz23
Copy link

lwz23 commented Nov 27, 2024

Description:
The ptr_to_string function uses CStr::from_ptr and str::from_utf8_unchecked to convert a raw pointer (*const c_char) to a String. However, it makes several unsafe assumptions about the validity and contents of the pointer. These assumptions can lead to Undefined Behavior (UB) if the pointer or the data it references does not meet the required conditions.

pub fn ptr_to_string(ptr: *const c_char) -> String {

pub fn ptr_to_string(ptr: *const c_char) -> String {
  unsafe {
    str::from_utf8_unchecked(CStr::from_ptr(ptr).to_bytes()).to_owned()
  }
}

Problem Description:

  1. Invalid Pointer:
    The function assumes that ptr is a valid, non-null pointer. If ptr is null or points to invalid memory, calling CStr::from_ptr(ptr) will result in UB.
  2. Missing Null-Termination:
    CStr::from_ptr(ptr) requires that the memory pointed to by ptr is null-terminated. If the memory is not properly null-terminated, the function may read beyond the allocated memory, leading to UB.
  3. Invalid UTF-8 Encoding:
    The function uses str::from_utf8_unchecked to interpret the byte slice as a UTF-8 string without checking its validity. If the data is not valid UTF-8, the function will cause UB.
    Steps to Reproduce:
    Provide a null pointer:
let null_pointer: *const c_char = std::ptr::null();
let result = ptr_to_string(null_pointer); // UB: Null pointer

Expected Behavior:
The function should validate the pointer and ensure it points to a valid, null-terminated C string.
The function should verify that the byte slice contains valid UTF-8 before converting it to a String.
Additional Notes:
The current implementation assumes that all inputs are valid, which makes the function unsafe. Adding proper validation will make the function robust and prevent potential crashes or UB.
This issue highlights common pitfalls when working with raw pointers and unsafe string conversions in Rust.

@lwz23
Copy link
Author

lwz23 commented Dec 1, 2024

ping?

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