xss攻击就是jq或html代码攻击,用户提交的数据是jq或html代码,
前台拿到数据库中查出的jq或html代码,浏览器会直接解析执行
重写request.getParamter()方法,在controller获取参数之前进行jq代码转换,
也就是将 <Script>所有标签代码进行替换,
在这里要注意,HttpServletRequest是个接口,
它的实现类是HttpServletRequestWrapper,所以只需要继承HttpServletRequestWrapper,
重写request.getParamter方法,
在通过过滤器将原本的HttpServeltRequest替换为自定义的HttpServeltRequest
XssHttpServletRequestWrapper
package cn.ce.ebiz.framework.front.xss;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.HashMap;
import java.util.Map;
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper{
public XssHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
}
@Override
public String[] getParameterValues(String parameter) {
String[] values = super.getParameterValues(parameter);
if (values == null || values.length < 1) {
return values;
}
int length = values.length;
String[] encodedValues = new String[length];
for (int i = 0; i < length; i++) {
String value = values[i];
if (value == null || value.length() < 1) {
continue;
}
encodedValues[i] = encodeXSS(value);
}
return encodedValues;
}
@Override
public String getParameter(String name) {
String value = super.getParameter(name);
if (value == null || value.length() < 1 ) {
return value;
}
return encodeXSS(value);
}
@Override
public String getHeader(String name) {
String value = super.getHeader(name);
if (value == null || value.length() < 1) {
return value;
}
return encodeXSS(value);
}
@Override
public Map<String, String[]> getParameterMap() {
return super.getParameterMap();
// Map<String, String[]> map = super.getParameterMap();
// if (map == null || map.isEmpty()) {
// return map;
// }
//
// Map<String, String[]> result = new HashMap<>();
// for (Map.Entry<String, String[]> entry : map.entrySet()) {
// //只处理value
// String key = entry.getKey();
// if (key == null || key.length() < 1) {
// continue;
// }
//
// String[] values = getParameterValues(key);
// result.put(key, values);
// }
//
// return result;
}
private String encodeXSS(String value) {
if (value == null || value.length() < 1) {
return value;
}
value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
value = value.replaceAll("'", "& #39;");
value = value.replaceAll("eval\\((.*)\\)", "");
value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
value = value.replaceAll("script", "");
return value;
}
}