转自:http://www.what21.com/programming/java/javaweb-summary/xss3.html
Java防止跨站脚本(XSS)注入攻击
前边既说明了XSS攻击的危害性,也通过模拟案例了解了XSS攻击原理,这里就介绍一下如何防御XSS攻击。
采用Filter技术,对所有参数都进行过滤,处理方案为:
1. 含有html标签做转义。
2. 含有敏感的html脚本,直接处理掉。
XSS Filter源码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
package
import
import
import
import
import
import
import
import
import
import
public
XSSFilter
implements
// XSS处理Map
private
Map<String,String> xssMap =
new
public
init(FilterConfig filterConfig)
throws
// 含有脚本: script
xssMap.put(
"[s|S][c|C][r|R][i|C][p|P][t|T]"
,
""
);
// 含有脚本 javascript
xssMap.put(
"[\\\"\\\'][\\s]*[j|J][a|A][v|V][a|A][s|S][c|C][r|R][i|I][p|P][t|T]:(.*)[\\\"\\\']"
,
"\"\""
);
// 含有函数: eval
xssMap.put(
"[e|E][v|V][a|A][l|L]\\((.*)\\)"
,
""
);
// 含有符号 <
xssMap.put(
"<"
,
"<"
);
// 含有符号 >
xssMap.put(
">"
,
">"
);
// 含有符号 (
xssMap.put(
"\\("
,
"("
);
// 含有符号 )
xssMap.put(
"\\)"
,
")"
);
// 含有符号 '
xssMap.put(
"'"
,
"'"
);
// 含有符号 "
xssMap.put(
"\""
,
""
");
}
public
doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws
// 强制类型转换 HttpServletRequest
HttpServletRequest httpReq = (HttpServletRequest)request;
// 构造HttpRequestWrapper对象处理XSS
HttpRequestWrapper httpReqWarp =
new
//
chain.doFilter(httpReqWarp, response);
}
public
destroy() {
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
package
import
import
import
import
public
class
HttpRequestWrapper
extends
private
public
super
(request);
}
public
Map<String, String> xssMap) {
super
(request);
this
.xssMap = xssMap;
}
@Override
public
String[] values =
super
.getParameterValues(parameter);
if
null
) {
return
;
}
int
// 遍历每一个参数,检查是否含有
String[] encodedValues =
new
for
int
0
; i < count; i++) {
encodedValues[i] = cleanXSS(values[i]);
}
return
}
@Override
public
String value =
super
.getParameter(parameter);
if
null
) {
return
;
}
return
}
public
String value =
super
.getHeader(name);
if
null
)
return
;
return
}
/**
* 清除恶意的XSS脚本
*
* @param value
* @return
*/
private
Set<String> keySet = xssMap.keySet();
for
(String key : keySet){
String v = xssMap.get(key);
value = value.replaceAll(key,v);
}
return
}
}
|
1
2
3
4
5
6
7
8
|
<filter>
<filter-name>XSSFilter</filter-name>
<filter-
class
>com.what21.filter.xss.XSSFilter</filter-
class
>
</filter>
<filter-mapping>
<filter-name>XSSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
|