logo

Database

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.

Weakness:

211 - Asymmetric denial of service - ReDoS

Category: Functionality Abuse

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);...