FAQ - Help and questions

Can a regular expression take my Rust server down (ReDoS)?

#security#regex#denial-of-servicepublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

With the regex crate, matching time grows with the size of the text, because the engine does not backtrack, so the classic catastrophic patterns are not a threat. The cost that remains is compiling a pattern: if users supply patterns, set a size limit. Crates that add backtracking features need the usual care.

Checked with rustc 1.93.0, regex 1.13.1, Windows 11 (release build)

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Regular expression denial of service happens when a pattern such as ^(a+)+$ meets a text such as many a characters followed by !. A backtracking engine tries an exponential number of ways to split the text, and one request can occupy a CPU for hours.

The regex crate documents a different design: its matching is based on finite automata, and searches take time proportional to the size of the pattern and the haystack. The program below applies the classic bad pattern to a 50,001-character text; it finishes and answers false. (The program prints no timings: this thread makes no speed claim beyond the documented guarantee.)

src/main.rsrust
use regex::{Regex, RegexBuilder};

fn main() {
    // In a backtracking engine this shape (nested repetition, then a failure at the end) can take
    // exponential time. The regex crate does not backtrack: its running time grows with the input.
    let re = Regex::new(r"^(a+)+$").unwrap();
    let mut hay = "a".repeat(50_000);
    hay.push('!');
    println!("matches: {}", re.is_match(&hay));

    // If users may supply the pattern itself, cap what it may cost to compile.
    let user_pattern = r"(\w{50}){50}";
    match RegexBuilder::new(user_pattern).size_limit(50_000).build() {
        Ok(_) => println!("pattern accepted"),
        Err(e) => println!("pattern refused: {e}"),
    }
}
text
matches: false
pattern refused: Compiled regex exceeds size limit of 50000 bytes.

The second part addresses the remaining risk. If users can supply the pattern itself (a search box with "regex" mode), a large pattern can use much memory to compile. RegexBuilder::size_limit caps the size of the compiled program and returns an error, as shown.

How to do it#

  1. Prefer the regex crate for untrusted text. Read its documentation on performance guarantees for the version you use.
  2. Never build a pattern from user input without escaping it: use regex::escape when the user means literal text.
  3. If users need to write patterns, set size_limit (and dfa_size_limit if you tune it), and limit the length of the pattern and the haystack.
  4. If you use a crate that supports look-around or back-references (backtracking features, such as fancy-regex), read its documentation about limits, and add timeouts or backtrack limits.
  5. Treat regular expressions in other languages that your code calls (for example through a database) with the same care.

Common mistakes#

  • Believing "Rust means no ReDoS" for every crate. The guarantee belongs to the engine, not to the language.
  • Validating e-mail addresses or URLs with one huge pattern. Use a parser (for example the url crate) instead.
  • Forgetting escape and letting a search term such as a.* change the meaning of the query.

Does a size limit make a pattern safe?#

It bounds compilation cost. Combine it with limits on the haystack, and with request timeouts.

Does the regex crate have other limits?#

Yes: a limit on the size of the compiled program and one on the lazy matching cache. They are documented in its builder; read them before accepting patterns from users.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet