Java

Java

Made by DeepSource

Audit: Including request data within HTML response strings may lead to XSS attacks JAVA-A1035

Security
Critical
a03 cwe-20 cwe-79 sans top 25 owasp top 10

Avoid directly including request data within HTML, as this may lead to a cross-site-scripting vulnerability.

When unsanitized data from a HTTP request is used to create a HTML page to be sent back in the response, an attacker may be able to include malicious scripts or links within the response by controlling the data in the request.

Bad Practice

String userName = req.getParameter("user");

String template = "<p>Hi, %s</p>";

String renderedPage = String.format(template, userName);

PrintWriter writer = resp.getWriter();

response.setStatus(200);

writer.print(renderedPage);
writer.flush();

Here, if the request parameter user was "Ralph", the data in the response would read as:

<p>Hi, Ralph!</p>

Now, what if name contained some JavaScript code in a <script> tag?

<script>alert("hacked")</script>Ralph

If a request was sent with this data, the output in the response would look like this:

<p>Hi, <script>alert("hacked")</script>Ralph!</p>

When the user's browser displays the result of the response, an alert would pop up that said "hacked".

Obviously, this is just a simple example of what is possible. A more dangerous attack may involve malicious UI elements or popups that look similar to the real website, but are used only to gain access to account information.

Recommended

Make use of tools such as OWASP's ESAPI or Java HTML Sanitizer libraries to sanitize untrusted input data before using that data within a user-facing response.

Here is an example of using the OWASP HTML Sanitizer library, adapted from OWASP's XSS cheat sheet:

import org.owasp.html.Sanitizers;
import org.owasp.html.PolicyFactory;

// ...

PolicyFactory sanitizer = Sanitizers.FORMATTING.and(Sanitizers.BLOCKS);
String sanitizedText = sanitizer.sanitize(userName);

String safeRenderedText = String.format(template, sanitizedText);

Note that the location of text to be rendered matters greatly; escape sequences that are valid within a HTML attribute may not be valid in JavaScript code for example. For this reason, the ESAPI library provides a variety of different encoders, and context specific encoding methods within the Encode class for various use cases:

String htmlSafe = Encode.forHtml(userName);

String htmlAttrSafe = Encode.forJavaScript(userName);

References