Java Filter过滤XSS注入非法参数
程序员文章站
2024-02-08 17:35:22
...
XSS又称CSS,全称Cross SiteScript,跨站脚本攻击,是Web程序中常见的漏洞,XSS属于被动式且用于客户端的攻击方式,所以容易被忽略其危害性。其原理是攻击者向有XSS漏洞的网站中输入(传入)恶意的HTML代码,当其它用户浏览该网站时,这段HTML代码会自动执行,从而达到攻击的目的。如,盗取用户Cookie、破坏页面结构、重定向到其它网站等。
web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<filter>
<filter-name>ParametersFilter</filter-name>
<filter-class>com.aiTech.filter.ParametersFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ParametersFilter</filter-name>
<url-pattern>/web/*</url-pattern>
</filter-mapping>
</web-app>
过滤器代码:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public final class RequestWrapper extends HttpServletRequestWrapper
{
public RequestWrapper(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;
try {
value = super.getParameter(parameter);
}
catch (Exception e)
{
value = "";
}
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("/\\*(.|[\\r\\n])*?\\*/", "");
value = value.replaceAll("<", "<").replaceAll(">", ">");
value = value.replaceAll("\\(", "(").replaceAll("\\)", ")");
value = value.replaceAll("'", "'").replaceAll("\"", """);
value = value.replaceAll("(?i)eval", "");
value = value.replaceAll("(?i)javascript", "");
value = value.replaceAll("(?i)expression", "");
value = value.replaceAll("(?i)script", "");
return value;
}
}