ByteBuddy附加到本地正在运行的进程

时间:2019-03-06 18:31:52

标签: java byte-buddy bytecode-manipulation

我正在尝试使用ByteBuddy附加到计算机上运行的正在运行的进程。我希望在附加到正在运行的程序时,我的代理将导致重新加载已加载的类,并显示我的Transformer的打印语句。

相反,发生的事情是,当我停止正在附加的运行进程时,我从Transformer中看到了一些JDK类的打印语句。

代码如下:

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.implementation.FixedValue;

import java.io.*;

import static net.bytebuddy.matcher.ElementMatchers.named;

public class Thief {

    public static void main(String[] args) throws Throwable {
        String pid = "86476"; // <-- modify this to attach to any java process running on your computer
        System.out.println(new Thief().guessSecurityCode(pid));
    }

    public String guessSecurityCode(final String pid) throws Throwable {
        File jarFile = createAgent();
        ByteBuddyAgent.attach(jarFile, pid);
        return "0000";
    }


    private static String generateSimpleAgent() {

        return  "import java.lang.instrument.ClassFileTransformer;" + "\n" +
                "import java.lang.instrument.Instrumentation;" + "\n" +
                "import java.security.ProtectionDomain;" + "\n" +
                "\n\n" +
                "public class Agent {" +"\n" +
                "    public static void agentmain(String argument, Instrumentation inst) {" +"\n" +
                "        inst.addTransformer(new ClassFileTransformer() {" +"\n" +
                "            @Override" +"\n" +
                "            public byte[] transform(" +"\n" +
                "                ClassLoader loader," +"\n" +
                "                String className," +"\n" +
                "                Class<?> classBeingRedefined," +"\n" +
                "                ProtectionDomain protectionDomain," +"\n" +
                "                byte[] classFileBuffer) {" +"\n" +
                "            System.out.println(\"transform on : \" +className);" +"\n" +
                "            return classFileBuffer;" +"\n" +
                "            }" +"\n" +
                "        });" +"\n" +
                "    }" +"\n" +
                "}" +"\n";
    }

    private static String generateAgentManifest() {
        return  String.join("\n", "Agent-Class: Agent",
                                                         "Can-Retransform-Classes: true",
                                                         "Can-Redefine-Classes: true",
                                                         "Premain-Class: Agent"
        );
    }

    private static String generateAgentManifest2() {
        return  String.join("\n",
                "Manifest-Version: 1.0",
                            "Agent-Class: Agent",
                            "Permissions: all-permissions"
        );
    }

    private static String generateTransformer() {
        return String.join("\n",
                "import java.lang.instrument.ClassFileTransformer;",
                            "import java.security.ProtectionDomain;",
                            "import java.util.Arrays;",
                            "public class Transformer implements ClassFileTransformer {",
                            "    public byte[] transform(ClassLoader loader, String className, Class<?> cls, ProtectionDomain dom, byte[] buf) {",
                            "        return null;",
                            "    }",
                            "}"
        );
    }

    private static void writeFile(String path, String data) throws IOException {
        final PrintWriter out = new PrintWriter(path);
        out.print(data);
        out.close();
    }

    private static void runCommand(String cmd) throws Exception {
        System.out.println("[commmand] " + cmd);
        String s;
        Process p = Runtime.getRuntime().exec(cmd);
        BufferedReader out = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while ((s = out.readLine()) != null) {
            System.out.println("[out] " + s);
        }
        out = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        while ((s = out.readLine()) != null) {
            System.out.println("[err] " + s);
        }
        p.waitFor();
        System.out.println("[exit status] " + p.exitValue());
        p.destroy();
    }

    private static File createAgent() throws Throwable {
        writeFile("Agent.java", generateSimpleAgent());
        writeFile("Transformer.java", generateTransformer());
        writeFile("manifest.mf", generateAgentManifest2());
        runCommand("javac Agent.java Transformer.java");
        runCommand("jar -cfm agent.jar manifest.mf Agent.class Transformer.class");
        return new File("agent.jar");
    }
}

1 个答案:

答案 0 :(得分:1)

仅添加一个转换器不会导致重新加载已经加载的类。默认情况下,您的转换器仅会看到新加载的类,因此,您在退出时看到某些类的原因是这些类以前未使用过,而是专门为关闭过程加载的。

要重新转换类,您首先必须使用addTransformer(yourTransformer, true)进行注册,然后对要转换的类调用retransformClasses。注意getAllLoadedClassesgetInitiatedClasses(ClassLoader)

的存在

作为补充说明,我强烈不鼓励采用将Java Agent作为源代码字符串嵌入的方法,需要将它们写入临时文件,调用编译器并最终创建jar文件。您可以轻松地将Agent类集成到您的普通源代码中。然后,要生成仅包含Agent类的jar文件,只需要将应用程序代码库中已经存在的.class文件复制到Agent jar。对于简单的情况,您可以同时使应用程序jar文件成为有效的Agent jar文件,而无需任何其他复制步骤即可直接使用它。

此外,请记住,ClassFileTransformer对于所有不变的类,应始终返回null。返回原始的类文件字节在语义上是相同的,但是在调用方方面需要付出更多的努力才能发现您没有更改它。对于将为每个已加载类调用的代码,但通常只对少数几个类感兴趣(或只希望打印信息而不更改任何内容),这样的性能问题就很重要。