...
Output encoding and escaping is mandatory when accepting dangerous characters such as double quotes and angle braces. Even when input is whitelisted to disallow such characters, output escaping is recommended because it provides a second level of defense. Note that the exact escape sequence can vary depending on where the output is embedded. For example, untrusted output may occur in an HTML value attribute, CSS, URL, or script; output encoding routine will be different in each case. It is also impossible to securely use untrusted data in some contexts. Consult the OWASP XSS (Cross-Site Scripting) Prevention Cheat Sheet for more information on preventing XSS attacks.
Noncompliant Code Example
This noncompliant code example takes a user input query string and build a URL. Because the URL is not properly encoded, the URL returned may not be valid if it contains non-URL-safe characters, as per RFC 1738.
Code Block | ||
---|---|---|
| ||
String buildUrl(String q) {
String url = "https://example.com?query=" + q;
return url;
}
|
For example, if the user supplies the input string "<#catgifs>", the url
returned is "https://example.com?query=<#catgifs>"
which is not a valid URL.
Compliant Solution (Java 8)
Use java.util.Base64
to encode and decode data when transferring binary data over mediums that only allow printable characters like URLs, filenames, and MIME.
Code Block | ||
---|---|---|
| ||
String buildEncodedUrl(String q) {
String encodedUrl = "https://example.com?query=" + Base64.getUrlEncoder().encodeToString(q.getBytes());
return encodedUrl;
}
|
If the user supplies the input string "<#catgifs>", the url
returned is "
https://example.com?query=%3C%23catgifs%3E"
which is a valid URL.
Applicability
Failure to encode or escape output before it is displayed or passed across a trust boundary can result in the execution of arbitrary code.
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
The Checker Framework |
| Tainting Checker | Trust and security errors (see Chapter 8) | ||||||
Parasoft Jtest |
| CERT.IDS51.TDRESP CERT.IDS51.TDXSS | Protect against HTTP response splitting Protect against XSS vulnerabilities |
Related Vulnerabilities
The Apache GERONIMO-1474 vulnerability, reported in January 2006, allowed attackers to submit URLs containing JavaScript. The Web Access Log Viewer failed to sanitize the data it forwarded to the administrator console, thereby enabling a classic XSS attack.
Bibliography
[OWASP 2011] | Cross-site Scripting (XSS) |
[OWASP 2014] | How to Add Validation Logic to HttpServletRequest XSS (Cross-Site Scripting) Prevention Cheat Sheet |
...
...