Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added CS about Pattern.quote()

...

Code Block
bgColor#ccccff
	public static void FindLogEntry(String search) {
		// Sanitize search string
		StringBuilder sb = new StringBuilder(search.length());
		for (int i = 0; i < search.length(); ++i) {
			char ch = search.charAt(i);
			if (Character.isLetterOrDigit(ch) || ch == ' ' || ch == '\'') {
				sb.append(ch);
			}
		}
		search = sb.toString();
		
		// Construct regex dynamically from user string
		String regex = "(.*? +public\\[\\d+\\] +.*" + search + ".*)";
        // ...
    }

This solution prevents regex injection but also restricts search terms. For example, a user may no longer search for "name =" because nonalphanumeric characters are removed from the search term.

Compliant Solution (Pattern.quote())

This compliant solution sanitizes the search terms by using Pattern.quote() to escape any malicious characters in the search string. Unlike the previous compliant solution, a search string using punctuation characters, such as "name =" is permitted.

Code Block
bgColor#ccccff
	public static void FindLogEntry(String search) {
		// Sanitize search string
        search = Pattern.quote(search);
		// Construct regex dynamically from user string
		String regex = "(.*? +public\\[\\d+\\] +.*" + search + ".*)";
        // ...
    }

The  Matcher.quoteReplacement() method can be used to escape strings used when doing regex substitution.

Compliant Solution

Another method of mitigating this vulnerability is to filter out the sensitive information prior to matching. Such a solution would require the filtering to be done every time the log file is periodically refreshed, incurring extra complexity and a performance penalty. Sensitive information may still be exposed if the log format changes but the class is not also refactored to accommodate these changes.

...