0

I have a JSP page with a scriptlet of the form

<%
String imageId = request.getParameter("imageId");
if(getImageById == null){
    throw new JspException("No data found for " + imageId);
}
%>

When the exception is thrown, the request parameter "imageId" is printed, allowing an XSS attack.

What's the best way to sanitize the input to Exception() to prevent this?

PiotrChernin
  • 441
  • 8
  • 18

1 Answers1

2

It depends on what image id should be.

If it's a number then try to parse it first. If you are expecting string data (like a GUID) you chould check that it follows the spec.

In either case - if the Id is not valid then don't pass it back - just say no data found.

If the ID can be any random set of characters, then on the JSP side use the JSTL

<c:out value="${myId}"/>

or

escapeXml(myId)

from

<%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="t" %>

This may help: How can I escape special HTML characters in JSP?

Or this: Recommended method for escaping HTML in Java

Here is a sanitizer by OWASP: https://github.com/owasp/java-html-sanitizer

Community
  • 1
  • 1
Allan
  • 2,889
  • 2
  • 27
  • 38
  • I've been using tags and fn:escapeXml() in other areas, but I can't use either of those inside a scriptlet, can I? – PiotrChernin May 16 '17 at 16:15
  • 1
    I just added another SO question for Java. Do you need to display the ID? Do you have anymore info about the format of the ID? – Allan May 16 '17 at 16:19
  • This isn't my code. I can look up some examples of the ID, but I can't be certain that I can account for every possible valid form as intended by whoever wrote it. I was hoping something simple like or fn:escapeXml but for pure Java would exist. I need to fix the code while leaving it as close to its functioning form as possible, which means displaying the ID. – PiotrChernin May 16 '17 at 16:46
  • 1
    The 2nd link and 3rd links have utilities that can escape HTML. You would need to include the library in your code base. – Allan May 16 '17 at 17:27