Struts2.3 以及 2.5 過濾 xss攻擊 的一種解決方案
阿新 • • 發佈:2018-12-31
Struts 2.3
本方案採用struts2的攔截器過濾,將提交上來的引數轉碼來解決。
配置struts.xml
<package name="default" namespace="/"
extends="struts-default, json-default">
<!-- 配置攔截器 -->
<interceptors>
<!-- 定義xss攔截器 -->
<interceptor name="xssInterceptor" class ="...此處填寫攔截器類名"></interceptor>
<!-- 定義一個包含xss攔截的攔截棧 -->
<interceptor-stack name="myDefault">
<interceptor-ref name="xssInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref >
</interceptor-stack>
</interceptors>
<!-- 這個必須配置,否則攔截器不生效 -->
<default-interceptor-ref name="myDefault"></default-interceptor-ref>
<action>
...此處省略n個action
</action>
</package>
Java程式碼,攔截器實現類
import java.util.Map;
import org.apache.commons.lang3.StringEscapeUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class XssInterceptor extends AbstractInterceptor{
@Override
public String intercept(ActionInvocation invocation) throws Exception {
// TODO Auto-generated method stub
ActionContext actionContext = invocation.getInvocationContext();
Map<String, Object> map = actionContext.getParameters();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String value = ((String[])(entry.getValue()))[0];
entry.setValue(StringEscapeUtils.escapeHtml4(value));//將提交上來的字串進行轉碼
//System.out.println((entry.getValue()));
}
return invocation.invoke();
}
}
Struts 2.5
感謝使用者qq_39561487的提問才有了以下的內容:
需要注意的是,根據測試,從Struts2.3升級到Struts2.5並不能平滑升級,也就是說不能向前相容。
Apache官方修改了invocation.getInvocationContext().getParameters();介面的實現,原來返回的是一個java.util.Map,現在返回了一個org.apache.struts2.dispatcher.HttpParameters型別的物件,總體來說更加合理。
2.5版本的攔截器與2.3版本的差異主要在XssInterceptor.java這個類的intercept方法的具體實現,簡單測試了一下,應該問題不大。
public class XssInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
ActionContext actionContext = invocation.getInvocationContext();
HttpParameters parameters = actionContext.getParameters();
for (Map.Entry<String,Parameter> entry : parameters.entrySet()) {
if (!entry.getValue().isMultiple() && entry.getValue().isDefined()){
if (!entry.getValue().getValue().equals(StringEscapeUtils.escapeHtml4(entry.getValue().getValue()))){
entry.setValue(new Parameter.Request(entry.getValue().getName(),StringEscapeUtils.escapeHtml4(entry.getValue().getValue())));
}
}
}
return invocation.invoke();
}
}