From 21806495ea8024ea1a9c61643cfbe8af4dfa1e64 Mon Sep 17 00:00:00 2001 From: manunio Date: Fri, 14 Jun 2024 03:38:51 +0530 Subject: [PATCH] filter: fix errors found by fuzz While fuzzing built-in filters `center` and `indent`, they errored out or caused an OOM due to a large value as input. --- askama/src/filters/mod.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/askama/src/filters/mod.rs b/askama/src/filters/mod.rs index 3e5a1652..701ca1bf 100644 --- a/askama/src/filters/mod.rs +++ b/askama/src/filters/mod.rs @@ -40,6 +40,9 @@ const URLENCODE_STRICT_SET: &AsciiSet = &NON_ALPHANUMERIC // Same as URLENCODE_STRICT_SET, but preserves forward slashes for encoding paths const URLENCODE_SET: &AsciiSet = &URLENCODE_STRICT_SET.remove(b'/'); +// MAX_LEN is maximum allowed length for filters. +const MAX_LEN: usize = 10000; + /// Marks a string (or other `Display` type) as safe /// /// Use this is you want to allow markup in an expression, or if you know @@ -374,6 +377,9 @@ impl fmt::Display for TruncateFilter { #[inline] pub fn indent(s: impl ToString, width: usize) -> Result { fn indent(s: String, width: usize) -> Result { + if width >= MAX_LEN { + return Ok(s); + } let mut indented = String::new(); for (i, c) in s.char_indices() { indented.push(c); @@ -483,7 +489,7 @@ pub fn capitalize(s: impl ToString) -> Result { pub fn center(src: impl ToString, dst_len: usize) -> Result { fn center(src: String, dst_len: usize) -> Result { let len = src.len(); - if dst_len <= len { + if dst_len <= len || dst_len >= MAX_LEN { Ok(src) } else { let diff = dst_len - len; @@ -704,6 +710,7 @@ mod tests { indent("hello\nfoo\n bar", 4).unwrap().to_string(), "hello\n foo\n bar" ); + assert_eq!(indent("hello", 267332238858).unwrap().to_string(), "hello"); } #[cfg(feature = "num-traits")] @@ -806,6 +813,10 @@ mod tests { center("foo bar", 8).unwrap().to_string(), "foo bar ".to_string() ); + assert_eq!( + center("foo", 111669149696).unwrap().to_string(), + "foo".to_string() + ); } #[test]