Skip to content

Commit

Permalink
Fix potential vulnerability (#1)
Browse files Browse the repository at this point in the history
- 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
  • Loading branch information
Enet4 committed Jan 3, 2021
1 parent ff2b299 commit aabf556
Showing 1 changed file with 7 additions and 18 deletions.
25 changes: 7 additions & 18 deletions src/greedy.rs
Expand Up @@ -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<R> {
inner: R,
buf: Vec<u8>,
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit aabf556

Please sign in to comment.