记个加班要做的事,,,,公司项目被检测出XSS攻击漏洞
点击了解什么是XSS攻击
解决思路:自定义个过滤器,过滤掉所有请求中的非法参数
代码记录:公司名用***代替了
web.xml配置这个过滤器写在靠前的位置
<filter>
<filter-name>XssFilter</filter-name>
<filter-class>com.***.utils.XssFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>XssFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
package com.***.utils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* @Description Xss攻击参数过滤
* @Author Crazy
* @Version 2020/8/1 12:46
* @Copyright ***
*/
public class XssFilter implements Filter {
private FilterConfig filterConfig;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
/**这里只处理request请求
重写的XssServletRequest继承HttpServletRequestWrapper,这个类允许重写request的各种方法*/
chain.doFilter(new XssServletRequest((HttpServletRequest) request), response);
}
@Override
public void destroy() {
this.filterConfig=null;
}
}
package com.***.utils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* @Description Xss攻击参数过滤的具体实现
* @Author Crazy
* @Version 2020/8/1 12:49
* @Copyright ***
*/
public class XssServletRequest extends HttpServletRequestWrapper {
/**
* Constructs a request object wrapping the given request.
*
* @param request
* @throws IllegalArgumentException if the request is null
*/
public XssServletRequest(HttpServletRequest request) {
super(request);
}
@Override
public String getHeader(String par) {
return clearXssStr(super.getHeader(par));
}
@Override
public String getParameter(String par) {
return clearXssStr(super.getParameter(par));
}
/**
* 主要就是参数值过滤
* @param name
* @return
*/
@Override
public String[] getParameterValues(String par) {
String[] val = super.getParameterValues(par);
if (val == null) {
return val;
}
String[] valNew = new String[val.length];
for (int i = 0; i < val.length; i++) {
valNew[i] = clearXssStr(val[i]);
}
return valNew;
}
/**过滤内容*/
private String clearXssStr(String value) {
if (value == null || "".equals(value)) {
return value;
}
value = value .replaceAll("\\&[a-zA-Z]{0,9};", "").replaceAll("<[^>]*>", "");
value = value.replaceAll("<", "").replaceAll(">", "");
value = value.replaceAll("\\(", "").replaceAll("\\)", "");
value = value.replaceAll("'", "'");
value = value.replaceAll("eval\\((.*)\\)", "");
value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
return value;
}
}
搞定
声明:
博客中标注原创的文章,版权归本博客作者所有,若转载或者引用本文内容请注明来源及原作者,否则依法保留追究权
==如果帮到你了点个赞呗