Is code injection possible in Java?
There are a couple ways in which Java code could be injected into an application such as using the scripting API or dynamic JSP includes.
The code below allows a user to inject arbitrary Javascript into Java's script engine.
import javax.script.*;
public class Example1 {
public static void main(String[] args) {
try {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
System.out.println(args[0]);
engine.eval("print('"+ args[0] + "')");
} catch(Exception e) {
e.printStackTrace();
}
}
}
In this case, the attacker decides to inject code that creates a file on the file system.
hallo'); var fImport = new JavaImporter(java.io.File); with(fImport) { var f = new File('new'); f.createNewFile(); } //
check owasp website for more examples
A java program itself is pretty much not vulnerable to code injection. However, all the native code that supports the app is vulnerable to all the different kinds of code injection - this includes the JVM and all native code parts in the app or its libraries.
Also, there are a few more things to consider:
Anything where java is used as a gateway to other systems is possible:
SQL Injection
XSS (which is in the end nothing more than JavaScript Injection)
If the java program is itself a interpreter/compiler of some kind, it might be possible to inject code into your interpreted language/compiled program (this includes using your program as a java compiler...)
And of course if you can get the java program to write a file to disk that contains code (be it native, java or something else) you might be able to get it executed by other means (which can be a different vulnerability in your app, the os or another app) - this is not direct code injection but quite similar in effect.
You could write a web service that accepted a Java code snippet, wrapped it in a class/method declaration, saved it to disk, ran the compiler on it and then dynamically loaded and executed the result. So code injection is certainly possible.
But with typical Java implementations, it's perhaps not very efficient because of the relatively heavyweight compilation process (it might still be practical for some apps though).
Code injection is highly relevant with SQL because the "first guess" of many beginners is to use string concatenation to insert variables into a statement. But it rarely crops up as an idea amongst Java programmers. So that's the reason it isn't much of a concern.
If Java compilers become exposed as light-weight library services, then you'd have something much closer to the equivalent of eval
and therefore it might start to become a relevant concern.
If the server application creates bytecode at runtime (for example with BCEL or Javassist), and if this creation can be influenced by user input, then a code injection is possible.
However, if you application uses no magic (which should be 99% of all applications), it will not be possible.