Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unsoundness in BufReader with a broken inner Read impl #120603

Closed
conradludgate opened this issue Feb 3, 2024 · 2 comments · Fixed by #120607 or #120660
Closed

Unsoundness in BufReader with a broken inner Read impl #120603

conradludgate opened this issue Feb 3, 2024 · 2 comments · Fixed by #120607 or #120660
Assignees
Labels
A-io Area: `std::io`, `std::fs`, `std::net` and `std::path` C-bug Category: This is a bug. I-unsound Issue: A soundness hole (worst kind of bug), see: https://en.wikipedia.org/wiki/Soundness T-libs Relevant to the library team, which will review and decide on the PR/issue.

Comments

@conradludgate
Copy link
Contributor

conradludgate commented Feb 3, 2024

I tried this code:

(source: @davidzeng0 from the Community Discord server)
https://play.rust-lang.org/?version=stable&mode=release&edition=2021&gist=198b86fbcfb8144e6fbb39d037f95f4e

use std::io::{Read, BufReader, Result};

pub struct MalformedRead {}

impl Read for MalformedRead {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        Ok(buf.len() * 20)
    }
}

fn main() {
    let mut reader = BufReader::new(MalformedRead {});
    let mut buf = [0u8; 1024];
    
    for _ in 0..8 {
        let read = reader.read(&mut buf).unwrap();
        dbg!(read);
    }

    reader.read(&mut buf).unwrap();
    dbg!(buf);
}

I expected to see this happen: panic, out of bounds read

Instead, this happened:

In debug: SEGMENTATION VIOLATION
In release: Heap buffer overflow
In miri: Undefined Behavior: out-of-bounds pointer use: alloc893 has size 8192, so pointer to 163840 bytes starting at offset 0 is out-of-bounds

Meta

Stable (1.75.0) and Nightly (1.77.0-nightly 2024-02-01 bf3c6c5) have the issue.

Issue

BufReader uses read_buf to read from the Reader, using the BorrowedBuf's len as the filled value.

reader.read_buf(buf.unfilled())?;
self.pos = 0;
self.filled = buf.len();
self.initialized = buf.init_len();

The default_read_buf function calls advance(n) with the dodgy read amount.

let n = read(cursor.ensure_init().init_mut())?;
unsafe {
// SAFETY: we initialised using `ensure_init` so there is no uninit data to advance to.
cursor.advance(n);
}

BufReader uses the filled value as the upper bound of the read buffer.

unsafe { MaybeUninit::slice_assume_init_ref(self.buf.get_unchecked(self.pos..self.filled)) }

@conradludgate conradludgate added the C-bug Category: This is a bug. label Feb 3, 2024
@rustbot rustbot added the needs-triage This issue may need triage. Remove it if it has been sufficiently triaged. label Feb 3, 2024
@Noratrieb Noratrieb added I-unsound Issue: A soundness hole (worst kind of bug), see: https://en.wikipedia.org/wiki/Soundness T-libs Relevant to the library team, which will review and decide on the PR/issue. A-io Area: `std::io`, `std::fs`, `std::net` and `std::path` and removed needs-triage This issue may need triage. Remove it if it has been sufficiently triaged. labels Feb 3, 2024
@rustbot rustbot added the I-prioritize Issue: Indicates that prioritization has been requested for this issue. label Feb 3, 2024
@conradludgate
Copy link
Contributor Author

It's unclear whether

  • default_read_buf should be fixed to check that n is in bounds
  • BufReader should be fixed to check that the buf.len() is in bounds

Reading the current safety comments, it appears that default_read_buf is in the wrong:

Safety
The caller must ensure that the first n bytes of the cursor have been properly initialised.

this is violated as only 8192 bytes are intiialised.

I would personally suggest that default_read_buf be updated to add a bounds check.

@conradludgate
Copy link
Contributor Author

@rustbot claim

matthiaskrgr added a commit to matthiaskrgr/rust that referenced this issue Feb 3, 2024
fix rust-lang#120603 by adding a check in default_read_buf

Fixes rust-lang#120603 by checking the returned read n is in-bounds of the cursor.

