Skip to content

Non-utf8 String can be created with TimeBuf::as_str #2305

@shinmao

Description

@shinmao

We consider that the function as_str can create a illegal string, which contains non-utf8 characters.

impl TimeBuf {
/// Represent this instance as standard string, serialized in a format compatible with
/// signature fields in Git commits, also known as anything parseable as [raw format](function::parse_header()).
pub fn as_str(&self) -> &str {
// SAFETY: We know that serialized times are pure ASCII, a subset of UTF-8.
// `buf` and `len` are written only by time-serialization code.
let time_bytes = self.buf.as_slice();
#[allow(unsafe_code)]
unsafe {
std::str::from_utf8_unchecked(time_bytes)
}
}

The reason is that TimeBuf implements the trait Write, which allows to write arbitrary bytes.
impl std::io::Write for TimeBuf {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.buf.write(buf)
}

Following is a simple PoC to prove this reachable undefined behavior:

fn main() {
    let mut buf = TimeBuf::default();
    buf.write(&[0xff]).unwrap();
    println!("{}", buf.as_str()); // print �
}

Therefore, the safety invariant for TimeBuf mentioned at line 31 can be broken here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    acknowledgedan issue is accepted as shortcoming to be fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions