1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| class KeywordCheckUtils7 {
private static final Set<String> blacklist = Sets.newHashSet( "java.io.File", "java.io.RandomAccessFile", "java.io.FileInputStream", "java.io.FileOutputStream", "java.lang.Class", "java.lang.ClassLoader", "java.lang.Runtime", "java.lang.System", "System.getProperty", "java.lang.Thread", "java.lang.ThreadGroup", "java.lang.reflect.AccessibleObject", "java.net.InetAddress", "java.net.DatagramSocket", "java.net.DatagramSocket", "java.net.Socket", "java.net.ServerSocket", "java.net.MulticastSocket", "java.net.MulticastSocket", "java.net.URL", "java.net.HttpURLConnection", "java.security.AccessControlContext", "java.lang.ProcessBuilder", "invoke","newinstance", "eval", "new function", "Java.type","importPackage","importClass","JavaImporter" );
public KeywordCheckUtils7() { }
public static void checkInsecureKeyword(String code) throws Exception { String removeComment = StringUtils.replacePattern(code, "(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*[\n\r\u2029\u2028])", " "); removeComment =StringUtils.replacePattern(removeComment,"[\u2028\u2029\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\ufeff]",""); String removeWhitespace = StringUtils.replacePattern(removeComment, "\\s+", ""); String oneWhiteSpace = StringUtils.replacePattern(removeComment, "\\s+", " "); System.out.println(removeWhitespace); System.out.println(oneWhiteSpace); Set<String> insecure = blacklist.stream().filter(s -> StringUtils.containsIgnoreCase(removeWhitespace, s) || StringUtils.containsIgnoreCase(oneWhiteSpace, s)).collect(Collectors.toSet());
if (!CollectionUtils.isEmpty(insecure)) { System.out.println("存在不安全的关键字:"+insecure); throw new Exception("存在安全问题"); }else{ ScriptEngineManager manager = new ScriptEngineManager(null); ScriptEngine engine = manager.getEngineByName("js"); engine.eval(code); } } }
|