javabytecodejava-bytecode-asmjavassistjavaagents

Why does java agent get stuck and not perform any actions?


I am writing a term paper for the university. The task is to write two programs, one of which collects some information, signs it with a digital key, and saves the encrypted data and the key to separate files. The next program collects the same information, reads the encrypted data and keys, and verifies the digital signature.

Step number two is to write an agent that uses java.lang.instrument.Instrumentation; and possibly third-party libraries such as javaassist to do bytecode substitution so that the program always gives a successful verification result

I tried to implement this with the help of tutorials, but my program gets stuck at the change stage

Here is the analysis of the bytecode that needs to be changed

static void checkSign(java.lang.String, java.lang.String, java.lang.String) throws java.lang.Exception;
    Code:
       0: new           #206                // class java/io/BufferedReader
       3: dup
       4: new           #258                // class java/io/FileReader
       7: dup
       8: aload_0
       9: invokespecial #260                // Method java/io/FileReader."<init>":(Ljava/lang/String;)V
      12: invokespecial #219                // Method java/io/BufferedReader."<init>":(Ljava/io/Reader;)V
      15: astore_3
      16: aload_3
      17: invokevirtual #225                // Method java/io/BufferedReader.readLine:()Ljava/lang/String;
      20: astore        4
      22: invokestatic  #262                // Method java/util/Base64.getDecoder:()Ljava/util/Base64$Decoder;
      25: aload         4
      27: invokevirtual #268                // Method java/util/Base64$Decoder.decode:(Ljava/lang/String;)[B
      30: astore        5
      32: aload_3
      33: invokevirtual #245                // Method java/io/BufferedReader.close:()V
      36: new           #206                // class java/io/BufferedReader
      39: dup
      40: new           #258                // class java/io/FileReader
      43: dup
      44: aload_1
      45: invokespecial #260                // Method java/io/FileReader."<init>":(Ljava/lang/String;)V
      48: invokespecial #219                // Method java/io/BufferedReader."<init>":(Ljava/io/Reader;)V
      51: astore        6
      53: aload         6
      55: invokevirtual #225                // Method java/io/BufferedReader.readLine:()Ljava/lang/String;
      58: astore        7
      60: aload         6
      62: invokevirtual #245                // Method java/io/BufferedReader.close:()V
      65: invokestatic  #262                // Method java/util/Base64.getDecoder:()Ljava/util/Base64$Decoder;
      68: aload         7
      70: invokevirtual #268                // Method java/util/Base64$Decoder.decode:(Ljava/lang/String;)[B
      73: astore        8
      75: ldc_w         #274                // String RSA
      78: invokestatic  #276                // Method java/security/KeyFactory.getInstance:(Ljava/lang/String;)Ljava/security/KeyFactory;
      81: astore        9
      83: new           #281                // class java/security/spec/X509EncodedKeySpec
      86: dup
      87: aload         8
      89: invokespecial #283                // Method java/security/spec/X509EncodedKeySpec."<init>":([B)V
      92: astore        10
      94: aload         9
      96: aload         10
      98: invokevirtual #286                // Method java/security/KeyFactory.generatePublic:(Ljava/security/spec/KeySpec;)Ljava/security/PublicKey;
     101: checkcast     #290                // class java/security/interfaces/RSAPublicKey
     104: astore        11
     106: ldc_w         #274                // String RSA
     109: invokestatic  #292                // Method javax/crypto/Cipher.getInstance:(Ljava/lang/String;)Ljavax/crypto/Cipher;
     112: astore        12
     114: aload         12
     116: iconst_2
     117: aload         11
     119: invokevirtual #297                // Method javax/crypto/Cipher.init:(ILjava/security/Key;)V
     122: aload         12
     124: aload         5
     126: invokevirtual #301                // Method javax/crypto/Cipher.doFinal:([B)[B
     129: astore        13
     131: new           #17                 // class java/lang/String
     134: dup
     135: aload         13
     137: invokespecial #304                // Method java/lang/String."<init>":([B)V
     140: astore        14
     142: aload         14
     144: aload_2
     145: invokevirtual #237                // Method java/lang/String.equals:(Ljava/lang/Object;)Z
     148: ifeq          163
     151: getstatic     #10                 // Field java/lang/System.out:Ljava/io/PrintStream;
     154: ldc_w         #305                // String Verification successfully!
     157: invokevirtual #26                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
     160: goto          171
     163: getstatic     #10                 // Field java/lang/System.out:Ljava/io/PrintStream;
     166: ldc           #204                // String Verification failed!
     168: invokevirtual #26                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
     171: return

This is my agent

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;

public class AgentMain {

    public static void premain(String agentArgs, Instrumentation inst) {
        System.out.println("Ha, ha! This program was hacked ;-)");
        inst.addTransformer(new ClassFileTransformer() {
            @Override
            public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
                                    ProtectionDomain protectionDomain, byte[] classfileBuffer) {

                if (className.equals("Defender")) {
                    try {
                        System.out.println("I'm here");
                        ClassPool cp = ClassPool.getDefault();
                        System.out.println("Class pool created");
                        CtClass cc = cp.get("Defender"); 

                        CtMethod method = cc.getDeclaredMethod("checkSign");

                        String newBody = "{" +
                                "    System.out.println(\"Verification successfully!\");" +
                                "}";

                        method.setBody(newBody);

                        return cc.toBytecode();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
               
                return classfileBuffer;
            }
        });
    }
}

I specially arranged the output of the “I'm here” message to understand where the error is.

After compiling all the classes into a jar, I ran it with the command

java -javaagent:HackAgent.jar -jar Defender.jar

But as a result, I get this

result

What am I doing wrong?


Solution

  • This one is clearly a follow-up on that question, which was closed because you only presented the original code, but did not explain what you tried to solve the problem. Here, it is the other way around. Anyway, with both questions combined, I see that you tried something yourself and are not just looking for someone to do the work completely for you, which is commendable. So, even though it is not a Javassist but an AspectJ answer, I want to show you how to solve the problem. I tried with your original code.

    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    
    @Aspect
    public class DefenderAspect {
      @Around("cflow(execution(void checkSign(String, String, String)) && args(*, *, hash)) && call(String.new(byte[]))")
      public String replaceDecryptedSignString(String hash) {
        return hash;
      }
    }
    

    The pointcut tells AspectJ to pick out String(byte[]) constructor calls, if they are in the control flow of the checkSign method. It also binds the third parameter hash to an advice method argument and uses it to simply return what the constructor call ought to return in order to satisfy the dectyptedSignString.equals(hash) condition in your if statement.

    Your sample code now produces this console log:

    ...
    General information: 
        Author: Artem Lebid
        Number in student list: 9
        Task number: 9
        Task description: Program Defender
    
    ...
    
    MD5 Hash: 19ef14ef0778ac786cd0a32e83b5ab19
    Verification successfully!
    ...
    

    This solution works with both post-compile and load-time weaving.

    Of course, like I said in my comment over there, you can devise a similar solution with ASM, Byte Buddy, BCEL, Javassist or similar frameworks. AspectJ is just my tool of choice, because I like its elegant syntax.