Java common methods for preventing XSS attacks

Source: Internet
Author: User

1. Write the filter intercept yourself, but be aware that when you configure filter in Web. XML, put this filter in the first place.
2. Implement Esapi Library with open source, reference website: Https://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API

3. It can be implemented using the tool classes provided in spring.

One, the first method.
Web. xml file Filter configuration

<!--configuring anti-SQL Injection Filters--    <filter>        <filter-name>XssFilter</filter-name>        < filter-class> newly written xssfilter path </filter-class>    </filter>    < filter-mapping>        <filter-name>XssFilter</filter-name>        <url-pattern>/* </url-pattern>    </filter-mapping>

Writing filter Filters

 Public classXssfilterImplementsFilter {@Override Public voidInit (Filterconfig filterconfig)throwsservletexception {} @Override Public voiddestroy () {} @Override Public voidDoFilter (servletrequest request, servletresponse response, Filterchain chain)throwsIOException, servletexception {chain.dofilter (NewXssrequestwrapper ((httpservletrequest) request), response); }}

Re-implementation of ServletRequest packaging class

ImportJava.util.regex.Pattern;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletRequestWrapper; Public classXssrequestwrapperextendsHttpservletrequestwrapper { PublicXssrequestwrapper (HttpServletRequest servletrequest) {Super(ServletRequest); } @Override Publicstring[] getparametervalues (String parameter) {string[] values=Super. getparametervalues (parameter); if(Values = =NULL) {            return NULL; }        intCount =values.length; String[] Encodedvalues=NewString[count];  for(inti = 0; I < count; i++) {Encodedvalues[i]=STRIPXSS (Values[i]); }        returnencodedvalues; } @Override Publicstring GetParameter (string parameter) {String value=Super. GetParameter (parameter); returnSTRIPXSS (value); } @Override Publicstring GetHeader (string name) {String Value=Super. GetHeader (name); returnSTRIPXSS (value); }    Privatestring Stripxss (String value) {if(Value! =NULL) {            //Note:it ' s highly recommended to use the ESAPI library and uncomment the following//avoid encoded attacks. //value = Esapi.encoder (). canonicalize (value); //Avoid Null charactersValue = Value.replaceall ("", ""); //Avoid Anything between script tagsPattern Scriptpattern = Pattern.compile ("<script> (. *?) </script> ", pattern.case_insensitive); Value= Scriptpattern.matcher (value). ReplaceAll (""); //Avoid anything in a src= "..." type of e-xpressionScriptpattern = Pattern.compile ("src[\r\n]*=[\r\n]*\\\" (. *?) \\\ ' ", pattern.case_insensitive | Pattern.multiline |Pattern.dotall); Value= Scriptpattern.matcher (value). ReplaceAll (""); Scriptpattern= Pattern.compile ("src[\r\n]*=[\r\n]*\\\" (. *?) \\\ "", Pattern.case_insensitive | Pattern.multiline |Pattern.dotall); Value= Scriptpattern.matcher (value). ReplaceAll (""); //Remove any lonesome </script> tagScriptpattern = Pattern.compile ("</script>", pattern.case_insensitive); Value= Scriptpattern.matcher (value). ReplaceAll (""); //Remove any lonesome <script ...> tagScriptpattern = Pattern.compile ("<script (. *?) > ", pattern.case_insensitive | Pattern.multiline |Pattern.dotall); Value= Scriptpattern.matcher (value). ReplaceAll (""); //Avoid eval (...) e-xpressionsScriptpattern = Pattern.compile ("eval\\" (. *?) \ \) ", Pattern.case_insensitive | Pattern.multiline |Pattern.dotall); Value= Scriptpattern.matcher (value). ReplaceAll (""); //Avoid e-xpression (...) e-xpressionsScriptpattern = Pattern.compile ("e-xpression\\" (. *?) \ \) ", Pattern.case_insensitive | Pattern.multiline |Pattern.dotall); Value= Scriptpattern.matcher (value). ReplaceAll (""); //Avoid javascript: ... e-xpressionsScriptpattern = Pattern.compile ("javascript:", pattern.case_insensitive); Value= Scriptpattern.matcher (value). ReplaceAll (""); //Avoid VBScript: ... e-xpressionsScriptpattern = Pattern.compile ("VBScript:", pattern.case_insensitive); Value= Scriptpattern.matcher (value). ReplaceAll (""); //Avoid onload= e-xpressionsScriptpattern = Pattern.compile ("onload (. *?)" = ", Pattern.case_insensitive | Pattern.multiline |Pattern.dotall); Value= Scriptpattern.matcher (value). ReplaceAll (""); }        returnvalue; }}

The annotated part of the example is the recommended use of the ESAPI library to prevent XSS attacks.

Of course, I've also seen such a way to put all the programming full-width characters to the solution, but personally feel that there is no such thing as using regular expressions to replace

Private Staticstring Xssencode (string s) {if(s = =NULL|| S.equals ("")) {            returns; } StringBuilder SB=NewStringBuilder (s.length () + 16);  for(inti = 0; I < s.length (); i++) {            Charc =S.charat (i); Switch(c) { Case' > ': Sb.append (' > ');//full width greater than sign  Break;  Case' < ': Sb.append (' ');//full-width less than sign Break;  Case‘\‘‘: Sb.append (‘\\‘); Sb.append (‘\‘‘); Sb.append (‘\\‘); Sb.append (‘\‘‘);  Break;  Case‘\"‘: Sb.append (‘\\‘); Sb.append (‘\"‘);//full-width double quotes Break;  Case' & ': Sb.append (‘&‘);//Full Width Break;  Case‘\\‘: Sb.append (‘\‘);//full-width slash  Break;  Case‘#‘: Sb.append (‘#‘);//Full-width well number Break;  Case‘:‘: Sb.append (‘:‘);//full-width colon Break;  Case‘%‘: Sb.append ("\\\\%");  Break; default: Sb.append (c);  Break; }        }        returnsb.tostring (); }

Of course, there are more simple ways to do this:

 private   string CLEANXSS (string value) {  // you ' ll need to remove the spaces from the HT ML entities below  value = Value.replaceall ("<", "& lt;"). ReplaceAll (">", "& gt;"         = Value.replaceall ("\ \ (", "& #40;"). ReplaceAll ("\ \)", "& #41;"         = Value.replaceall ("'", "& #39;"         = Value.replaceall ("eval\\ ((. *) \ \)", " = Value.replaceall ("[\\\" \\\ '][\\s]*javascript: (. *) [\\\ "\\\ ']", "\" \ ")        ;        Value  = Value.replaceall ("Script", "" " return   value; }

In the background or with spring how to implement it:
First add a jar package: Commons-lang-2.5.jar, and then call these functions in the background:

Stringescapeutils.escapehtml (string); Stringescapeutils.escapejavascript (string); Stringescapeutils.escapesql (string);

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. 48649389

Java common methods for preventing XSS attacks

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.