Race Condition Matcher
ID |
java.race_condition_matcher |
Severity |
high |
Resource |
Synchronization |
Language |
Java |
Tags |
CWE:362, NIST.SP.800-53, PCI-DSS:6.5.6 |
Description
Concurrent execution of Matcher shared resource with improper synchronization ('Race Condition').
Rationale
java.util.regex.Matcher
is not thread-safe, meaning concurrent access from multiple threads without synchronization mechanisms can result in incorrect matching behavior and data corruption. The Matcher object maintains state such as the input string and match results, which can be altered unpredictably when accessed concurrently.
Consider the following example:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RaceConditionFormat {
private static final Pattern pattern = Pattern.compile(".*");
private Matcher matcher; // FLAW
public RaceConditionFormat(String input) {
matcher = pattern.matcher(input);
}
public String find(String input) {
return matcher.find();
}
}
In this example, the containsPattern
method creates a Matcher
object and uses it without synchronization. If multiple threads invoke this method simultaneously, there can be unwanted interactions causing undefined behavior and incorrect matching results.
Remediation
To remediate race condition issues with java.util.regex.Matcher
, ensure that access to the Matcher
object is synchronized when used in a multi-threaded context.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RaceConditionFormat {
private static final Pattern pattern = Pattern.compile(".*");
private Matcher matcher;
public RaceConditionFormat(String input) {
matcher = pattern.matcher(input);
}
public String find(String input) {
synchronized(matcher) {
return matcher.find();
}
}
public synchronized String find2(String input) {
return matcher(input).find();
}
}
By either synchronizing the code block that interacts with the Matcher
or providing separate Matcher
instances per thread, you can prevent race conditions and ensure the correct operation of your regex processing code. Regular code reviews and testing in concurrent environments can further aid in identifying and remediating race condition vulnerabilities.