百度百科:
XSS攻击通常指的是通过利用网页开发时留下的漏洞,通过巧妙的方法注入恶意指令代码到网页,使用户加载并执行攻击者恶意制造的网页程序。这些恶意网页程序通常是JavaScript,但实际上也可以包括Java、 VBScript、ActiveX、 Flash 或者甚至是普通的HTML。攻击成功后,攻击者可能得到包括但不限于更高的权限(如执行一些操作)、私密网页内容、会话和cookie等各种内容。
处理方案:
/**
* xss过滤器定义
*
*/
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 XSSRequestWrapper(request) , servletResponse);
}
@Override
public void destroy() {
}
}
/**
* 对传入的恶意指令代码进行编码转换
*/
public class XSSRequestWrapper extends HttpServletRequestWrapper {
public XSSRequestWrapper(HttpServletRequest request) {
super(request);
}
@Override
public String[] getParameterValues(String name) {
//获取所有参数值的集合
String[] results = this.getParameterMap().get(name);
if (results != null && results.length > 0) {
int length = results.length;
for (int i = 0; i < length; i++) {
//过滤参数值
results[i] = HtmlUtils.htmlEscape(results[i]);
}
return results;
}
return null;
}
}
/**
* 获取项目中的所有的url,并注册到过滤器中
*/
@Component
public class FilterUrlMapping {
@Autowired
ApplicationContext applicationContext;
/**
* 获取项目中的所有url
*
* @return
*/
public Set<String> allUrlMappings() {
Set<String> result = new HashSet();
RequestMappingHandlerMapping rmhp = applicationContext.getBean(RequestMappingHandlerMapping.class);
Map<RequestMappingInfo, HandlerMethod> map = rmhp.getHandlerMethods();
for (RequestMappingInfo info : map.keySet()) {
result.add(info.getPatternsCondition().toString().replace("[", "").replace("]", ""));
}
return result;
}
@Bean
public FilterRegistrationBean filterRegistration() {
FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
filterRegistration.setFilter(new XSSFilter());//添加过滤器
Set<String> allSaveUrlPattern = allUrlMappings();// 若过滤所有,可使用 /* 处理
filterRegistration.setUrlPatterns(allSaveUrlPattern);
filterRegistration.setName("XSSFilter");
return filterRegistration;
}
}
处理效果:
1、恶意指令不会执行
2、在数据库中的存储方式发生变化:
修复前:test1<script>alert(1)</script>
修复后: test1<script>alert(22)</script>