From aabf5562f8c6374ab30f615b28e0cff9b5c79e5f Mon Sep 17 00:00:00 2001 From: Eduardo Pinho Date: Sun, 3 Jan 2021 14:21:17 +0000 Subject: [PATCH] Fix potential vulnerability (#1) - Implementations of Read still can try to read `buf` on `read`, even though they shouldn't - also derive Debug and Clone for GreedyAccessReader - all uses of unsafe were removed --- src/greedy.rs | 25 +++++++------------------ 1 file changed, 7 insertions(+), 18 deletions(-) diff --git a/src/greedy.rs b/src/greedy.rs index 3627daf..6e07d88 100644 --- a/src/greedy.rs +++ b/src/greedy.rs @@ -15,6 +15,7 @@ use std::ops::RangeBounds; /// [`std::io::BufReader`]: https://doc.rust-lang.org/std/io/struct.BufReader.html /// [`new`]: ./struct.GreedyAccessReader.html#method.new /// [`with_capacity`]: ./struct.GreedyAccessReader.html#method.with_capacity +#[derive(Debug, Clone)] pub struct GreedyAccessReader { inner: R, buf: Vec, @@ -197,26 +198,14 @@ where } let b = self.buf.len(); - let buf = unsafe { - // safe because it's within the buffer's limits - // and we won't be reading uninitialized memory - std::slice::from_raw_parts_mut( - self.buf.as_mut_ptr().add(b), - self.buf.capacity() - b) - }; + self.buf.resize(self.buf.capacity(), 0); + let buf = &mut self.buf[b..]; + let o = self.inner.read(buf)?; - match self.inner.read(buf) { - Ok(o) => { - unsafe { - // reset the size to include the written portion, - // safe because the extra data is initialized - self.buf.set_len(b + o); - } + // truncate to exclude non-written portion + self.buf.truncate(b + o); - Ok(&self.buf[self.consumed..]) - } - Err(e) => Err(e), - } + Ok(&self.buf[self.consumed..]) } fn consume(&mut self, amt: usize) {