Skip to content

Add a way to limit recursion depth #4928

@nyh

Description

@nyh

ANTLR uses recursion to perform the parsing, and there is a risk that a maliciously-crafted deeply-nested expression, perhaps even something as simple as a long string of parentheses (((((((((((..., can cause a stack overflow and the entire application to crash.

For example, in the ScyllaDB project we had this bug and solved it in scylladb/scylladb@04e5082 by manually adding depth counters to every potentially-recursive rule, and announce a parse error if the depth becomes too high. But these manually-inserted counters are hard to do correctly, and it's very easy to miss some cases of recursion and forget to protect them (I saw this happening in another project just today, which is why I came here to create this issue).

I think the real solution is what YACC did already 45 years ago (!), when it had the global YYMAXDEPTH parameter. Since YACC used its own stack implementation, it was easy for them to implement it, but I think it should be possible to implement in ANTLR as well, by counting the parsing recursion depth and failing the parse when this counter is over the limit.

I also think that this limit should be enabled by default. YACC started with YYMAXDEPTH set to just 150, but modern Bison increased this to 10,000 - which "Should Be Enough For Everyone (TM)" and yet be low enough to prevent stack overflows on modern systems. Having some limit enacted by default will prevent the security risk that ANTLR adds today to every application that uses it and can crash if given a deeply-nested expression.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions