Answer#
read_to_end and read_to_string keep reading until the source ends. A client who sends a very large body, or never stops, makes your program allocate until it runs out of memory: a denial of service with no bug in the parser at all.
Put the limit on the reader. Read::take(n) returns a reader that stops after n bytes. Ask for one byte more than you allow: if that byte arrives, the input was too big.
use std::io::{self, Cursor, Read};
/// Read at most `max` bytes. Fails if the source has more, instead of growing without limit.
fn read_limited<R: Read>(reader: R, max: usize) -> io::Result<Vec<u8>> {
let mut buf = Vec::new();
// Ask for one byte more than allowed: if we get it, the input was too big.
reader.take(max as u64 + 1).read_to_end(&mut buf)?;
if buf.len() > max {
return Err(io::Error::new(io::ErrorKind::InvalidData, format!("input is larger than {max} bytes")));
}
Ok(buf)
}
fn main() {
let small = Cursor::new(vec![b'a'; 10]);
let large = Cursor::new(vec![b'a'; 5000]);
println!("{:?}", read_limited(small, 1024).map(|v| v.len()));
println!("{:?}", read_limited(large, 1024).map(|v| v.len()));
}Ok(10)
Err(Custom { kind: InvalidData, error: "input is larger than 1024 bytes" })How to do it#
- Pick a maximum for each kind of input from what the feature really needs (a login form needs bytes, not megabytes).
- Apply it where the data is read, and again for anything that expands, such as decompression.
- Return a clear error (HTTP 413 for web requests) and close the connection.
- In a web framework, use its built-in body limit rather than reading the body yourself.
- Combine with timeouts, so a client that sends one byte a minute cannot hold a connection forever.
Common mistakes#
- Checking
Content-Lengthonly. The header is claimed by the client and may be missing or wrong. - Limiting the compressed size but not the size after decompression. A small file can expand enormously; limit the output of the decompressor with
take. - A limit on the total but not on the number of items, fields or nesting depth.
Related questions#
What limit should I choose?#
The smallest that serves the feature. You can raise it for the routes that need more; a global generous limit is the usual mistake.
What if I need to accept very large uploads?#
Stream them to disk in pieces with a total limit that you enforce while reading, and never hold the whole body in memory. See the thread on file uploads.
Sources#
- Standard library,
Read::take: https://doc.rust-lang.org/std/io/trait.Read.html#method.take - OWASP Denial of Service Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Denial_of_Service_Cheat_Sheet.html