diff --git a/pkgs/id/src/web/routes.rs b/pkgs/id/src/web/routes.rs index 808fa64445..088d06b01a 100644 --- a/pkgs/id/src/web/routes.rs +++ b/pkgs/id/src/web/routes.rs @@ -80,6 +80,183 @@ fn mime_to_extension(mime: &str) -> &'static str { } } +/// Verify that uploaded bytes actually look like the image type the +/// multipart field declared (#5342). Before this check, `upload_handler` +/// trusted the declared Content-Type alone, so any bytes (HTML, script, +/// plain text) could be stored — and later served — as an image of the +/// declared type. Raster formats are recognised by their magic +/// signatures; SVG is text, so it is checked structurally by +/// [`svg_document_starts`]. This is a signature check, not a full format +/// decode: it stops type masquerading, it does not prove the rest of +/// the file is well-formed. +fn image_bytes_match_declared_type(content_type: &str, data: &[u8]) -> bool { + match content_type { + "image/png" => data.starts_with(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]), + "image/jpeg" => data.starts_with(&[0xFF, 0xD8, 0xFF]), + "image/gif" => data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a"), + "image/webp" => data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP", + "image/bmp" => data.starts_with(b"BM"), + // ICO (type 1) and CUR (type 2) share the container header. + "image/x-icon" => { + data.starts_with(&[0x00, 0x00, 0x01, 0x00]) + || data.starts_with(&[0x00, 0x00, 0x02, 0x00]) + } + "image/svg+xml" => match decode_utf16_text(data) { + // An SVG encoded as UTF-16 (Codex P2 on PR #5357, round 3) + // is a valid image/svg+xml document whose markup is not + // ASCII bytes; decode it and run the same check on the text. + Some(decoded) => svg_document_starts(decoded.as_bytes()), + None => svg_document_starts(data), + }, + _ => false, + } +} + +/// Decode UTF-16 text when `data` carries one of its signatures: a +/// UTF-16LE (`FF FE`) or UTF-16BE (`FE FF`) byte-order mark, or the +/// UTF-16 spelling of an opening `<` (`3C 00` / `00 3C`) when there is +/// no BOM. Returns `None` for anything else (the caller then treats +/// the bytes as UTF-8/ASCII, as before). Lossy on unpaired surrogates — +/// only the prolog/root prefix is inspected afterwards. +fn decode_utf16_text(data: &[u8]) -> Option { + let (body, little_endian) = if data.starts_with(&[0xFF, 0xFE]) { + (&data[2..], true) + } else if data.starts_with(&[0xFE, 0xFF]) { + (&data[2..], false) + } else if data.starts_with(&[0x3C, 0x00]) { + (data, true) + } else if data.starts_with(&[0x00, 0x3C]) { + (data, false) + } else { + return None; + }; + let units: Vec = body + .chunks_exact(2) + .map(|c| { + if little_endian { + u16::from_le_bytes([c[0], c[1]]) + } else { + u16::from_be_bytes([c[0], c[1]]) + } + }) + .collect(); + Some(String::from_utf16_lossy(&units)) +} + +/// Whether `data` is an SVG document: after an optional UTF-8 BOM and +/// the legal XML prolog constructs — whitespace, `` or +/// another processing instruction, `` comments, and a +/// `` declaration (real-world SVGs carry all of these: +/// see `doc/database_structure_20231217_074440.svg`, a Graphviz export +/// with a declaration, an SVG 1.1 DOCTYPE, and comments before the +/// root) — the document must open with an `svg` root element (plain or namespace-prefixed). +fn svg_document_starts(data: &[u8]) -> bool { + let mut rest = data; + if rest.starts_with(&[0xEF, 0xBB, 0xBF]) { + rest = &rest[3..]; + } + loop { + while rest.first().is_some_and(u8::is_ascii_whitespace) { + rest = &rest[1..]; + } + if rest.starts_with(b"") { + Some(end) => rest = &rest[end + 2..], + None => return false, + } + } else if rest.starts_with(b"") { + Some(end) => rest = &rest[end + 3..], + None => return false, + } + } else if rest.starts_with(b" rest = &rest[end + 1..], + None => return false, + } + } else { + break; + } + } + svg_root_element_opens(rest) +} + +/// Byte index of the `>` that ends a `` declaration at +/// the start of `rest`. The declaration ends at the first `>` that is +/// outside the `[ ... ]` internal subset, outside any quoted literal +/// (`"..."` / `'...'`), and outside any `` comment — +/// brackets and angle brackets inside quotes or comments are data, +/// not delimiters (Codex P2 on PR #5357, round 4: an entity value of +/// `"["` used to corrupt the subset depth and reject a legal SVG). +fn doctype_end(rest: &[u8]) -> Option { + let mut subset_depth = 0usize; + let mut quote: Option = None; + let mut in_comment = false; + let mut i = 0usize; + while i < rest.len() { + if in_comment { + if rest[i..].starts_with(b"-->") { + in_comment = false; + i += 3; + } else { + i += 1; + } + continue; + } + if let Some(q) = quote { + if rest[i] == q { + quote = None; + } + i += 1; + continue; + } + if rest[i..].starts_with(b"\n\n" + )); + assert!(image_bytes_match_declared_type( + "image/svg+xml", + b"b\"> ]>\n" + )); + assert!(!image_bytes_match_declared_type( + "image/svg+xml", + b"" + )); + // Codex P2 on PR #5357 (second round): a namespace-prefixed + // root is still an SVG root; lookalike tag names are not. + assert!(image_bytes_match_declared_type( + "image/svg+xml", + b"" + )); + assert!(!image_bytes_match_declared_type( + "image/svg+xml", + b"" + )); + assert!(!image_bytes_match_declared_type( + "image/svg+xml", + b"" + )); + // Codex P2 on PR #5357 (round 3): UTF-16-encoded SVGs are valid + // image/svg+xml documents; LE and BE, with and without a BOM, + // are decoded before the prolog/root check. + fn utf16(text: &str, little_endian: bool, bom: bool) -> Vec { + let mut out = Vec::new(); + if bom { + out.extend_from_slice(if little_endian { + b"\xff\xfe" + } else { + b"\xfe\xff" + }); + } + for unit in text.encode_utf16() { + out.extend_from_slice(&if little_endian { + unit.to_le_bytes() + } else { + unit.to_be_bytes() + }); + } + out + } + let svg_doc = "\n"; + assert!(image_bytes_match_declared_type( + "image/svg+xml", + &utf16(svg_doc, true, true) + )); + assert!(image_bytes_match_declared_type( + "image/svg+xml", + &utf16(svg_doc, false, true) + )); + assert!(image_bytes_match_declared_type( + "image/svg+xml", + &utf16("", true, false) + )); + assert!(!image_bytes_match_declared_type( + "image/svg+xml", + &utf16("", true, true) + )); + // Codex P2 on PR #5357 (round 4): brackets inside quoted + // literals or comments within the internal subset are data, + // not subset delimiters. + assert!(image_bytes_match_declared_type( + "image/svg+xml", + b"]>" + )); + assert!(image_bytes_match_declared_type( + "image/svg+xml", + b" ]>\n" + )); + assert!(!image_bytes_match_declared_type( + "image/svg+xml", + b"]>" + )); + assert!(!image_bytes_match_declared_type( + "image/png", + b"" + )); + assert!(!image_bytes_match_declared_type( + "image/jpeg", + b"plain text" + )); + assert!(!image_bytes_match_declared_type( + "image/svg+xml", + b"" + )); + assert!(!image_bytes_match_declared_type("image/png", b"")); + assert!(!image_bytes_match_declared_type( + "image/webp", + b"RIFF\x04\x00\x00\x00WAVErest" + )); + } + + // #5342 (the probe that filed the issue): HTML/script bytes declared + // image/png were accepted, stored, and served as a PNG. They must + // now be refused 400, and nothing may be stored or listed. + #[tokio::test] + async fn upload_html_declared_as_png_is_refused_and_stores_nothing() { + let (router, _dir, _endpoint, _docs) = router().await; + let (status, body) = upload( + router.clone(), + multipart_body_named( + "evil.png", + "image/png", + b"", + ), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "body: {body}"); + assert!( + body.contains("do not match the declared image type"), + "body: {body}" + ); + assert!(list_images(router).await.is_empty()); + } + + #[tokio::test] + async fn upload_mismatched_bytes_are_refused_for_other_declared_types() { + let (router, _dir, _endpoint, _docs) = router().await; + for (name, content_type, bytes) in [ + ("photo.jpg", "image/jpeg", b"plain text".as_slice()), + ("icon.svg", "image/svg+xml", b"not an svg".as_slice()), + ( + "anim.gif", + "image/gif", + b"\x89PNG\r\n\x1a\nnot-a-gif".as_slice(), + ), + ( + "pic.webp", + "image/webp", + b"RIFF\x04\x00\x00\x00WAVErest".as_slice(), + ), + ] { + let (status, body) = upload( + router.clone(), + multipart_body_named(name, content_type, bytes), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{content_type}: {body}"); + } + assert!(list_images(router).await.is_empty()); + } + + #[tokio::test] + async fn upload_real_headers_for_each_allowed_type_are_accepted() { + let (router, _dir, _endpoint, _docs) = router().await; + for (name, content_type, bytes) in [ + ("a.png", "image/png", b"\x89PNG\r\n\x1a\nx".as_slice()), + ("a.jpg", "image/jpeg", b"\xff\xd8\xff\xe0x".as_slice()), + ("a.gif", "image/gif", b"GIF89ax".as_slice()), + ( + "a.webp", + "image/webp", + b"RIFF\x04\x00\x00\x00WEBPx".as_slice(), + ), + ("a.bmp", "image/bmp", b"BMx".as_slice()), + ("a.ico", "image/x-icon", b"\x00\x00\x01\x00x".as_slice()), + ( + "a.svg", + "image/svg+xml", + b"".as_slice(), + ), + ] { + let (status, body) = upload( + router.clone(), + multipart_body_named(name, content_type, bytes), + ) + .await; + assert_eq!(status, StatusCode::OK, "{content_type}: {body}"); + } + } } // =============================================================================