spring boot实战之XSS过滤

XSS攻击全称跨站脚本攻击,是为不和层叠样式表(Cascading Style Sheets, CSS)的缩写混淆,故将跨站脚本攻击缩写为XSS,XSS是一种在web应用中的计算机安全漏洞,它允许恶意web用户将代码植入到提供给其它用户使用的页面中。

你可以自己做个简单尝试:
1. 在任何一个表单内,你输入一段简单的js代码:,将其存入数据库;
2. 在页面上一个div元素内直接展示第一步内存入的值,你会发现弹出框出现了;

以上XSS攻击只算一个小恶作剧,但如果这玩意被发到了网站的首页上,我估计老板一定会因为频繁的投诉而和你来场愉快的谈话…

以上两个示例仅仅算是恶作剧,恶意用户能做的更多,如获取用户信息,进行“网络钓鱼”攻击等。

应对XSS攻击的其中一个方式就是后端对输入内容进行过滤,输入内容里面的敏感信息直接过滤,如sss"; System.out.println(clean(text)); } }

2、创建XssHttpServletRequestWrapper

这是实现XSS过滤的关键,在其内重写了getParameter,getParameterValues,getHeader等方法,对http请求内的参数进行了过滤。

public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {  
    HttpServletRequest orgRequest = null;  
    private boolean isIncludeRichText = false;

    public XssHttpServletRequestWrapper(HttpServletRequest request, boolean isIncludeRichText) {  
        super(request);  
        orgRequest = request;
        this.isIncludeRichText = isIncludeRichText;
    }  

    /** 
    * 覆盖getParameter方法,将参数名和参数值都做xss过滤。
* 如果需要获得原始的值,则通过super.getParameterValues(name)来获取
* getParameterNames,getParameterValues和getParameterMap也可能需要覆盖 */ @Override public String getParameter(String name) { if(("content".equals(name) || name.endsWith("WithHtml")) && !isIncludeRichText){ return super.getParameter(name); } name = JsoupUtil.clean(name); String value = super.getParameter(name); if (StringUtils.isNotBlank(value)) { value = JsoupUtil.clean(value); } return value; } @Override public String[] getParameterValues(String name) { String[] arr = super.getParameterValues(name); if(arr != null){ for (int i=0;i * 如果需要获得原始的值,则通过super.getHeaders(name)来获取
* getHeaderNames 也可能需要覆盖 */ @Override public String getHeader(String name) { name = JsoupUtil.clean(name); String value = super.getHeader(name); if (StringUtils.isNotBlank(value)) { value = JsoupUtil.clean(value); } return value; } /** * 获取最原始的request * * @return */ public HttpServletRequest getOrgRequest() { return orgRequest; } /** * 获取最原始的request的静态方法 * * @return */ public static HttpServletRequest getOrgRequest(HttpServletRequest req) { if (req instanceof XssHttpServletRequestWrapper) { return ((XssHttpServletRequestWrapper) req).getOrgRequest(); } return req; } }

3、创建XssFilter

XssFilter是过滤XSS请求的入口,在这里通过XssHttpServletRequestWrapper将HttpServletRequest进行了封装,filterChain.doFilter(xssRequest, response);保证了后续代码执行request.getParameter,request.getParameterValues,request.getHeader时调用的都是XssHttpServletRequestWrapper内重写的方法,获取到的参数是已经进行过标签过滤的内容,从而消除了敏感信息。

/** 
 * 拦截防止xss注入
 * 通过Jsoup过滤请求参数内的特定字符
 * @author yangwk 
 */  
public class XssFilter implements Filter {  
    private static Logger logger = LoggerFactory.getLogger(XssFilter.class);

    private static boolean IS_INCLUDE_RICH_TEXT = false;//是否过滤富文本内容

    public List excludes = new ArrayList();

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,ServletException {  
        if(logger.isDebugEnabled()){
            logger.debug("xss filter is open");
        }

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        if(handleExcludeURL(req, resp)){
            filterChain.doFilter(request, response);
            return;
        }

        XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request,IS_INCLUDE_RICH_TEXT);
        filterChain.doFilter(xssRequest, response);
    }

    private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {

        if (excludes == null || excludes.isEmpty()) {
            return false;
        }

        String url = request.getServletPath();
        for (String pattern : excludes) {
            Pattern p = Pattern.compile("^" + pattern);
            Matcher m = p.matcher(url);
            if (m.find()) {
                return true;
            }
        }

        return false;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        if(logger.isDebugEnabled()){
            logger.debug("xss filter init~~~~~~~~~~~~");
        }
        String isIncludeRichText = filterConfig.getInitParameter("isIncludeRichText");
        if(StringUtils.isNotBlank(isIncludeRichText)){
            IS_INCLUDE_RICH_TEXT = BooleanUtils.toBoolean(isIncludeRichText);
        }

        String temp = filterConfig.getInitParameter("excludes");
        if (temp != null) {
            String[] url = temp.split(",");
            for (int i = 0; url != null && i < url.length; i++) {
                excludes.add(url[i]);
            }
        }
    }

    @Override
    public void destroy() {}  

}

4、注册XssFilter

通过java config的方式注册XSSFilter,使其生效。

/**
 * xss过滤拦截器
 */
@Bean
public FilterRegistrationBean xssFilterRegistrationBean() {
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
    filterRegistrationBean.setFilter(new XssFilter());
    filterRegistrationBean.setOrder(1);
    filterRegistrationBean.setEnabled(true);
    filterRegistrationBean.addUrlPatterns("/*");
    Map initParameters = Maps.newHashMap();
    initParameters.put("excludes", "/favicon.ico,/img/*,/js/*,/css/*");
    initParameters.put("isIncludeRichText", "true");
    filterRegistrationBean.setInitParameters(initParameters);
    return filterRegistrationBean;
}
  • excludes用于配置不需要参数过滤的请求url
  • isIncludeRichText默认为true,主要用于设置富文本(项目内约束以content为名或以WithHtml结尾)内容是否需要过滤,该选项可根据公司具体情况调整,建议约束富文本编辑框支持的标签并开启改约束,减少安全隐患

小结

防御XSS攻击,可以通过后端统一进行标签过滤,去掉所有输入内容中包含的类似于

你可能感兴趣的:(spring-boot)