Skip to content

[2.12.1] Issue in ureq::Response::into_reader() example code #940

@Monadic-Cat

Description

@Monadic-Cat

The doc comment for Response::into_reader() says this:

Note: If you use read_to_end() on the resulting reader, a malicious server might return enough bytes to exhaust available memory. If you’re making requests to untrusted servers, you should use .take() to limit the response bytes read.

This is all well and good, but it makes me interpret the example snippet below as being intended to handle that threat model, wherein the server may return a response crafted to cause you to crash in some way.

use std::io::Read;
let resp = ureq::get("http://httpbin.org/bytes/100")
    .call()?;

assert!(resp.has("Content-Length"));
let len: usize = resp.header("Content-Length")
    .unwrap()
    .parse()?;

let mut bytes: Vec<u8> = Vec::with_capacity(len);
resp.into_reader()
    .take(10_000_000)
    .read_to_end(&mut bytes)?;

assert_eq!(bytes.len(), len);

(Note that I am ignoring the asserts here, as well as .unwrap(), "don't panic if you care about not panicking when the server does something wrong" is well known enough anyway...)

The problem here is that the Content-Length header is being trusted to be okay to pass to Vec::with_capacity(), when it's server controlled in exactly the same way as the actual size of the body. If a user is using .take(10_000_000) to limit the size of the body they'll process, they should also use std::cmp::min(len, 10_000_000) when computing what to pass into Vec::with_capacity() there.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions