Cyber in Bretagne: Android malware reverse engineering

Jean-François Lalande

July 4th 2016

Solutions of this tutorial is provided here.

Exercise 1 : Observing under cover the Mobidash adware

Prerequisite

For this exercise, you should have one of the following smartphones:

Import the provided Virtualbox image Android-Malware.ova. User login is “user”. Root password is “azerty”.

Connect your phone and attach the phone to the virtual image (4th button on the bottom right). If your phone does not appear for virtualbox, it is because you are not in the vboxusers group. Thus, add yourself (sudo adduser login vboxusers) and reconnect your X session).

Introduction

In this exercise we will analyse the activities of a malware called Mobidash (SHA 256: b41d8296242c6395eee9e5aa7b2c626a208a7acce979bc37f6cb7ec5e777665a). The goal is to observe its activities at operating system level. The difficulty is that this malware will not trigger at first run.

For this exercise, we need a custom rom that includes AndroBlare. AndroBlare traces all the information flows between processes, files and sockets. The kernel module (Blare), ported to android (AndroBlare), monitors these flows. This is why you need a pre-installed Nexus that already contains AndroBlare.

Mobidash is an adware discovered in January 2015 that covers its malicious activities with a benign app: a card game. When the malware triggers itself, it displays unwanted ads each time the user unlocks the screen. To evade dynamic analysis tools during an analysis that would occur after the installation, the malware waits several days or even weeks before executing its malicious code. The user would also not suspect a fresh installed application several days later.

Let’s go !

Step 1: connect your device

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 on your phone under 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.

Step 2: connect the phone to internet

Connect your smartphone to the internet using the provided access point. This is mandatory for such a malware that will download ads from remote servers.

Step 3: clean your Nexus

Before executing a malware, we need to clean the smartphone of any artifact that remains from a previous experiment.

1st case: command oriented restoration.

2nd case: manual oriented restauration

Deploy the backup for flashing the phone

Step 4: install MobiDash and configure Androblare

The first thing to do is to install the malware. In our case this is ModiDash.

adb install com.cardgame.durak.apk

DO NOT LAUNCH THE MALWARE YET !

If the malware is successfully installed you should have a new application called Durak Pro but we need to prepare Blare to audit the malware.

You need to apply some Androblare configuration after you installed it. An automated script finalize.sh apply thoses settings.

adb install BlareLogger.apk
adb shell mount -o remount,rw /system
./finalize.sh

Now you need to tell AndroBlare which file you want monitor:

adb shell setinfo /data/app/com.cardgame.durak-1.apk 1
adb reboot

After the reboot, on the smartphone, launch the BlareLogger application and hit the “Start Log” button. Logs are created on /data/data/org.blareids.logger/logs/log_name.blarelog. Check that logs appear in the Blare folder:

adb shell ls /data/data/org.blareids.logger/logs

Step 5: launch the malware

Launch the Durak Pro application. You should see a card game. You can play with it, it’s fully functional ! (Not on the Nexus S)

Blare is auditing the malware and propagating the observed flows. It produces log. You can see the log on the phone:

