├── .gitignore ├── LICENSE.md ├── README.md ├── agent ├── build.gradle └── src │ └── main │ └── java │ └── me │ └── threedr3am │ └── guanyu │ └── agent │ └── GuanYu.java ├── build.gradle ├── conf └── deny.conf ├── core ├── build.gradle └── src │ └── main │ └── java │ └── me │ └── threedr3am │ └── guanyu │ └── core │ ├── Config.java │ ├── DenyEvilClassException.java │ ├── GuanYuClassFileTransformer.java │ ├── LoadCache.java │ ├── Plugin.java │ └── PluginManager.java ├── plugin ├── build.gradle └── src │ └── main │ ├── java │ └── me │ │ └── threedr3am │ │ └── guanyu │ │ └── plugin │ │ ├── BcelDenyPlugin.java │ │ ├── BlackMethodDenyPlugin.java │ │ ├── DenyMethods.java │ │ ├── GuanYuMethod.java │ │ └── asm │ │ ├── ASTClassVisitor.java │ │ └── ASTMethodVisitor.java │ └── resources │ └── META-INF │ └── services │ └── me.threedr3am.guanyu.core.Plugin └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | /build/ 2 | .idea 3 | *.iws 4 | *.iml 5 | *.ipr 6 | /out/ 7 | .DS_Store 8 | out/ 9 | /gradlew.bat 10 | /gradle 11 | /gradlew 12 | **/build 13 | **/*.jar 14 | .gradle -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GuanYu -> 关羽 2 | 3 | JVM类加载监控agent,可配置黑名单,禁止恶意类加载(包括jsp webshell) 4 | 5 | ### 一、使用方法 6 | 7 | ##### 1、打包编译 8 | 9 | 命令: 10 | ```text 11 | gradle :agent:shadowJar 12 | ``` 13 | 或 14 | ```text 15 | ./gradlew :agent:shadowJar 16 | ``` 17 | 18 | 编译后得到 agent/build/libs/agent-xxx.jar 19 | 20 | ##### 2、javaagent使用 21 | 22 | 在需要监控的应用启动时,加入以下参数用于指定当前agent程序: 23 | ```text 24 | -javaagent:/Users/threedr3am/git-project/GuanYu/agent/build/libs/agent-1.0-SNAPSHOT-all.jar="denyMethodsConfigFile=/Users/threedr3am/git-project/GuanYu/conf/deny.conf" 25 | ``` 26 | denyMethodsConfigFile为agent参数,更多参数请往下翻阅! 27 | 28 | ##### 3、attach运行时使用 29 | 30 | ```text 31 | java -jar GuanYu.jar 23232 denyMethodsConfigFile=/tmp/deny.conf 32 | ``` 33 | 34 | - 23232 为需要attach的jvm进程号 35 | - denyMethodsConfigFile=/tmp/deny.conf 为黑名单方法配置文件路径配置项! 36 | 37 | 38 | ### 二、方法调用黑名单 39 | 40 | agent参数:denyMethodsConfigFile 41 | 42 | 例:denyMethodsConfigFile=/Users/threedr3am/git-project/GuanYu/conf/deny.conf 43 | 44 | 内容: 45 | ```text 46 | java/lang/Runtime exec * sun/usagetracker/UsageTrackerClient 47 | java/lang/ProcessBuilder start * 48 | ``` 49 | 空格划分 50 | - 第一项:需要拦截的类名 51 | - 第二项:需要拦截的方法名(*表示全部拦截) 52 | - 第三项:需要拦截的方法描述(*表示全部拦截) 53 | - 第四项:白名单调用类(非必须) 54 | -------------------------------------------------------------------------------- /agent/build.gradle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/threedr3am/GuanYu/2c7098284fcdfa9186bd6269cbb9ed781207d5ed/agent/build.gradle -------------------------------------------------------------------------------- /agent/src/main/java/me/threedr3am/guanyu/agent/GuanYu.java: -------------------------------------------------------------------------------- 1 | package me.threedr3am.guanyu.agent; 2 | 3 | import com.sun.tools.attach.AgentInitializationException; 4 | import com.sun.tools.attach.AgentLoadException; 5 | import com.sun.tools.attach.AttachNotSupportedException; 6 | import com.sun.tools.attach.VirtualMachine; 7 | import java.io.IOException; 8 | import java.lang.instrument.Instrumentation; 9 | import me.threedr3am.guanyu.core.Config; 10 | import me.threedr3am.guanyu.core.GuanYuClassFileTransformer; 11 | 12 | /** 13 | * @author threedr3am 14 | */ 15 | public class GuanYu { 16 | 17 | public static void premain(String agentArg, Instrumentation inst) { 18 | init(agentArg, inst); 19 | } 20 | 21 | public static void agentmain(String agentArg, Instrumentation inst) { 22 | init(agentArg, inst); 23 | } 24 | 25 | public static synchronized void init(String action, Instrumentation inst) { 26 | System.out.println("[GuanYu] 类加载监控Agent启动 ..."); 27 | System.out.println(String.format("[GuanYu] 参数: %s", action)); 28 | try { 29 | Config.init(action); 30 | GuanYuClassFileTransformer guanYuClassFileTransformer = new GuanYuClassFileTransformer(inst); 31 | inst.addTransformer(guanYuClassFileTransformer, true); 32 | guanYuClassFileTransformer.retransform(); 33 | } catch (Throwable e) { 34 | System.err.println("[GuanYu] 类加载监控Agent初始化失败,将会失去安全保护。"); 35 | e.printStackTrace(); 36 | } 37 | } 38 | 39 | public static void main(String[] args) 40 | throws IOException, AttachNotSupportedException, AgentLoadException, AgentInitializationException { 41 | if (args.length == 0) { 42 | System.err.println("参数缺少,例:java -jar GuanYu.jar 23232 denyMethodsConfigFile=/tmp/deny.conf,23232为需要attach的jvm进程号,denyMethodsConfigFile=/tmp/deny.conf为黑名单方法配置文件路径配置项!"); 43 | System.exit(-1); 44 | } 45 | VirtualMachine vmObj = null; 46 | 47 | try { 48 | vmObj = VirtualMachine.attach(args[0]); 49 | String agentpath = GuanYu.class.getProtectionDomain().getCodeSource().getLocation().getFile(); 50 | if (vmObj != null) { 51 | vmObj.loadAgent(agentpath, args[1]); 52 | } 53 | } finally { 54 | if (null != vmObj) { 55 | vmObj.detach(); 56 | } 57 | 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | jcenter() 4 | } 5 | 6 | dependencies { 7 | classpath "com.github.jengelman.gradle.plugins:shadow:4.0.3" 8 | } 9 | } 10 | 11 | allprojects { 12 | apply plugin: 'java' 13 | 14 | group 'me.threedr3am.guanyu' 15 | version '1.0-SNAPSHOT' 16 | } 17 | 18 | subprojects { 19 | dependencies { 20 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0' 21 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine' 22 | 23 | runtime files(org.gradle.internal.jvm.Jvm.current().toolsJar) 24 | } 25 | 26 | repositories { 27 | mavenCentral() 28 | } 29 | 30 | test { 31 | useJUnitPlatform() 32 | } 33 | } 34 | 35 | project(":agent") { 36 | 37 | apply plugin: 'com.github.johnrengelman.shadow' 38 | 39 | shadowJar { 40 | manifest { 41 | attributes 'Main-Class': 'me.threedr3am.guanyu.agent.GuanYu' 42 | attributes 'Premain-Class': 'me.threedr3am.guanyu.agent.GuanYu' 43 | attributes 'Agent-Class': 'me.threedr3am.guanyu.agent.GuanYu' 44 | attributes 'Can-Redefine-Classes': true 45 | attributes 'Can-Retransform-Classes': true 46 | } 47 | } 48 | 49 | dependencies { 50 | compile project(":core") 51 | compile project(":plugin") 52 | } 53 | } 54 | 55 | project(":core") { 56 | 57 | } 58 | 59 | project(":plugin") { 60 | 61 | dependencies { 62 | compile project(":core") 63 | 64 | implementation "org.ow2.asm:asm:8.0.1" 65 | implementation "org.ow2.asm:asm-commons:8.0.1" 66 | } 67 | } -------------------------------------------------------------------------------- /conf/deny.conf: -------------------------------------------------------------------------------- 1 | java/lang/Runtime exec * sun/usagetracker/UsageTrackerClient 2 | java/lang/ProcessBuilder start * -------------------------------------------------------------------------------- /core/build.gradle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/threedr3am/GuanYu/2c7098284fcdfa9186bd6269cbb9ed781207d5ed/core/build.gradle -------------------------------------------------------------------------------- /core/src/main/java/me/threedr3am/guanyu/core/Config.java: -------------------------------------------------------------------------------- 1 | package me.threedr3am.guanyu.core; 2 | 3 | import java.lang.reflect.Field; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | import java.util.regex.Matcher; 7 | import java.util.regex.Pattern; 8 | 9 | /** 10 | * @author jingfeng 11 | */ 12 | public class Config { 13 | 14 | private String denyMethodsConfigFile; 15 | 16 | private static Config config; 17 | 18 | public static final Config getInstance() { 19 | if (config == null) { 20 | synchronized (Config.class) { 21 | if (config == null) { 22 | config = new Config(); 23 | } 24 | } 25 | } 26 | return config; 27 | } 28 | 29 | public static void init(String action) throws IllegalAccessException { 30 | Config config = getInstance(); 31 | Map fieldMap = new HashMap<>(); 32 | Field[] fields = Config.class.getDeclaredFields(); 33 | for (Field field : fields) { 34 | if (field.getName().equals("config")) { 35 | continue; 36 | } 37 | fieldMap.put(field.getName(), field); 38 | } 39 | 40 | Pattern pattern = Pattern.compile("((.+?)=(.+?))(,|$)"); 41 | Matcher matcher = pattern.matcher(action); 42 | while (matcher.find()) { 43 | String key = matcher.group(2); 44 | String value = matcher.group(3); 45 | Field field; 46 | if ((field = fieldMap.get(key)) != null) { 47 | field.set(config, value); 48 | } 49 | } 50 | } 51 | 52 | public String getDenyMethodsConfigFile() { 53 | return denyMethodsConfigFile; 54 | } 55 | 56 | public static void main(String[] args) throws IllegalAccessException { 57 | init("denyMethodsConfigFile=/Users/threedr3am/git-project/GuanYu/conf/deny.conf"); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /core/src/main/java/me/threedr3am/guanyu/core/DenyEvilClassException.java: -------------------------------------------------------------------------------- 1 | package me.threedr3am.guanyu.core; 2 | 3 | /** 4 | * @author threedr3am 5 | */ 6 | public class DenyEvilClassException extends Exception { 7 | 8 | public DenyEvilClassException(String message) { 9 | super(message); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /core/src/main/java/me/threedr3am/guanyu/core/GuanYuClassFileTransformer.java: -------------------------------------------------------------------------------- 1 | package me.threedr3am.guanyu.core; 2 | 3 | import java.lang.instrument.ClassFileTransformer; 4 | import java.lang.instrument.IllegalClassFormatException; 5 | import java.lang.instrument.Instrumentation; 6 | import java.lang.instrument.UnmodifiableClassException; 7 | import java.security.ProtectionDomain; 8 | import java.util.HashSet; 9 | import java.util.Set; 10 | 11 | /** 12 | * @author threedr3am 13 | */ 14 | public class GuanYuClassFileTransformer implements ClassFileTransformer { 15 | 16 | private Instrumentation inst; 17 | 18 | public GuanYuClassFileTransformer(Instrumentation inst) { 19 | this.inst = inst; 20 | } 21 | 22 | public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { 23 | if (!LoadCache.check(className)) { 24 | System.out.println(String.format("[GuanYu] 检测到新的类加载: %s", className)); 25 | PluginManager.check(className, classfileBuffer); 26 | } 27 | return classfileBuffer; 28 | } 29 | 30 | public void retransform() { 31 | Class[] classes = inst.getAllLoadedClasses(); 32 | Set classSet = new HashSet<>(); 33 | for (Class aClass : classes) { 34 | if (PluginManager.condition(aClass.getName()) && inst.isModifiableClass(aClass)) { 35 | classSet.add(aClass); 36 | System.out.println(String.format("[GuanYu] retransform class: %s", aClass.getName())); 37 | continue; 38 | } 39 | } 40 | if (!classSet.isEmpty()) { 41 | try { 42 | inst.retransformClasses(classSet.toArray(new Class[classSet.size()])); 43 | } catch (UnmodifiableClassException e) { 44 | e.printStackTrace(); 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /core/src/main/java/me/threedr3am/guanyu/core/LoadCache.java: -------------------------------------------------------------------------------- 1 | package me.threedr3am.guanyu.core; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * @author threedr3am 8 | */ 9 | public class LoadCache { 10 | 11 | private static Map cache = new HashMap<>(); 12 | 13 | public static boolean check(String className) { 14 | return cache.putIfAbsent(className, null) != null; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /core/src/main/java/me/threedr3am/guanyu/core/Plugin.java: -------------------------------------------------------------------------------- 1 | package me.threedr3am.guanyu.core; 2 | 3 | /** 4 | * @author threedr3am 5 | */ 6 | public interface Plugin { 7 | 8 | boolean condition(String className); 9 | 10 | byte[] check(String className, byte[] byteCode) throws Exception; 11 | } 12 | -------------------------------------------------------------------------------- /core/src/main/java/me/threedr3am/guanyu/core/PluginManager.java: -------------------------------------------------------------------------------- 1 | package me.threedr3am.guanyu.core; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Iterator; 5 | import java.util.List; 6 | import java.util.ServiceLoader; 7 | 8 | /** 9 | * @author threedr3am 10 | */ 11 | public class PluginManager { 12 | 13 | private static List pluginList = new ArrayList<>(); 14 | 15 | static { 16 | ServiceLoader pluginServiceLoader = ServiceLoader.load(Plugin.class); 17 | Iterator pluginIterator = pluginServiceLoader.iterator(); 18 | while (pluginIterator.hasNext()) { 19 | Plugin plugin = pluginIterator.next(); 20 | pluginList.add(plugin); 21 | System.out.println(String.format("[GuanYu] 加载插件: %s", plugin.getClass().toString())); 22 | } 23 | System.out.println(String.format("[GuanYu] 加载插件数量: %d", pluginList.size())); 24 | } 25 | 26 | public static byte[] check(String className, byte[] byteCode) { 27 | for (Plugin plugin : pluginList) { 28 | try { 29 | plugin.check(className, byteCode); 30 | } catch (DenyEvilClassException e) { 31 | System.err.println(e.getMessage()); 32 | return new byte[0]; 33 | } catch (Exception e) { 34 | e.printStackTrace(); 35 | } 36 | } 37 | return byteCode; 38 | } 39 | 40 | public static boolean condition(String className) { 41 | for (Plugin plugin : pluginList) { 42 | if (plugin.condition(className)) { 43 | return true; 44 | } 45 | } 46 | return false; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /plugin/build.gradle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/threedr3am/GuanYu/2c7098284fcdfa9186bd6269cbb9ed781207d5ed/plugin/build.gradle -------------------------------------------------------------------------------- /plugin/src/main/java/me/threedr3am/guanyu/plugin/BcelDenyPlugin.java: -------------------------------------------------------------------------------- 1 | package me.threedr3am.guanyu.plugin; 2 | 3 | import java.util.Set; 4 | import me.threedr3am.guanyu.core.DenyEvilClassException; 5 | import me.threedr3am.guanyu.core.Plugin; 6 | import me.threedr3am.guanyu.plugin.asm.ASTClassVisitor; 7 | import org.objectweb.asm.ClassReader; 8 | 9 | /** 10 | * 11 | * 理论上,bcel类加载器加载的class,不应该存在一些危险方法的调用,所以,理应直接禁止 12 | * 13 | * @author threedr3am 14 | */ 15 | public class BcelDenyPlugin implements Plugin { 16 | 17 | @Override 18 | public boolean condition(String className) { 19 | return className.startsWith("$$BCEL$$"); 20 | } 21 | 22 | @Override 23 | public byte[] check(String className, byte[] byteCode) throws Exception { 24 | if (condition(className)) { 25 | if (DenyMethods.getDenyMethods().isEmpty()) { 26 | return byteCode; 27 | } 28 | ASTClassVisitor astClassVisitor = new ASTClassVisitor(className); 29 | ClassReader cr = new ClassReader(byteCode); 30 | cr.accept(astClassVisitor, ClassReader.EXPAND_FRAMES); 31 | Set guanYuMethods = astClassVisitor.getMethods(); 32 | for (GuanYuMethod guanYuMethod : guanYuMethods) { 33 | for (GuanYuMethod denyMethod : DenyMethods.getDenyMethods()) { 34 | if (denyMethod.match(guanYuMethod) && !denyMethod.white(className)) { 35 | throw new DenyEvilClassException(String.format("检测到一个不安全的BCEL字节码加载. 它调用了一个危险方法: %s. %s", guanYuMethod.toString(), className)); 36 | } 37 | } 38 | } 39 | } 40 | return byteCode; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /plugin/src/main/java/me/threedr3am/guanyu/plugin/BlackMethodDenyPlugin.java: -------------------------------------------------------------------------------- 1 | package me.threedr3am.guanyu.plugin; 2 | 3 | import java.util.Set; 4 | import me.threedr3am.guanyu.core.DenyEvilClassException; 5 | import me.threedr3am.guanyu.core.Plugin; 6 | import me.threedr3am.guanyu.plugin.asm.ASTClassVisitor; 7 | import org.objectweb.asm.ClassReader; 8 | 9 | /** 10 | * 11 | * 这个插件是直接禁止一些黑名单危险方法的调用,但是,可能会存在误报,需要谨慎使用,特别是agent attach运行时加载检测 12 | * 13 | * 默认自带的方法调用黑名单检测插件 14 | * 15 | * @author threedr3am 16 | */ 17 | public class BlackMethodDenyPlugin implements Plugin { 18 | 19 | 20 | @Override 21 | public boolean condition(String className) { 22 | if (DenyMethods.getDenyMethods().isEmpty()) { 23 | return false; 24 | } 25 | return true; 26 | } 27 | 28 | @Override 29 | public byte[] check(String className, byte[] byteCode) throws Exception { 30 | if (!condition(className)) { 31 | return byteCode; 32 | } 33 | ASTClassVisitor astClassVisitor = new ASTClassVisitor(className); 34 | ClassReader cr = new ClassReader(byteCode); 35 | cr.accept(astClassVisitor, ClassReader.EXPAND_FRAMES); 36 | Set guanYuMethods = astClassVisitor.getMethods(); 37 | for (GuanYuMethod guanYuMethod : guanYuMethods) { 38 | for (GuanYuMethod denyMethod : DenyMethods.getDenyMethods()) { 39 | if (denyMethod.match(guanYuMethod) && !denyMethod.white(className)) { 40 | throw new DenyEvilClassException(String.format("检测到一个恶意类加载, 它调用了一个危险方法: %s. %s", guanYuMethod.toString(), className)); 41 | } 42 | } 43 | } 44 | return byteCode; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /plugin/src/main/java/me/threedr3am/guanyu/plugin/DenyMethods.java: -------------------------------------------------------------------------------- 1 | package me.threedr3am.guanyu.plugin; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileNotFoundException; 5 | import java.util.HashSet; 6 | import java.util.Scanner; 7 | import java.util.Set; 8 | import me.threedr3am.guanyu.core.Config; 9 | 10 | /** 11 | * @author threedr3am 12 | */ 13 | public class DenyMethods { 14 | 15 | private static Set denyMethods; 16 | 17 | private static void init() { 18 | denyMethods = new HashSet<>(); 19 | try { 20 | System.out.println("[GuanYu] 读取方法调用黑名单配置文件 ..."); 21 | Scanner scanner = new Scanner(new FileInputStream(Config.getInstance().getDenyMethodsConfigFile())); 22 | while (scanner.hasNext()) { 23 | String line = scanner.nextLine(); 24 | System.out.println(line); 25 | String[] items = line.split(" "); 26 | denyMethods.add(new GuanYuMethod(items[0], items[1], items[2], items.length > 3 ? items[3] : "")); 27 | } 28 | } catch (FileNotFoundException e) { 29 | System.err.println("[GuanYu] 无法找到方法调用黑名单配置文件,请通过参数denyMethodsConfigFile配置"); 30 | } 31 | } 32 | 33 | public static Set getDenyMethods() { 34 | if (denyMethods == null) { 35 | synchronized (DenyMethods.class) { 36 | if (denyMethods == null) { 37 | init(); 38 | } 39 | } 40 | } 41 | return denyMethods; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /plugin/src/main/java/me/threedr3am/guanyu/plugin/GuanYuMethod.java: -------------------------------------------------------------------------------- 1 | package me.threedr3am.guanyu.plugin; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | import java.util.Objects; 6 | import java.util.Set; 7 | 8 | /** 9 | * @author threedr3am 10 | */ 11 | public class GuanYuMethod { 12 | 13 | private String className; 14 | private String method; 15 | private String desc; 16 | private Set whiteClassNames; 17 | 18 | public GuanYuMethod(String className, String method, String desc, 19 | String whiteClassNames) { 20 | this.className = className; 21 | this.method = method; 22 | this.desc = desc; 23 | this.whiteClassNames = new HashSet<>(Arrays.asList(whiteClassNames.split(","))); 24 | } 25 | 26 | public String getClassName() { 27 | return className; 28 | } 29 | 30 | public String getMethod() { 31 | return method; 32 | } 33 | 34 | public String getDesc() { 35 | return desc; 36 | } 37 | 38 | public boolean match(GuanYuMethod target) { 39 | if (!className.equals(target.getClassName())) { 40 | return false; 41 | } 42 | if (!(Objects.equals(method, "*") || Objects.equals(method, target.getMethod()))) { 43 | return false; 44 | } 45 | if (!(Objects.equals(desc, "*") || Objects.equals(desc, target.getDesc()))) { 46 | return false; 47 | } 48 | return true; 49 | } 50 | 51 | public boolean white(String className) { 52 | return whiteClassNames.contains(className); 53 | } 54 | 55 | @Override 56 | public String toString() { 57 | return "{" + 58 | "className='" + className + '\'' + 59 | ", method='" + method + '\'' + 60 | ", desc='" + desc + '\'' + 61 | '}'; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /plugin/src/main/java/me/threedr3am/guanyu/plugin/asm/ASTClassVisitor.java: -------------------------------------------------------------------------------- 1 | package me.threedr3am.guanyu.plugin.asm; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | import me.threedr3am.guanyu.plugin.GuanYuMethod; 6 | import org.objectweb.asm.ClassVisitor; 7 | import org.objectweb.asm.MethodVisitor; 8 | import org.objectweb.asm.Opcodes; 9 | 10 | /** 11 | * @author threedr3am 12 | */ 13 | public class ASTClassVisitor extends ClassVisitor { 14 | 15 | private String className; 16 | private Set methods; 17 | 18 | public ASTClassVisitor(String className) { 19 | super(Opcodes.ASM6); 20 | this.className = className; 21 | this.methods = new HashSet<>(); 22 | } 23 | 24 | @Override 25 | public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, 26 | String[] exceptions) { 27 | return new ASTMethodVisitor(className, methods); 28 | } 29 | 30 | public Set getMethods() { 31 | return methods; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /plugin/src/main/java/me/threedr3am/guanyu/plugin/asm/ASTMethodVisitor.java: -------------------------------------------------------------------------------- 1 | package me.threedr3am.guanyu.plugin.asm; 2 | 3 | import java.util.Set; 4 | import me.threedr3am.guanyu.plugin.GuanYuMethod; 5 | import org.objectweb.asm.MethodVisitor; 6 | import org.objectweb.asm.Opcodes; 7 | 8 | /** 9 | * @author threedr3am 10 | */ 11 | public class ASTMethodVisitor extends MethodVisitor { 12 | 13 | private String className; 14 | private Set methods; 15 | 16 | public ASTMethodVisitor(String className, Set methods) { 17 | super(Opcodes.ASM8); 18 | this.className = className; 19 | this.methods = methods; 20 | } 21 | 22 | @Override 23 | public void visitMethodInsn(int opcode, String owner, String name, String descriptor, 24 | boolean isInterface) { 25 | super.visitMethodInsn(opcode, owner, name, descriptor, isInterface); 26 | 27 | methods.add(new GuanYuMethod(owner, name, descriptor, "")); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /plugin/src/main/resources/META-INF/services/me.threedr3am.guanyu.core.Plugin: -------------------------------------------------------------------------------- 1 | me.threedr3am.guanyu.plugin.BcelDenyPlugin 2 | me.threedr3am.guanyu.plugin.BlackMethodDenyPlugin -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'GuanYu' 2 | include 'agent' 3 | include 'core' 4 | include 'plugin' 5 | 6 | --------------------------------------------------------------------------------