SpringMVC防⽌XSS注⼊
xss(Cross Site Scripting)注⼊就是,跨站脚本攻击,和sql注⼊类似的,在请求中添加恶意脚本,实现控制⽤户。XssHttpServletRequestWrappe.java
重写XssHttpServletRequestWrapper中的⽅法:
package com.henu.util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* XSS
*
* @author duxiangyu
*
*/
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
public XssHttpServletRequestWrapper(HttpServletRequest servletRequest) {
super(servletRequest);
}
public String[] getParameterValues(String parameter) {
String[] values = ParameterValues(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;
}
spring framework高危漏洞public String getParameter(String parameter) {
String value = Parameter(parameter);
if (value == null)
return null;
return cleanXSS(value);
}
public String getHeader(String name) {
String value = Header(name);
if (value == null)
return null;
return cleanXSS(value);
}
// 这⾥可以⾃⼰实现转义,也可以直接⽤⼯具类进⾏转义,⽐如说org.apachemon.lang.StringEscapeUtils和org.springframework.web.util.HtmlUtils private String cleanXSS(String str) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
switch (c) {
case '\n':
sb.append(c);
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '&':
sb.append("&");
break;
case '\'':
sb.append("'");
break;
case '"':
sb.append(""");
break;
default:
if ((c < ' ') || (c > '~')) {
sb.append("&#x");
sb.String(c, 16));
sb.append(';');
} else {
sb.append(c);
}
break;
}
}
String();
}
}
XssFilter.java
写个,对请求进⾏拦截过滤:
package com.henu.util;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
/
**
* XSS 过滤器
*
* @author duxiangyu
*
*/
public class XssFilter implements Filter {
FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
// 对request进⾏包装
public void doFilter(ServletRequest request, ServletResponse response,            FilterChain chain) throws IOException, ServletException {
chain.doFilter(new XssHttpServletRequestWrapper(
(HttpServletRequest) request), response);
}
}
在l中配置,对所有的.ht请求进⾏过滤:
<filter>
<filter-name>xssFilter</filter-name>
<filter-class>com.henu.util.XssFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>xssFilter</filter-name>
<url-pattern>*.ht</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。