springboot 防止xss 和sql 注入 改写 http 请求 getParameter,getParameterValues,getHeader等方法 有点东西

 

 目录

1.springboot 启动类 引入 过滤器配置

2.过滤器

3.XssAndSqlHttpServletRequestWrapper包装器 包装类

4.修改验证登录代码 这里只写了基础的 了解意思即可 

5.测试内容 

6.测试结果

7.反黑客小介绍(黑客大哥们好小弟这没啥大用O(∩_∩)O~,但是对待小白黑客还好)


springboot 防止xss 和sql 注入 改写 http 请求 getParameter,getParameterValues,getHeader等方法 有点东西_第1张图片springboot 防止xss 和sql 注入 改写 http 请求 getParameter,getParameterValues,getHeader等方法 有点东西_第2张图片springboot 防止xss 和sql 注入 改写 http 请求 getParameter,getParameterValues,getHeader等方法 有点东西_第3张图片

springboot 防止xss 和sql 注入 改写 http 请求 getParameter,getParameterValues,getHeader等方法 有点东西_第4张图片

1.springboot 启动类 引入 过滤器配置

package com.superman;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.BasicConfigurator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

import com.superman.conf.filter.XssAndSqlFilter;
import com.superman.tonifi.InitInfo;

/**
 * 项目启动类
 * 
 * @author yushen
 *
 */
@SpringBootApplication
public class Provider_App {

	/**
	 * 项目启动入口
	 * 
	 * @param args
	 */
	public static void main(String[] args) {

		SpringApplication.run(Provider_App.class, args);
		
		InitInfo.Info(); //初始化内容
		
		// 自动快速地使用缺省Log4j环境。
		BasicConfigurator.configure();

	}

	/**
	 * 防止xss 和 sql 注入 
	 * 
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Bean
	public FilterRegistrationBean xssFilterRegistrationBean() {
		FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
		filterRegistrationBean.setFilter(new XssAndSqlFilter());
		filterRegistrationBean.setOrder(1);
		filterRegistrationBean.setEnabled(true);
		filterRegistrationBean.addUrlPatterns("/*");
		filterRegistrationBean.setName("XssAndSqlFilter");
		Map initParameters = new HashMap();
		initParameters.put("excludes", "/favicon.ico,/img/*,/js/*,/css/*");
		initParameters.put("isIncludeRichText", "true");
		filterRegistrationBean.setInitParameters(initParameters);
		return filterRegistrationBean;
	}
 
	
}
  • 这个可以注册到的的地方除了springbootappliaction 以外别的 配置也可以注册更具自己选择,最好方springbootappliaction 中 方便省事

    springboot 防止xss 和sql 注入 改写 http 请求 getParameter,getParameterValues,getHeader等方法 有点东西_第5张图片 springboot 防止xss 和sql 注入 改写 http 请求 getParameter,getParameterValues,getHeader等方法 有点东西_第6张图片

2.过滤器

package com.superman.conf.filter;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

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 org.apache.commons.lang3.StringUtils;

/**
 * 防止
 * xss 和 sql 注入漏洞
 * @author yushen
 * 20200611
 *
 */
public class XssAndSqlFilter implements Filter {

	/**
	 * TODO 这个可以注册到的的地方除了springbootappliaction 以外别的 配置也可以注册更具自己选择,最好方springbootappliaction 中 方便省事
	 *
	 * @Bean
	public FilterRegistrationBean xssFilterRegistrationBean() {
		FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
		filterRegistrationBean.setFilter(new XssAndSqlFilter());
		filterRegistrationBean.setOrder(1);
		filterRegistrationBean.setEnabled(true);
		filterRegistrationBean.addUrlPatterns("/*");
		filterRegistrationBean.setName("XssAndSqlFilter");
		Map initParameters = new HashMap();
		initParameters.put("excludes", "/favicon.ico,/img/*,/js/*,/css/*");
		initParameters.put("isIncludeRichText", "true");
		filterRegistrationBean.setInitParameters(initParameters);
		return filterRegistrationBean;
	}
	 */
    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        String method = "GET";
        String param = "";
        XssAndSqlHttpServletRequestWrapper xssRequest = null;
        if (request instanceof HttpServletRequest) {
            method = ((HttpServletRequest) request).getMethod();
            xssRequest = new XssAndSqlHttpServletRequestWrapper((HttpServletRequest) request);
        }
        if ("POST".equalsIgnoreCase(method)) {
            param = this.getBodyString(xssRequest.getReader());
            if(StringUtils.isNotBlank(param)){
                if(xssRequest.checkXSSAndSql(param)){
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/json;charset=UTF-8");
                    PrintWriter out = response.getWriter();
//                    out.write(JSONResponseUtil.getWrappedERRString("您所访问的页面请求中有违反安全规则元素存在,拒绝访问!"));
                      out.write("您所访问的页面请求中有违反安全规则元素存在,拒绝访问!");
                    return;
                }
            }
        }
        if (xssRequest.checkParameter()) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
//            out.write(JSONResponseUtil.getWrappedERRString("您所访问的页面请求中有违反安全规则元素存在,拒绝访问!"));
            out.write("您所访问的页面请求中有违反安全规则元素存在,拒绝访问!");
            return;
        }
        chain.doFilter(xssRequest, response);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

    // 获取request请求body中参数
    public static String getBodyString(BufferedReader br) {
        String inputLine;
        String str = "";
        try {
            while ((inputLine = br.readLine()) != null) {
                str += inputLine;
            }
            br.close();
        } catch (IOException e) {
            System.out.println("IOException: " + e);
        }
        return str;

    }

}

springboot 防止xss 和sql 注入 改写 http 请求 getParameter,getParameterValues,getHeader等方法 有点东西_第7张图片

3.XssAndSqlHttpServletRequestWrapper包装器 包装类

package com.superman.conf.filter;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.regex.Pattern;

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

import org.springframework.util.StreamUtils;

/**
 * 过滤器相关
 * @author yushen
 * 20200611
 *	创建XssAndSqlHttpServletRequestWrapper包装器,这是实现XSS过滤的关键,
 *	在其内重写了getParameter,getParameterValues,getHeader等方法,对http请求内的参数进行了过滤
 *
 */
public class XssAndSqlHttpServletRequestWrapper extends HttpServletRequestWrapper {

    HttpServletRequest orgRequest = null;
    private Map parameterMap;
    private final byte[] body; //用于保存读取body中数据

    public XssAndSqlHttpServletRequestWrapper(HttpServletRequest request) throws IOException{
        super(request);
        orgRequest = request;
        parameterMap = request.getParameterMap();
        body = StreamUtils.copyToByteArray(request.getInputStream());
    }

    // 重写几个HttpServletRequestWrapper中的方法
    /**
     * 获取所有参数名
     *
     * @return 返回所有参数名
     */
    @Override
    public Enumeration getParameterNames() {
        Vector vector = new Vector(parameterMap.keySet());
        return vector.elements();
    }

    /**
     * 覆盖getParameter方法,将参数名和参数值都做xss & sql过滤。
* 如果需要获得原始的值,则通过super.getParameterValues(name)来获取
* getParameterNames,getParameterValues和getParameterMap也可能需要覆盖 */ @Override public String getParameter(String name) { String[] results = parameterMap.get(name); if (results == null || results.length <= 0) return null; else { String value = results[0]; if (value != null) { value = xssEncode(value); } return value; } } /** * 获取指定参数名的所有值的数组,如:checkbox的所有数据 接收数组变量 ,如checkobx类型 */ @Override public String[] getParameterValues(String name) { String[] results = parameterMap.get(name); if (results == null || results.length <= 0) return null; else { int length = results.length; for (int i = 0; i < length; i++) { results[i] = xssEncode(results[i]); } return results; } } /** * 覆盖getHeader方法,将参数名和参数值都做xss & sql过滤。
* 如果需要获得原始的值,则通过super.getHeaders(name)来获取
* getHeaderNames 也可能需要覆盖 */ @Override public String getHeader(String name) { String value = super.getHeader(xssEncode(name)); if (value != null) { value = xssEncode(value); } return value; } /** * 将容易引起xss & sql漏洞的半角字符直接替换成全角字符 * * @param s * @return */ private static String xssEncode(String s) { if (s == null || s.isEmpty()) { return s; } else { s = stripXSSAndSql(s); } StringBuilder sb = new StringBuilder(s.length() + 16); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '>': sb.append(">");// 转义大于号 break; case '<': sb.append("<");// 转义小于号 break; // case '\'': // sb.append("'");// 转义单引号 // break; // case '\"': // sb.append(""");// 转义双引号 // break; case '&': sb.append("&");// 转义& break; case '#': sb.append("#");// 转义# break; default: sb.append(c); break; } } return sb.toString(); } /** * 获取最原始的request * * @return */ public HttpServletRequest getOrgRequest() { return orgRequest; } /** * 获取最原始的request的静态方法 * * @return */ public static HttpServletRequest getOrgRequest(HttpServletRequest req) { if (req instanceof XssAndSqlHttpServletRequestWrapper) { return ((XssAndSqlHttpServletRequestWrapper) req).getOrgRequest(); } return req; } /** * * 防止xss跨脚本攻击(替换,根据实际情况调整) */ public static String stripXSSAndSql(String value) { if (value != null) { // NOTE: It's highly recommended to use the ESAPI library and // uncomment the following line to // avoid encoded attacks. // value = ESAPI.encoder().canonicalize(value); // Avoid null characters /** value = value.replaceAll("", ""); ***/ // Avoid anything between script tags Pattern scriptPattern = Pattern.compile( "<[\r\n| | ]*script[\r\n| | ]*>(.*?)", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); // Avoid anything in a // src="http://www.yihaomen.com/article/java/..." type of // e-xpression scriptPattern = Pattern.compile("src[\r\n| | ]*=[\r\n| | ]*[\\\"|\\\'](.*?)[\\\"|\\\']", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Remove any lonesome tag scriptPattern = Pattern.compile("", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); // Remove any lonesome tag scriptPattern = Pattern.compile("", Pattern.CASE_INSENSITIVE); flag = scriptPattern.matcher(value).find(); if (flag) { return flag; } // Remove any lonesome

你可能感兴趣的:(springboot 防止xss 和sql 注入 改写 http 请求 getParameter,getParameterValues,getHeader等方法 有点东西)