We are trying to use ESAPI in our web app. We have following function in servlet.
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
response.setHeader(SearchConstants.CACHE_CONTROL_HEADER,
SearchConstants.MAX_AGE_ZERO);
response.setHeader(SearchConstants.CACHE_CONTROL_HEADER,
SearchConstants.NO_CACHE);
response.setDateHeader(SearchConstants.EXPIRES_HEADER, 0);
response.setHeader(SearchConstants.PRAGMA_HEADER, "no cache");
result = processRequest(request, response);
if (SearchConstants.XSLT_ERROR_MSG.equals(result)) {
LOGGER.error("XSLT ERROR FOR QUERY STRING: "
+ request.getQueryString());
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} else if (SearchConstants.SEARCH_PAGE_MISSING_MSG.equals(result)) {
LOGGER.error("NOT FOUND ERROR FOR QUERY STRING: "
+ request.getQueryString());
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} else {
final PrintWriter out = response.getWriter();
out.println(result); // this works
// out.println(ESAPI.encoder().encodeForHTML(result));
}
}
In above code if I use out.println(ESAPI.encoder().encodeForHTML(result));
, this actually prints html as text on browser. i.e. it's showing like simple text <html>
other contents.. </html>
, instead of rendering html page. result
is nothing but html contents which needs to get rendred on client.
We are doing something wrong over here. Please provide some pointers. How we can achieve encoding over here?
The Solution for your problem is not encoding but to rendere Safe HTMl.. below is the solution
import org.owasp.validator.html.*; // Import AntiSamy
String POLICY_FILE_LOCATION = "antisamy-1.4.1.xml"; // Path to policy file
String dirtyInput = "<div><script>alert(1);</script></div>"; // Your HTML RESPONSE
Policy policy = Policy.getInstance(POLICY_FILE_LOCATION); // Create Policy object
AntiSamy as = new AntiSamy(); // Create AntiSamy object
CleanResults cr = as.scan(dirtyInput, policy, AntiSamy.SAX); // Scan dirtyInput
System.out.println(cr.getCleanHTML()); // Do something with your clean output!
Before you write this code ensure that you have following: antisamy.jar
.
This jar needs below dependent jars:
You will also need policy.xml
file.