...
As an aside, this particular condition gains remarkable importance in automatic exploit signature detection systems and filters that rely on patter matching.
Noncompliant Code Example
In the following example, a method splitWords()
finds matches between the String
literal and the input sequence. Since '\b' is the escape sequence for a word boundary, the misleading notion that String
literals can be used as is, can convince the implementer that the pattern matches to word boundaries and thus splits a given string into individual words. Instead, the string WORDS
silently compiles to a backspace character.
Code Block | ||
---|---|---|
| ||
import java.util.regex.Pattern; public class BadSplitter { private final String WORDS = "\b"; // Intend to split on word boundaries public String[] splitWords(String input){ Pattern p = Pattern.compile(WORDS); String[] input_array = p.split(input); return input_array; } } |
Compliant Solution
This compliant solution shows the correctly escaped value of the String
literal WORDS
that results in a regular expression designed to split on word boundaries.
Code Block | ||
---|---|---|
| ||
import java.util.regex.Pattern; public class GoodSplitter { private final String WORDS = "\\b"; // Will allow splitting on word boundaries public String[] split(String input){ Pattern p = Pattern.compile(WORDS); String[] input_array = p.split(input); return input_array; } } |
Risk Assessment
Incorrect usage of escape characters in String
literals can result in misinterpretation and potential corruption of data.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MSC35-J | low | unlikely | high | P1 | L3 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[JLS 05|AA. Java References#JLS 05]\] 3.10.6 Escape Sequences for Character and String Literals \[[API 06|AA. Java References#API 06]\] [Class Pattern|http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html] "Backslashes, escapes, and quoting" \[[API 06|AA. Java References#API 06]\] [Package java.sql|http://java.sun.com/javase/6/docs/api/java/sql/package-summary.html] |