过滤器filter:
public class XSSProtectFilter
implements Filter
{
private static final Logger logger = Logger.getLogger(XSSProtectFilter.class);
private static String[] safeless = new String[0];
private static String xssAtackRedirectPath = "";
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)
throws IOException, ServletException
{
Enumeration params = req.getParameterNames();
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)resp;
boolean isSafe = true;
String requestUrl = request.getRequestURI();
if (isSafe(requestUrl)) {
while (params.hasMoreElements())
{
String cache = req.getParameter((String)params.nextElement());
if ((cache != null) && (!cache.isEmpty()) &&
(!isSafe(cache)))
{
isSafe = false;
break;
}
}
} else {
isSafe = false;
}
if (!isSafe)
{
logger.info("=========xss atack redirect path :" +
xssAtackRedirectPath);
response.sendRedirect(request.getContextPath() +
xssAtackRedirectPath);
return;
}
filterChain.doFilter(req, resp);
}
private static boolean isSafe(String str)
{
if ((str != null) && (!str.isEmpty())) {
for (String s : safeless) {
if (str.toLowerCase().contains(s))
{
logger.info("=========请求参数(" + str + ")包含非法参数:" + s);
return false;
}
}
}
return true;
}
public void destroy() {}
public void init(FilterConfig config)
throws ServletException
{
String filterSymbols = config.getInitParameter("filterSymbols");
if ((filterSymbols != null) && (filterSymbols.length() > 0)) {
safeless = filterSymbols.split("\\|");
}
String errorPagePath = config
.getInitParameter("xssAtackRedirectPageUrl");
if ((errorPagePath != null) && (!errorPagePath.isEmpty())) {
xssAtackRedirectPath = errorPagePath;
}
}
}
web.xml配置
<filter>
<filter-name>XSSProtectFilter</filter-name>
<filter-class>
com.test.security.filter.XSSProtectFilter
</filter-class>
<init-param>
<param-name>filterSymbols</param-name>
<param-value>
<![CDATA[;|'|"|\*|<|>|\"|#|alert|<script|</script|<iframe|</iframe|<frame|</frame|set-cookie|%3cscript|%3c/script
|%3ciframe|%3c/iframe|%3cframe|%3c/frame|src=\"javascript:|<body|</body|%3cbody|%3c/body|src|onload
|onmouseover|onblue|onkeydown|onchange|onclick|ondblclick|onmouseup|onmousemove|onkeypress
|onkeyup|onmove|onresize|onscroll|onstop|onfocus|onsubmit|||]]>
</param-value>
</init-param>
<init-param>
<param-name>xssAtackRedirectPath</param-name>
<param-value>/</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>XSSProtectFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>