Implement XSS protection based on the Antisamy project

Source: Internet
Author: User

Recently, the project was launched. A third-party company was invited to perform a penetration test and multiple XSS attacks were detected. Because we have used URLFilter to filter special characters for URL Get requests, the Get request vulnerability has been blocked. However, for Post requests, considering the existence of form submission in our project, rich text editing and other functions, dare not rashly use Filter to Filter keywords.

To solve the above problem, we adopted AntiSamy, an open-source project of OWASP, to completely solve the XSS attack problem. AntiSamy is an API that ensures that HTML, CSS, and JavaScript entered by users comply with the specifications. It ensures that users cannot submit malicious code in HTML, which is usually input into personal data, comments, and other data that will be stored by the server.

AntiSamy's:

Https://www.owasp.org/index.php/Category:OWASP_AntiSamy_Project

Project address: https://code.google.com/p/owaspantisamy/downloads/list

In addition to the antisamy-1.5.3.jar package, we also need the following jar packages.

The use of AntiSamy is as follows:

Defines an XssFilter Class, which must implement the Filter Class and implement the doFilter function in the XssFilter Class. Put the policy file in the same directory as pom. xml, and then write XssFilter.

Public class XssFilter implements Filter {@ SuppressWarnings ("unused") private FilterConfig filterConfig; public void destroy () {this. filterConfig = null;} public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {chain. doFilter (new XssRequestWrapper (HttpServletRequest) request), response);} public void init (FilterConfig filterConfig) throws ServletException {this. filterConfig = filterConfig ;}}
We need to override the request, create a class XssRequestWrapper, inherit from HttpServletRequestWrapper, and rewrite the getParameter (String param), getParameterValues (String param), and getHeader (String param) methods, and xssClean ()

Public class XssRequestWrapper extends HttpServletRequestWrapper {private static Policy policy = null; static {// String path = URLUtility. getClassPath (XssRequestWrapper. class) + File. separator + "antisamy-anythinggoes-1.4.4.xml"; String path = XssRequestWrapper. class. getClassLoader (). getResource ("antisamy-anythinggoes-1.4.4.xml "). getFile (); System. out. println ("policy_filepath:" + path); if (path. startsWith ("file") {path = path. substring (6);} try {policy = Policy. getInstance (path);} catch (PolicyException e) {e. printStackTrace () ;}} public XssRequestWrapper (HttpServletRequest request) {super (request) ;}@ SuppressWarnings ("rawtypes") public Map <String, String []> getParameterMap () {Map <String, String []> request_map = super. getParameterMap (); Iterator iterator = request_map.entrySet (). iterator (); System. out. println ("request_map" + request_map.size (); while (iterator. hasNext () {Map. entry me = (Map. entry) iterator. next (); // System. out. println (me. getKey () + ":"); String [] values = (String []) me. getValue (); for (int I = 0; I <values. length; I ++) {System. out. println (values [I]); values [I] = xssClean (values [I]) ;}return request_map;} public String [] getParameterValues (String paramString) {String [] arrayOfString1 = super. getParameterValues (paramString); if (arrayOfString1 = null) return null; int I = arrayOfString1.length; String [] arrayOfString2 = new String [I]; for (int j = 0; j <I; j ++) arrayOfString2 [j] = xssClean (arrayOfString1 [j]); return arrayOfString2;} public String getParameter (String paramString) {String str = super. getParameter (paramString); if (str = null) return null; return xssClean (str);} public String getHeader (String paramString) {String str = super. getHeader (paramString); if (str = null) return null; return xssClean (str);} private String xssClean (String value) {AntiSamy antiSamy = new AntiSamy (); try {// CleanResults cr = antiSamy. scan (dirtyInput, policyFilePath); final CleanResults cr = antiSamy. scan (value, policy); // secure HTML output return cr. getCleanHTML ();} catch (ScanException e) {e. printStackTrace ();} catch (PolicyException e) {e. printStackTrace ();} return value ;}}
When we used AntiSamy for testing, we found that xss attacks could be effectively controlled. All illegal user input was deleted or replaced, but we also found that "& nbsp; "into garbled characters and double quotation marks into" & quot ;"

To solve the conversion of these two errors, we modified the xssClean (String value) method.

Public static String xssClean (String value) {AntiSamy antiSamy = new AntiSamy (); try {final CleanResults cr = antiSamy. scan (value, policy); // safe HTML output, converts the quotation marks into safe double quotation marks String str = StringEscapeUtils. unescapeHtml (cr. getCleanHTML ());
<Span style = "white-space: pre"> </span> // Set <span style = "color: # 2A00FF;"> & nbsp; convert to space </span>
Str = str. replaceAll (antiSamy. scan ("<span style =" color: rgb (42, 0,255); "> & nbsp; </span> <span style =" color: # 362e2b; "> ", policy )). getCleanHTML (), ""); return str;} catch (ScanException e) {e. printStackTrace ();} catch (PolicyException e) {e. printStackTrace ();} return value ;}</span>
<P align = "left"> </p>



Implement XSS protection based on the Antisamy project

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.