xss攻击:跨站脚本攻击(Cross Site Scripting),为不和层叠样式表(Cascading Style Sheets, CSS)的缩写混淆,故将跨站脚本攻击缩写为XSS。恶意攻击者往Web页面里插入恶意Script代码,当用户浏览该页之时,嵌入其中Web里面的Script代码会被执行,从而达到恶意攻击用户的特殊目的。
来看看简单的攻击案例:
脚本:
?nextUrl=xss%20alert%22%3C/sCript%3E%3Cscript%3E(/zheli/)%3C/script%3Ed=%22
效果图:
脚本二:/loginView?nextUrl=%27%22%2F%3E%3C%2Fscript%3E%3Cscript%3Ealert%3Cscript%3
效果图:
大家看到了吗?本来一个正常的页面经过XSS攻击后就不正常了。通过javascript还可以获取到cookie信息的。所以防御是很关键的。
下面给大家提供一个简单实用filter来处理的。
1:创建 XssHttpServletRequestWrapper 类
代码如下:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
public XssHttpServletRequestWrapper(HttpServletRequest servletRequest) {
super(servletRequest);
}
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 (value == null) {
return null;
}
return cleanXSS(value);
}
public String getHeader(String name) {
String value = super.getHeader(name);
if (value == null)
return null;
return cleanXSS(value);
}
private String cleanXSS(String value) {
//转义 <>符号的
value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
//转义 ()符号的
value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
//转义 '的
value = value.replaceAll("'", "& #39;");
//转义双引号
value = value.replaceAll("\"", " "");
//转义/的
value = value.replaceAll("/", "& #x2f;");
//转义双引号
value = value.replaceAll("\"", " "");
//转义 函数的
value = value.replaceAll("eval\\((.*)\\)", "");
//转义 javascript的
value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
value = value.replaceAll("script", "");
return value;
}
}
2:创建filter类
代码如下:
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;
public class XssFilter implements Filter {
FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
chain.doFilter(new XssHttpServletRequestWrapper(
(HttpServletRequest) request), response);
}
}
3:在web.xml中配置:
重启项目。重新访问。页面正常