项目中防御xss攻击

###1.什么是XSS攻击
XSS攻击全称是跨站脚本攻击,是经常出现在web应用中的安全漏洞,它允许恶意web用户将代码植入到页面中,比如:sql脚本,srcipt脚本,或者html代码。
黑客界共识是:跨站脚本攻击是新型的缓冲区溢出攻击。
例如:在页面输入一个转账的sql或者js脚本,然后发给后台,后台接收浏览器参数,没有任何校验,接着执行了该脚本,造成数据被篡改。
###2.如何防御XSS攻击
我的项目是springboot项目,要防御XSS攻击只需要增加一个filter,然后在filter中包装http请求。
Talk is cheap,show me the code!
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * Created by shaomaolin on 2018/9/6.
 */
@WebFilter(urlPatterns = "/*", filterName = "XssFilter")
public class XssFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse servletResponse = (HttpServletResponse)response;
        servletResponse.setHeader("Set-Cookie", "name=value; HttpOnly");
        chain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request), servletResponse);
    }

    @Override
    public void destroy() {

    }
}

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.util.HtmlUtils;
import org.springframework.web.util.JavaScriptUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
 * Created by shaomaolin on 2018/9/6.
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper{
    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    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 (StringUtils.isBlank(value))
            return null;
        return cleanXSS(value);
    }
    private String cleanXSS(String value) {
        if (StringUtils.isNotBlank(value)) {
            value = HtmlUtils.htmlEscape(value);
            value = JavaScriptUtils.javaScriptEscape(value);
            value = StringEscapeUtils.escapeSql(value);
        }
        return value;
    }
}
 

相关推荐