adb shell cat /data/data/org.blareids.logger/logs/*.log

You should see some policy violation rules:

<6>[   74.757664] [BLARE_POLICY_VIOLATION] process .cardgame.durak:.cardgame.durak 787 > file /data/data/com.cardgame.durak/shared_prefs/com.cardgame.durak_preferences.xml 57598 > itag[1]

Such a rule says that the process cardgame.durak with PID 787 has produced a write flow in the file /data/…/com.cardgame.durak_preferences.xml with the tag number 1.

Step 6: extraction, conversion, visualization

In order to extract it we use a python script that automate this extraction.

mkdir extracted
python logExtractor.py extracted
ls -l extracted

Now we need to convert the blarelog file to a graph in order to visualize it. For this tutorial we will use .dot files as a lot of tools exist to visualize such a format. To do so, you need to use the logToDot.sh script that converts the Blare log to a .dot file.

./logToDot.sh extracted/extract.log

Open the resulting dot with zgrviewer.

zgrviewer -f extracted/extract.tmp.dot

You should see the graph of all processes, files and sockets that the application has contaminated. This graph is unusable, because there are a lot of nodes in this graph. We propose to filter the nodes that are not useful for this tutorial (mainly the ones that contaminated the android system i.e. the system_server process). A quick and dirty solution is given below:

# filter nodes and edges from the log based on their name
cat extracted/<log_name>.blarelog | grep -v "[C\|c]ache" | grep -v "[S\|s]ystem_server" > extracted/extract.blarelog
./logToDot.sh extracted/extract.blarelog cardgame.durak

Now, convert again the log file to a dot graph with logToDot.sh and visualize the resulting graph.
Focus on the red ellipse. This is the process that has been launched from our tagged apk (cardgame.durak). Explore the graph and try to understand what it has done:

You should not observe any socket connection: the malware has not been triggered and is waiting silently. We will know trigger it.

Step 7: trigger the malicious behavior

You may have observed one important things: the access/creation of the file /data/data/com.cardgame.durak/shared_prefs/com.cardgame.durak_preferences.xml com.cardgame.durak_preferences.xml. This XML is the malware configuration file. Maybe it has something cool in it ?

We are going to see what’s inside. Pull out this file from the phone:

adb pull /data/data/com.cardgame.durak/shared_prefs/com.cardgame.durak_preferences.xml com.cardgame.durak_preferences.xml
nano com.cardgame.durak_preferences.xml

The most important line is at the end long name=“mobi.dash.extras.overapp.AdsOverappWaiter.waitStartTime” value=“33316051155” /> with a big number as value. In fact MobiDash delays its execution: it decrements this number until it reachs 0 and then trigger its execution.
We are going to force its triggering by replacing the number by a 0 (use gedit, nano, vi...)

Change:

long name="mobi.dash.extras.overapp.AdsOverappWaiter.waitStartTime" value="33316051155" />

Into:

long name="mobi.dash.extras.overapp.AdsOverappWaiter.waitStartTime" value="0" />

After that we need to push this modified file to the phone and reboot it immediately in order to prevent the modification of this file by the malware.

adb shell "/system/bin/busybox rm -rf /data/data/org.blareids.logger/logs/*"
adb push com.cardgame.durak_preferences.xml /data/data/com.cardgame.durak/shared_prefs/com.cardgame.durak_preferences.xml && adb reboot

Once the phone has rebooted unlock it and wait BlareLogger screen. Return Home, lock the phone and unlock it. What’s happened? Lot of undesired Ads.

Step 8: visualization

Exract logs again and convert it to a .dot file. Once finished open the .dot with zgrviewer:

mkdir extracted2
python logExtractor.py extracted2
cat extracted2/<log_name>.blarelog | grep -v "[C\|c]ache" | grep -v "[S\|s]ystem_server" > extracted2/extract.blarelog
./logToDot.sh extracted2/extract.blarelog cardgame.durak

Once finished on zgrviewer open it File > Open > dot…
Focus on the red ellipse and explore the neighbors nodes. You can see the creation of sockets, access to android.browser and many more !

Conclusion

You have done your first dynamic analysis of an adware. You can see the same result with a better look and feel of the graph on the Kharon project. Check:

http://kharon.gforge.inria.fr/dataset/malware_MobiDash.html

Wow ! :thumbsup:

Exercise 2: Preparing an antidote for a ransomware

Prerequisite

For this exercise, you should have one of the following smartphones:

Import the provided Virtualbox image Android-Malware.ova. User login is “user”. Root password is “azerty”.

Connect your phone and attach the phone to the virtual image (4th button on the bottom right). If your phone does not appear for virtualbox, it is because you are not in the vboxusers group. Thus, add yourself (sudo adduser login vboxusers) and reconnect your X session).

Introduction

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 !

Let’s go !

Step 1: connect your device

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.

Step 2: disconnect the phone from the internet

For this exercise we do not need an internet connection. Disconnect your smartphone from the internet.

Step 3: take a photo of yourself

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.

Step 4: execute the SimpLocker malware

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 !!!*

Step 5: reverse a simple .apk

We propose to use BytecodeViewer which enables to open and decompile an Android application. It proposes several decompilers and basic search capabilities.

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.

Step 6: reverse the SimpleLocker malware .apk

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 !

Step 7: convert, edit the classes and repackage

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 and change the encrypt() to a call to decrypt():

  jbe.sh
  #&nbsp;Edit the file and save it

Instructions:

Repackage the classes in a jar file:

# In the malware-source-jar folder
&nbsp; 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 :smile:

Step 8: deploy the antidote

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 !

Conclusion

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

:thumbsup:

Exercise 3: Capturing the data leaked by a Spyware

Prefer exercise 1 and 2 to this one. But if no smartphone is available for exercise 1 or if you have already finished the previous exercises, go to this one !

Prerequisite

For this exercise, you should have one of the same smartphones of exercise 2.

Introduction

The goal of this exercise is to study the malware SaveMe (SHA 256: 919a015245f045a8da7652cefac26e71808b22635c6f3217fd1f0debd61d4330). You can find an overview of this malware on its kharon page. This spyware steals the personal data of the users and upload them on a website.

In the following we propose to capture the stolen data without modifying the malware. Instead, we will redirect the network traffic to a server that will reveal the stolen data.

Let’s go !

Step 1: reverse the malware to learn where data go

As previously done in exercise 2, open the malware with BytecodeViewer. Have a look at the following classes in order to find the server name where the malware leaks the data:

You’ll deduce that the data are sent to topemarketing.com with different php files.

Step 2: capture the network traffic

In order to analyze the leak of data, we should redirect the traffic to a controled web server. We could try to route the network via the USB cable but it requires to have a rooted smartphone.

Thus, in the following, we propose to use your laptop as a Wifi Access Point (not the virtualmachine but your real laptop). All the required steps are given below.

On your real Linux computer do:

Install dnsmask (for distributing an IP to your smartphone) and hostapd (for creating an access point).

sudo apt-get install dnsmasq hostapd

Configure dnsmasq in /etc/dnsmasq.d/dnsmasq.conf with the following:

interface=wlan0
dhcp-range=10.0.0.2,10.0.0.10,255.255.255.0,12h
address=/topemarketing.com/10.0.0.1

You see in this configuration file that the domain used by the malware will be routed to 10.0.0.1.
Additionally, reroute the domain name topemarketing.com by putting in your /etc/hosts file:

10.0.0.1       topemarketing.com

Start dnsmasq:

sudo /etc/init.d/dnsmasq start

Now create the file hostapd.conf and customize your SSID:

# interface wlan du Wi-Fi
interface=wlan0
# nl80211 avec tous les drivers Linux mac80211 
driver=nl80211
# Nom du spot Wi-Fi
ssid=YOURNAMEDAP
# mode Wi-Fi (a = IEEE 802.11a, b = IEEE 802.11b, g = IEEE 802.11g)
hw_mode=g
# canal de fréquence Wi-Fi (1-14)
channel=6
# Wi-Fi ouvert, pas d'authentification !
auth_algs=1
# Beacon interval in kus (1.024 ms)
beacon_int=100
# DTIM (delivery trafic information message) 
dtim_period=2
# Maximum number of stations allowed in station table
max_num_sta=255
# RTS/CTS threshold; 2347 = disabled (default)
rts_threshold=2347
# Fragmentation threshold; 2346 = disabled (default)
fragm_threshold=2346

Modify the /etc/network/interfaces to setup a static IP:

auto wlan0
iface wlan0 inet static
address 10.0.0.1
netmask 255.255.255.0

Disable network-manager and remount the network interface:

sudo service network-manager stop
sudo ifdown wlan0
sudo ifup wlan0

Finally, launch hostapd to create the AP:

sudo hostapd hostapd.conf 
Configuration file: hostapd.conf
Using interface wlan0 with hwaddr 00:22:43:26:3b:c0 and ssid 'YOURNAMEDAP'

Check your smartphone. You should now be able to connect it to the AP. When the smartphone connects, hostapd says:

wlan0: STA 24:da:9b:05:b6:xx IEEE 802.11: authenticated
wlan0: STA 24:da:9b:05:b6:xx IEEE 802.11: associated (aid 1)
AP-STA-CONNECTED 24:da:9b:05:b6:xx
wlan0: STA 24:da:9b:05:b6:xx RADIUS: starting accounting session 57756E35-00000000

You are now ready to listen to the malware !

Step 3: cheat the malware

The last step consists in building a fake web server to capture the data leaked by the malware. This can be easily done using the following sript:

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
import threading
from cgi import parse_header, parse_multipart
from sys import version as python_version
if python_version.startswith('3'):
  from urllib.parse import parse_qs
  from http.server import BaseHTTPRequestHandler
else:
  from urlparse import parse_qs
  from BaseHTTPServer import BaseHTTPRequestHandler
  
class Handler(BaseHTTPRequestHandler):
  def do_GET(self):
      self.send_response(200)
      self.end_headers()
      message =  threading.currentThread().getName()
      self.wfile.write(message)
      self.wfile.write('\n')
      return

  def do_POST(self):
      self.send_response(200)
      self.end_headers()
      ctype, pdict = parse_header(self.headers['content-type'])
      postvars = {}
      if ctype == 'multipart/form-data':
          postvars = parse_multipart(self.rfile, pdict)
      elif ctype == 'application/x-www-form-urlencoded':
          length = int(self.headers['content-length'])
          postvars = parse_qs(
                  self.rfile.read(length), 
                  keep_blank_values=1)
      print(postvars)
      return postvars

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
  """Handle requests in a separate thread."""

if __name__ == '__main__':
  server = ThreadedHTTPServer(('10.0.0.1', 80), Handler)
  print 'Starting server, use <Ctrl-C> to stop'
  server.serve_forever()

Launch this multi-threaded web server:

python exo3-webserver.py

On the smartphone, open a browser. enter the url http://topemarketing.com/blabla. You should see logs about a GET request appearing in the console.

Finally, launch the malware and play with it. You should capture the leaked data.

:thumbsup:

Conclusion

A lot of spyware use basic communication request to leak the data to a server. More sophisticated one use HTTPS, Tor proxys or Cloud storage. With such ones, using network sniffing is no more reliable and solutions getting the information from the malware itself is easier.

About us and this tutorial

Contributors


J.-F. Lalande is associate professor at INSA Centre Val de Loire. He is the only serious guy of the team. He proposes this tutorial as a result of 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 beta tested this tutorial and supports the participants. Find him in the room !


Nicolas Kiss is an engineer that achieved most of the reverse engineering efforts of the two studied malware. He’s the hacker of the team !


Korlan Colas is a master student at INSA Centre Val de Loire. He woke up very early (before noon) to write good parts of this tutorial. After testing testing and testing again he wrote the solution you’ll have at the end !


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 !

Software

Papers