xss漏洞完美解决方法

 搞什么安全漏洞检查,在加个防止恶意弹窗的吧

package com.wh.tms.xss;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper{

	public XssHttpServletRequestWrapper(HttpServletRequest servletRequest) {
		super(servletRequest);
		
	}
	public String[] getParameterValues(String parameter) {
	      String[] values = super.getParameterValues(parameter);
	      if (values==null)  {
	                  return null;
	          }
	      int count = values.length;
	      String[] encodedValues = new String[count];
	      for (int i = 0; i < count; i++) {
	                 encodedValues[i] = cleanXSS(values[i]);
	       }
	      return encodedValues;
	    }
	    public String getParameter(String parameter) {
	          String value = super.getParameter(parameter);
	          if (value == null) {
	                 return null;
	                  }
	          return cleanXSS(value);
	    }
	    public String getHeader(String name) {
	        String value = super.getHeader(name);
	        if (value == null)
	            return null;
	        return cleanXSS(value);
	    }
	    private String cleanXSS(String value) {
	        value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
	        value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
	        value = value.replaceAll("'", "& #39;");
	        value = value.replaceAll("eval\\((.*)\\)", "");
	        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
	        value = value.replaceAll("script", "");
	        return value;
	    }

}
package com.wh.tms.xss;

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;

public class XssFilter implements Filter{

	FilterConfig filterConfig = null;
	 
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }
 
    public void destroy() {
        this.filterConfig = null;
    }
 
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        chain.doFilter(new XssHttpServletRequestWrapper( (HttpServletRequest) request), response);
    }

}

在filter里完成恶意字符串的过滤,如果有更多的过滤,可以再clear方法中过滤更多的恶意输入.

主要防止

你可能感兴趣的:(xss)