Interestingly, I noticed that `BorrowedBuf` side-steps this issue by using checked accesses. Maybe this can be switched to unchecked to mirror what BufReader does https://github.com/rust-lang/rust/blob/bf3c6c5bed498f41ad815641319a1ad9bcecb8e8/library/core/src/io/borrowed_buf.rs#L95
matthiaskrgr added a commit to matthiaskrgr/rust that referenced this issue Feb 4, 2024
fix rust-lang#120603 by adding a check in default_read_buf

Fixes rust-lang#120603 by checking the returned read n is in-bounds of the cursor.

Interestingly, I noticed that `BorrowedBuf` side-steps this issue by using checked accesses. Maybe this can be switched to unchecked to mirror what BufReader does https://github.com/rust-lang/rust/blob/bf3c6c5bed498f41ad815641319a1ad9bcecb8e8/library/core/src/io/borrowed_buf.rs#L95
bors added a commit to rust-lang-ci/rust that referenced this issue Feb 5, 2024
…iaskrgr

Rollup of 8 pull requests

Successful merges:

 - rust-lang#120507 (Account for non-overlapping unmet trait bounds in suggestion)
 - rust-lang#120518 (riscv only supports split_debuginfo=off for now)
 - rust-lang#120521 (Make `NonZero` constructors generic.)
 - rust-lang#120527 (Switch OwnedStore handle count to AtomicU32)
 - rust-lang#120550 (Continue to borrowck even if there were previous errors)
 - rust-lang#120587 (miri: normalize struct tail in ABI compat check)
 - rust-lang#120590 (Remove unused args from functions)
 - rust-lang#120607 (fix rust-lang#120603 by adding a check in default_read_buf)

Failed merges:

 - rust-lang#120575 (Simplify codegen diagnostic handling)

r? `@ghost`
`@rustbot` modify labels: rollup
matthiaskrgr added a commit to matthiaskrgr/rust that referenced this issue Feb 5, 2024
fix rust-lang#120603 by adding a check in default_read_buf

Fixes rust-lang#120603 by checking the returned read n is in-bounds of the cursor.

Interestingly, I noticed that `BorrowedBuf` side-steps this issue by using checked accesses. Maybe this can be switched to unchecked to mirror what BufReader does https://github.com/rust-lang/rust/blob/bf3c6c5bed498f41ad815641319a1ad9bcecb8e8/library/core/src/io/borrowed_buf.rs#L95
bors added a commit to rust-lang-ci/rust that referenced this issue Feb 5, 2024
…iaskrgr

Rollup of 9 pull requests

Successful merges:

 - rust-lang#119481 (Clarify ambiguity in select_nth_unstable docs)
 - rust-lang#119600 (Remove outdated references to librustc_middle)
 - rust-lang#120458 (Document `&CStr` to `CString` conversion)
 - rust-lang#120569 (coverage: Improve handling of function/closure spans)
 - rust-lang#120572 (Update libc to 0.2.153)
 - rust-lang#120587 (miri: normalize struct tail in ABI compat check)
 - rust-lang#120607 (fix rust-lang#120603 by adding a check in default_read_buf)
 - rust-lang#120636 (Subtree update of `rust-analyzer`)
 - rust-lang#120641 (rustdoc: trait.impl, type.impl: sort impls to make it not depend on serialization order)

r? `@ghost`
`@rustbot` modify labels: rollup
@bors bors closed this as completed in a27e45a Feb 5, 2024
rust-timer added a commit to rust-lang-ci/rust that referenced this issue Feb 5, 2024
Rollup merge of rust-lang#120607 - conradludgate:fix-120603, r=dtolnay

fix rust-lang#120603 by adding a check in default_read_buf

Fixes rust-lang#120603 by checking the returned read n is in-bounds of the cursor.

Interestingly, I noticed that `BorrowedBuf` side-steps this issue by using checked accesses. Maybe this can be switched to unchecked to mirror what BufReader does https://github.com/rust-lang/rust/blob/bf3c6c5bed498f41ad815641319a1ad9bcecb8e8/library/core/src/io/borrowed_buf.rs#L95
@apiraino apiraino removed the I-prioritize Issue: Indicates that prioritization has been requested for this issue. label Feb 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-io Area: `std::io`, `std::fs`, `std::net` and `std::path` C-bug Category: This is a bug. I-unsound Issue: A soundness hole (worst kind of bug), see: https://en.wikipedia.org/wiki/Soundness T-libs Relevant to the library team, which will review and decide on the PR/issue.
Projects
None yet
4 participants