Skip to content

Commit

Permalink
Fixes datrs#3: Crashes found by Honggfuzz
Browse files Browse the repository at this point in the history
  • Loading branch information
khernyo committed Jun 5, 2018
1 parent 7f0fe2b commit 2b6e1e7
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
22 changes: 20 additions & 2 deletions src/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ pub struct Header {
pub hash_type: HashType,
}

const HEADER_LENGTH: usize = 32;
const MAX_ALGORITHM_NAME_LENGTH: usize = HEADER_LENGTH - 8;

impl Header {
/// Create a new `Header`.
pub fn new(
Expand Down Expand Up @@ -134,11 +137,26 @@ impl Header {
let hash_name_len = rdr.read_u8().unwrap() as usize;
let current = rdr.position() as usize;

ensure!(
hash_name_len <= MAX_ALGORITHM_NAME_LENGTH,
"Algorithm name is too long: {} (max: {})",
hash_name_len,
MAX_ALGORITHM_NAME_LENGTH
);

let hash_name_upper = current + hash_name_len;
ensure!(
buffer.len() >= hash_name_upper,
"Broken parser: algorithm name is out of bounds: {} {}",
hash_name_upper,
buffer.len()
);

let buf_slice = &buffer[current..hash_name_upper];
rdr.set_position(hash_name_upper as u64 + 1);
let algo = ::std::str::from_utf8(buf_slice)
.expect("The algorithm string was invalid utf8 encoded");
let algo = ::std::str::from_utf8(buf_slice).map_err(|e| {
format_err!("The algorithm string was invalid utf8 encoded: {:?}", e)
})?;

let hash_type = match algo {
"BLAKE2b" => HashType::BLAKE2b,
Expand Down
11 changes: 11 additions & 0 deletions tests/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,14 @@ fn to_vec() {
]
);
}

#[test]
fn issue_3() {
// https://github.com/datrs/sleep-parser/issues/3

let data = b"\x05\x02W\x01\x00\xb0\xb0\xb0\xb0\xb0\xb0\xb0\xb0\xb0\xb0\xb0\xfb\x03p\xb0\xb0\xb0\xb0\xb0\xb0\xb0\xb0\xbb9\xb0\xf5\xf5";
assert!(Header::from_vec(data).is_err());

let data = b"\x05\x02W\x01\x00\x00\x00\x12\x12\x12\x00\x00S\xc3\xcf\x8a2\xcc\xd1\xce9\xc4K\x9343\x00602\xb5\x07";
assert!(Header::from_vec(data).is_err());
}

0 comments on commit 2b6e1e7

Please sign in to comment.