Nested comments causes parser to timeout
manunio opened this issue · comments
Hi,
Large nested comments like below(produced by fuzzing);
{{#{{#{{#{{#{{#{{#{{#{{#{{#{{#{{#{{#{{#{{#{{##}#}#}#}#}#}#}#}#}#}#}#}#}#}#}#}#}#}#}#}#}#}#
makes the parser get stuck at following lines.
askama/askama_parser/src/node.rs
Lines 1027 to 1029 in 5955ba2
Steps to reproduce:
comment-testcase.txt
#[test]
fn test_fuzzed_comment_recursion() {
const TEMPLATE: &str = include_str!("../../comment-testcase.txt");
assert!(Ast::from_str(TEMPLATE, None, &Syntax::default()).is_err());
}
Executing task: cargo test --package askama_parser --lib -- tests::test_fuzzed_comment_recursion --exact --show-output
Compiling askama_parser v0.2.1 (/home/maxx/dev/security/oss-fuzz-projects/askama/askama_parser)
Finished test [unoptimized + debuginfo] target(s) in 1.12s
Running unittests src/lib.rs (target/debug/deps/askama_parser-c458ed7d8982bb6b)
running 1 test
Will having a guard against deep nesting can be considered as a fix here ?
use nom::multi::{fold_many0, many0, many1, separated_list0, separated_list1};
use nom::sequence::{delimited, pair, preceded, terminated, tuple};
-use crate::{ErrorContext, ParseResult};
+use crate::{ErrorContext, Level, ParseResult};
use super::{
bool_lit, char_lit, filter, identifier, is_ws, keyword, num_lit, path_or_identifier, skip_till,
@@ -1025,6 +1025,9 @@ impl<'a> Comment<'a> {
let (end, tail) = take_until(s.syntax.comment_end)(i)?;
match take_until::<_, _, ErrorContext<'_>>(s.syntax.comment_start)(i) {
Ok((start, _)) if start.as_ptr() < end.as_ptr() => {
+ if level >= Level::MAX_DEPTH {
+ return Err(nom::Err::Failure(error_position!(i, ErrorKind::TooLarge)));
+ }
level += 1;
i = &start[2..];
}
Thank you very much for finding the error and providing a test case! I rewrote the comment parsing from scratch in #1027.
Thank you very much for finding the error and providing a test case! I rewrote the comment parsing from scratch in #1027.
Hi, Thanks for the quick fix! I've tested it against fuzz_parser.rs locally, and it's not reporting any issues here :)