青锋开源产品漏洞防护升级!!!
需要源码的朋友码云搜索青锋,或者私信留V。期待与您一起交流。
一、升级文件介绍
1、增加XSS拦截器

2、新增CRSF拦截器

ShiroConfig修改内容如下:


2、修改配置文件

3、修复CRSF页面

4、增加xss.js过滤



二、XSS代码重点讲解
请求XSS安全漏洞防护-过滤器
请求XSS安全漏发防护比较简单,只需要实现对应的过滤器,对请求的参数内容进行过滤即可。
1、新增FilterConfig过滤器配置
在FilterConfig过滤配置中实现了XssFilter过滤器。
import com.qingfeng.framework.filter.CsrfFilter;
import com.qingfeng.framework.filter.XssFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.DispatcherType;
import java.util.Arrays;
import java.util.Collections;
import java.util.Objects;
/**
* @ProjectName FilterConfig
* @author Administrator
* @version 1.0.0
* @Description Filter配置
* @createTime 2021/7/18 0018 17:27
*/
@Configuration
public class FilterConfig {
//xss 不拦截的过滤器
@Value("${xss.domains}")
private String xss_domains;
//crsf 添加Referer
@Value("${csrf.domains}")
private String csrf_domains;
/**
* @title xssFilterRegistration
* @description 注册Xss过滤器 实现配置不过滤部分接口,部分接口需要不做过滤
* @author Administrator
* @updateTime 2021/7/18 0018 17:53
*/
@Bean
public FilterRegistrationBean xssFilterRegistration() {
FilterRegistrationBean registration = getFilterRegistrationBean();
return registration;
}
private FilterRegistrationBean getFilterRegistrationBean() {
FilterRegistrationBean registration = new FilterRegistrationBean();
//指定发起请求时过滤
registration.setDispatcherTypes(DispatcherType.REQUEST);
registration.setFilter(new XssFilter(Objects.isNull(xss_domains) ? null : Arrays.asList(xss_domains.toString().split(","))));
//默认所有接口
registration.addUrlPatterns("/*");
registration.setName("xssFilter");
//设置最后执行,防止有其他过滤器对值需要修改等操作,保证最后过滤字符即可
registration.setOrder(Integer.MAX_VALUE);
return registration;
}
}
2、新增XssFilter过滤器
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Set;
/**
* @ProjectName XssFilter
* @author Administrator
* @version 1.0.0
* @Description XSS过滤器
* @createTime 2021/7/18 0018 19:33
*/
public class XssFilter implements Filter {
private List<String> excludedUris;
public XssFilter() {
}
public XssFilter(List<String> excludedUris) {
this.excludedUris = excludedUris;
}
/**
* 是否排除
*
* @param uri
* @return
*/
private boolean isExcludedUri(String uri) {
if (CollectionUtils.isEmpty(excludedUris)) {
return false;
}
for (String ex : excludedUris) {
if (match(ex, uri)) {
return true;
}
}
return false;
}
/**
* 地址匹配
*
* @param patternPath
* @param requestPath
* @return
*/
public static boolean match(String patternPath, String requestPath) {
if (StringUtils.isEmpty(patternPath) || StringUtils.isEmpty(requestPath)) {
return false;
}
PathMatcher matcher = new AntPathMatcher();
return matcher.match(patternPath, requestPath);
}
@Override
public void init(FilterConfig config) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
//跨域设置
if(response instanceof HttpServletResponse){
HttpServletResponse httpServletResponse=(HttpServletResponse)response;
//通过在响应 header 中设置 ‘*’ 来允许来自所有域的跨域请求访问。
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
//通过对 Credentials 参数的设置,就可以保持跨域 Ajax 时的 Cookie
//设置了Allow-Credentials,Allow-Origin就不能为*,需要指明具体的url域
//httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
//请求方式
httpServletResponse.setHeader("Access-Control-Allow-Methods", "*");
//(预检请求)的返回结果(即 Access-Control-Allow-Methods 和Access-Control-Allow-Headers 提供的信息) 可以被缓存多久
httpServletResponse.setHeader("Access-Control-Max-Age", "86400");
//首部字段用于预检请求的响应。其指明了实际请求中允许携带的首部字段
httpServletResponse.setHeader("Access-Control-Allow-Headers", "*");
}
//可配置多个字符串过滤
XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper(
(HttpServletRequest) request, new HTMLFilter());
String url = xssRequest.getServletPath();
if (isExcludedUri(url)) {
chain.doFilter(request, response);
return;
}
chain.doFilter(xssRequest, response);
}
@Override
public void destroy() {
}
}
3、新增XssHttpServletRequestWrapper实现过滤
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @ProjectName XssHttpServletRequestWrapper
* @author Administrator
* @version 1.0.0
* @Description XSS过滤处理
* @createTime 2021/7/18 0018 19:33
*/
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
//没被包装过的HttpServletRequest(特殊场景,需要自己过滤)
HttpServletRequest orgRequest;
/**
* 字符串过滤器
*/
private final HTMLFilter htmlFilter;
public XssHttpServletRequestWrapper(HttpServletRequest request, HTMLFilter htmlFilter) {
super(request);
this.htmlFilter = htmlFilter;
this.orgRequest = request;
}
@Override
public ServletInputStream getInputStream() throws IOException {
//非json类型,直接返回
if (!MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(super.getHeader(HttpHeaders.CONTENT_TYPE))) {
return super.getInputStream();
}
//为空,直接返回
String json = IOUtils.toString(super.getInputStream(), StandardCharsets.UTF_8);
if (StringUtils.isBlank(json)) {
return super.getInputStream();
}
//xss过滤
json = xssEncode(json);
final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
return new ServletInputStream() {
@Override
public boolean isFinished() {
return true;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener readListener) {
}
@Override
public int read() throws IOException {
return bis.read();
}
};
}
@Override
public String getParameter(String name) {
String value = super.getParameter(xssEncode(name));
if (StringUtils.isNotBlank(value)) {
value = xssEncode(value);
}
return value;
}
@Override
public String[] getParameterValues(String name) {
String[] parameters = super.getParameterValues(name);
if (parameters == null || parameters.length == 0) {
return null;
}
for (int i = 0; i < parameters.length; i++) {
parameters[i] = xssEncode(parameters[i]);
}
return parameters;
}
@Override
public Map<String, String[]> getParameterMap() {
Map<String, String[]> map = new LinkedHashMap<>();
Map<String, String[]> parameters = super.getParameterMap();
for (String key : parameters.keySet()) {
String[] values = parameters.get(key);
for (int i = 0; i < values.length; i++) {
values[i] = xssEncode(values[i]);
}
map.put(key, values);
}
return map;
}
@Override
public String getHeader(String name) {
String value = super.getHeader(xssEncode(name));
if (StringUtils.isNotBlank(value)) {
value = xssEncode(value);
}
return value;
}
/**
* 编码过滤
*
* @param input
* @return
*/
private String xssEncode(String input) {
return htmlFilter.filter(input);
}
/**
* 获取最原始的request
*/
public HttpServletRequest getOrgRequest() {
return orgRequest;
}
/**
* 获取最原始的request
*/
public static HttpServletRequest getOrgRequest(HttpServletRequest request) {
if (request instanceof XssHttpServletRequestWrapper) {
return ((XssHttpServletRequestWrapper) request).getOrgRequest();
}
return request;
}
}
4、新增HTMLFilter实现具体的标签及正则过滤
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @ProjectName HTMLFilter
* @author Administrator
* @version 1.0.0
* @Description HTMLFilter
* @createTime 2021/7/18 0018 19:33
*/
public final class HTMLFilter implements CharacterFilter {
/**
* regex flag union representing /si modifiers in php
**/
private static final int REGEX_FLAGS_SI = Pattern.CASE_INSENSITIVE | Pattern.DOTALL;
private static final Pattern P_COMMENTS = Pattern.compile("<!--(.*?)-->", Pattern.DOTALL);
private static final Pattern P_COMMENT = Pattern.compile("^!--(.*)--#34;, REGEX_FLAGS_SI);
private static final Pattern P_TAGS = Pattern.compile("<(.*?)>", Pattern.DOTALL);
private static final Pattern P_END_TAG = Pattern.compile("^/([a-z0-9]+)", REGEX_FLAGS_SI);
private static final Pattern P_START_TAG = Pattern.compile("^([a-z0-9]+)(.*?)(/?)#34;, REGEX_FLAGS_SI);
private static final Pattern P_QUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)=([\"'])(.*?)\\2", REGEX_FLAGS_SI);
private static final Pattern P_UNQUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)(=)([^\"\\s']+)", REGEX_FLAGS_SI);
private static final Pattern P_PROTOCOL = Pattern.compile("^([^:]+):", REGEX_FLAGS_SI);
private static final Pattern P_ENTITY = Pattern.compile("(\\d+);?");
private static final Pattern P_ENTITY_UNICODE = Pattern.compile("([0-9a-f]+);?");
private static final Pattern P_ENCODE = Pattern.compile("%([0-9a-f]{2});?");
private static final Pattern P_VALID_ENTITIES = Pattern.compile("&([^&;]*)(?=(;|&|$))");
private static final Pattern P_VALID_QUOTES = Pattern.compile("(>|^)([^<]+?)(<|$)", Pattern.DOTALL);
private static final Pattern P_END_ARROW = Pattern.compile("^>");
private static final Pattern P_BODY_TO_END = Pattern.compile("<([^>]*?)(?=<|$)");
private static final Pattern P_XML_CONTENT = Pattern.compile("(^|>)([^<]*?)(?=>)");
private static final Pattern P_STRAY_LEFT_ARROW = Pattern.compile("<([^>]*?)(?=<|$)");
private static final Pattern P_STRAY_RIGHT_ARROW = Pattern.compile("(^|>)([^<]*?)(?=>)");
private static final Pattern P_AMP = Pattern.compile("&");
private static final Pattern P_QUOTE = Pattern.compile("<");
private static final Pattern P_LEFT_ARROW = Pattern.compile("<");
private static final Pattern P_RIGHT_ARROW = Pattern.compile(">");
private static final Pattern P_BOTH_ARROWS = Pattern.compile("<>");
// @xxx could grow large... maybe use sesat's ReferenceMap
private static final ConcurrentMap<String, Pattern> P_REMOVE_PAIR_BLANKS = new ConcurrentHashMap<String, Pattern>();
private static final ConcurrentMap<String, Pattern> P_REMOVE_SELF_BLANKS = new ConcurrentHashMap<String, Pattern>();
/**
* set of allowed html elements, along with allowed attributes for each element
**/
private final Map<String, List<String>> vAllowed;
/**
* counts of open tags for each (allowable) html element
**/
private final Map<String, Integer> vTagCounts = new HashMap<String, Integer>();
/**
* html elements which must always be self-closing (e.g. "<img />")
**/
private final String[] vSelfClosingTags;
/**
* html elements which must always have separate opening and closing tags (e.g. "<b></b>")
**/
private final String[] vNeedClosingTags;
/**
* set of disallowed html elements
**/
private final String[] vDisallowed;
/**
* attributes which should be checked for valid protocols
**/
private final String[] vProtocolAtts;
/**
* allowed protocols
**/
private final String[] vAllowedProtocols;
/**
* tags which should be removed if they contain no content (e.g. "<b></b>" or "<b />")
**/
private final String[] vRemoveBlanks;
/**
* entities allowed within html markup
**/
private final String[] vAllowedEntities;
/**
* flag determining whether comments are allowed in input String.
*/
private final boolean stripComment;
private final boolean encodeQuotes;
private boolean vDebug = false;
/**
* flag determining whether to try to make tags when presented with "unbalanced"
* angle brackets (e.g. "<b text </b>" becomes "<b> text </b>"). If set to false,
* unbalanced angle brackets will be html escaped.
*/
private final boolean alwaysMakeTags;
/**
* Default constructor.
*/
public HTMLFilter() {
vAllowed = new HashMap<>();
final ArrayList<String> a_atts = new ArrayList<String>();
a_atts.add("href");
a_atts.add("target");
vAllowed.put("a", a_atts);
final ArrayList<String> img_atts = new ArrayList<String>();
img_atts.add("src");
img_atts.add("width");
img_atts.add("height");
img_atts.add("alt");
vAllowed.put("img", img_atts);
final ArrayList<String> no_atts = new ArrayList<String>();
vAllowed.put("b", no_atts);
vAllowed.put("strong", no_atts);
vAllowed.put("i", no_atts);
vAllowed.put("em", no_atts);
vSelfClosingTags = new String[]{"img"};
vNeedClosingTags = new String[]{"a", "b", "strong", "i", "em"};
vDisallowed = new String[]{};
vAllowedProtocols = new String[]{"http", "mailto", "https"}; // no ftp.
vProtocolAtts = new String[]{"src", "href"};
vRemoveBlanks = new String[]{"a", "b", "strong", "i", "em"};
vAllowedEntities = new String[]{"amp", "gt", "lt", "quot"};
stripComment = true;
encodeQuotes = true;
alwaysMakeTags = true;
}
/**
* Set debug flag to true. Otherwise use default settings. See the default constructor.
*
* @param debug turn debug on with a true argument
*/
public HTMLFilter(final boolean debug, boolean isBlank) {
this();
vDebug = debug;
}
/**
* Map-parameter configurable constructor.
*
* @param conf map containing configuration. keys match field names.
*/
public HTMLFilter(final Map<String, Object> conf) {
assert conf.containsKey("vAllowed") : "configuration requires vAllowed";
assert conf.containsKey("vSelfClosingTags") : "configuration requires vSelfClosingTags";
assert conf.containsKey("vNeedClosingTags") : "configuration requires vNeedClosingTags";
assert conf.containsKey("vDisallowed") : "configuration requires vDisallowed";
assert conf.containsKey("vAllowedProtocols") : "configuration requires vAllowedProtocols";
assert conf.containsKey("vProtocolAtts") : "configuration requires vProtocolAtts";
assert conf.containsKey("vRemoveBlanks") : "configuration requires vRemoveBlanks";
assert conf.containsKey("vAllowedEntities") : "configuration requires vAllowedEntities";
vAllowed = Collections.unmodifiableMap((HashMap<String, List<String>>) conf.get("vAllowed"));
vSelfClosingTags = (String[]) conf.get("vSelfClosingTags");
vNeedClosingTags = (String[]) conf.get("vNeedClosingTags");
vDisallowed = (String[]) conf.get("vDisallowed");
vAllowedProtocols = (String[]) conf.get("vAllowedProtocols");
vProtocolAtts = (String[]) conf.get("vProtocolAtts");
vRemoveBlanks = (String[]) conf.get("vRemoveBlanks");
vAllowedEntities = (String[]) conf.get("vAllowedEntities");
stripComment = conf.containsKey("stripComment") ? (Boolean) conf.get("stripComment") : true;
encodeQuotes = conf.containsKey("encodeQuotes") ? (Boolean) conf.get("encodeQuotes") : true;
alwaysMakeTags = conf.containsKey("alwaysMakeTags") ? (Boolean) conf.get("alwaysMakeTags") : true;
}
private void reset() {
vTagCounts.clear();
}
private void debug(final String msg) {
if (vDebug) {
Logger.getAnonymousLogger().info(msg);
}
}
//---------------------------------------------------------------
// my versions of some PHP library functions
public static String chr(final int decimal) {
return String.valueOf((char) decimal);
}
/**
* 替换特殊标识
*
* @param s
* @return
*/
public static String htmlSpecialChars(final String s) {
String result = s;
result = regexReplace(P_AMP, "&", result);
result = regexReplace(P_QUOTE, """, result);
result = regexReplace(P_LEFT_ARROW, "<", result);
result = regexReplace(P_RIGHT_ARROW, ">", result);
return result;
}
//---------------------------------------------------------------
/**
* given a user submitted input String, filter out any invalid or restricted
* html.
*
* @param input text (i.e. submitted by a user) than may contain html
* @return "clean" version of input, with only valid, whitelisted html elements allowed
*/
@Override
public String filter(final String input) {
reset();
String s = input;
debug("************************************************");
debug(" INPUT: " + input);
s = escapeComments(s);
debug(" escapeComments: " + s);
s = balanceHTML(s);
debug(" balanceHTML: " + s);
s = checkTags(s);
debug(" checkTags: " + s);
s = processRemoveBlanks(s);
debug("processRemoveBlanks: " + s);
s = validateEntities(s);
debug(" validateEntites: " + s);
s = validateCustomizeParam(s);
// System.out.println("---------------------完成了-------------------");
// System.out.println(s);
debug("************************************************\n\n");
return s;
}
public boolean isAlwaysMakeTags() {
return alwaysMakeTags;
}
public boolean isStripComments() {
return stripComment;
}
private String validateCustomizeParam(final String s){
String value = s;
// System.out.println(value);
value = value.replaceAll("'","");
value = value.replaceAll("-","");
value = value.replaceAll("alert","");
value = value.replaceAll("prompt","");
// System.out.println("---------------------进来了-------------------");
// System.out.println(value);
return value;
}
private String escapeComments(final String s) {
final Matcher m = P_COMMENTS.matcher(s);
final StringBuffer buf = new StringBuffer();
if (m.find()) {
final String match = m.group(1); //(.*?)
m.appendReplacement(buf, Matcher.quoteReplacement("<!--" + htmlSpecialChars(match) + "-->"));
}
m.appendTail(buf);
return buf.toString();
}
/**
* 处理html
* 替换特殊字符,处理<>符号
*
* @param s
* @return
*/
private String balanceHTML(String s) {
if (alwaysMakeTags) {
//
// try and form html 保留原字符
//
s = regexReplace(P_END_ARROW, "", s);
//自动补充<,> 注释允许传递<>符号
// s = regexReplace(P_BODY_TO_END, "<$1>", s);
// s = regexReplace(P_XML_CONTENT, "$1<$2", s);
} else {
//
// escape stray brackets 替换成编码
//
s = regexReplace(P_STRAY_LEFT_ARROW, "<$1", s);
s = regexReplace(P_STRAY_RIGHT_ARROW, "$1$2><", s);
//
// the last regexp causes '<>' entities to appear
// (we need to do a lookahead assertion so that the last bracket can
// be used in the next pass of the regexp)
//
s = regexReplace(P_BOTH_ARROWS, "", s);
}
return s;
}
/**
* 处理标签
*
* @param s
* @return
*/
private String checkTags(String s) {
Matcher m = P_TAGS.matcher(s);
final StringBuffer buf = new StringBuffer();
while (m.find()) {
String replaceStr = m.group(1);
replaceStr = processTag(replaceStr);
m.appendReplacement(buf, Matcher.quoteReplacement(replaceStr));
}
m.appendTail(buf);
// these get tallied in processTag
// (remember to reset before subsequent calls to filter method)
StringBuilder sBuilder = new StringBuilder(buf.toString());
for (String key : vTagCounts.keySet()) {
for (int ii = 0; ii < vTagCounts.get(key); ii++) {
sBuilder.append("</").append(key).append(">");
}
}
s = sBuilder.toString();
return s;
}
/**
* 删除空白
*
* @param s
* @return
*/
private String processRemoveBlanks(final String s) {
String result = s;
for (String tag : vRemoveBlanks) {
if (!P_REMOVE_PAIR_BLANKS.containsKey(tag)) {
P_REMOVE_PAIR_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?></" + tag + ">"));
}
result = regexReplace(P_REMOVE_PAIR_BLANKS.get(tag), "", result);
if (!P_REMOVE_SELF_BLANKS.containsKey(tag)) {
P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>"));
}
result = regexReplace(P_REMOVE_SELF_BLANKS.get(tag), "", result);
}
return result;
}
private static String regexReplace(final Pattern regex_pattern, final String replacement, final String s) {
Matcher m = regex_pattern.matcher(s);
return m.replaceAll(replacement);
}
private String processTag(final String s) {
// ending tags
Matcher m = P_END_TAG.matcher(s);
if (m.find()) {
final String name = m.group(1).toLowerCase();
if (allowed(name)) {
if (!inArray(name, vSelfClosingTags)) {
if (vTagCounts.containsKey(name)) {
vTagCounts.put(name, vTagCounts.get(name) - 1);
return "</" + name + ">";
}
}
}
}
// starting tags
m = P_START_TAG.matcher(s);
if (m.find()) {
final String name = m.group(1).toLowerCase();
final String body = m.group(2);
String ending = m.group(3);
//debug( "in a starting tag, name='" + name + "'; body='" + body + "'; ending='" + ending + "'" );
if (allowed(name)) {
String params = "";
final Matcher m2 = P_QUOTED_ATTRIBUTES.matcher(body);
final Matcher m3 = P_UNQUOTED_ATTRIBUTES.matcher(body);
final List<String> paramNames = new ArrayList<String>();
final List<String> paramValues = new ArrayList<String>();
while (m2.find()) {
paramNames.add(m2.group(1)); //([a-z0-9]+)
paramValues.add(m2.group(3)); //(.*?)
}
while (m3.find()) {
paramNames.add(m3.group(1)); //([a-z0-9]+)
paramValues.add(m3.group(3)); //([^\"\\s']+)
}
String paramName, paramValue;
for (int ii = 0; ii < paramNames.size(); ii++) {
paramName = paramNames.get(ii).toLowerCase();
paramValue = paramValues.get(ii);
// debug( "paramName='" + paramName + "'" );
// debug( "paramValue='" + paramValue + "'" );
// debug( "allowed? " + vAllowed.get( name ).contains( paramName ) );
if (allowedAttribute(name, paramName)) {
if (inArray(paramName, vProtocolAtts)) {
paramValue = processParamProtocol(paramValue);
}
params += " " + paramName + "=\"" + paramValue + "\"";
}
}
if (inArray(name, vSelfClosingTags)) {
ending = " /";
}
if (inArray(name, vNeedClosingTags)) {
ending = "";
}
if (ending == null || ending.length() < 1) {
if (vTagCounts.containsKey(name)) {
vTagCounts.put(name, vTagCounts.get(name) + 1);
} else {
vTagCounts.put(name, 1);
}
} else {
ending = " /";
}
return "<" + name + params + ending + ">";
} else {
return "";
}
}
// comments
m = P_COMMENT.matcher(s);
if (!stripComment && m.find()) {
return "<" + m.group() + ">";
}
return "";
}
private String processParamProtocol(String s) {
s = decodeEntities(s);
final Matcher m = P_PROTOCOL.matcher(s);
if (m.find()) {
final String protocol = m.group(1);
if (!inArray(protocol, vAllowedProtocols)) {
// bad protocol, turn into local anchor link instead
s = "#" + s.substring(protocol.length() + 1, s.length());
if (s.startsWith("#//")) {
s = "#" + s.substring(3, s.length());
}
}
}
return s;
}
private String decodeEntities(String s) {
StringBuffer buf = new StringBuffer();
Matcher m = P_ENTITY.matcher(s);
while (m.find()) {
final String match = m.group(1);
final int decimal = Integer.decode(match).intValue();
m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
}
m.appendTail(buf);
s = buf.toString();
buf = new StringBuffer();
m = P_ENTITY_UNICODE.matcher(s);
while (m.find()) {
final String match = m.group(1);
final int decimal = Integer.valueOf(match, 16).intValue();
m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
}
m.appendTail(buf);
s = buf.toString();
buf = new StringBuffer();
m = P_ENCODE.matcher(s);
while (m.find()) {
final String match = m.group(1);
final int decimal = Integer.valueOf(match, 16).intValue();
m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
}
m.appendTail(buf);
s = buf.toString();
s = validateEntities(s);
return s;
}
private String validateEntities(final String s) {
StringBuffer buf = new StringBuffer();
// validate entities throughout the string
Matcher m = P_VALID_ENTITIES.matcher(s);
while (m.find()) {
final String one = m.group(1); //([^&;]*)
final String two = m.group(2); //(?=(;|&|$))
m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two)));
}
m.appendTail(buf);
return encodeQuotes(buf.toString());
}
private String encodeQuotes(final String s) {
if (encodeQuotes) {
StringBuffer buf = new StringBuffer();
Matcher m = P_VALID_QUOTES.matcher(s);
while (m.find()) {
final String one = m.group(1); //(>|^)
final String two = m.group(2); //([^<]+?)
final String three = m.group(3); //(<|$)
m.appendReplacement(buf, Matcher.quoteReplacement(one + regexReplace(P_QUOTE, """, two) + three));
}
m.appendTail(buf);
return buf.toString();
} else {
return s;
}
}
private String checkEntity(final String preamble, final String term) {
return ";".equals(term) && isValidEntity(preamble)
? '&' + preamble
: "&" + preamble;
}
private boolean isValidEntity(final String entity) {
return inArray(entity, vAllowedEntities);
}
private static boolean inArray(final String s, final String[] array) {
for (String item : array) {
if (item != null && item.equals(s)) {
return true;
}
}
return false;
}
private boolean allowed(final String name) {
return (vAllowed.isEmpty() || vAllowed.containsKey(name)) && !inArray(name, vDisallowed);
}
private boolean allowedAttribute(final String name, final String paramName) {
return allowed(name) && (vAllowed.isEmpty() || vAllowed.get(name).contains(paramName));
}
}
响应或展示XSS安全漏洞防护
1、XSS.JS 对JavaScript参数进行过滤
xss.js 位置和引用,大家可以参考升级文件内容介绍,使用方法如下:
filterXSS(data.name);
table.render({
elem: '#system_user'
,url:'${pageContext.request.contextPath}/system/user/findListPage'
,toolbar: '#toolbarDemo' //开启头部工具栏,并为其绑定左侧模板
,defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义,去除该参数即可
title: '提示'
,layEvent: 'laytable_tips'
,icon: 'layui-icon-tips'
}]
,title: '用户数据表'
,cols: [[
{type: 'checkbox', fixed: 'left', width:40}
,{field:'', fixed: 'left',title:'登录名', width:120, templet: function(res){
return filterXSS(res.login_name);
}}
,{field:'', title:'姓名', width:120, templet: function(res){
return filterXSS(res.name);
}}
]]
})
在layui动态列表中,使用filterXSS对展示的内容进行过滤,切记field:''一定设置为空。如果不设置为空,layui table会认为此字段是使用的,一样会存在XSS漏洞。
2、详情页面内容
在默认展示内容上使用的是:${pd.name}这种写法是不安全的。存在XSS安全漏洞。如下:

