From a14390c7451ac425b3f828704010021768a06850 Mon Sep 17 00:00:00 2001 From: Takeru Ohta Date: Tue, 19 Feb 2019 10:08:48 +0900 Subject: [PATCH] Fix buffer overflow bug See: https://github.com/sile/libflate/issues/21 --- src/lz77/default.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/lz77/default.rs b/src/lz77/default.rs index 36dd1e8..f11aae0 100644 --- a/src/lz77/default.rs +++ b/src/lz77/default.rs @@ -86,6 +86,9 @@ impl Lz77Encode for DefaultLz77Encoder { backward_distance: distance as u16, }); for k in (i..).take(length as usize).skip(1) { + if k >= end { + break; + } prefix_table.insert(prefix(&self.buf[k..]), k as u32); } i += length as usize; @@ -179,3 +182,28 @@ impl LargePrefixTable { None } } + +#[cfg(test)] +mod tests { + use super::*; + use deflate::symbol::Symbol; + + #[test] + // See: https://github.com/sile/libflate/issues/21 + fn issue21() { + let mut enc = DefaultLz77Encoder::new(); + let mut sink = Vec::new(); + enc.encode(b"aaaaa", &mut sink); + enc.flush(&mut sink); + assert_eq!( + sink, + vec![ + Symbol::Literal(97), + Symbol::Share { + length: 4, + distance: 1 + } + ] + ); + } +}