user1039063
user1039063

Reputation: 211

Is there a way to escape from a printing statement and treat string variable as a valid code in java?

I'm exploring some security issues in a piece of code and was wondering if there is a way to break out of the System.out.println(""); statement and treat string as an executable code?

So for example i have the following two lines:

String exit = "System.exit(0);";
System.out.println(exit);

So, that instead of printing the "System.exit(0);" to console, I want JVM treat it as an executable code. Is it even possible? if so, does anyone have ideas on how to do it?

Thank you

Upvotes: 1

Views: 113

Answers (4)

Stephen C
Stephen C

Reputation: 719709

I'm exploring some security issues in a piece of code and was wondering if there is a way to break out of the System.out.println(""); statement and treat string as an executable code?

It is possible to do this, as per Emory's answer. However, in order to do it, you first have to be able to inject code into the application (*). And if you can inject code, there are far simpler ways to shut down the JVM. So:

  • this does not represent a new security risk in your Java application, and
  • this is not a sensible way to compromise someone else's Java application.

* This code injection could entail using some existing or new Java security hole, or it could simply involve modifying the Java application's source code or build process, or modifying the application's bytecodes after a compromise of the host computer.

Upvotes: 0

emory
emory

Reputation: 10891

Yes it is possible. It is easy conceptually, nonetheless extremely difficult to implement. I will not test my answer so it may well be completely wrong.

Write a custom PrintStream class. This PrintStream should for each input line produce a string like

public class Xid implements Runnable { public void run ( ) { line } }

where id is unique for each line and line is the text of the line.

Then it should send that text to a compiler.

Then it should load the class Xid and create and instance of it and the run it.

After you have a PrintStream class like that, you create an instance of itout and use System.setOut(out).

Upvotes: 2

Eugene Retunsky
Eugene Retunsky

Reputation: 13139

It's possible:

  1. Generate a java source file with any code you want.
  2. Execute "javac" to compile it
  3. Load the byte code into the JVM using the class-loader
  4. Execute the class (i.e. call a method).

Now write a class with a single method which accepts a string, a perform all these 4 steps:

JavaInterpreter.execute("System.exit(0);");

Upvotes: 2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272802

Is it even possible?

No.

Not without first deliberately messing about with your JVM, etc.

Upvotes: 7

Related Questions