This is one of my field in one of my jsp file:
<input class="form-input" id="login" type="text" name="login"
<c:choose>
<c:when test="${action == 'edit' && userToEdit != null}">value="${userToEdit.login}"</c:when>
<c:when test="${userFromForm != null}">value="${userFromForm.login}"</c:when>
<c:otherwise>value=""</c:otherwise>
</c:choose>
<c:if test="${action == 'edit'}">readonly="readonly"</c:if>>
At adding a user the login name is writeable and not protected against XSS attack. Could I escape userToEdit.login
and userFromForm.login
somehow? As far as I know, basically I could use c:out
for this purpose or fn:escapeXml()
(with a variable, for example). For the latter I tried something like this:
<c:set var="loginValue" value="${userToEdit.login}"/>
<c:set var="loginValueForm" value="${userFromForm.login}"/>
Inside choose:
<c:when test="${action == 'edit' && userToEdit != null}">value="${fn:escapeXml(loginValue)}"</c:when>
<c:when test="${userFromForm != null}">value="${fn:escapeXml(loginValueForm)}"</c:when>
In case of c:out I tried something like this
<c:choose>
<c:when test="${action == 'edit' && userToEdit != null}">value="<c:out value="${userToEdit.login}"/>"</c:when>
<c:when test="${userFromForm != null}">value="<c:out value="${userFromForm.login}"/>"</c:when>
<c:otherwise>value=""</c:otherwise>
</c:choose>
or something like this:
<c:choose>
<c:when test="${action == 'edit' && userToEdit != null}">value=<c:out value="${userToEdit.login}"/></c:when>
<c:when test="${userFromForm != null}">value=<c:out value="${userFromForm.login}"/></c:when>
<c:otherwise>value=""</c:otherwise>
</c:choose>
None of them worked. If I put a login name like <script>alert("test")</script>
then the script run without any problem. I tried some other possibilities but I didn't find the right syntax (if the problem is with the syntax). I do something very wrongly.
Update: solved. Possibly I was just dumb as I had to handle this problem somewhere else. When I put that script then it will goes a page where users are listed. Users are listed with the help of a custom tag and a java class belonging to it. So in the other jsp there are these parts:
<%@ taglib prefix="custom" uri="mytags.tld" %>
and
<custom:userList />
userList
uses UserList.java (extends TagSupport
) and I had to prevent XSS attack there. There I used this:
Apache Commons Text
and StringEscapeUtils.escapeHtml4
from it.
You just confuse XSS with escaping HTML output. If you use <c:out>
or ${fn.escapeXml()}
then it prevents XSS to be rendered. The tags and EL expressions are executed on the server. It doesn't execute immediately when you input <script>
tag into the input field of the form. But it's sent to the server for rendering.
You can use any escape utils to escape the html tags, js code, and xml from outputting to the response.
For further reading see Cross Site Scripting (XSS).