Article Last Updated , 22 June 2010
Greetings Earthlings ,
After some years of experience in the Java language and the Bytecode it compiles to , i've been also interested for a while in hacking other Java applications , discovering their points of weakness and trying to suggest security advises.
[I guess Xterm would most probably be the most interested guy to read such a thread since it concerns Java =p, anyways greetings all and specially xterm],o Let's start :
Introduction :
There are two types of Java applications, Secured and non secured which correspond to obfuscated and non obfuscated, and as we know that upon compiling Java sources, they definitely turn into classes that contain instructions that are known as bytecode which gets handled and executed by the Java Virtual Machine (JVM),but
now i am going to divide the Java hacking into scales , and describe how each is done:
Very Low Scale - Decompiling[Applies on Unsecured classes only
So basically , if we are able to return back the source code from the bytecode, we are then able to edit the source and compile it again , to do that , we go to the package containing the classes or the jars , if the classes you want to edit are packed in a jar, you just extract that jar by using an achiever like winRar or so , and then you have to download a tool off of the internet, that will decompile classes and give you back their original sources (In case they weren''t secured/obfuscated) , Famous tools : JAD ,CAVAJ and DJ Java Decompilers.
Now to know whether its secured , you often see "missing label" statement inside the source , and the try catch block will look totally unfamiliar , and most probably fields and methods would be randomly refactored to random alphabits (Class a , Class b , Class ac ..), else if it looked good and compiled, then its unsecured, you are ready to edit source, and make your own version of it ;).
Download Cavaj for free @ :
http://download.cnet.com/Cavaj-Java-Decompiler/3000-2213_4-10071619.html
Download JAD for free @ :
http://www.varaneckas.com/jad
[DJ decompiler is pay]
Low Scale - Overriding Methods and morphing classes [Applies on secured classes]
-Class "a" <- this is the class you want to hack;
-refactor its name to (example : "c", by using some class refactoring util)
-create a new class of the same original name of the class you wanted to hack ("a")
-let "a" extends ("c" which is the original class to hack), and let it override the methods that you want to modify on your own.
- "now class "a" contains the original content of the class you wanted to hack with an overridden method(s) of your choice .
Medium Scale - using Reflection / Bytecode editing libraries (ex : BCEL) [Applies on secured Applications]
Incase those classes where obfuscated and you were never able to compile the decompiled sources, then in this scale of hacking you are just able to to read fields values of any accessors/modifiers or to change them at runtime, and even create and add new objects to secured classes note that that can be done using the origional java reflection package , however its direct and faster upon using bytecode editing libraries like BCEL, its much faster than using reflection, however here is a sample code of how to change values of fields of any modifier by using Reflection :
import java.lang.reflect.*;
public class field2 {
public double d;
public static void main(String args[])
{
try {
Class cls = Class.forName("field2");
Field fld = cls.getField("d");
field2 f2obj = new field2();
System.out.println("d = " + f2obj.d);
fld.setDouble(f2obj, 12.34);
System.out.println("d = " + f2obj.d);
}
catch (Throwable e) {
System.err.println(e);
}
}
}
High Scale - Editing Methods components and constant pool data with BCEL [Applies on unsecured classes]
This might requires some bytecode knowledge , its a matter of modifying the bytecode directly of classes without working with their sources, for that you must learn how to use byte code editing libraries such as BCEL or ASM(supports Tree structures).
I'm not in the mood to post some snippets right now, maybe later, but infact its not very necessarly that you have some ideas about bytecode instructions even, let's say you want to change the following method.
public int getID()
{
return id;
}
then you might just want to let it always return a value of 5 by hacking its bytecode , and to do that, just write
the same method name with same type and modifiers and let it return 5 , then compile it, and use BCEL to output the instructions of your new created method, and just replace the original method's instructions with that :) .
Here is a simple snippet of BCEL that i wrote to change the class name of a class (that could be used as a tool to refactor a class , useful @ low scale hacking (read up):
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.generic.ClassGen;
import java.io.IOException;
public class NameChanger {
public static void main(String[] argV) {
//an object for parsign a JavaClass object.
ClassGen cg;
//declaring + initializing the class name that you want to hack.
final String class_name = "HackMe";
try {
//Javaclass is used to parse a class, do a repository look up to parse a class.
JavaClass jc = Repository.lookupClass(class_name ;
//initializing cg of a constructor that accepts a JavaClass , which we pre-defined.
cg = new ClassGen(jc);
//refactor the class Name
cg.setClassName("ImHacked");
}
catch(ClassNotFoundException ex) {
ex.printStackTrace();
return;
}
//dump the class back to get changes applied.
try {
cg.getJavaClass().dump(class_name);
}
catch(IOException ex) {
ex.printStackTrace();
}
}
}
Look back @ that class, you'd see that it have been refactored to the new name that you setted =).
,alternatively and simply without using any library ,you can just download a fancy bytecode viewer tool called JBE
with that tool, you are able to view the bytecode of any method of any class, and also edit it by placing your own instructions ( which you get from viewing with the same tool bytecode of your own modified method) , so you can just hack with that visual technique, but make sure that you also copy and modify other stuff along such as the table of exceptions, max and minimum stack sizes, or it won run upon execution, other than that, it goes smooth.
New:
Here is an explanation on it, its all in the image.
JBE (Java ByteCode Editor) can be found free @ : JBE :
http://www.cs.ioc.ee/~ando/jbe/
BCEL (ByteCode Editing Library) can be found free @ :
http://www.jakarta.apache.org/bcel
Very High Scale - Writing Deobfuscators [Definitely applies on secured classes]
When you come to compile classes and make sure that they are obfuscated , and you really want to get the whole source back but with renamed classes, methods and fields of course (because they already have been renamed by the used obfuscator @ the constant pool level, you have to write a custome deobfuscater for it.
This is a very difficult task to do, it requires huge bytecode knowledge , where you have to apply binary shifts and exclusive operations (xor's) and stuff, so you need to basically check methods of the obfuscation algorithm of many classes, notice what it does, and reverse its functionality,note that the hardest part of reversing is the control-flow try-catch block part, many deobfuscators remains incomplete because of that part, however its all doable.
I'm not going to mention any further details on how this difficult technique of cascading stages is done, since it can cause a great harm and a big loss for many commercial companies that really want to sell their very propriatory applications , and certainly to the Java Sun Company itself.
Note: There are no public obfuscators over the internet.
NEW - Additional hack using Java Instrumentation Package to get classes loaded in the JVM
We actually can get instances of the classes loaded in the JVM that are obviously used by other applications.
This is useful to use Reflection or BCEL with applications that already ran, and loaded naturally (as being launched in browser) , so all we want is to obtain all the classes loaded in to the JVM.
To do that, we use the Instrumentation package from Java , we write an agent , turn it into a jar file and finally add it to the Java arguments as an agent.
First , we have to write the Agent class, that will have a very special method, a premain method.\
import java.lang.instrument.*;
// Agent Class
public class PreMain{
private static Instrumentation instrument;
public static Instrumentation getInstrumentation() { return instrument; }
public static void premain(String argV, Instrumentation inst) {
instrument = inst;
}
}
Compile this and put it in a jar file with a manifest as described in the api package summary, and then you can run your main program with the follwing args:
java -PreMain:agent.jar Main
implementation example :
import java.lang.instrument.*;
public class Main
{
public static void main (String argv[])
{
Instrumentation instrument = PreMain.getInstrumentation();
Class[] loadedClasses = instrument.getAllLoadedClasses() ;
for(Class c : loadedClasses)
System.out.println(c.getName()); // will print the name of all loaded classes ( in JVM).
}
}
Hope you enjoyed this powerful explanation of Java hacking and securing , and hope that it won't be abused and that it will remain for educational Reasons =)
---------------------------- Fully written by Nader Sleiman -----------------------------------