Question

I had a problem in one of my java products, in which players would run a cheat class as the main class. Is there a way in which I can check for the main class running? I've tried adding a UID but they seemed to get past it.

Was it helpful?

Solution

This is hardly a robust and bulletproof solution, but you could try looking at the thread's stack trace and ensure that your class is the last element:

final StackTraceElement[] stack = Thread.currentThread().getStackTrace();

if (! stack[stack.length-1].getClassName().equals(YourClass.class.getName()))
{
  // abort
}

However, there's nothing to stop someone compiling a class with the same fully qualified class name as your legitimate class and replacing your original one.

OTHER TIPS

I think you could use something like this,

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;

public class Checker {
  private static final String HASH_MAIN_CLASS = "Hash of your valid Main class";

  public boolean isExecutingValidMainClass() throws IOException{
     StackTraceElement[] stack = Thread.currentThread().getStackTrace();
     String mainClassName = stack[stack.length-1].getClassName();

     String pathToMainClass = mainClassName.replaceAll("\\.", File.separator) + ".class";

     InputStream inputStream = AppMain.class.getClassLoader().getResourceAsStream(pathToMainClass);

     byte[] mainClassBytes = IOUtils.toByteArray(inputStream);

     if(HASH_MAIN_CLASS.equals(byteArrayHash(mainClassBytes))){
       return true;
     }else{
       return false;
     }
  }

  private String byteArrayHash(byte[] byteArray){

    //Calculate hash for byte array

    //Return  hash for byte array

  }
}

It is not infallible, but they would have to compile a cheat Main class with the same hash that your Main class. Using an appropriate hash algorithm would be complex using a cheat Main class.

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