通过java.util.regex.Pattern正则表达式定义前端xss常见js/vbscript等脚本库,实现字符串是否包含xss跨站攻击脚本,详细代码demo如下
package xss;@b@@b@import java.util.regex.Pattern;@b@@b@public class XSSUtil {@b@ @b@ private static Pattern[] patterns = new Pattern[]{@b@ // Script fragments@b@ Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE),@b@ // src='...'@b@ Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),@b@ Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),@b@ // lonely script tags@b@ Pattern.compile("</script>", Pattern.CASE_INSENSITIVE),@b@ Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),@b@ // eval(...)@b@ Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),@b@ // expression(...)@b@ Pattern.compile("expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),@b@ // javascript:...@b@ Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE),@b@ // vbscript:...@b@ Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE),@b@ // onload(...)=...@b@ Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),@b@ //现场安全测试增加校验@b@ Pattern.compile("alert(.*?)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),@b@ Pattern.compile("<", Pattern.MULTILINE | Pattern.DOTALL),@b@ Pattern.compile(">", Pattern.MULTILINE | Pattern.DOTALL)@b@ };@b@ @b@ //过滤替换xss脚本为空@b@ public static String stripXSS(String value){@b@ if (value != null) {@b@ value = value.replaceAll("\0", "");@b@ @b@ for (Pattern scriptPattern : patterns){@b@ value = scriptPattern.matcher(value).replaceAll("");@b@ }@b@ }@b@ return value;@b@ }@b@ @b@ //含xss脚本则返回false@b@ public static boolean isXssPass(String valueString){@b@ if(valueString!=null){@b@ for (Pattern scriptPattern : patterns){@b@ if(scriptPattern.matcher(valueString).find()==true){@b@ return false;@b@ }@b@ }@b@ }@b@ return true;@b@ }@b@ @b@ public static void main(String[] args) {@b@ System.out.println("11"+ XSSUtil.stripXSS("<IMG SRC=http://3w.org/XSS/xss.js/>"));@b@ System.out.println(XSSUtil.isXssPass("<img src=0 onerror=alert(1)>"));@b@ }@b@@b@}