SpringBoot解决xss攻击问题
⾃定义Filter
package com.stylefeng.sso.xss;
slf4j.Slf4j;
import org.apachemons.lang3.BooleanUtils;
import org.apachemons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import t.annotation.Configuration;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import Matcher;
import Pattern;
/
**
* 拦截防⽌xss注⼊
* 通过Jsoup过滤请求参数内的特定字符
*/
@WebFilter(filterName = "xssFilter", urlPatterns = "/*", asyncSupported = true)
@Slf4j
@Configuration
@Component
public class XssFilter implements Filter {
private static Logger logger = Logger(XssFilter.class);
private static boolean IS_INCLUDE_RICH_TEXT = false;//是否过滤富⽂本内容
public List<String> excludes = new ArrayList<String>();
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,ServletException {
if(logger.isDebugEnabled()){
logger.debug("xss filter is open");
}
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
if(handleExcludeURL(req, resp)){
filterChain.doFilter(request, response);
return;
}
//xss攻击过滤
Map<String, String[]> parameterMap = ParameterMap();
Map<String, String[]> map =new HashMap<>();
for (String s : parameterMap.keySet()) {
String[] arr = (s);
if(arr != null){
for (int i=0;i<arr.length;i++) {
//解码
logger.debug("解码前:"+arr[i]);
String decode = URLDecoder.decode(arr[i], "UTF-8");
logger.debug("解码后"+decode);
arr[i]= xssEncode(decode);
// arr[i] = JsoupUtil.clean(decode);
logger.debug("转义后"+arr[i]);
}
map.put(s,arr);
}
}
XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request,IS_INCLUDE_RICH_TEXT); xssRequest.setParameterMap(parameterMap);
filterChain.doFilter(xssRequest, response);
}
private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {
if (excludes == null || excludes.isEmpty()) {
return false;
}
String url = ServletPath();
for (String pattern : excludes) {
Pattern p = Patternpile("^" + pattern);
Matcher m = p.matcher(url);
if (m.find()) {
return true;
}
}
return false;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
if(logger.isDebugEnabled()){
logger.debug("xss filter init~~~~~~~~~~~~");
}
String isIncludeRichText = InitParameter("isIncludeRichText"); if(StringUtils.isNotBlank(isIncludeRichText)){
IS_INCLUDE_RICH_TEXT = Boolean(isIncludeRichText); }
String temp = InitParameter("excludes");
if (temp != null) {
String[] url = temp.split(",");
for (int i = 0; url != null && i < url.length; i++) {
excludes.add(url[i]);
}
}
}
@Override
public void destroy() {}
/**
* 将容易引起xss漏洞的半⾓字符直接替换成全⾓字符
*
* @param s
* @return
*/
private static String xssEncode(String s) {
if (s == null || "".equals(s)) {
return s;
}
StringBuilder sb = new StringBuilder(s.length() + 16);
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '>':
sb.append('>');// 全⾓⼤于号
break;
case '<':
sb.append('<');// 全⾓⼩于号
break;
case '\'':
sb.append('‘');// 全⾓单引号
break;
case '\"':
sb.append('“');// 全⾓双引号
break;
case '&':
sb.append('&');// 全⾓&
break;
case '\\':
sb.append('\');// 全⾓斜线
break;
case '/':
sb.append('/');// 全⾓斜线
break;
case '#':
sb.append('#');// 全⾓井号
break;
case '(':
sb.append('(');// 全⾓(号
break;
case ')':
sb.append(')');// 全⾓)号
break;
default:
sb.append(c);
break;
}
}
String value = String());
return value;
}
/**
*过滤script脚本
* @param value
* @return
*/
private static String stripXss(String value) {
if (StringUtils.isNotEmpty(value)) {
Pattern scriptPattern = Patternpile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE);
value = scriptPattern.matcher(value).replaceAll("");
scriptPattern = Patternpile("</script>",
Pattern.CASE_INSENSITIVE);
value = scriptPattern.matcher(value).replaceAll("");
scriptPattern = Patternpile("<script(.*?)>",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
| Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
scriptPattern = Patternpile("javascript:",
Pattern.CASE_INSENSITIVE);
value = scriptPattern.matcher(value).replaceAll("");
scriptPattern = Patternpile("<iframe>(.*?)</iframe>",
Pattern.CASE_INSENSITIVE);
value = scriptPattern.matcher(value).replaceAll("");
scriptPattern = Patternpile("</iframe>",
Pattern.CASE_INSENSITIVE);
value = scriptPattern.matcher(value).replaceAll("");
scriptPattern = Patternpile("<iframe(.*?)>",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
| Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
scriptPattern = Patternpile("onload(.*?)=",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
| Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
scriptPattern = Patternpile("oninput(.*?)=",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
| Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
scriptPattern = Patternpile("onerror(.*?)=",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
| Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
scriptPattern = Patternpile("onclick(.*?)=",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
| Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
scriptPattern = Patternpile("confirm(.*?)",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
| Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
scriptPattern = Patternpile("onfocus(.*?)=",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
| Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
scriptPattern = Patternpile("alert(.*?)",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
| Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
}
return value;
}
}
⾃定义HttpServletRequestWrapper
package com.stylefeng.sso.xss;
import org.apachemons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.HashMap;
import java.util.Map;
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
HttpServletRequest orgRequest = null;
private boolean isIncludeRichText = false;
private Map<String , String[]> params = new HashMap<String, String[]>();
public XssHttpServletRequestWrapper(HttpServletRequest request, boolean isIncludeRichText) { super(request);
orgRequest = request;
this.isIncludeRichText = isIncludeRichText;
this.params.ParameterMap());
}
/**
* 添加参数到map中
* @param extraParams
*/
public void setParameterMap(Map<String, String[]> extraParams) {
for (Map.Entry<String, String[]> entry : Set()) {
Key(), Value());
}
}
/**
* 添加参数到map中
* @param name
* @param value
*/
public void setParameter(String name, Object value) {
if (value != null) {
/
/ System.out.println(value);
if (value instanceof String[]) {
params.put(name, (String[]) value);
} else if (value instanceof String) {
params.put(name, new String[]{(String) value});
} else {
params.put(name, new String[]{String.valueOf(value)});
}
}
}
/**
* 重写getParameter,代表参数从当前类中的map获取
* @param name
* @return
*/
@Override
public String getParameter(String name) {
String[]values = (name);
if(values == null || values.length == 0) {
return null;
}
return values[0];
}
/**
* 重写getParameterValues⽅法,从当前类的 map中取值
* @param name
* @return
*/
@Override
public String[] getParameterValues(String name) {
(name);
}
/**
spring boot选择题
* 覆盖getHeader⽅法,将参数名和参数值都做xss过滤。<br/>
* 如果需要获得原始的值,则通过Headers(name)来获取<br/>
* getHeaderNames 也可能需要覆盖
*/
@Override
public String getHeader(String name) {
name = JsoupUtil.clean(name);
String value = Header(name);
if (StringUtils.isNotBlank(value)) {
value = JsoupUtil.clean(value);
}
return value;
}
/**
* 获取最原始的request
*
* @return
*/
public HttpServletRequest getOrgRequest() {
return orgRequest;
}
/**
* 获取最原始的request的静态⽅法
*
* @return
*/
public static HttpServletRequest getOrgRequest(HttpServletRequest req) {
if (req instanceof XssHttpServletRequestWrapper) {
return ((XssHttpServletRequestWrapper) req).getOrgRequest();
}
return req;
}
}
XssFilterConfig
package com.stylefeng.sso.xss;
llect.Maps;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import t.annotation.Bean;
import t.annotation.Configuration;
import java.util.Map;
/**
* @author linan144
* @date 2021/7/911:00
*/
@Configuration
public class XssFilterConfig {
/**
* xss过滤
*/
@Bean
public FilterRegistrationBean xssFilterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean (); filterRegistrationBean.setFilter(new XssFilter());
filterRegistrationBean.setOrder(1);
filterRegistrationBean.setEnabled(true);
filterRegistrationBean.addUrlPatterns("/*");
Map<String, String> initParameters = wHashMap();
initParameters.put("excludes", "/favicon.ico,/img/*,/js/*,/css/*");
initParameters.put("isIncludeRichText", "true");
filterRegistrationBean.setInitParameters(initParameters);
return filterRegistrationBean;
}
}
JsoupUtil
有些字符过滤,JsoupUtil不是太全,所以Filter中⾃定义了过滤⽅法package com.stylefeng.sso.xss;
import org.jsoup.Jsoup;
import des.Document;
import org.jsoup.safety.Whitelist;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* xss⾮法标签过滤
*/
public class JsoupUtil {
/**
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论