Search code examples
javajavac

How to compile and run code from user in Java?


How can I run a Java code, which user send me in request?

I need to take a code from user, that uses some of my classes, run it and take a result.


Solution

  • A very crude way would be this:

    String code = request.getParameter("code");
    String className = "Code" + DigestUtils.sha1hex(code);
    String classCode = ""
      + "public class " + className + " implements Runnable {\n" +
      + "  public void run() {\n" +
      + code + "\n"
      + "  }\n"
      + "}\n";
    Files.write(new File(className + ".java"), code, StandardCharsets.UTF_8);
    
    Runtime.getRuntime().exec("javac " + className + ".java");
    
    Class<?> clazz = Class.forName(className);
    ((Runnable)clazz.newInstance()).run();
    

    Assuming that the current directory is in the classpath, and further assuming that the classloader loads classes on-demand, this or something similar should work, at least for your System.out example.

    When playing with this code, be aware that the uploaded code may do anything, including invoking System.exit(1), reading all the files in the filesystem, starting a botnet on the computer, and so on.

    Instead of the last two lines of code, you could also do:

    Runtime.getRuntime().exec("java " + className);
    

    (Or some variation of it, which then allows you to capture System.out and System.err, so you can feed them back to the HTTP client. This would also prevent any danger from System.exit, so that only the numerous other vulnerabilities are left.)