Cross Site Scripting attacks - XSS

https://owasp.org/www-community/attacks/xss/

Checkmarx vulnerability - untrusted data, XSS attack

The application’s methodName() embeds untrusted data in the generated output with setCatList, at line 10 of MyClass.java. This untrusted data is embedded straight into the output without proper sanitization or encoding, enabling an attacker to inject malicious code into the output. This can enable a Reflected Cross-Site Scripting (XSS) attack.

If the checkmarx report for your application raises this issue, you need to fix it.

How to sanitize file names to avoid this checkmarx issue?

http://www.java2s.com/example/java-utility-method/file-name-sanitize-index-0.html

private String encodeValue(String value) {
    return URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
}

@Test
public void givenRequestParam_whenUTF8Scheme_thenEncode() throws Exception {
    Map<String, String> requestParams = new HashMap<>();
    requestParams.put("key1", "value 1");
    requestParams.put("key2", "value@!$2");
    requestParams.put("key3", "value%3");

    String encodedURL = requestParams.keySet().stream()
      .map(key -> key + "=" + encodeValue(requestParams.get(key)))
      .collect(joining("&", "http://www.baeldung.com?", ""));

    assertThat(testUrl, is(encodedURL));
}

Use the one above. Don’t use this one. This method converts a string into an other string that looks about as similar to the original as possible, while being save (and nice) to be used as a (part of a) file name.

private String sanitizeFilename(String name) {
  if (StringUtils.isNotEmpty(name)) {
    return name.replaceAll("[^_\\-.0-9a-zA-Z]");
  }
  return name;
}

Other helpful libraries when working with html code in Java

  1. Antisamy
  2. Jsoup

Reading material

https://www.baeldung.com/java-url-encoding-decoding


Links to this note