Xss过滤器之文件上传特殊处理

当表单提交的enctype="multipart/form-data" 且同一个页面中有附件上传功能时,xss过滤器需要做特殊处理

package com.ffcs.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;
import javax.servlet.http.HttpServletResponse;

public class XssFilter implements Filter {
  
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    //替换了request
   
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        String currentURL = req.getRequestURI();//截取当前文件名用于比较
        String head = req.getHeader("Content-Type");

        if(currentURL.contains(".jsp")||currentURL.contains(".do")||currentURL.equals("/")){
            System.out.println(head);
            if(head!=null){
                if(!head.contains("application/x-www-form-urlencoded")){//payload
                    chain.doFilter(new PayloadXssRequest(req),res);//核心,替换了request
                    System.out.println("payload");
                }else {//form data
                    System.out.println("form data");
                    chain.doFilter(new FormDataXssRequest(req),res);
                }
            }else {
                chain.doFilter(req,res);
            }
        }else {
            chain.doFilter(req,res);
        }

    }

    @Override
    public void destroy() {

    }
}
package com.ffcs.common.filter;

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

public class FormDataXssRequest extends HttpServletRequestWrapper {
   /**
    * Constructs a request object wrapping the given request.
    *
    * @param request
    * @throws IllegalArgumentException if the request is null
    */
   public FormDataXssRequest(HttpServletRequest request) {
       super(request);
   }
   //替换非法字符
   private String clean(String s){
       System.out.println("do xss");
       s=s.replaceAll("<","<").replaceAll("script","").replaceAll("eval\\((.*)\\)","");
       return s;
   }

   @Override
   public String[] getParameterValues(String name) {
       String[] values = super.getParameterValues(name);
       if(values==null){
           return null;
       }
       int count = values.length;
       String[] encodedValues = new String[count];
       for(int i= 0;i
package com.ffcs.common.filter;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

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

public class PayloadXssRequest extends HttpServletRequestWrapper {

    private final String body;

    /**
     * Constructs a request object wrapping the given request.
     *
     * @param request
     * @throws IllegalArgumentException if the request is null
     */
    public PayloadXssRequest(HttpServletRequest request) throws IOException {
        super(request);
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            InputStream inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[1024];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                stringBuilder.append("");
            }
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    throw ex;
                }
            }
        }
        body = stringBuilder.toString();
    }


    //替换非法字符
    private String clean(String s) {
        System.out.println("do xss :"+s);
        s = s.replaceAll("script", "").replaceAll("eval\\((.*)\\)", "");

        return s;
    }




    /**
     * Read Request Body payload  in Filter
     * 读取输入流,,文件post时采用这种方式
     *
     * @return
     * @throws IOException
     */
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }


    /**
     * Read Request Body payload  in Filter
     * 读取输入流,,文件post时采用这种方式
     *
     * @return
     * @throws IOException
     */
    public ServletInputStream getInputStream() throws IOException {
        System.out.println("getInputStream");
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(clean(body).getBytes());//在这里过滤非法字符
        ServletInputStream servletInputStream = new ServletInputStream() {
            public boolean isFinished() {
                return false;
            }

            public boolean isReady() {
                return false;
            }

            public void setReadListener(ReadListener readListener) {

            }

            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
        return servletInputStream;
    }

}

 最后在web.xml中添加如下配置即可(以下为我项目中的配置)

    
		XssFilter
		com.ffcs.common.filter.XssFilter
		
			encoding
			UTF-8
		
		
	
		XssFilter
		*.do
	
	
		XssFilter
		*.jsp
	  

 

 

 

你可能感兴趣的:(Xss过滤器之文件上传特殊处理)