Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

In general, for a particular escape character of the form '\X', the equivalent Java representation is:

Code Block
"\\X"

Noncompliant Code Example

This noncompliant code example defines a method splitWords() that finds matches between the String literal and the input sequence. The programmer believes that String literals can be used as is for regular expression patterns. Consequently, he initializes the string WORDS to "\b", expecting that the string literal will hold the escape sequence for matching a word boundary. However, the Java compiler treats the "\b" as a Java escape sequence, and the string WORDS silently compiles to a backspace character.

Code Block
bgColor#FFCCCC
public class BadSplitter {
  private final String WORDS = "\b"; // 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
bgColor#ccccff
public class GoodSplitter {
  private final String WORDS = "\\b"; // Allows 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 use of escape characters in String literals can result in misinterpretation and potential corruption of data.

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

IDS17-J

low

unlikely

high

P1

L3

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this guideline on the CERT website.

Bibliography

Wiki Markup
\[[API 2006|AA. Bibliography#API 06]\] [Class Pattern|http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html] "Backslashes, escapes, and quoting"
\[[API 2006|AA. Bibliography#API 06]\] [Package java.sql|http://java.sun.com/javase/6/docs/api/java/sql/package-summary.html]
\[[JLS 2005|AA. Bibliography#JLS 05]\] 3.10.6 Escape Sequences for Character and String Literals

...