原由
在网上找了很多文章 但是在使用过程发现当使用jsonArray传参时并不会过滤xss,然后对网上的代码了进行更改,在此记录。。(不太会用这个复制代码格式化即可)
框架
这里只说springboot如何配置(项目就是springboot)
类
XSSFilter
1、实现filter并加入@WebFilter、@Order注解
import io.swagger.models.HttpMethod;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.core.annotation.Order;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@WebFilter(filterName = "myFilter",urlPatterns = "/*")
@Order(FilterRegistrationBean.LOWEST_PRECEDENCE)
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);
}
}
`
XSSRequestWrapper
1、继承HttpServletRequestWrapper
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections4.MapUtils;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class XSSRequestWrapper extends HttpServletRequestWrapper {
//接收表单格式数据
private Map<String, String[]> parameterMap;
private byte[] body;
public XSSRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
parameterMap = request.getParameterMap();
//由于request并没有提供现成的获取json字符串的方法,所以我们需要将body中的流转为字符串
String json = request.getReader().lines().parallel().collect(Collectors.joining(System.lineSeparator()));
//处理json传参数据
if(!StringUtils.isEmpty(json)){
if(JSONUtil.isJson(json)){
if(JSONUtil.isJsonArray(json)){
json = JSONUtil.toJsonStr(parseArray(json));
}else {
json = JSONUtil.toJsonStr(parseObject(json));
}
}
}
body = json.getBytes();
}
/**
* 处理jsonArray格式数据
* @author shenYue
* @date 2022/11/8 18:27
* @param
* @param json
* @return java.lang.String
* @Version1.0
**/
private Object parseArray(String json) {
List<Object> lists = new ArrayList<>(15);
//字符串先转为jsonArray
JSONArray jsonArray = JSONUtil.parseArray(json);
//对每个数据进行处理
for (int i = 0; i < jsonArray.size(); i++) {
String jsonStr = jsonArray.getStr(i);
//判断当前数据是否为json格式
if (JSONUtil.isJson(jsonStr)) {
//当前数据为jsonArrayStr 进行递归
if (JSONUtil.isJsonArray(jsonStr)) {
//有可能遇到jsonArray或者jsonobject使用字符串的方式传过来 单独处理
if(jsonArray.get(i) instanceof String){
lists.add(i,JSONUtil.toJsonStr(parseArray(jsonStr)));
}else {
lists.add(i,parseArray(jsonStr));
}
} else {
//当前数据为jsonObjectStr 调用parseObject
if(jsonArray.get(i) instanceof String){
lists.add(i,JSONUtil.toJsonStr(parseObject(jsonStr)));
}else {
lists.add(i,parseObject(jsonStr));
}
}
} else {
//不是json格式直接进行xss校验
lists.add(i,stripXSS(jsonStr));
}
}
return lists;
}
/**
* 处理jsonObject格式数据
*
* @param
* @param json
* @return java.lang.String
* @author shenYue
* @date 2022/11/8 18:27
* @Version1.0
*/
private Object parseObject(String json) {
HashMap<Object, Object> map = new HashMap<>();
JSONObject jsonObject = JSONUtil.parseObj(json);
//对object进行循环 处理每个对象 与parseArray同理
for (String key : jsonObject.keySet()) {
String jsonStr = jsonObject.getStr(key);
if (JSONUtil.isJson(jsonStr)) {
if (JSONUtil.isJsonArray(jsonStr)) {
if(jsonObject.get(key) instanceof String){
map.put(key, JSONUtil.toJsonStr(parseArray(jsonStr)));
}else{
map.put(key, parseArray(jsonStr));
}
} else {
if(jsonObject.get(key) instanceof String){
map.put(key, JSONUtil.toJsonStr(parseObject(jsonStr)));
}else{
map.put(key, parseObject(jsonStr));
}
}
} else {
// jsonObject.set(key, stripXSS(jsonStr));
map.put(key, stripXSS(jsonStr));
}
}
return map;
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
//以下都是网上百度到的 来源忘了 还是感谢各位大佬分享
/**
* 在使用@RequestBody注解的时候,其实框架是调用了getInputStream()方法,所以我们要重写这个方法
* @return
* @throws IOException
*/
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
@Override
public int read() throws IOException {
return bais.read();
}
};
}
@Override
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] = stripXSS(values[i]);
}
return encodedValues;
}
@Override
public String getParameter(String parameter) {
String value = super.getParameter(parameter);
return stripXSS(value);
}
@Override
public String getHeader(String name) {
String value = super.getHeader(name);
return stripXSS(value);
}
//这个方法就是通过正则表达式对每个参数进行xss校验
private String stripXSS(String value) {
//System.out.println(value);
if (value != null) {
value = value.replaceAll("", "");
// Avoid anything between script tags
Pattern scriptPattern = Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE);
value = scriptPattern.matcher(value).replaceAll("");
// Avoid anything in a src="http://www.yihaomen.com/article/java/..." type of expression
scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
// Remove any lonesome </script> tag
scriptPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE);
value = scriptPattern.matcher(value).replaceAll("");
// Remove any lonesome <script ...> tag
scriptPattern = Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
// Avoid eval(...) expressions
scriptPattern = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
// Avoid expression(...) expressions
scriptPattern = Pattern.compile("expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
// Avoid javascript:... expressions
scriptPattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE);
value = scriptPattern.matcher(value).replaceAll("");
// Avoid vbscript:... expressions
scriptPattern = Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE);
value = scriptPattern.matcher(value).replaceAll("");
// Avoid οnlοad= expressions
scriptPattern = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
scriptPattern = Pattern.compile("<(.*?)img(.*?)src=(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
}
return value;
}
}
最后还需要在启动类加上@ServletComponentScan注解
结尾
这只是一个记录,希望也能帮助到各位秃头佬