Prevent XSS attacks and filter special characters (parameter/response value)

Source: Internet
Author: User

Prevent XSS attacks and filter special characters (parameter/response value)

1. What is XSS attacks? XSS is a computer security vulnerability that often occurs in web applications. It allows malicious web users to implant code into pages provided to other users. For example, these codes include HTML code and client script. Attackers exploit the XSS vulnerability to bypass access control, such as the same origin policy ). This type of vulnerability is widely known because it is used by hackers to write Phishing attacks that are more harmful. For cross-site scripting attacks, the hacker community consensus is that cross-site scripting attacks are new "buffer overflow attacks", while JavaScript is the new "ShellCode ".

Ii. hazards of XSS vulnerabilities

(1) phishing, including stealing various user accounts;

(2) Stealing users' cookies to obtain users' privacy information or using their identities to further perform operations on the website;

(3) hijack a user (browser) session to perform any operations, such as illegal transfer, forced log posting, and email sending;

(4) force pop-up of advertisement pages and traffic refreshing;

(5) webpage Trojans;

(6) conduct malicious operations, such as tampering with page information or deleting Articles;

(7) Conduct a large number of client attacks, such as DDoS attacks;

(8) obtain client information, such as the user's browsing history, real IP address, and open port;

(9) control the victim's machines to initiate attacks to other websites;

(10) combine with other vulnerabilities, such as CSRF vulnerabilities, to commit further evil;

(11) enhance user permissions, including further website penetration;

(12) spread cross-site scripting worms;

......

3. How to write code to avoid

The following code can avoid XSS injection. However, due to limited knowledge, the author cannot ensure that 100% can completely shut down the XSS attackers. We also need to optimize and improve the code based on the actual situation.

Since we solve the problem through code, we try not to involve the developer's modifications to the original code, so we add a filter to intercept the processing. The original framework in this article uses springmvc.

1. IllegalCharacterFilter. java

Package com. lenovo. common. filter; import java. io. IOException; import javax. servlet. filter; import javax. servlet. filterChain; import javax. servlet. filterConfig; import javax. servlet. servletException; import javax. servlet. servletRequest; import javax. servlet. servletResponse; import javax. servlet. http. httpServletRequest;/*** invalid character filter, used to process request. invalid character in getParamater. For example, <script> alert ('000000'); </script> ** @ author single Hongyu (123) * @ myblog http://blog.csdn.net/catoop/ * @ create September 18, 2015 */Optional {@ initialize init (FilterConfig filterConfig) throws ServletException {}@ Overridepublicvoid doFilter (ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, servletException {HttpServletRequest request = (HttpServletRequest) req; request = new MHttpServletRequest (request); chain. doFilter (request, res) ;}@ Overridepublicvoid destroy (){}}

 

2. MHttpServletRequest. java

Package com. lenovo. common. filter; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletRequestWrapper; import com. lenovo. common. utils. xssShieldUtil;/*** parameter special character filter ** @ author single redwoo (365384722) * @ myblog http://blog.csdn.net/catoop/ * @ create September 18, 2015 */login {public MHttpServletRequest (HttpServletRequest request) {Super (request) ;}@ Overridepublic String getParameter (String name) {// filter return XssShieldUtil before returning the value. stripXss (super. getParameter (name);} @ Overridepublic String [] getParameterValues (String name) {// filter String [] values = super before returning values. getParameterValues (name); if (values! = Null) {for (int I = 0; I <values. length; I ++) {values [I] = XssShieldUtil. stripXss (values [I]) ;}} return values ;}}

3. XssShieldUtil. java

Package com. lenovo. common. utils; import java. util. arrayList; import java. util. list; import java. util. regex. matcher; import java. util. regex. pattern; import org. apache. commons. lang. stringUtils;/*** handle invalid characters ** @ author single Hongyu (365384722) * @ myblog http://blog.csdn.net/catoop/ * @ Create September 18, 2015 */public class XssShieldUtil {private static List <Pattern> patterns = null; private static List <Object []> getXssPatternList () {List <Object []> ret = new ArrayList <Object []> (); ret. add (new Object [] {"<(no )? Script [^>] *> .*? (No )? Script> ", Pattern. CASE_INSENSITIVE}); ret. add (new Object [] {" eval \\((.*?) \) ", Pattern. CASE_INSENSITIVE | Pattern. MULTILINE | Pattern. DOTALL}); ret. add (new Object [] {" expression \\((.*?) \) ", Pattern. CASE_INSENSITIVE | Pattern. MULTILINE | Pattern. DOTALL}); ret. add (new Object [] {"(javascript: | vbscript: | view-source :) *", Pattern. CASE_INSENSITIVE}); ret. add (new Object [] {"<(\" [^ \ "] * \" | \ '[^ \'] * \ '| [^ \' \ ">]) *> ", Pattern. CASE_INSENSITIVE | Pattern. MULTILINE | Pattern. DOTALL}); ret. add (new Object [] {"(window \\. location | window \\. | \\. location | document \\. cookie | document \\. | alert \\(. *? \) | Window \\. open \ () * ", Pattern. CASE_INSENSITIVE | Pattern. MULTILINE | Pattern. DOTALL}); ret. add (new Object [] {"<+ \ s * \ w * \ s * (oncontrolselect | oncopy | oncut | ondataavailable | ondatasetchanged | ondatasetcomplete | ondblclick | ondeactivate | ondrag | ondragend | ondragenter | ondragleave | ondragover | ondragstart | ondrop | onerror = | onerroupdate | onfilterchange | onfinish | onfocus | average | onhelp | onkeydown | onkeypress | onkeyup | average | onload | internal | onmousedown | onmouseenter | internal | onmousemove | internal | onmouseover | onmouseup | onmousewheel | onmove | onmoveend | onmovestart | onabort | onactivate | onafterprint | onafterupdate | internal | response | response | onbeforeprint | response | onbeforeupdate | onblur | response | oncellchange | onchange | onclick | oncontextmenu | onpaste | onpropertychange | response | onreset | onresize | onresizend | response | onrowenter | onrowexit | onrowsdelete | onrowsinserted | onscroll | onselect | onselectionchange | onselectstart | onstart | onstop | onsubmit | onunload) + \ s * = + ", Pattern. CASE_INSENSITIVE | Pattern. MULTILINE | Pattern. DOTALL}); returnret;} privatestaticList <Pattern> getPatterns () {if (patterns = null) {List <Pattern> list = new ArrayList <Pattern> (); string regex = null; Integer flag = null; int arrLength = 0; for (Object [] arr: getXssPatternList () {arrLength = arr. length; for (int I = 0; I <arrLength; I ++) {regex = (String) arr [0]; flag = (Integer) arr [1]; list. add (Pattern. compile (regex, flag) ;}} patterns = list;} returnpatterns;} publicstaticStringstripXss (Stringvalue) {if (StringUtils. isNotBlank (value) {Matchermatcher = null; for (Patternpattern: getPatterns () {matcher = pattern. matcher (value); // specify two conditions when two conditions are passed when two conditions exist if (matcher. find () {// please specify your own variable when generating variable value = matcher. replaceAll ("") ;}} value = value. replaceAll ("<", "<"). replaceAll (">", ">") ;}// if (LOG. isDebugEnabled () // LOG. debug ("strip value:" + value); return value;} public static void main (String [] args) {String value = null; value = XssShieldUtil. stripXss ("<scriptlanguage = text/javascript> alert (document. cookie); script> "); System. out. println ("type-1: '" + value + "'"); value = XssShieldUtil. stripXss ("<scriptsrc = ''onerror = 'alert (document. cookie) '> script> "); System. out. println ("type-2: '" + value + "'"); value = XssShieldUtil. stripXss ("script>"); System. out. println ("type-3: '" + value + "'"); value = XssShieldUtil. stripXss ("eval (abc);"); System. out. println ("type-4: '" + value + "'"); value = XssShieldUtil. stripXss ("expression (abc);"); System. out. println ("type-5: '" + value + "'"); value = XssShieldUtil. stripXss (" img> "); System. out. println ("type-6: '" + value + "'"); value = XssShieldUtil. stripXss (" "); System. out. println ("type-7: '" + value + "'"); value = XssShieldUtil. stripXss (" "); System. out. println ("type-8: '" + value + "'"); value = XssShieldUtil. stripXss ("<scriptlanguage = text/javascript> alert (document. cookie); "); System. out. println ("type-9: '" + value + "'"); value = XssShieldUtil. stripXss ("<script> window. location = 'url' "); System. out. println ("type-10: '" + value + "'"); value = XssShieldUtil. stripXss ("");}}

4. web. xml configuration

 
  
   
    IllegalCharacterFilter
   
   
    com.lenovo.common.filter.IllegalCharacterFilter
   
  
  
   
    IllegalCharacterFilter
   
   
    *.do
   
  

</Script>

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.