Question

I have a jar in which all of the class files have their magic number and type removed, I am not very knowledgeable about this specific area. What would be the best way to go about adding back in 0XCAFEBABE and the type back into each classfile and repacking the jar?

EDIT: i have checked, only the magic number is missing, the files are intact if i add it manually.

Was it helpful?

Solution

If you would like to do this at runtime, you could create your own classloader. I have attached some pseudo-code that might get you on the way:

public class MyClassLoader extends SecureClassLoader {

  @Override
  protected Class<?> findClass(String name) throws ClassNotFoundException {
     ...
     FileInputStream fis = new FileInputStream(brokenClassFile);
     BufferedInputStream bis = new BufferedInputStream(fis);
     ByteArrayOutputStream bas = new ByteArrayOutputStream((int) encryptedClassFile.length());
     byte[] wrongBytes = bas.toByteArray(); 
     byte[] goodbytes = ...     
     // add  a new byte[] and put in the appropiate missing bytes for the cafebabe and magic number
     CodeSource cs = new CodeSource(jarfile.toURI().toURL(), (CodeSigner[]) null);
     return super.defineClass(name, goodbytes, 0, bytes.length, cs);



  }

}

But i guess it is better to just fix the jar file using some OS tooling.

OTHER TIPS

If you just want to add the magic number back to the class files, you could use a simple shell script for this (assuming you are on Linux, or have Cygwin on Windows).

First create a file with just the 4 bytes of the header (CAFEBABE).

Then, extract the class files from the jar to some directory, and run this command at the root:

find . -name "*.class" | while read file; do
    mv ${file} ${file}-old
    cat /path/to/file/with/header ${file}-old > $file
    rm ${file}-old
done

Note: The above script works in bash, but you should be able to write something similar for any shell, or even for Windows.

But what do you mean by "have their magic number and type removed"? If the bytecode has been mangled in any way, the changes might be much more difficult to fix if not impossible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top