XSS腳本過濾
腳本攻擊經(jīng)常是項目測試人員或者“不法分子”閑著沒事干,想辦法讓你的程序不正常狞洋,最近項目中剛好用到所以就貼出來做個筆記变屁。
1.思路
我們可以通過servlet規(guī)范中的過濾器,對每一次請求進(jìn)行過濾 --> 將請求參數(shù)獲取到對腳本數(shù)據(jù)進(jìn)行轉(zhuǎn)義處理后再進(jìn)行持久化操作继低,比如< script > < /script>中的'<' ,'>'號竹宋。
2.配置過濾器
在項目中web.xml中添加:
<filter>
<filter-name>XSSEscape</filter-name>
<filter-class>com.hp.up.front.xss.XSSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>XSSEscape</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
其中com.hp.up.front.xss.XSSFilter就是過濾器路徑
3.編寫過濾器
自然是實現(xiàn)javax.servlet.Filter 重寫doFilter了:
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 {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
chain.doFilter(new XSSRequestWrapper((HttpServletRequest) request), response);
}
}
doFilter方法中傳入XSSRequestWrapper對象劳澄,該類集成自HttpServletRequestWrapper,其實就是對HttpServletRequest中獲取參數(shù)的方法的重寫蜈七,從而實現(xiàn)對參數(shù)進(jìn)行過濾秒拔、操作
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.lang.StringEscapeUtils;
public class XSSRequestWrapper extends HttpServletRequestWrapper{
public XSSRequestWrapper(HttpServletRequest request) {
super(request);
}
@Override
public String getHeader(String name) {
return StringEscapeUtils.escapeHtml(super.getHeader(name));
}
@Override
public String getQueryString() {
return StringEscapeUtils.escapeHtml(super.getQueryString());
}
@Override
public String getParameter(String name) {
return StringEscapeUtils.escapeHtml(super.getParameter(name));
}
@Override
public String[] getParameterValues(String name) {
String[] values = super.getParameterValues(name);
if(values != null) {
int length = values.length;
String[] escapseValues = new String[length];
for(int i = 0; i < length; i++){
escapseValues[i] = htmlEncode(values[i]);
}
return escapseValues;
}
return super.getParameterValues(name);
}
private static String htmlEncode(String source) {
if (source == null) {
return "";
}
String html = "";
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < source.length(); i++) {
char c = source.charAt(i);
switch (c) {
case '<':
buffer.append("<");
break;
case '>':
buffer.append(">");
break;
case '&':
buffer.append("&");
break;
case '"':
buffer.append(""");
break;
case 10:
case 13:
break;
default:
buffer.append(c);
}
}
html = buffer.toString();
return html;
}
}
最終發(fā)現(xiàn)每次提交數(shù)據(jù)攔截器都會對數(shù)據(jù)中的腳本進(jìn)行轉(zhuǎn)義后再存到數(shù)據(jù)庫中: