Java防止XSS攻击

Posted myyBlog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java防止XSS攻击相关的知识,希望对你有一定的参考价值。

方法一:

1.添加XssFilter 

技术分享图片
@Configuration
public class XssFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        filterChain.doFilter(new XssHttpServletRequestWrapper(request),servletResponse);
    }

    @Override
    public void destroy() {

    }
}
XSSFilter

2.添加XssHttpServletRequestWrapper.java类

技术分享图片
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {  
  
    public XssHttpServletRequestWrapper(HttpServletRequest request) {  
        super(request);  
    }  
  
    @Override  
    public String getHeader(String name) {  
        return StringEscapeUtils.escapehtml4(super.getHeader(name));  
    }  
  
    @Override  
    public String getQueryString() {  
        return StringEscapeUtils.escapeHtml4(super.getQueryString());  
    }  
  
    @Override  
    public String getParameter(String name) {  
        return StringEscapeUtils.escapeHtml4(super.getParameter(name));  
    }  
  
    @Override  
    public String[] getParameterValues(String name) {  
        String[] values = super.getParameterValues(name);  
        if(values != null) {  
            int length = values.length;  
            String[] escapseValues = new String[length];  
            for(int i = 0; i < length; i++){  
                escapseValues[i] = StringEscapeUtils.escapeHtml4(values[i]);  
            }  
            return escapseValues;  
        }  
        return super.getParameterValues(name);  
    }  
      
}  
XssHttpServletRequestWrapper

自此,即能实现,

假如在网站的文本框输入<script>alert("OK");</script>,

提交到数据库后保存的数据为:&amp;lt;script&amp;gt;alert(&amp;quot;OK&amp;quot;);&amp;lt;/script&amp;gt;

 方法二:

1.添加XssFilter ,(同上)

2..添加XssHttpServletRequestWrapper.java类

技术分享图片
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
    /**
     * Constructs a request object wrapping the given request.
     *
     * @param request The request to wrap
     * @throws IllegalArgumentException if the request is null
     */
    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public String getHeader(String name) {
        String value = super.getHeader(name);
        if(StringUtils.isEmpty(value)){
            return value;
        }
        else{
            return cleanXSS(value);
        }

    }

    @Override
    public String getParameter(String name) {
        String value = super.getParameter(name);
        if(StringUtils.isEmpty(value)){
            return value;
        }
        else{
            return cleanXSS(value);
        }
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] values = super.getParameterValues(name);
        if (values != null) {
            int length = values.length;
            String[] escapseValues = new String[length];
            for (int i = 0; i < length; i++) {
                escapseValues[i] = cleanXSS(values[i]);
            }
            return escapseValues;
        }
        return super.getParameterValues(name);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        String str=getRequestBody(super.getInputStream());
        str=cleanXSS(str);
        final ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes());

        return new ServletInputStream() {

            @Override
            public int read() throws IOException {
                return bais.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener listener) {

            }
        };
    }

    private String getRequestBody(InputStream stream) {
        String line = "";
        StringBuilder body = new StringBuilder();
        int counter = 0;

        // 读取POST提交的数据内容
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream, Charset.forName("UTF-8")));
        try {
            while ((line = reader.readLine()) != null) {

                body.append(line);
                counter++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return body.toString();
    }
    private String cleanXSS(String value) {
        if(StringUtils.isEmpty(value)){
            return value;
        }
        else{
            value = value.replaceAll("<", "");
            value = value.replaceAll(">", "");

            String tmp="^script$";
            value = value.replaceAll(tmp, "");
            return value;
        }
    }
}
XssHttpServletRequestWrapper

两种方法,原理一致只是写法不一样,

第二种写法保存到数据库为:scriptalert("OK");/script

 

以上是关于Java防止XSS攻击的主要内容,如果未能解决你的问题,请参考以下文章

java 防止xss攻击

开发:防止xss,sql注入,clickjacking攻击的工具类编写

如何使用 Java 防止 XSS 攻击或 Rest API JSON 中的不可信数据?

java 防止 XSS 攻击的常用方法

防止xss攻击的核心代码

Web安全之防止XSS跨站脚本攻击