464
Scope Impact Likelihood
In PHP, regular expression checks can sometimes be
bypassed with a null byte, leading to any number of
weaknesses.
Detection Methods
Automated Static Analysis
Automated static analysis, commonly referred to as Static Application Security Testing (SAST),
can find some instances of this weakness by analyzing source code (or binary/compiled code)
without having to execute it. Typically, this is done by building a model of data flow and control
flow, then searching for potentially-vulnerable patterns that connect "sources" (origins of input)
with "sinks" (destinations where the data interacts with external components, a lower layer such
as the OS, etc.)
Effectiveness = High
Potential Mitigations
Phase: Architecture and Design
Strategy = Refactoring
Regular expressions can become error prone when defining a complex language even for those
experienced in writing grammars. Determine if several smaller regular expressions simplify one
large regular expression. Also, subject the regular expression to thorough testing techniques
such as equivalence partitioning, boundary value analysis, and robustness. After testing and a
reasonable confidence level is achieved, a regular expression may not be foolproof. If an exploit
is allowed to slip through, then record the exploit and refactor the regular expression.
Demonstrative Examples
Example 1:
The following code takes phone numbers as input, and uses a regular expression to reject invalid
phone numbers.
Example Language: Perl (Bad)
$phone = GetPhoneNumber();
if ($phone =~ /\d+-\d+/) {
# looks like it only has hyphens and digits
system("lookup-phone $phone");
}
else {
error("malformed number!");
}
An attacker could provide an argument such as: "; ls -l ; echo 123-456" This would pass the check,
since "123-456" is sufficient to match the "\d+-\d+" portion of the regular expression.
Example 2:
This code uses a regular expression to validate an IP string prior to using it in a call to the "ping"
command.
Example Language: Python (Bad)
import subprocess
import re
def validate_ip_regex(ip: str):
ip_validator = re.compile(r"((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}")
if ip_validator.match(ip):
return ip
else:
raise ValueError("IP address does not match valid pattern.")
CWE Version 4.14
CWE-185: Incorrect Regular Expression
CWE-185: Incorrect Regular Expression