Jean-François Lalande
November 2016
For this exercise, you should have one of the following smartphones:
In this exercise of the tutorial, we will study the SimpLocker malware which is a ransomware (SHA 256: 8a918c3aa53ccd89aaa102a235def5dcffa047e75097c1ded2dd2363bae7cf97). It encrypts the user’s files and displays a fullscreen warning asking to pay a ransom to decrypt the file. The malware is connected to the attacker via the Tor network but we do not need to let the malware connect to Tor.
The goal of this exercise is to understand how works the malware by reverse engineering its code. We will let the malware operate and encrypt your files… But then, we will write an antidote by modifying the malware to force it to decrypt the encrypted files !
You should see your device by doing:
adb devices
List of devices attached
XXXXX device
If you cannot see your device when you type adb devices
check your adb installation and make sure Usb debugging option is enabled in Settings > Developers Options.
If you still can not see your device enable Settings > Storage > 3 vertically aligned dot (top-right) > Usb computer connection > Camera (PTP)
If you still can not see your device the last thing to do is to enable Settings > More > Tethering & portable hotspot > USB tethering
If your device is unauthorized, you should accept the fingerprint of the computer that connects to the smartphone on the smartphone screen.
For this exercise we do not need an internet connection. Disconnect your smartphone from the internet.
We need to provide some personal data to the malware. Take a photo of yourself or something if you do not trust totally this tutorial…
Check in the gallery app that the photo is there.
Install the malware (if the device asks you to share data with google, decline):
adb install SimpLocker.apk
Launch the malware by hitting the icon “Sex xonix” or “Locker” (depends of the phone language). You should see a fullscreen message.
Wait 1 minute (the malware encrypts your file). You can check the files to see if the malware produces .enc files:
adb shell ls /storage/sdcard0/DCIM/Camera
IMG_20160629_115145933.jpg.enc
IMG_20160629_115148191.jpg.enc
...
Reboot the phone.
adb reboot
Uninstall the malware:
adb uninstall org.simplelocker
Check the images of the gallery: you should not see your photo anymore. All your data is gone (encrypted) !!! Damn !!!*
We propose to use BytecodeViewer which enables to open and decompile an Android application. It proposes several decompilers and basic search capabilities. Download the FATJAR version (that includes all plugins).
Test BytecodeViewer on a demo file demo1.apk that is a small application of three activities (three screens):
BytecodeViewer demo1.apk
Open the jf.andro.malcon15demo package and the MainActivity class. You should see a decompilation of the bytecode where two buttons are created in the activity.
This shows how it is simple to browse the source code of an app.
Reverse the malware bytecode:
BytecodeViewer SimpLocker.apk
Boom ! You obtain an exception “MALFORMED”. This is because one of the files (probably the Manifest) is malformed. This is an obvious protection of the malware developer to prevent any static analysis from classical tools (here apktool which is one of the components of BytecodeViewer). Thus, we will need to the reverse with manual operations.
Unpack the malware:
mkdir malware-source
cd malware-source
unzip ../SimpLocker.apk
cd ..
The code is located in malware-source/classes.dex. This is a jar file containing all the classes using the dex format. Open the classes.dex file that is well formed with BytecodeViewer:
BytecodeViewer malware-source/classes.dex
Now you can browse the code of SimpleLocker.
The malware developer is a well organized person. All the malicious code is located in the org.simplocker package. Have a look to:
You can use the search box (bottom left) to discover where the encrypt() function is called. Search all classes with Regex “encrypt()”. You should find that the MainService$5 class launches the encryption. Of course, the ciphering process is performed in background. We can suppose that the deciphering is also performed in a service.
Now, search the calls to decrypt(). You will discover that the call is handled in HttpSender. Of course, the malware waits for a message from the attacker’s server to decipher the files.
Modifying this part is not an easy task (but would be possible). A better idea is to modify the primary behavior of the malware when MainService$5 encrypts files. Instead of calling the encrypt() method, we will force MainService$5 to call the decrypt() method. This way, our new malware will act as an antidote !
The classes should be converted to the standard .class format in order to be edited. Convert the dex file to a jar file and extracted the classes:
d2j-dex2jar.sh malware-source/classes.dex
mkdir malware-source-jar
cd malware-source-jar
unzip ../classes-dex2jar.jar
To change the class MainService$5.class, use the bytecode editor JBE. You have to patch the CLASSPATH to put in it the …/bin directory in order to have jbe.sh find the main class (use export CLASSPATH=…/bin).
When JBE is running, change the encrypt() to a call to decrypt():
jbe.sh
# Edit the file and save it
Instructions:
encrypt()
and replace it by decrypt()
Repackage the classes in a jar file:
# In the malware-source-jar folder
jar cvf ../classes-patch.jar *
Convert the jar in the dex format:
cd ..
d2j-jar2dex.sh classes-patch.jar
Backup and replace the classes.dex file:
# Backup of the original classes.dex
cp malware-source/classes.dex ./classes-backup.dex
# Replacing the classes.dex by the new one
cp classes-patch-jar2dex.dex malware-source/classes.dex
Rebuild the apk and sign it:
# Rebuilding the apk
cd malware-source
rm -rf META-INF
jar cvf ../simplocker-antidote.apk *
# Sign it with the debug key
cd ..
jarsigner -verbose -sigalg MD5withRSA -digestalg SHA1 -keystore ~/.android/debug.keystore simplocker-antidote.apk androiddebugkey -storepass android -keypass android
We have now the antidote against SimpLocker
Install the antidote (if the device asks you to share data with google, decline):
adb install simplocker-antidote.apk
Launch the malware by hitting the icon “Sex xonix” or “Locker”. You should see a fullscreen message.
Wait 1 minute (the antidote deciphers your file). You can check the files to see if the malware deciphers .enc files:
adb shell ls /storage/sdcard0/DCIM/Camera
IMG_20160629_115145933.jpg.enc
IMG_20160629_115145933.jpg
IMG_20160629_115148191.jpg.enc
IMG_20160629_115148191.jpg
Eventually reboot the phone. Uninstall adb uninstall org.simplelocker
, open the gallery app. Your photos should reappear magically !
This malware is a fully functional ransomware that is able to decipher the encrypted files. The command is sent via the Tor network by the attacker, when the user has paid for recovering its files. The main drawback of the malware is the poor quality of the ciphering algorithm that uses a constant as encryption key. A more advanced version of such a malware should generate the key and store it on server side to become a more dangerous malware.
For more information, you can enjoy the Kharon webpage about this malware. The graph button gives you a view of the Tor process used to anonymize the communication with the attacker.
http://kharon.gforge.inria.fr/dataset/malware_SimpLocker.html
For this exercise, you should use an Android emulator. A kitkat version (Android 4.4) is fine, but newer version may work.
The malware to study is sp_ntm.apk
In this exercise of the tutorial, we will study the KitchenService malware which is a spyware (SHA 256: 2fbc32387f9b5c5a8678af3a76c0630ba4d04fd520b21782642a517794063f05). It leaks some user information to the internet and display web pages. What is cool is that the web pages still exist !
The goal of this exercise is to understand how works the malware by reverse engineering its code. Then we will try to capture the data when the malware leaks them.
You should see your device by doing:
adb devices
List of devices attached
XXXXX device
With the apktools, decode the apk. You should get the files in a directory sp_ntm.
Study the required permission in the Manifest file. You should get a better idea of the malware type by reading the asked permissions. You also see the declaration of a service KitchenTimerService.
Open the apk file with BytecodeViewer. Configure Pane 1 to open a reversed version of the code (CFR). Configure Pane 2 to open the Bytecode.
Study the class KitchenTimerService. You see the the service launches futur tasks (TimerTask) for an unavailable inner class. Search in the Bytecode
the type of the new TimerTask. When you have found this class, open it: You see that the messages are sent using an informative broadcast containing “Kitchen Timer Service”.
Open the Main class. The first place to look is the onCreate() method, which is called when the application is launched by the user. You’ll see several things:
Then, you have to inspect the KitchenTimerReceiver to see what happens when the intent is received. Yyou will see that the malware gets these informations:
And the malware makes the phone vibrate !
Then, a long loop starts a lof of other activities:
The malware takes care to reprogram a task with a call to Main.this.kitchenTimerService.schedule(120000L) ;.
Execute the malware in the Android Emulator. Install it with:
adb install sp_ntm.apk
The malware appears with an anonymous icon.
In this step, we propose to make an application to capture the moment where the Intent is launched.
Create an application in Android Studio (blank activity). Create a BroadcastReceiver MyReceiver and put a Log in the onReceive method. In the Manifest file, filter the intent named “myintent”. Test that your receiver captures the intent: after launching the application, send a fake intent using adb:
adb shell am broadcast -a "myintent"
You should see your log line.
Modify the Manifest to filter the “Kitchen Timer Service”. What happens ? Try to use adb to send such a intent. What happens ? WTF ! An intent should not contain whitespace !!!
Ok, so we should register the intent filter dynamically:
IntentFilter filter = new IntentFilter(param1);
MyReceiver r = new MyReceiver();
registerReceiver(new MyReceiver(),filter);
Put this code in your Activity (onCreate) and test it. What happens if you close your application ?
To make your filter persistent we have to put this code in a service. To do so, create a new IntentService called MyIntentService (using the wizard). The wizard will generate the IntentService code for two actions Foo and Baz. We will use the Foo action.
Start the service by calling the action Foo from your onCreate() method of your main activity:
MyIntentService.startActionFoo(this, intentName, null);
In the handleActionFoo(String param1, String param2) method, put the following:
This will make the service alive for 60s and listening for the Intent.
Test it ! You should now be able to capture the moment where the “Kitchen Timer Service”. What do you see when it happens on the smartphone’s screen ?
Setup a local web server that will print the HTTP requests (for example https://gist.github.com/huyng/814831)
Repackage the malware and replace the domain name 14243444.com by 10.0.2.2:8080 (the IP of your computer from the android emulator). For repackage operations, see Step 7 of exercise 1.
You should capture the leaks sent by the malware !
The captured intent does not contain useful information (not extra key/pairs on it). Thus, it only helps to see the moment when the intent is launched. The capture of the HTTP traffic should be done outside of the emulator. It could be done more easily by changing the DNS server and redirecting all the traffic to a fake web server. Nevertheless, such a setup require to be root on your host.
For this exercise, you should have one of the following smartphones:
In this exercise of the tutorial, we will steal the files that are created by a malware in the internal storage. Internal storage is the place where private files of applications are stored. On the contrary, external storage is the place where user’s files can be mounted via a USB cable. See Files for more details.
The first thing that you can do is exploring your device with the shell:
adb shell
At the root place /, you can list files. You will see several things:
Each application can write files in /data/data/packageid where packageid is the package name of your target application. Thus, we need to find how to get files from /data/data/packageid. If you need to find what is the package id, you can list all available installed apps:
pm list packages -f
List the processes of the system:
ps
You will observe that the owner of the processes can be:
For testing purpose we will create an simple application that writes a private file.
Run your application and list processes. What is the owner of your app ?
As you can see on this webpage, two methods can be used to get files from the /data directory:
Let us use the first method. Switch of context using:
run-as fw.jf.andro.filewritting
Use the command “whoami” to check your identity. Launch another shell in a second terminal and list the processes. You will see that your shell is now owned by the user associated to w.jf.andro.filewritting.
Use the pwd command to check where you are.
Use the cat command to display the content of the file your application have created.
Great !
Get the MADDEN NFL 12 malware (SHA256: 213e042b3d5b489467c5a461ffdd2e38edaa0c74957f0b1a0708027e66080890). This application deploys some files in the internal storage. They could have been downloaded from the internet, but in this case they are embedded in the apk (thus of course, we can get it by uncompressing the apk but for the exercise we will suppose that they are dynamically generated by the malware, for example after a download).
Install it and try the run-as method:
shell@bullhead:/ $ run-as com.android.bot
run-as: Package 'com.android.bot' is not debuggable
Of course, it does not work because this appilcation is not debuggable ! We have to use the second method: the backup method.
The principle of the method is to extract the app files using the backup functionality: the extracted file is an archive encrypted by AES. The difficulty is the deciphering of the archive.
Backup the files:
adb backup -noapk com.android.bot
If the phone does not ask for the password, you can try:
adb backup com.android.bot
Build the backup tool:
Unpack the backup:
./abe unpack ~/swap/backup-com.android.bot.ab ~/swap/backup.tar azerty
tar -xvf backup.tar
You will obtain the malware files !
What are the type of these files ?
And the show continues…
Even on a non rooted device, there is some methods to get files that are generated by a malware. Of course it require to have access to the phone (a locked phone would be unusable) but then, the method is quite simple. The limitation is that a lot of malware download the payload but do not write them into files. But most of malware that gets some apk and push them for installation write files because this is the way new apps are deployed.
For this exercise, any smartphone or emulator should work.
In this exercise, we use Soot, a library that is able to manipulate java classes. In 2013, authors of soot implemented the opening of .apk files. Thus, it easy as ABC to take a malware and automate transformation of its bytecode. This exercise is based on the publication Instrumenting Android and Java Applications as Easy as abc and on our experience when designing GroddDroid in the publication GroddDroid: a Gorilla for Triggering Malicious Behaviors.
The studied malware is the Koler which is a spyware (SHA 256: 4d3de2103f740345aa2041691fde0878d7d32e9e4985adf6b030d2e679560118).
The global goal is to log the dynamic information manipulated by the malware by modifying the malware from the inside…
In this step, we will setup and expore the demo project of Soot (that have been setup for another tutorial in 2013). The project takes an APK RV2013.apk and applies some transformations where SMS are used.
Remark: the source of the application RV2013 is located at android-instrumentation-tutorial/app-example/RV2013. You can rebuilt it if you need to change the source code of RV2013.
Replace soot.jar by a an more up-to-date version. This will avoid some old bugs coming from the 2013 version of soot.
Quickly inspect the malware in order to find interesting variables or methods to inspect.
In this step we propose to check if the LockActivity is running. We can suspect such an activity to be the one that lock the screen. In order to check this, we will insert some code in the onCreate() method.
In your transformation body, check if the classname starts with “com.android.LockActivity” and check that the current method contains onCreate. Put a System.out line “Here is LockActivity.onCreate” the if these conditions are met. Generate Koler.apk and check in the Eclipse output that you see the log “Here is LockActivity.onCreate” (because at some points, soot should encounter this method).
In this block, you can then iterate over all statements by keeping the code:
// Here we are in LockActivity.onCreate
Iterator<Unit> i = body.getUnits().snapshotIterator();
while (i.hasNext()) {
Unit u = i.next();
...
}
Take inspiration from the replaceStatementByLog method and generate a Log.i call to print “coucou” in the Logcat log, each time a Unit u contains “StrictMode” (for example). This way, when the method onCreate will execute, some “coucou” will appear in the Logcat.
Generate Koler.apk again. You can check the result in BytecodeViewer. If you are lucky, the decompiler will work. In my case, it crashes. At list, you can look at the Smali code.
Sign the APK:
jarsigner -verbose -keystore ~/.android/debug.keystore -storepass android -keypass android Koler.apk androiddebugkey
Execute it on the smartphone. You are now sure that this Activity is executed.
Difficult !
The goal here is to disable the repetive task by removing some parts of the code that triggers the lock screen. Some advices:
The most difficult part is to generate new code with Soot and to avoid breaking the semantics of the bytecode. Logging is very easy but manipulating variables or creating new ones need more skills :)
For this exercise, any smartphone or emulator should work.
In this exercise of the tutorial, we will build a covert channel between two applications. The idea is to transmit data between one application CCSender to an application CCReceiver without any legal communication channel !
Such covert communication helps to parts of a malware to transmit data without being discovered, as represented in this screenshot:
Create two Android projects. The first one will implement CC sender and the second one CC receiver.
In CC sender, implement a TimerTask that will regularly load the disk or the memory (with some useless data), then unload the disk or the memory. Memory unloading maybe be tricky, as you do not kno when the garbage collector will be triggered.
In CC receiver, implement a TimerTask that will regularly check the available disk space or memory load. With the osbserved variation, you can infer a 0 or a 1. Refresh a TextView in order to see the incoming bits.
For memory, you can be helped looking at http://stackoverflow.com/questions/3170691/how-to-get-current-memory-usage-in-android
Now you have to encode the data to send from CC sender. Update the code of CC sender in order to encode a byte, and thus a String.
The difficulty is to know when the a byte begins in the flow. You can use a special sequence e.g. 00000000 to setup a “starting point”.
Display in your CC receiver app the received bits. Then decode the bits to display the received String.
In this exercice, the difficulty step is to synchronize the two applications before starting the transmission. Other implementations can use another channel for synchronizing. Additionally, some channels may fail depending of the used smartphone, the available space (disk or memory). Obtaining a high throughput is also a difficult challenge. If the TimerTask goes quick, the receiver may fail to be synchronized (at some points) introducing errors in the transmission.
J.-F. Lalande is associate professor at INSA Centre Val de Loire. He is the only serious guy of the team. He proposes these exercises for building this tutorial as a hobby compared to the work achieved in the kharon project.
Valérie Viet Triem Tong is associate professor at CentraleSupélec and Inria. She’s the lead director of the kharon project (here is the view of the buildings). This also implies that working on malware means to fund others for working on malware !
Mourad Leslous is a PhD student from Inria and University of Rennes 1. He has more malware in his computer and phone than regular apps !
Korlan Colas is a master student at INSA Centre Val de Loire. He woke up very early (before noon) to write some parts of this tutorial or to develop graphical tools for seeing malware.
Aymeric Lambrecht is a master student at INSA Centre Val de Loire. If your smartphone is flashed correctly, then his job has been done right. He also bricked one 500€ smartphone in order to make AndroBlare still alive !