Ways to abuse your ClassLoader

ClassLoading in Java can be a tricky business. For those who are not really familiar with writing a ClassLoader, here are some of the basics (before we start getting into the abuse):

  1. Custom ClassLoaders should always override the “find*” methods
    1. This means you will conform to the standard ClassLoader policies
  2. A ClassLoader first checks the classes it’s already loaded to avoid re-loading an already linked in class
  3. A ClassLoader then checks with it’s parent ClassLoader to see if it can load the requested class
    1. This avoids people overloading the java.* packages
  4. If all that failed, the ClassLoader attempts “findClass” which then calls “defineClass”

So you see, theres an order that things are done in to make things work smoothly. However, there are ways to abuse this system. Writing custom ClassLoaders requires certain permissions, so it’s assumed that you’re trusted when you write ClassLoaders.

Overriding java.* classes

First off, you can change the loading order and override java.* classes for other loaded classes. ClassLoaders can only effect what Classes they (and their child ClassLoaders) load see. This is a simple trick, simply overload all the “loadClass” methods and change it to simply “findClass”.

Injecting Classes

You could expose “defineClass” publicly, but that would be very dangerous, since any classes loaded by you automatically have a reference to your ClassLoader. So it’s a better idea to encapsulate the injection logic into the ClassLoader itself. For example:

public class InjectingClassLoader extends ClassLoader {
public InjectingClassLoader(Set<String> classFiles) {
for(String s : classFiles) {

private void injectClass(String name) {
InputStream in = InjectingClassLoader.class.getResourceAsStream(name);
byte[] buffer = ...;

// read the bytecode from the stream into the buffer

String className = ...; // transform the filename into a class name
defineClass(className, buffer, 0, buffer.length);

Class injection is a very useful trick if you’re generating byte codes on the fly. It breaks the lazy-loading in Java, since you’re forcing the classes to be loaded before they are actually needed. However, this in it’s own right could be useful for a gaming environment, where even class-loading may appear to hinder performance.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: