HeadlinesBriefing favicon HeadlinesBriefing.com

Java Regex ReDoS Vulnerability and Fix

DEV Community •
×

A common Java email validation regex can be weaponized to crash servers through ReDoS attacks. The pattern `^([a-zA-Z0-9]+)+@[a-zA-Z0-9]+\.[a-zA-Z]{2,}$` uses nested quantifiers that cause exponential backtracking. Feeding it a long string of 'a's followed by an exclamation point forces the engine to try billions of combinations, pegging CPU at 100%.

Java's `java.util.regex` engine uses backtracking, which is the root cause. Attackers exploit this by sending crafted inputs to validation endpoints, aiming to melt servers. The vulnerability stems from how the Nondeterministic Finite Automaton (NFA) explores alternative paths when a match fails, leading to catastrophic performance degradation for certain patterns.

The fix involves switching to a deterministic regex engine like Google's RE2. A new Java library called Rules bundles a patched fork of RE2J, which guarantees linear time matching. This approach eliminates backtracking entirely, making patterns impossible to weaponize. The library also addresses other input validation attacks like HashDoS and timing vulnerabilities.