Search code examples
jspjstlxssowaspesapi

How to defend against stored XSS inside a JSP attribute value in a form


Question How to defend against stored XSS inside a JSP attribute value in a form?

The initial code is like

<form ..>
    <input value="<c:out value="${name}"/>" type="text" />
</form>

Using c:out :

<input value="<c:out value="${name}"/>" type="text" />

or esapi:encodeForHTMLAttribute?

<%@ taglib prefix="esapi" uri="http://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API" %>
<input value="<esapi:encodeForHTMLAttribute>${name}</esapi:encodeForHTMLAttribute>" type="text" />

My first thought From what I read, the esapi encoding is the safest way. I don't think c:out is safe enough when we are writing the value of an attribute. Based on the Owasp cheat sheet to prevent xss escaping should be done different depending on the context where the value is used - attribute value in this case. c:out only escapes for HTML sensitive characters, so only these characters: & < > " ' /.

An example of vulnerability: it is possible someone deletes by mistake the characters " or ' surrounding the attribute value. The page will still be valid HTML and working well. But if the value to be inserted in the attribute is something onclick=alert(1) then, because c:out will not escape anything, we will have the html <input value=something onclick=alert(1) ... which will execute javascript on click.


Solution

  • Thanks to @avgvstvs for confirming this approach. So the safe way to go is indeed encodeForHTMLAttribute