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

Fix UTF-8 unsoundness in string::merge #194

Merged
merged 3 commits into from
Jun 11, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 14 additions & 9 deletions src/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
//! Meant to be used only from `Message` implementations.

use std::cmp::min;
use std::str;
use std::mem;
use std::u32;
use std::usize;

Expand Down Expand Up @@ -728,14 +728,10 @@ pub mod string {
where
B: Buf,
{
unsafe {
// String::as_mut_vec is unsafe because it doesn't check that the bytes
// inserted into it the resulting vec are valid UTF-8. We check
// explicitly in order to ensure this is safe.
super::bytes::merge(wire_type, value.as_mut_vec(), buf)?;
str::from_utf8(value.as_bytes())
.map_err(|_| DecodeError::new("invalid string value: data is not UTF-8 encoded"))?;
}
let mut value_bytes = mem::replace(value, String::new()).into_bytes();
bytes::merge(wire_type, &mut value_bytes, buf)?;
*value = String::from_utf8(value_bytes)
.map_err(|_| DecodeError::new("invalid string value: data is not UTF-8 encoded"))?;
Ok(())
}

Expand Down Expand Up @@ -1307,6 +1303,15 @@ mod test {
}
}

#[test]
fn string_merge_failure() {
let mut s = String::new();
let mut buf = Cursor::new(b"\x80\x80");
let r = string::merge(WireType::LengthDelimited, &mut s, &mut buf);
r.expect_err("must be an error");
assert!(s.is_empty());
}

#[test]
fn varint() {
fn check(value: u64, encoded: &[u8]) {
Expand Down