import java.util.regex.Pattern;
//具体过滤关键字符
public class XSSUtil {
private static Pattern[] patterns = new Pattern[]{
// Script fragments
Pattern.compile("", Pattern.CASE_INSENSITIVE),
// src='...'
Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
// lonely script tags
Pattern.compile("", Pattern.CASE_INSENSITIVE),
Pattern.compile("
// eval(...)
Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
// expression(...)
Pattern.compile("expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
// javascript:...
Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE),
// vbscript:...
Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE),
// onload(...)=...
Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
//现场安全测试增加校验
Pattern.compile("alert(.*?)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
Pattern.compile("<", Pattern.MULTILINE | Pattern.DOTALL),
Pattern.compile(">", Pattern.MULTILINE | Pattern.DOTALL)
};
public static String stripXSS(String value){
if (value != null) {
// TODO ESAPI library
// NOTE: It's highly recommended to use the ESAPI library and uncomment the following line to
// avoid encoded attacks.
// value = ESAPI.encoder().canonicalize(value);
// Avoid null characters
value = value.replaceAll("\0", "");
// Remove all sections that match a pattern
for (Pattern scriptPattern : patterns){
value = scriptPattern.matcher(value).replaceAll("");
}
}
return value;
}
public static void main(String[] args) {
System.out.println("11"+ XSSUtil.stripXSS(""));
// System.out.println(XSSUtil.stripXSS(""));
}
}
import com.ideatech.common.util.XSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import java.beans.PropertyEditorSupport;
//每一个请求进入控制层之前会先进行字符过滤
@ControllerAdvice
@Component
@Slf4j
public class GlobalBindingInitializer {
@InitBinder
protected void initBinder(WebDataBinder binder) {
// String类型转换,将所有传递进来的String进行HTML编码,防止XSS攻击
binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
if(text != null){
String cleanText = XSSUtil.stripXSS(text);
if(!cleanText.equals(text)){
log.info("xss clean, before[{}], after[{}]",text,cleanText);
text = cleanText;
}
}
setValue(text);
}
@Override
public String getAsText() {
Object value = getValue();
return value != null ? value.toString() : "";
}
});
}
}