Answer#
Everything about an upload is chosen by the sender: the name, the declared type, the contents. A safe handler therefore decides each of these itself.
| Property | Do not trust | Do instead |
|---|---|---|
| Size | Content-Length | A byte limit while reading |
| Type | file extension, Content-Type | Check the first bytes ("magic numbers") against an allow-list |
| Name | the client's file name | Generate a random name; choose the extension from the detected type |
| Location | a path from the request | A fixed folder outside the web root |
const MAX_BYTES: usize = 2 * 1024 * 1024;
/// Decide the file type from the first bytes, never from the name or the Content-Type header.
fn sniff(data: &[u8]) -> Option<&'static str> {
if data.starts_with(b"\x89PNG\r\n\x1a\n") {
Some("png")
} else if data.starts_with(&[0xFF, 0xD8, 0xFF]) {
Some("jpg")
} else {
None
}
}
/// Returns the name to store the file under: random, with an extension we chose.
fn accept_upload(data: &[u8]) -> Result<String, &'static str> {
if data.is_empty() || data.len() > MAX_BYTES {
return Err("empty or too large");
}
let ext = sniff(data).ok_or("not a PNG or JPEG")?;
let mut id = [0u8; 16];
getrandom::getrandom(&mut id).map_err(|_| "no randomness")?;
Ok(format!("{}.{ext}", hex::encode(id)))
}
fn main() {
let png = [&b"\x89PNG\r\n\x1a\n"[..], &[0u8; 20]].concat();
let fake = b"<script>alert(1)</script>"; // sent with a name like "photo.png"
println!("{:?}", accept_upload(&png).map(|n| (n.len(), n.ends_with(".png"))));
println!("{:?}", accept_upload(fake));
println!("{:?}", accept_upload(&vec![0xFF; MAX_BYTES + 1]));
}Ok((36, true))
Err("not a PNG or JPEG")
Err("empty or too large")The output shows a genuine PNG header accepted under a name of 36 characters (32 hex characters plus .png), a script presented as an image refused, and an oversized file refused.
How to do it#
- Enforce the size limit in the web framework before the body reaches your code.
- Detect the type from the content and allow only the types the feature needs.
- Generate the stored name; keep the original name, if you need it, only as display text, escaped on output.
- Store files outside the web root, serve them through a handler that sets the right
Content-TypeandX-Content-Type-Options: nosniff, and for downloads of non-image types addContent-Disposition: attachment. - For images, re-encode them with an image library if you need to remove embedded data, and set a maximum width and height so a small file cannot expand into a huge bitmap.
- Scan or sandbox documents when the use case requires it, and never run uploaded files.
Common mistakes#
- Checking the extension only:
shell.pngcan contain anything. - Letting the web server execute files in the upload folder.
- Magic-number checks treated as proof the file is harmless: a valid image header can be followed by anything. The check narrows the type; it does not make a file safe.
- Reading the entire upload into memory before checking its size.
Related questions#
Where do temporary files go while the upload is processed?#
In a private temporary file with a random name; see the thread on temporary files.
Should I store uploads in the database instead?#
It avoids file-system path problems but makes the database larger and slower for big files. The other checks (size, type, name) still apply.
Sources#
- OWASP File Upload Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html
- MDN,
X-Content-Type-Options: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Content-Type-Options