正确的写法可以使用 c :out标签,如: < c :out value =" ${ p . login_name } " />

说明:此处工作流修改情况比较大,大家可以根据自己的情况确定是否需要修改,如果在数据写入时候增加了过滤器,数据不存在对应的注入情况,展示的内容当然也不存在XSS注入的代码,当然,请求和相应都做防护是最安全的。
三、CRSF代码重点讲解
1、修复ShiroConfig,增加CsrfFilter过滤器配置
在ShiroConfig配置中增加XssFilter过滤器。
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
...
//加入csrfFilter拦截器
filters.put("csrfFilter", csrfFilter());
shiroFilterFactoryBean.setFilters(filters);
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
@Bean
public CsrfFilter csrfFilter() {
// 这里使用的是配置文件信息,获取配置文件中的csrf.domains相关值信息
String csrfDomains = csrf_domains;
List list = Collections.<String>emptyList();
if (StringUtils.isNotBlank(csrfDomains)) {
list = Arrays.asList(csrfDomains.split(","));
}
CsrfFilter csrfFilter = new CsrfFilter(list);
return csrfFilter;
}
2、新增CsrfFilter过滤器
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qingfeng.util.Json;
import com.qingfeng.util.PageData;
import com.qingfeng.util.Verify;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
public class CsrfFilter extends OncePerRequestFilter {
private Collection<String> domains;
// 临时过滤路径。对用户管理使用`csrf token`的方式进行防范。
private List<String> paths = Arrays.asList("/system/user/updateAuth", "/system/user/updatePwd");
public CsrfFilter(Collection<String> domains) {
this.domains = domains;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
HttpSession session = request.getSession();
PageData user = (PageData) session.getAttribute("loginUser");
if(Verify.verifyIsNotNull(user)) {
Object token = session.getAttribute("csrfToken");
Object httpToken = request.getHeader("httpToken");
boolean missingToken = false;
if (token == null) {
missingToken = true;
token = UUID.randomUUID().toString().replace("-", "");
session.setAttribute("csrfToken",token);
}
request.setAttribute("csrfToken", token);
// GET 等方式不用提供Token,自动放行,不能用于修改数据。修改数据必须使用 POST、PUT、DELETE、PATCH 方式并且Referer要合法。
if (Arrays.asList("GET", "HEAD", "TRACE", "OPTIONS").contains(request.getMethod())) {
filterChain.doFilter(request, response);
return;
}
String uri = request.getRequestURI();
if (paths.contains(uri) && !token.equals(httpToken)) {
// response.sendError(HttpServletResponse.SC_FORBIDDEN, missingToken ? "CSRF Token Missing" : "CSRF Token Invalid");
Json json = new Json();
json.setSuccess(false);
json.setMsg(missingToken ? "CSRF 令牌丢失" : "CSRF 令牌无效");
response.setContentType("text/html;charset=utf-8");
ObjectMapper objMapper = new ObjectMapper();
JsonGenerator jsonGenerator = objMapper.getJsonFactory()
.createJsonGenerator(response.getOutputStream(),
JsonEncoding.UTF8);
jsonGenerator.writeObject(json);
jsonGenerator.flush();
jsonGenerator.close();
return;
}
if (!domains.isEmpty() && !verifyDomains(request)) {
// response.sendError(HttpServletResponse.SC_FORBIDDEN, "CSRF Protection: Referer Illegal");
Json json = new Json();
json.setSuccess(false);
json.setMsg("CSRF 保护:Referer 非法");
response.setContentType("text/html;charset=utf-8");
ObjectMapper objMapper = new ObjectMapper();
JsonGenerator jsonGenerator = objMapper.getJsonFactory()
.createJsonGenerator(response.getOutputStream(),
JsonEncoding.UTF8);
jsonGenerator.writeObject(json);
jsonGenerator.flush();
jsonGenerator.close();
return;
}
}
filterChain.doFilter(request, response);
}
private boolean verifyDomains(HttpServletRequest request) {
// 从 HTTP 头中取得 Referer 值
String referer = request.getHeader("Referer");
// 判断 Referer 是否以 合法的域名 开头。
if (referer != null) {
// 如 http://mysite.com/abc.html https://www.mysite.com:8080/abc.html
if (referer.indexOf("://") > 0) referer = referer.substring(referer.indexOf("://") + 3);
// 如 mysite.com/abc.html
if (referer.indexOf("/") > 0) referer = referer.substring(0, referer.indexOf("/"));
// 如 mysite.com:8080
if (referer.indexOf(":") > 0) referer = referer.substring(0, referer.indexOf(":"));
// 如 mysite.com
for (String domain : domains) {
if (referer.contains(domain)) return true;
}
}
return false;
}
private boolean verifyToken(HttpServletRequest request, String token) {
return token.equals(request.getParameter("csrfToken"));
}
3、过滤内容讲解
安全Referer的验证
默认Referer是请求的地址路径,但是Referer很容易被篡改,改成别的路径继续访问,特此我们对Referer进行安全校验。


安全token的验证
为了数据的一致性,在数据提交的时候可以设置token,这样在过滤器验证中可以对token进行验证,我们实现的模式是对特殊的请求如设置密码、设置权限增加token验证。
过滤路径设置
// 临时过滤路径。对用户管理使用`csrf token`的方式进行防范。
private List<String> paths = Arrays.asList("/system/user/updateAuth", "/system/user/updatePwd");
ajax增加beforeSend
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("httpToken", '${csrfToken}');
},
过滤实现
String uri = request.getRequestURI();
if (paths.contains(uri) && !token.equals(httpToken)) {
}