diff --git a/crates/formats/src/mesh.rs b/crates/formats/src/mesh.rs index 9d712879..539b3952 100644 --- a/crates/formats/src/mesh.rs +++ b/crates/formats/src/mesh.rs @@ -13,6 +13,65 @@ pub const MESH_EXTENSIONS: &[&str] = &["obj", "glb", "gltf"]; /// Largest mesh accepted (triangles). const MAX_TRIANGLES: usize = 4_000_000; +/// Largest mesh accepted (vertices). +const MAX_VERTICES: usize = 3 * MAX_TRIANGLES; + +fn check_vertex_bound(current: usize, added: usize) -> Result<()> { + if current.checked_add(added).is_none_or(|total| total > MAX_VERTICES) { + return Err(bad("the mesh is too large")); + } + Ok(()) +} + +/// Reject an OBJ whose raw attribute or face definitions exceed the bounds +/// before the parser allocates storage for them. Unreferenced definitions +/// never reach the parsed mesh, so counting parsed vertices alone cannot +/// bound this input. First tokens are matched with `split_whitespace`, the +/// same Unicode whitespace rules the OBJ parser uses. +fn check_obj_vertex_bound(bytes: &[u8]) -> Result<()> { + let mut vertices = 0usize; + let mut texcoords = 0usize; + let mut normals = 0usize; + let mut face_corners = 0usize; + for line in bytes.split(|b| *b == b'\n') { + let Ok(line) = std::str::from_utf8(line) else { continue }; + let mut tokens = line.split_whitespace(); + match tokens.next() { + Some("v") => { + vertices = vertices.saturating_add(1); + if vertices > MAX_VERTICES { + return Err(bad("the mesh is too large")); + } + } + Some("vt") => { + texcoords = texcoords.saturating_add(1); + if texcoords > MAX_VERTICES { + return Err(bad("the mesh is too large")); + } + } + Some("vn") => { + normals = normals.saturating_add(1); + if normals > MAX_VERTICES { + return Err(bad("the mesh is too large")); + } + } + Some("f") | Some("l") => { + // A triangulated face with k corners yields k - 2 triangles, so + // a mesh within the triangle limit has at most 3 * MAX_TRIANGLES + // corners. Lines are expanded by the parser like faces, so + // bounding their corners too bounds the vertices the parser + // expands from distinct index combinations. + face_corners = face_corners.saturating_add(tokens.count()); + if face_corners > 3 * MAX_TRIANGLES { + return Err(bad("the mesh is too large")); + } + } + _ => {} + } + } + Ok(()) +} + fn bad(msg: impl Into) -> FormatError { FormatError::BadPackage(msg.into()) } @@ -81,6 +140,7 @@ pub fn load_mesh(name: &str, bytes: &[u8]) -> Result { } fn obj(bytes: &[u8]) -> Result { + check_obj_vertex_bound(bytes)?; let mut reader = std::io::BufReader::new(bytes); let opts = tobj::LoadOptions { triangulate: true, single_index: true, ..Default::default() }; let (models, _) = crate::guard( @@ -95,6 +155,7 @@ fn obj(bytes: &[u8]) -> Result { let base = positions.len() as u32; let mesh = &m.mesh; let n = mesh.positions.len() / 3; + check_vertex_bound(positions.len(), n)?; for i in 0..n { positions.push(Vec3::new(mesh.positions[i * 3], mesh.positions[i * 3 + 1], mesh.positions[i * 3 + 2])); if mesh.normals.len() == mesh.positions.len() { @@ -129,11 +190,16 @@ fn gltf(bytes: &[u8]) -> Result { let reader = prim.reader(|b| buffers.get(b.index()).map(|d| d.0.as_slice())); let Some(pos) = reader.read_positions() else { continue }; let base = positions.len() as u32; - let pos: Vec = pos.map(|p| m.transform_point3(Vec3::from(p))).collect(); - let n = pos.len(); + let pos_it = pos.map(|p| m.transform_point3(Vec3::from(p))); + let n = pos_it.len(); + check_vertex_bound(positions.len(), n)?; + let pos: Vec = pos_it.collect(); match reader.read_normals() { Some(ns) => { for q in ns { + if normals.len() >= MAX_VERTICES { + return Err(bad("the mesh is too large")); + } let v = m.transform_vector3(Vec3::from(q)); if !v.is_finite() { return Err(bad("the mesh has non-finite (NaN or infinite) normals")); @@ -144,7 +210,14 @@ fn gltf(bytes: &[u8]) -> Result { None => all_normals = false, } match reader.read_tex_coords(0) { - Some(t) => uvs.extend(t.into_f32().map(Vec2::from)), + Some(t) => { + for uv in t.into_f32() { + if uvs.len() >= MAX_VERTICES { + return Err(bad("the mesh is too large")); + } + uvs.push(Vec2::from(uv)); + } + } None => uvs.extend(std::iter::repeat_n(Vec2::ZERO, n)), } match reader.read_indices() { @@ -244,6 +317,49 @@ mod tests { assert_eq!(read, 6); } + #[test] + fn obj_with_excess_vertices_is_rejected() { + let mut obj = String::from("v 0 0 0\nv 1 0 0\nv 0 1 0\n"); + for _ in 0..3 * MAX_TRIANGLES { + obj.push_str("v 1 0 0\n"); + } + obj.push_str("f 1 2 3\n"); + + let e = load_mesh("excess.obj", obj.as_bytes()).unwrap_err(); + assert!(matches!(&e, FormatError::BadPackage(msg) if msg == "the mesh is too large"), "{e:?}"); + } + + #[test] + fn gltf_with_excess_vertices_is_rejected() { + use base64::Engine as _; + // One position accessor of 100_000 vertices, referenced by 121 + // primitives: the cumulative count exceeds MAX_VERTICES on the + // last primitive, while the single indexed triangle per primitive + // stays far below the triangle limit. + const COUNT: usize = 100_000; + let mut buf = vec![0u8; COUNT * 12]; + // Give the referenced triangle non-degenerate positions. + for (i, v) in [[0.0f32, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]].iter().enumerate() { + buf[i * 12..i * 12 + 12].copy_from_slice(&v.iter().flat_map(|f| f.to_le_bytes()).collect::>()); + } + buf.extend([0u16, 1, 2].iter().flat_map(|i| i.to_le_bytes())); + let b64 = base64::engine::general_purpose::STANDARD.encode(&buf); + let prim = r#"{"attributes":{"POSITION":0},"indices":1}"#; + let prims = (0..121).map(|_| prim).collect::>().join(","); + let gltf = format!( + r#"{{"asset":{{"version":"2.0"}},"scene":0,"scenes":[{{"nodes":[0]}}],"nodes":[{{"mesh":0}}], +"meshes":[{{"primitives":[{prims}]}}], +"accessors":[{{"bufferView":0,"componentType":5126,"count":{COUNT},"type":"VEC3","min":[0.0,0.0,0.0],"max":[1.0,1.0,0.0]}},{{"bufferView":1,"componentType":5123,"count":3,"type":"SCALAR"}}], +"bufferViews":[{{"buffer":0,"byteOffset":0,"byteLength":{}}},{{"buffer":0,"byteOffset":{},"byteLength":6}}], +"buffers":[{{"byteLength":{},"uri":"data:application/octet-stream;base64,{b64}"}}]}}"#, + COUNT * 12, + COUNT * 12, + buf.len() + ); + let e = load_mesh("excess.gltf", gltf.as_bytes()).unwrap_err(); + assert!(matches!(&e, FormatError::BadPackage(msg) if msg == "the mesh is too large"), "{e:?}"); + } + #[test] fn obj_non_finite_normals_are_rejected() { assert!(load_mesh("x.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nvn nan 0 1\nf 1//1 2//1 3//1\n").is_err()); @@ -306,4 +422,10 @@ mod tests { assert!(load_mesh("x.fbx", b"").is_err()); assert!(load_mesh("x.obj", b"v 0 0 0\nf 1 2 3\n").is_err()); } + + #[test] + fn vertex_bound_allows_three_vertices_per_triangle() { + assert!(check_vertex_bound(0, 3 * MAX_TRIANGLES).is_ok()); + assert!(check_vertex_bound(0, 3 * MAX_TRIANGLES + 1).is_err()); + } }