Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions newsfragments/5008.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix `PyString::from_object`, avoid out of bounds reads by null terminating the `encoding` and `errors` parameters
28 changes: 28 additions & 0 deletions src/types/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use crate::types::PyBytes;
use crate::IntoPy;
use crate::{ffi, Bound, Py, PyAny, PyResult, Python};
use std::borrow::Cow;
use std::ffi::CString;
use std::str;

/// Deprecated alias for [`PyString`].
Expand Down Expand Up @@ -216,6 +217,8 @@ impl PyString {
encoding: &str,
errors: &str,
) -> PyResult<Bound<'py, PyString>> {
let encoding = CString::new(encoding)?;
let errors = CString::new(errors)?;
unsafe {
ffi::PyUnicode_FromEncodedObject(
src.as_ptr(),
Expand Down Expand Up @@ -670,6 +673,31 @@ mod tests {
})
}

#[test]
fn test_string_from_object() {
Python::with_gil(|py| {
let py_bytes = PyBytes::new(py, b"ab\xFFcd");

let py_string = PyString::from_object(&py_bytes, "utf-8", "ignore").unwrap();

let result = py_string.to_cow().unwrap();
assert_eq!(result, "abcd");
});
}

#[test]
fn test_string_from_obect_with_invalid_encoding_errors() {
Python::with_gil(|py| {
let py_bytes = PyBytes::new(py, b"abcd");

let result = PyString::from_object(&py_bytes, "utf\0-8", "ignore");
assert!(result.is_err());

let result = PyString::from_object(&py_bytes, "utf-8", "ign\0ore");
assert!(result.is_err());
});
}

#[test]
#[cfg(not(any(Py_LIMITED_API, PyPy)))]
fn test_string_data_ucs1() {
Expand Down
Loading