Java Vulnerable Regex With User Input
Description
Detects potential Regular Expression Denial of Service (ReDoS) vulnerabilities in Java code where user-controlled input is used in regex pattern matching operations. Malicious users could craft input strings that cause regex matching to take exponential time, potentially leading to denial of service.
Detection Strategy
• Look for calls to Java String.matches() method in the code
• Check if the regex pattern argument contains or is derived from user input
• Verify the matches() method has at least one argument
• Report a vulnerability if user-controlled data flows into the regex pattern
Vulnerable code example
public class VulnerableRegex {
public void processInput(String userInput) {
String regex = "(A+)+"; // Vulnerable regex pattern with catastrophic backtracking
userInput.matches(regex); // Vulnerable - can cause exponential processing time
}
}✅ Secure code example
public class SecureRegex {
public void processInput(String userInput) {
// Use a simple non-backtracking pattern or limit input length
String regex = "[A]+"; // Safe pattern without nested quantifiers
// Add input validation before matching
if (userInput != null && userInput.length() <= 100) { // Prevent DoS by limiting input size
userInput.matches(regex);...Search for vulnerabilities in your apps for free with Fluid Attacks' automated security testing! Start your 21-day free trial and discover the benefits of the Continuous Hacking Essential plan. If you prefer the Advanced plan, which includes the expertise of Fluid Attacks' hacking team, fill out this contact form.