views:

98

answers:

1

I am trying to resolve a cross site scripting exception in my code. I'm getting an XSS error at line where I was using JSP expression inside a JS code

ex: inside a JS function

function ex(){
    .....
    var loc = '<%= location.getLocDetails()>';
    .....
}

Please let me know, if you have any solution/workaround?
Note: location.getLocDetails() returns a String

A: 

There's only means of XSS risks if location.getLocDetails() can return user-controlled input. If it for example returns the value straight from the HTTP Accept-Language header without any syntax checking or escaping, then there's indeed means of XSS risks.

You should always escape user-controlled input during display, at least every input which can to a certain degree be controlled by the client, including HTTP request headers and request URL's. It is basically is fairly simple, just use a display tool which escapes HTML entities <, >, " and '.

In case of JSP, easiest way is to use JSTL (just drop jstl-1.2.jar in /WEB-INF/lib if not done yet) <c:out> tag for this. Thus the particular line should be replaced by (assuming that location is already available in page, request, session or application scope):

var loc = '<c:out value="${location.locDetails}" />';

That said, it's right high time to get rid of all scriptlets in your JSP file, it would only make it better :) To learn more about JSTL, read this.

BalusC
Another way to escape it is using ${fn:escapeXml(location.locDetails)}. I find it less cluttered.
Manolo Santos
@Manolo Santos: Matter of taste. If inside a HTML tag, e.g. `<input value="${fn:escapeXml(foo)}">`, then `fn:escapeXml` is nicer. If outside, it doesn't matter to me. The `c:out` has however as being a tag the advantage that you can put multiple expressions in it.
BalusC