SlideShare a Scribd company logo
Practice of
Android Reverse Engineering



Jim Huang ( 黃敬群 )
Developer, 0xlab
                         jserv@0xlab.org

                    July 23, 2011 / HITcon
Rights to copy
                                                                    © Copyright 2011 0xlab
                                                                           http://0xlab.org/
                                                                            contact@0xlab.org
Attribution – ShareAlike 3.0
You are free                                                  Corrections, suggestions, contributions and
                                                                               translations are welcome!
   to copy, distribute, display, and perform the work
   to make derivative works                                                  Latest update:July 23, 2011
   to make commercial use of the work
Under the following conditions
      Attribution. You must give the original author credit.
      Share Alike. If you alter, transform, or build upon this work, you may distribute the
      resulting work only under a license identical to this one.
   For any reuse or distribution, you must make clear to others the license terms of this
   work.
   Any of these conditions can be waived if you get permission from the copyright holder.
Your fair use and other rights are in no way affected by the above.
License text: http://creativecommons.org/licenses/by-sa/3.0/legalcode
Myself   was a Kaffe Developer
           ●   Threaded Interpreter, JIT, AWT for
               embedded system, robustness

         was a GCJ (Java Frontend for GCC)
         and GNU Classpath Developer
         is an AOSP (Android Open Source
         Project) contributror
           ●   30+ patches are merged officially
           ●   bionic libc, ARM optimizations
Not Only
   for     (1) Sometimes, it takes __time__
Cracking   to obtain source code than
           expected. → Taiwanese ODM
           (2) Post-optimizations over
           existing Android applications
           (3) “Borrow" something good
           to produce "goods"
Background Knowledge
                           (and Thank you!)
• The Code Injection and Data Protection of Android,
  Thinker Li @HITcon2011
• Reversing Android Malware,
  Mahmud ab Rahman @HITcon2011



• My focus would be the practice.
  – Hack Android applications for Beginners
Agenda   (1) Development Flow
         (2) Reverse Practice
         (3) Real world tasks
Android Application Development Flow
                          aapt
                            Create
Manifest
Manifest                   packaged                      Packaged resource file
                                                         Packaged resource file
                           resource
                                             R
                                             R
Resources
Resources                 javac             dx
                                            Dalvik
                          compile                               classes.dex
                                                                classes.dex
  Assets
  Assets                                   bytecode

                                                        apkbuilder -u
Source code
Source code
                                                                Create unsigned apk
                                    unsigned apk
                                    unsigned apk
              Libraries
              Libraries
                                                                        adb
   Key
   Key                                                                  Publish or
                               Sign apk            signed apk
                                                   signed apk             Test        7

                             jarsigner
APK content

$ unzip Angry+Birds.apk
Archive: Angry+Birds.apk
...
  inflating: AndroidManifest.xml
 extracting: resources.arsc
 extracting: res/drawable-hdpi/icon.png
 extracting: res/drawable-ldpi/icon.png
 extracting: res/drawable-mdpi/icon.png
  inflating: classes.dex Dalvik DEX
  inflating: lib/armeabi/libangrybirds.so JNI
  inflating: lib/armeabi-v7a/libangrybirds.so
  inflating: META-INF/MANIFEST.MF
  inflating: META-INF/CERT.SF
                                   manifest +
  inflating: META-INF/CERT.RSA      signature
APK content

    $ unzip Angry+Birds.apk
    Archive: Angry+Birds.apk
    ...
       inflating: AndroidManifest.xml
Name: extracting: resources.arsc
      classes.dex
      extracting: res/drawable-hdpi/icon.png
SHA1-Digest: I9Vne//i/5Wyzs5HhBVu9dIoHDY=
      extracting: res/drawable-ldpi/icon.png
Name: lib/armeabi/libangrybirds.so
      extracting: res/drawable-mdpi/icon.png
SHA1-Digest: pSdb9FYauyfjDUxM8L6JDmQk4qQ=
       inflating: classes.dex
       inflating: lib/armeabi/libangrybirds.so
       inflating: lib/armeabi-v7a/libangrybirds.so
       inflating: META-INF/MANIFEST.MF
       inflating: META-INF/CERT.SF
       inflating: META-INF/CERT.RSA
AndroidManifest

    $ unzip Angry+Birds.apk
    Archive: Angry+Birds.apk
    ...
    ...
      inflating: AndroidManifest.xml
     extracting: resources.arsc
     extracting: res/drawable-hdpi/icon.png
$ file AndroidManifest.xml
     extracting: res/drawable-ldpi/icon.png
AndroidManifest.xml: DBase 3 data file (2328 records)
     extracting: res/drawable-mdpi/icon.png
$ apktool d ../AngryBirds/Angry+Birds.apk
      inflating: classes.dex
I: Baksmaling...
I: Loading resource lib/armeabi/libangrybirds.so
      inflating: table...
...
      inflating: lib/armeabi-v7a/libangrybirds.so
I: Decoding file-resources...
      inflating: META-INF/MANIFEST.MF
I: Decoding values*/* XMLs...
I: Done.
      inflating: META-INF/CERT.SF
I: Copying assets and libs...
$ fileinflating: META-INF/CERT.RSA
       Angry+Birds/AndroidManifest.xml
Angry+Birds/AndroidManifest.xml: XML   document text
Before performing reverse
engineering, let's observe how
    Android system works
In this presentation,
                                Android platform 2.3.3 is selected.




                              Widget

How can Launcher find widgets/activities and invoke them?



                              Android Launcher
When installing FrozenBubble.apk

            $ adb logcat -c
            $ adb install -r FrozenBubble.apk
            1222 KB/s (499568 bytes in 0.399s)
            pkg: /data/local/tmp/FrozenBubble.apk
            Success
            $ adb logcat
            D/AndroidRuntime( 329):
            D/AndroidRuntime( 329): >>>>>>
            AndroidRuntime START
            com.android.internal.os.RuntimeInit <<<<<<
            D/PackageParser(   60): Scanning
            package: /data/app/vmdl10628918.tmp
            ...

Download the whole package: http://0xlab.org/~jserv/dex-dis-example.tar.bz2
APK Installation Procedure
D/AndroidRuntime( 329):
D/AndroidRuntime( 329): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
D/PackageParser( 60): Scanning package: /data/app/vmdl10628918.tmp
I/PackageManager( 60): Removing non-system package:org.jfedor.frozenbubble
I/ActivityManager( 60): Force stopping package org.jfedor.frozenbubble uid=10034
D/PackageManager( 60): Scanning package org.jfedor.frozenbubble
I/PackageManager( 60): Package org.jfedor.frozenbubble codePath changed from
/data/app/org.jfedor.frozenbubble-2.apk to /data/app/org.jfedor.frozenbubble-1.apk; Retaining data and
using new
I/PackageManager( 60): Unpacking native libraries for /data/app/org.jfedor.frozenbubble-1.apk
D/installd( 34): DexInv: --- BEGIN '/data/app/org.jfedor.frozenbubble-1.apk' ---
D/dalvikvm( 340): DexOpt: load 54ms, verify+opt 137ms
D/installd( 34): DexInv: --- END '/data/app/org.jfedor.frozenbubble-1.apk' (success) ---
W/PackageManager( 60): Code path for pkg : org.jfedor.frozenbubble changing from
/data/app/org.jfedor.frozenbubble-2.apk to /data/app/org.jfedor.frozenbubble-1.apk
W/PackageManager( 60): Resource path for pkg : org.jfedor.frozenbubble changing from
/data/app/org.jfedor.frozenbubble-2.apk to /data/app/org.jfedor.frozenbubble-1.apk
D/PackageManager( 60): Activities: org.jfedor.frozenbubble.FrozenBubble
I/ActivityManager( 60): Force stopping package org.jfedor.frozenbubble uid=10034
I/installd( 34): move /data/dalvik-cache/data@app@org.jfedor.frozenbubble-1.apk@classes.dex ->
/data/dalvik-cache/data@app@org.jfedor.frozenbubble-1.apk@classes.dex
D/PackageManager( 60): New package installed in /data/app/org.jfedor.frozenbubble-1.apk
I/ActivityManager( 60): Force stopping package org.jfedor.frozenbubble uid=10034
I/installd( 34): unlink /data/dalvik-cache/data@app@org.jfedor.frozenbubble-2.apk@classes.dex
D/AndroidRuntime( 329): Shutting down VM
D/jdwp ( 329): adbd disconnected
APK Installation Procedure
D/AndroidRuntime( 329):
                                                Android Runtime performs init
                                               Android Runtime performs init
D/AndroidRuntime( 329): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
D/PackageParser( 60): Scanning package: /data/app/vmdl10628918.tmp
                                        Package Manager detects APK and installs
                                        Package Manager detects APK and
I/PackageManager( 60): Removing non-system package:org.jfedor.frozenbubble installs
I/ActivityManager( 60): Force stopping package org.jfedor.frozenbubble uid=10034
D/PackageManager( 60): Scanning package org.jfedor.frozenbubble
I/PackageManager( 60): Package org.jfedor.frozenbubble codePath changed from
/data/app/org.jfedor.frozenbubble-2.apk to /data/app/org.jfedor.frozenbubble-1.apk; Retaining data and
using new
I/PackageManager( 60): Unpacking native libraries for /data/app/org.jfedor.frozenbubble-1.apk
D/installd( 34): DexInv: --- BEGIN '/data/app/org.jfedor.frozenbubble-1.apk' ---
D/dalvikvm( 340): DexOpt: load 54ms, verify+opt 137ms
                                                                 DexOpt
                                                                 DexOpt
D/installd( 34): DexInv: --- END '/data/app/org.jfedor.frozenbubble-1.apk' (success) ---
                                     (verify and optimize all of the classes in the DEX file)
                                    (verify and optimize all of the classes in the DEX file)
W/PackageManager( 60): Code path for pkg : org.jfedor.frozenbubble changing from
/data/app/org.jfedor.frozenbubble-2.apk to /data/app/org.jfedor.frozenbubble-1.apk
W/PackageManager( 60): Resource path for pkg : org.jfedor.frozenbubble changing from
/data/app/org.jfedor.frozenbubble-2.apk to /data/app/org.jfedor.frozenbubble-1.apk
D/PackageManager( 60): Activities: org.jfedor.frozenbubble.FrozenBubble
I/ActivityManager( 60): Force stopping package org.jfedor.frozenbubble uid=10034
             Activities: org.jfedor.frozenbubble.FrozenBubble
I/installd( 34): move /data/dalvik-cache/data@app@org.jfedor.frozenbubble-1.apk@classes.dex ->
/data/dalvik-cache/data@app@org.jfedor.frozenbubble-1.apk@classes.dex
D/PackageManager( 60): New package installed in /data/app/org.jfedor.frozenbubble-1.apk
I/ActivityManager( 60): Force stopping package org.jfedor.frozenbubble uid=10034
I/installd( 34): unlink /data/dalvik-cache/data@app@org.jfedor.frozenbubble-2.apk@classes.dex
D/AndroidRuntime( 329): Shutting down VM
D/jdwp ( 329): adbd disconnected
I/ActivityManager( 60): Start proc org.jfedor.frozenbubble for activity
   org.jfedor.frozenbubble/.FrozenBubble: pid=356 uid=10034 gids={}
I/ActivityManager( 60): Displayed org.jfedor.frozenbubble/.FrozenBubble: +2s899ms
Execute FrozenBubble
                from Android Launcher
$ adb shell am start 
  -e debug true 
  -a android.intent.action.MAIN 
  -c android.intent.category.LAUNCHER 
  -n org.jfedor.frozenbubble/.FrozenBubble
Starting: Intent
{ act=android.intent.action.MAIN
cat=[android.intent.category.LAUNCHER]
cmp=org.jfedor.frozenbubble/.FrozenBubb
le (has extras)
Practice of Android Reverse Engineering
Execute FrozenBubble

$ adb shell dumpsys | grep -i bubble

name=org.jfedor.frozenbubble/org.jfedor.frozenbubble.Froz
enBubble
    Intent { act=android.intent.action.PACKAGE_ADDED
dat=package:org.jfedor.frozenbubble flg=0x10000000 (has
extras) }
  * TaskRecord{40744ad0 #4 A org.jfedor.frozenbubble}
    affinity=org.jfedor.frozenbubble
    intent={act=android.intent.action.MAIN
cat=[android.intent.category.LAUNCHER] flg=0x10200000
cmp=org.jfedor.frozenbubble/.FrozenBubble}
    realActivity=org.jfedor.frozenbubble/.FrozenBubble
...
ActivityManager

•   Start new Activities and Services
•   Fetch Content Providers
•   Intent broadcasting
•   OOM adj. Maintenance
•   ANR (Application Not Responding)
•   Permissions
•   Task management
•   Lifecycle management
ActivityManager

• starting new app from Launcher:
   – onClick(Launcher)
  – startActivity
  – <Binder>
  – ActivityManagerService
  – startViaZygote(Process.java)
  – <Socket>
  – Zygote
Use JDB to Trace Android Application
  #!/bin/bash
  adb wait-for-device
  adb shell am start 
        -e debug true 
        -a android.intent.action.MAIN 
        -c android.intent.category.LAUNCHER 
        -n org.jfedor.frozenbubble/.FrozenBubble &
  debug_port=$(adb jdwp | tail -1);
  adb forward tcp:29882 jdwp:$debug_port &
  jdb -J-Duser.home=. -connect 
  com.sun.jdi.SocketAttach:hostname=localhost,port=29882 &


In APK manifest, debuggable=”true"

 JDWP: Java Debug Wire Protocol
JDB usage
 > threads
 Group system:
   (java.lang.Thread)0xc14050e388  <6> Compiler         cond. Waiting
   (java.lang.Thread)0xc14050e218  <4> Signal Catcher   cond. waiting
   (java.lang.Thread)0xc14050e170  <3> GC               cond. waiting
   (java.lang.Thread)0xc14050e0b8  <2> HeapWorker       cond. waiting
 Group main:
   (java.lang.Thread)0xc14001f1a8  <1> main             running
   (org.jfedor.frozenbubble.GameView$GameThread)0xc14051e300
                                   <11> Thread­10       running
   (java.lang.Thread)0xc14050f670  <10> SoundPool       running
   (java.lang.Thread)0xc14050f568  <9> SoundPoolThread  running
   (java.lang.Thread)0xc140511db8  <8> Binder Thread #2 running
   (java.lang.Thread)0xc140510118  <7> Binder Thread #1 running




> suspend 0xc14051e300
> thread 0xc14051e300
<11> Thread-10[1] where
 [1] android.view.SurfaceView$3.internalLockCanvas (SurfaceView.java:789)
 [2] android.view.SurfaceView$3.lockCanvas (SurfaceView.java:745)
 [3] org.jfedor.frozenbubble.GameView$GameThread.run (GameView.java:415)
DDMS = Dalvik Debug Monitor Server
(JDB)
> thread 0xc14051e300
<11> Thread-10[1] where
 [1] android.view.SurfaceView$3.internalLockCanvas (SurfaceView.java:789)
 [2] android.view.SurfaceView$3.lockCanvas (SurfaceView.java:745)
 [3] org.jfedor.frozenbubble.GameView$GameThread.run (GameView.java:415)
hierarchyviewer: Traverse widgets
Figure out the association between APK resources and runtime behavior.
Decompile / Disassembly
• apktool: http://code.google.com/p/android-apktool/
• dex2jar: http://code.google.com/p/dex2jar/
• Jad / jd-gui: http://java.decompiler.free.fr/
smali :   assembler/disassembler for Android's dex format


    •   http://code.google.com/p/smali/
    •   smali: The assembler
    •   baksmali: The disassembler
    •   Fully integrated in apktool



$ apktool d ../AngryBirds/Angry+Birds.apk 
I: Baksmaling...
I: Loading resource table...
...
I: Decoding file­resources...
I: Decoding values*/* XMLs...
I: Done.
I: Copying assets and libs...
Java bytecode vs. Dalvik bytecode
  public int method( int i1, int i2 ) {
                                                  (stack vs. register)
    int i3 = i1 * i2;
    return i3 * 2;
  }
.var 0 is “this”                          this: v1 (Ltest2;)
.var 1 is argument #1                     parameter[0] : v2 (I)
.var 2 is argument #2                     parameter[1] : v3 (I)

method public method(II)I
    iload_1
    iload_2                               .method public method(II)I
    imul                                      mul­int v0,v2,v3
    istore_3                                  mul­int/lit­8 v0,v0,2
    iload_3                                   return v0
    iconst_2                              .end method
    imul
    ireturn
.end method
                               Java                               Dalvik
Dalvik Register frames

• Dalvik registers behave more like local variables
• Each method has a fresh set of registers.
• Invoked methods don't affect the registers of
  invoking methods.
Practice: Level Up




Change initial game level
Change initial game level
     From 1 to 5 !
     From 1 to 5 !
Disassembly
$ mkdir workspace smali­src
$ cd workspace
$ unzip ../FrozenBubble­orig.apk
Archive:  ../FrozenBubble­orig.apk
  inflating: META­INF/MANIFEST.MF
  inflating: META­INF/CERT.SF
  inflating: META­INF/CERT.RSA
  inflating: AndroidManifest.xml
...
extracting: resources.arsc
$ bin/baksmali ­o smali­src workspace/classes.dex
Output
              org.jfedor.frozenbubble/.FrozenBubble
smali­src$ find
./org/jfedor/frozenbubble/FrozenBubble.smali
./org/jfedor/frozenbubble/R$id.smali
./org/jfedor/frozenbubble/GameView.smali
./org/jfedor/frozenbubble/SoundManager.smali
./org/jfedor/frozenbubble/LaunchBubbleSprite.smali
./org/jfedor/frozenbubble/Compressor.smali
./org/jfedor/frozenbubble/R$attr.smali
./org/jfedor/frozenbubble/BubbleFont.smali
./org/jfedor/frozenbubble/PenguinSprite.smali
./org/jfedor/frozenbubble/GameView$GameThread.smali
./org/jfedor/frozenbubble/LevelManager.smali
./org/jfedor/frozenbubble/BubbleSprite.smali
./org/jfedor/frozenbubble/R$string.smali
...
                                 Generated
                              from resources
Output
 smali­src$ grep ".method" 
 org/jfedor/frozenbubble/LevelManager.smali
 .method public constructor <init>([BI)V
 .method private getLevel(Ljava/lang/String;)[[B
 .method public getCurrentLevel()[[B
 .method public getLevelIndex()I
 .method public goToFirstLevel()V
 .method public goToNextLevel()V
 .method public restoreState(Landroid/os/Bundle;)V
 .method public saveState(Landroid/os/Bundle;)V




List the methods implemented in class LevelManager
Dalvik::Types
        .method private getLevel(Ljava/lang/String;)[[B
           → private byte[][] getLevel(String data)

        .method public goToNextLevel()V
           → public void goToNextLevel();
• Base types
  – I : int / J : long / S : short
   – Z : boolean
   – D : double / F : float
   – C : char
   – V : void (when return value)
• Classes: Ljava/lang/Object;
• Arrays: [I, [Ljava/lang/Object;, [[I
Dalvik::Methods

• Rich meta-information is assigned to Dalvik
  methods
• Method meta-information:
  – Signature
  – Try-catch information
  – Annotations
  – Number of registers used
  – Debug information
     • Line numbers
     • Local variable lifetime
Output
   smali­src$ grep ­r goToFirstLevel *
   org/jfedor/frozenbubble/GameView$GameThread.smali: 
   invoke­virtual {v2},
     Lorg/jfedor/frozenbubble/LevelManager;­>goToFirstLevel()V
   org/jfedor/frozenbubble/LevelManager.smali:
   .method public goToFirstLevel()V




That the first argument of the method invocation is “this” as
this is a non-static method.
GameView$GameThread.smali
 .method public newGame()V
         . . .
     move­object/from16 v0, p0

     iget­object v0, v0, 
 Lorg/jfedor/frozenbubble/GameView$GameThread;­
 >mLevelManager:Lorg/jfedor/frozenbubble/LevelManager;


     move­object v2, v0

     invoke­virtual {v2}, 
 Lorg/jfedor/frozenbubble/LevelManager;­>goToFirstLevel ()V



Equals to Java:
objLevelManager.goToFirstLevel();
LevelManager.smali
   .method public goToFirstLevel()V
       .registers 2     Equals to Java:
                                      public class LevelManager {
                                          ...
       .prologue                          public void goToFirstLevel() {
       .line 175                               currentLevel = 0;
                                          }
       const/4 v0, 0x0                    ...
                                      }

       iput v0, p0,
    Lorg/jfedor/frozenbubble/LevelManager;­>currentLevel:I
                                                   Equals to Java:
       .line 176                                   currentLevel = 0;
       return­void
   .end method

Constants to registers: const/4, const/16, const, const/high16,
const-wide/16, const-wide/32, const-wide, const-wide/high16,
const-string, const-class
Modify constructor of
                                 GameView::GameThread()
• Look up output in GameView$GameThread.smali
 .class Lorg/jfedor/frozenbubble/GameView$GameThread;
 .super Ljava/lang/Thread;
 .annotation system Ldalvik/annotation/InnerClass;
   accessFlags = 0x0
   name = "GameThread"
 .end annotation


 # direct methods
 .method public constructor
 <init>(Lorg/jfedor/frozenbubble/GameView;Landroid/view/SurfaceHol
 der;[BI)V
Modify constructor of
                                GameView::GameThread()
• Look up output in GameView$GameThread.smali
 # direct methods
 .method public constructor
 <init>(Lorg/jfedor/frozenbubble/GameView;Landroid/view/SurfaceHol
 der;[BI)V

   Equals to Java:
   class GameView ??? {
       class GameThread extends Thread {
           public GameThread(SurfaceHolder s,
                             byte[] b,
                             int I) {
GameView.smali

• Look up output in GameView.smali
  .class Lorg/jfedor/frozenbubble/GameView;
  .super Landroid/view/SurfaceView;
  # interfaces
  .implements Landroid/view/SurfaceHolder$Callback;
• Look up output in GameView$GameThread.smali
.class Lorg/jfedor/frozenbubble/GameView$GameThread;
.super Ljava/lang/Thread;


   Equals to Java:
   class GameView extends SurfaceView
                  implements SurfaceHolder.Callback {
     class GameThread extends Thread {
Implementation of GameView::GameThread()

• Check GameView::public GameThread(SurfaceHolder s,   byte[] b, int I)
  const­string v3, "level"
  const/4 v4, 0x0
  move­object/from16 v0, v25
  move­object v1, v3
  move v2, v4
  invoke­interface {v0, v1, v2}, 
  Landroid/content/SharedPreferences;­
  >getInt(Ljava/lang/String;I)I
  move­result p4           Invoke constructor of LevelManager
  new­instance v3, Lorg/jfedor/frozenbubble/LevelManager;
  move­object v0, v3
  move­object/from16 v1, v22
  move/from16 v2, p4 invoke­direct {v0, v1, v2}, 
  Lorg/jfedor/frozenbubble/LevelManager;­><init>([BI)V
Register v1 related code
const­string v3, "level"
const/4 v4, 0x0
move­object/from16 v0, v25
move­object v1, v3
move v2, v4
invoke­interface {v0, v1, v2}, 
Landroid/content/SharedPreferences;­
>getInt(Ljava/lang/String;I)I
move­result p4
new­instance v3, 
Lorg/jfedor/frozenbubble/LevelManager;
move­object v0, v3
move­object/from16 v1, v22
move/from16 v2, p4
invoke­direct {v0, v1, v2}, 
Lorg/jfedor/frozenbubble/LevelManager;­><init>([BI)V
Register v2 related code
const­string v3, "level"
const/4 v4, 0x0
move­object/from16 v0, v25
move­object v1, v3       “0x0” is passed to LevelManager's
move v2, v4              constructor as parameter
invoke­interface {v0, v1, v2}, 
Landroid/content/SharedPreferences;­
>getInt(Ljava/lang/String;I)I
move­result p4
new­instance v3, 
Lorg/jfedor/frozenbubble/LevelManager;
move­object v0, v3
move­object/from16 v1, v22
move/from16 v2, p4
invoke­direct {v0, v1, v2}, 
Lorg/jfedor/frozenbubble/LevelManager;­><init>([BI)V
Recall the grep results
smali­src$ grep ".method" 
org/jfedor/frozenbubble/LevelManager.smali
.method public constructor <init>([BI)V
.method private getLevel(Ljava/lang/String;)[[B
.method public getCurrentLevel()[[B
.method public getLevelIndex()I
.method public goToFirstLevel()V
.method public goToNextLevel()V
.method public restoreState(Landroid/os/Bundle;)V
.method public saveState(Landroid/os/Bundle;)V

Equals to Java:
public class LevelManager {
    ...
    public LevelManager(byte[] b, int i)
Register v2 related code
const­string v3, "level"
                   p4 reserve the result after method invocation.
const/4 v4, 0x0
move­object/from16 v0, v25
move­object v1, v3
move v2, v4
invoke­interface {v0, v1, v2}, 
Landroid/content/SharedPreferences;­
>getInt(Ljava/lang/String;I)I
move­result p4
new­instance v3,    Therefore, v2 has return value of method
Lorg/jfedor/frozenbubble/LevelManager;
                    android.content.Shared.Preference.getInt()
move­object v0, v3
move­object/from16 v1, v22
move/from16 v2, p4
invoke­direct {v0, v1, v2}, 
Lorg/jfedor/frozenbubble/LevelManager;­><init>([BI)V
Modify!!!
• Check GameView::public GameThread(SurfaceHolder s, byte[] b, int I)
  const­string v3, "level"                  Change value from 0x0 to 0x4
  const/4 v4, 0x0
  move­object/from16 v0, v25
  move­object v1, v3
  move v2, v4                                                  Remove!
  invoke­interface {v0, v1, v2}, 
  Landroid/content/SharedPreferences;­>getInt(Ljava/lang/String;I)I
  move­result p4
  new­instance v3, Lorg/jfedor/frozenbubble/LevelManager;
  move­object v0, v3
  move­object/from16 v1, v22                       Remove!
  move/from16 v2, p4
  invoke­direct {v0, v1, v2}, 
  Lorg/jfedor/frozenbubble/LevelManager;­><init>([BI)V
Real World Tasks
Tasks

• ODEX (Optimized DEX)
  – platform-specific optimizations:
      • specific bytecode
      • vtables for methods
      • offsets for attributes
      • method inlining
• JNI
   – JNIEnv
• Native Activity
• Key signing
DEX Optimizations
• Before being executed by Dalvik, DEX files are optimized.
  – Normally it happens before the first execution of code from the DEX file
  – Combined with the bytecode verification
  – In case of DEX files from APKs, when the application is launched for
    the first time.
• Process
  – The dexopt process (which is actually a backdoor of Dalvik) loads the
    DEX, replaces certain instructions with their optimized counterparts
  – Then writes the resulting optimized DEX (ODEX) file into the
    /data/dalvik-cache directory
  – It is assumed that the optimized DEX file will be executed on the same
    VM that optimized it. ODEX files are NOT portable across VMs.
dexopt: Instruction Rewritten
• Virtual (non-private, non-constructor, non-static methods)
  invoke-virtual <symbolic method name> → invoke-virtual-quick <vtable index>
    Before:
    invoke-virtual
    {v1,v2},java/lang/StringBuilder/append;append(Ljava/lang/String;)Ljava/lang/StringBuilder;
    After:
    invoke-virtual-quick {v1,v2},vtable #0x3b

• Frequently used methods
  invoke-virtual/direct/static <symbolic method name> → execute-inline <method index>
  – Before:
    invoke-virtual {v2},java/lang/String/length
  – After:
    execute-inline {v2},inline #0x4

• instance fields: iget/iput <field name> → iget/iput-quick <memory offset>
   – Before: iget-object v3,v5,android/app/Activity.mComponent
  – After: iget-object-quick v3,v5,[obj+0x28]
Meaning of DEX Optimizations
• Sets byte ordering and structure alignment
• Aligns the member variables to 32-bits / 64-bits
• boundary (the structures in the DEX/ODEX file itself
  are 32-bit aligned)
• Significant optimizations because of the elimination
  of symbolic field/method lookup at runtime.
• Aid of Just-In-Time compiler
JNI specificities can ease reversing
•1- get the function signature in Java
•2- use IDA to generate a TIL file from jni.h
•3- assign the structure to the right variable
•4- see function calls directly
•5- do the same in Hex-Rays
Practice of Android Reverse Engineering
Further Considerations

• Optimizing, Obfuscating, and Shrinking your Android Applications with ProGuard
  http://www.androidengineer.com/2010/07/optimizing-obfuscating-and-shrinking.html
• Missions:
  – Obfuscation
   – Optimizing
• ProGuard
  <target name="-dex" depends="compile,optimize">
  <target name="-post-compile">
   <antcall target="optimize"/>
  </target>
• Google's License Verification Library (LVL)
  -keep class com.android.vending.licensing.ILicensingService
Reference

• Analysis of Dalvik Virtual Machine and Class Path
  Library, Security Engineering Research Group,
  Institute of Management SciencesPeshawar,
  Pakistan (2009)
  http://serg.imsciences.edu.pk
• Android: forensics and reverse engineering, Raphaël
  Rigo – ANSSI (2010)
• http://code.google.com/p/dex2jar/
• http://java.decompiler.free.fr/
http://0xlab.org

More Related Content

What's hot (20)

PDF
Spring Boot
Jaran Flaath
 
PPT
JAVA SCRIPT
Go4Guru
 
PPTX
Flutter
Shyju Madathil
 
PDF
React and redux
Mystic Coders, LLC
 
PDF
PUC SE Day 2019 - SpringBoot
Josué Neis
 
PPTX
Dependency injection presentation
Ahasanul Kalam Akib
 
PPT
Introduction to Eclipse IDE
Muhammad Hafiz Hasan
 
PDF
Angular
Lilia Sfaxi
 
PPTX
Flutter for web
rihannakedy
 
PPTX
Introduction to React JS for beginners | Namespace IT
namespaceit
 
PPTX
Basic Concept of Node.js & NPM
Bhargav Anadkat
 
PDF
React JS and why it's awesome
Andrew Hull
 
ZIP
Android Application Development
Benny Skogberg
 
PPTX
Angular tutorial
Rohit Gupta
 
PPTX
Flutter
Himanshu Singh
 
PDF
Spring boot jpa
Hamid Ghorbani
 
PPTX
Introduction to Bdd and cucumber
Nibu Baby
 
PDF
iOS Application Security
Egor Tolstoy
 
PPTX
Jetpack Compose.pptx
GDSCVJTI
 
PPTX
React Native
Artyom Trityak
 
Spring Boot
Jaran Flaath
 
JAVA SCRIPT
Go4Guru
 
React and redux
Mystic Coders, LLC
 
PUC SE Day 2019 - SpringBoot
Josué Neis
 
Dependency injection presentation
Ahasanul Kalam Akib
 
Introduction to Eclipse IDE
Muhammad Hafiz Hasan
 
Angular
Lilia Sfaxi
 
Flutter for web
rihannakedy
 
Introduction to React JS for beginners | Namespace IT
namespaceit
 
Basic Concept of Node.js & NPM
Bhargav Anadkat
 
React JS and why it's awesome
Andrew Hull
 
Android Application Development
Benny Skogberg
 
Angular tutorial
Rohit Gupta
 
Spring boot jpa
Hamid Ghorbani
 
Introduction to Bdd and cucumber
Nibu Baby
 
iOS Application Security
Egor Tolstoy
 
Jetpack Compose.pptx
GDSCVJTI
 
React Native
Artyom Trityak
 

Similar to Practice of Android Reverse Engineering (20)

PPTX
Android village @nullcon 2012
hakersinfo
 
PDF
hashdays 2011: Tobias Ospelt - Reversing Android Apps - Hacking and cracking ...
Area41
 
KEY
Scala on androids
thoraage
 
PPTX
Eclispe daytoulouse combining the power of eclipse with android_fr_1024_768_s...
Mathias Seguy
 
PDF
Improve Android System Component Performance
National Cheng Kung University
 
ODP
Java Meetup - 12-03-15 - Android Development Workshop
Kasun Dananjaya Delgolla
 
PDF
An Introduction To Android
natdefreitas
 
PDF
Mobile operating systems - Application Benchmarking
Nicolas Demetriou
 
PDF
CNIT 128 6. Analyzing Android Applications (Part 1)
Sam Bowne
 
PDF
[Android] Introduction to Android Programming
Nikmesoft Ltd
 
PDF
Android
Leo Liang
 
PDF
Targeting Android with Qt
Espen Riskedal
 
PPTX
Decompiling Android
Godfrey Nolan
 
PDF
Android Development
vishalkrv
 
PDF
Android Internals
Opersys inc.
 
PDF
Android Attacks
Michael Scovetta
 
PDF
Hacking your Droid (Aditya Gupta)
ClubHack
 
PPT
Android Introduction
aswapnal
 
PDF
Android For Managers Slides
Marko Gargenta
 
PDF
Jaime Blasco & Pablo Rincón - Lost in translation: WTF is happening inside m...
RootedCON
 
Android village @nullcon 2012
hakersinfo
 
hashdays 2011: Tobias Ospelt - Reversing Android Apps - Hacking and cracking ...
Area41
 
Scala on androids
thoraage
 
Eclispe daytoulouse combining the power of eclipse with android_fr_1024_768_s...
Mathias Seguy
 
Improve Android System Component Performance
National Cheng Kung University
 
Java Meetup - 12-03-15 - Android Development Workshop
Kasun Dananjaya Delgolla
 
An Introduction To Android
natdefreitas
 
Mobile operating systems - Application Benchmarking
Nicolas Demetriou
 
CNIT 128 6. Analyzing Android Applications (Part 1)
Sam Bowne
 
[Android] Introduction to Android Programming
Nikmesoft Ltd
 
Android
Leo Liang
 
Targeting Android with Qt
Espen Riskedal
 
Decompiling Android
Godfrey Nolan
 
Android Development
vishalkrv
 
Android Internals
Opersys inc.
 
Android Attacks
Michael Scovetta
 
Hacking your Droid (Aditya Gupta)
ClubHack
 
Android Introduction
aswapnal
 
Android For Managers Slides
Marko Gargenta
 
Jaime Blasco & Pablo Rincón - Lost in translation: WTF is happening inside m...
RootedCON
 
Ad

More from National Cheng Kung University (20)

PDF
PyPy's approach to construct domain-specific language runtime
National Cheng Kung University
 
PDF
Making Linux do Hard Real-time
National Cheng Kung University
 
PDF
2016 年春季嵌入式作業系統課程說明
National Cheng Kung University
 
PDF
Interpreter, Compiler, JIT from scratch
National Cheng Kung University
 
PDF
進階嵌入式作業系統設計與實做 (2015 年秋季 ) 課程說明
National Cheng Kung University
 
PDF
Construct an Efficient and Secure Microkernel for IoT
National Cheng Kung University
 
PDF
The Internals of "Hello World" Program
National Cheng Kung University
 
PDF
How A Compiler Works: GNU Toolchain
National Cheng Kung University
 
PDF
Virtual Machine Constructions for Dummies
National Cheng Kung University
 
PDF
給自己更好未來的 3 個練習:嵌入式作業系統設計、實做,與移植 (2015 年春季 ) 課程說明
National Cheng Kung University
 
PDF
從線上售票看作業系統設計議題
National Cheng Kung University
 
PDF
進階嵌入式系統開發與實做 (2014 年秋季 ) 課程說明
National Cheng Kung University
 
PDF
Xvisor: embedded and lightweight hypervisor
National Cheng Kung University
 
PDF
Making Linux do Hard Real-time
National Cheng Kung University
 
PDF
Implement Runtime Environments for HSA using LLVM
National Cheng Kung University
 
PDF
Priority Inversion on Mars
National Cheng Kung University
 
PDF
Develop Your Own Operating Systems using Cheap ARM Boards
National Cheng Kung University
 
PDF
Lecture notice about Embedded Operating System Design and Implementation
National Cheng Kung University
 
PDF
Explore Android Internals
National Cheng Kung University
 
PDF
中輟生談教育: 完全用開放原始碼軟體進行 嵌入式系統教學
National Cheng Kung University
 
PyPy's approach to construct domain-specific language runtime
National Cheng Kung University
 
Making Linux do Hard Real-time
National Cheng Kung University
 
2016 年春季嵌入式作業系統課程說明
National Cheng Kung University
 
Interpreter, Compiler, JIT from scratch
National Cheng Kung University
 
進階嵌入式作業系統設計與實做 (2015 年秋季 ) 課程說明
National Cheng Kung University
 
Construct an Efficient and Secure Microkernel for IoT
National Cheng Kung University
 
The Internals of "Hello World" Program
National Cheng Kung University
 
How A Compiler Works: GNU Toolchain
National Cheng Kung University
 
Virtual Machine Constructions for Dummies
National Cheng Kung University
 
給自己更好未來的 3 個練習:嵌入式作業系統設計、實做,與移植 (2015 年春季 ) 課程說明
National Cheng Kung University
 
從線上售票看作業系統設計議題
National Cheng Kung University
 
進階嵌入式系統開發與實做 (2014 年秋季 ) 課程說明
National Cheng Kung University
 
Xvisor: embedded and lightweight hypervisor
National Cheng Kung University
 
Making Linux do Hard Real-time
National Cheng Kung University
 
Implement Runtime Environments for HSA using LLVM
National Cheng Kung University
 
Priority Inversion on Mars
National Cheng Kung University
 
Develop Your Own Operating Systems using Cheap ARM Boards
National Cheng Kung University
 
Lecture notice about Embedded Operating System Design and Implementation
National Cheng Kung University
 
Explore Android Internals
National Cheng Kung University
 
中輟生談教育: 完全用開放原始碼軟體進行 嵌入式系統教學
National Cheng Kung University
 
Ad

Recently uploaded (20)

PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
July Patch Tuesday
Ivanti
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
July Patch Tuesday
Ivanti
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 

Practice of Android Reverse Engineering

  • 1. Practice of Android Reverse Engineering Jim Huang ( 黃敬群 ) Developer, 0xlab [email protected] July 23, 2011 / HITcon
  • 2. Rights to copy © Copyright 2011 0xlab http://0xlab.org/ [email protected] Attribution – ShareAlike 3.0 You are free Corrections, suggestions, contributions and translations are welcome! to copy, distribute, display, and perform the work to make derivative works Latest update:July 23, 2011 to make commercial use of the work Under the following conditions Attribution. You must give the original author credit. Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under a license identical to this one. For any reuse or distribution, you must make clear to others the license terms of this work. Any of these conditions can be waived if you get permission from the copyright holder. Your fair use and other rights are in no way affected by the above. License text: http://creativecommons.org/licenses/by-sa/3.0/legalcode
  • 3. Myself was a Kaffe Developer ● Threaded Interpreter, JIT, AWT for embedded system, robustness was a GCJ (Java Frontend for GCC) and GNU Classpath Developer is an AOSP (Android Open Source Project) contributror ● 30+ patches are merged officially ● bionic libc, ARM optimizations
  • 4. Not Only for (1) Sometimes, it takes __time__ Cracking to obtain source code than expected. → Taiwanese ODM (2) Post-optimizations over existing Android applications (3) “Borrow" something good to produce "goods"
  • 5. Background Knowledge (and Thank you!) • The Code Injection and Data Protection of Android, Thinker Li @HITcon2011 • Reversing Android Malware, Mahmud ab Rahman @HITcon2011 • My focus would be the practice. – Hack Android applications for Beginners
  • 6. Agenda (1) Development Flow (2) Reverse Practice (3) Real world tasks
  • 7. Android Application Development Flow aapt Create Manifest Manifest packaged Packaged resource file Packaged resource file resource R R Resources Resources javac dx Dalvik compile classes.dex classes.dex Assets Assets bytecode apkbuilder -u Source code Source code Create unsigned apk unsigned apk unsigned apk Libraries Libraries adb Key Key Publish or Sign apk signed apk signed apk Test 7 jarsigner
  • 8. APK content $ unzip Angry+Birds.apk Archive: Angry+Birds.apk ... inflating: AndroidManifest.xml extracting: resources.arsc extracting: res/drawable-hdpi/icon.png extracting: res/drawable-ldpi/icon.png extracting: res/drawable-mdpi/icon.png inflating: classes.dex Dalvik DEX inflating: lib/armeabi/libangrybirds.so JNI inflating: lib/armeabi-v7a/libangrybirds.so inflating: META-INF/MANIFEST.MF inflating: META-INF/CERT.SF manifest + inflating: META-INF/CERT.RSA signature
  • 9. APK content $ unzip Angry+Birds.apk Archive: Angry+Birds.apk ... inflating: AndroidManifest.xml Name: extracting: resources.arsc classes.dex extracting: res/drawable-hdpi/icon.png SHA1-Digest: I9Vne//i/5Wyzs5HhBVu9dIoHDY= extracting: res/drawable-ldpi/icon.png Name: lib/armeabi/libangrybirds.so extracting: res/drawable-mdpi/icon.png SHA1-Digest: pSdb9FYauyfjDUxM8L6JDmQk4qQ= inflating: classes.dex inflating: lib/armeabi/libangrybirds.so inflating: lib/armeabi-v7a/libangrybirds.so inflating: META-INF/MANIFEST.MF inflating: META-INF/CERT.SF inflating: META-INF/CERT.RSA
  • 10. AndroidManifest $ unzip Angry+Birds.apk Archive: Angry+Birds.apk ... ... inflating: AndroidManifest.xml extracting: resources.arsc extracting: res/drawable-hdpi/icon.png $ file AndroidManifest.xml extracting: res/drawable-ldpi/icon.png AndroidManifest.xml: DBase 3 data file (2328 records) extracting: res/drawable-mdpi/icon.png $ apktool d ../AngryBirds/Angry+Birds.apk inflating: classes.dex I: Baksmaling... I: Loading resource lib/armeabi/libangrybirds.so inflating: table... ... inflating: lib/armeabi-v7a/libangrybirds.so I: Decoding file-resources... inflating: META-INF/MANIFEST.MF I: Decoding values*/* XMLs... I: Done. inflating: META-INF/CERT.SF I: Copying assets and libs... $ fileinflating: META-INF/CERT.RSA Angry+Birds/AndroidManifest.xml Angry+Birds/AndroidManifest.xml: XML document text
  • 11. Before performing reverse engineering, let's observe how Android system works
  • 12. In this presentation, Android platform 2.3.3 is selected. Widget How can Launcher find widgets/activities and invoke them? Android Launcher
  • 13. When installing FrozenBubble.apk $ adb logcat -c $ adb install -r FrozenBubble.apk 1222 KB/s (499568 bytes in 0.399s) pkg: /data/local/tmp/FrozenBubble.apk Success $ adb logcat D/AndroidRuntime( 329): D/AndroidRuntime( 329): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<< D/PackageParser( 60): Scanning package: /data/app/vmdl10628918.tmp ... Download the whole package: http://0xlab.org/~jserv/dex-dis-example.tar.bz2
  • 14. APK Installation Procedure D/AndroidRuntime( 329): D/AndroidRuntime( 329): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<< D/PackageParser( 60): Scanning package: /data/app/vmdl10628918.tmp I/PackageManager( 60): Removing non-system package:org.jfedor.frozenbubble I/ActivityManager( 60): Force stopping package org.jfedor.frozenbubble uid=10034 D/PackageManager( 60): Scanning package org.jfedor.frozenbubble I/PackageManager( 60): Package org.jfedor.frozenbubble codePath changed from /data/app/org.jfedor.frozenbubble-2.apk to /data/app/org.jfedor.frozenbubble-1.apk; Retaining data and using new I/PackageManager( 60): Unpacking native libraries for /data/app/org.jfedor.frozenbubble-1.apk D/installd( 34): DexInv: --- BEGIN '/data/app/org.jfedor.frozenbubble-1.apk' --- D/dalvikvm( 340): DexOpt: load 54ms, verify+opt 137ms D/installd( 34): DexInv: --- END '/data/app/org.jfedor.frozenbubble-1.apk' (success) --- W/PackageManager( 60): Code path for pkg : org.jfedor.frozenbubble changing from /data/app/org.jfedor.frozenbubble-2.apk to /data/app/org.jfedor.frozenbubble-1.apk W/PackageManager( 60): Resource path for pkg : org.jfedor.frozenbubble changing from /data/app/org.jfedor.frozenbubble-2.apk to /data/app/org.jfedor.frozenbubble-1.apk D/PackageManager( 60): Activities: org.jfedor.frozenbubble.FrozenBubble I/ActivityManager( 60): Force stopping package org.jfedor.frozenbubble uid=10034 I/installd( 34): move /data/dalvik-cache/data@[email protected]@classes.dex -> /data/dalvik-cache/data@[email protected]@classes.dex D/PackageManager( 60): New package installed in /data/app/org.jfedor.frozenbubble-1.apk I/ActivityManager( 60): Force stopping package org.jfedor.frozenbubble uid=10034 I/installd( 34): unlink /data/dalvik-cache/data@[email protected]@classes.dex D/AndroidRuntime( 329): Shutting down VM D/jdwp ( 329): adbd disconnected
  • 15. APK Installation Procedure D/AndroidRuntime( 329): Android Runtime performs init Android Runtime performs init D/AndroidRuntime( 329): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<< D/PackageParser( 60): Scanning package: /data/app/vmdl10628918.tmp Package Manager detects APK and installs Package Manager detects APK and I/PackageManager( 60): Removing non-system package:org.jfedor.frozenbubble installs I/ActivityManager( 60): Force stopping package org.jfedor.frozenbubble uid=10034 D/PackageManager( 60): Scanning package org.jfedor.frozenbubble I/PackageManager( 60): Package org.jfedor.frozenbubble codePath changed from /data/app/org.jfedor.frozenbubble-2.apk to /data/app/org.jfedor.frozenbubble-1.apk; Retaining data and using new I/PackageManager( 60): Unpacking native libraries for /data/app/org.jfedor.frozenbubble-1.apk D/installd( 34): DexInv: --- BEGIN '/data/app/org.jfedor.frozenbubble-1.apk' --- D/dalvikvm( 340): DexOpt: load 54ms, verify+opt 137ms DexOpt DexOpt D/installd( 34): DexInv: --- END '/data/app/org.jfedor.frozenbubble-1.apk' (success) --- (verify and optimize all of the classes in the DEX file) (verify and optimize all of the classes in the DEX file) W/PackageManager( 60): Code path for pkg : org.jfedor.frozenbubble changing from /data/app/org.jfedor.frozenbubble-2.apk to /data/app/org.jfedor.frozenbubble-1.apk W/PackageManager( 60): Resource path for pkg : org.jfedor.frozenbubble changing from /data/app/org.jfedor.frozenbubble-2.apk to /data/app/org.jfedor.frozenbubble-1.apk D/PackageManager( 60): Activities: org.jfedor.frozenbubble.FrozenBubble I/ActivityManager( 60): Force stopping package org.jfedor.frozenbubble uid=10034 Activities: org.jfedor.frozenbubble.FrozenBubble I/installd( 34): move /data/dalvik-cache/data@[email protected]@classes.dex -> /data/dalvik-cache/data@[email protected]@classes.dex D/PackageManager( 60): New package installed in /data/app/org.jfedor.frozenbubble-1.apk I/ActivityManager( 60): Force stopping package org.jfedor.frozenbubble uid=10034 I/installd( 34): unlink /data/dalvik-cache/data@[email protected]@classes.dex D/AndroidRuntime( 329): Shutting down VM D/jdwp ( 329): adbd disconnected
  • 16. I/ActivityManager( 60): Start proc org.jfedor.frozenbubble for activity org.jfedor.frozenbubble/.FrozenBubble: pid=356 uid=10034 gids={} I/ActivityManager( 60): Displayed org.jfedor.frozenbubble/.FrozenBubble: +2s899ms
  • 17. Execute FrozenBubble from Android Launcher $ adb shell am start -e debug true -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -n org.jfedor.frozenbubble/.FrozenBubble Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=org.jfedor.frozenbubble/.FrozenBubb le (has extras)
  • 19. Execute FrozenBubble $ adb shell dumpsys | grep -i bubble name=org.jfedor.frozenbubble/org.jfedor.frozenbubble.Froz enBubble Intent { act=android.intent.action.PACKAGE_ADDED dat=package:org.jfedor.frozenbubble flg=0x10000000 (has extras) } * TaskRecord{40744ad0 #4 A org.jfedor.frozenbubble} affinity=org.jfedor.frozenbubble intent={act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=org.jfedor.frozenbubble/.FrozenBubble} realActivity=org.jfedor.frozenbubble/.FrozenBubble ...
  • 20. ActivityManager • Start new Activities and Services • Fetch Content Providers • Intent broadcasting • OOM adj. Maintenance • ANR (Application Not Responding) • Permissions • Task management • Lifecycle management
  • 21. ActivityManager • starting new app from Launcher: – onClick(Launcher) – startActivity – <Binder> – ActivityManagerService – startViaZygote(Process.java) – <Socket> – Zygote
  • 22. Use JDB to Trace Android Application #!/bin/bash adb wait-for-device adb shell am start -e debug true -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -n org.jfedor.frozenbubble/.FrozenBubble & debug_port=$(adb jdwp | tail -1); adb forward tcp:29882 jdwp:$debug_port & jdb -J-Duser.home=. -connect com.sun.jdi.SocketAttach:hostname=localhost,port=29882 & In APK manifest, debuggable=”true" JDWP: Java Debug Wire Protocol
  • 23. JDB usage > threads Group system:   (java.lang.Thread)0xc14050e388  <6> Compiler         cond. Waiting   (java.lang.Thread)0xc14050e218  <4> Signal Catcher   cond. waiting   (java.lang.Thread)0xc14050e170  <3> GC               cond. waiting   (java.lang.Thread)0xc14050e0b8  <2> HeapWorker       cond. waiting Group main:   (java.lang.Thread)0xc14001f1a8  <1> main             running   (org.jfedor.frozenbubble.GameView$GameThread)0xc14051e300                                   <11> Thread­10       running   (java.lang.Thread)0xc14050f670  <10> SoundPool       running   (java.lang.Thread)0xc14050f568  <9> SoundPoolThread  running   (java.lang.Thread)0xc140511db8  <8> Binder Thread #2 running   (java.lang.Thread)0xc140510118  <7> Binder Thread #1 running > suspend 0xc14051e300 > thread 0xc14051e300 <11> Thread-10[1] where [1] android.view.SurfaceView$3.internalLockCanvas (SurfaceView.java:789) [2] android.view.SurfaceView$3.lockCanvas (SurfaceView.java:745) [3] org.jfedor.frozenbubble.GameView$GameThread.run (GameView.java:415)
  • 24. DDMS = Dalvik Debug Monitor Server
  • 25. (JDB) > thread 0xc14051e300 <11> Thread-10[1] where [1] android.view.SurfaceView$3.internalLockCanvas (SurfaceView.java:789) [2] android.view.SurfaceView$3.lockCanvas (SurfaceView.java:745) [3] org.jfedor.frozenbubble.GameView$GameThread.run (GameView.java:415)
  • 27. Figure out the association between APK resources and runtime behavior.
  • 29. • apktool: http://code.google.com/p/android-apktool/ • dex2jar: http://code.google.com/p/dex2jar/ • Jad / jd-gui: http://java.decompiler.free.fr/
  • 30. smali : assembler/disassembler for Android's dex format • http://code.google.com/p/smali/ • smali: The assembler • baksmali: The disassembler • Fully integrated in apktool $ apktool d ../AngryBirds/Angry+Birds.apk  I: Baksmaling... I: Loading resource table... ... I: Decoding file­resources... I: Decoding values*/* XMLs... I: Done. I: Copying assets and libs...
  • 31. Java bytecode vs. Dalvik bytecode public int method( int i1, int i2 ) { (stack vs. register) int i3 = i1 * i2; return i3 * 2; } .var 0 is “this” this: v1 (Ltest2;) .var 1 is argument #1 parameter[0] : v2 (I) .var 2 is argument #2 parameter[1] : v3 (I) method public method(II)I     iload_1     iload_2 .method public method(II)I     imul     mul­int v0,v2,v3     istore_3     mul­int/lit­8 v0,v0,2     iload_3     return v0     iconst_2 .end method     imul     ireturn .end method Java Dalvik
  • 32. Dalvik Register frames • Dalvik registers behave more like local variables • Each method has a fresh set of registers. • Invoked methods don't affect the registers of invoking methods.
  • 33. Practice: Level Up Change initial game level Change initial game level From 1 to 5 ! From 1 to 5 !
  • 35. Output org.jfedor.frozenbubble/.FrozenBubble smali­src$ find ./org/jfedor/frozenbubble/FrozenBubble.smali ./org/jfedor/frozenbubble/R$id.smali ./org/jfedor/frozenbubble/GameView.smali ./org/jfedor/frozenbubble/SoundManager.smali ./org/jfedor/frozenbubble/LaunchBubbleSprite.smali ./org/jfedor/frozenbubble/Compressor.smali ./org/jfedor/frozenbubble/R$attr.smali ./org/jfedor/frozenbubble/BubbleFont.smali ./org/jfedor/frozenbubble/PenguinSprite.smali ./org/jfedor/frozenbubble/GameView$GameThread.smali ./org/jfedor/frozenbubble/LevelManager.smali ./org/jfedor/frozenbubble/BubbleSprite.smali ./org/jfedor/frozenbubble/R$string.smali ... Generated from resources
  • 36. Output smali­src$ grep ".method"  org/jfedor/frozenbubble/LevelManager.smali .method public constructor <init>([BI)V .method private getLevel(Ljava/lang/String;)[[B .method public getCurrentLevel()[[B .method public getLevelIndex()I .method public goToFirstLevel()V .method public goToNextLevel()V .method public restoreState(Landroid/os/Bundle;)V .method public saveState(Landroid/os/Bundle;)V List the methods implemented in class LevelManager
  • 37. Dalvik::Types .method private getLevel(Ljava/lang/String;)[[B → private byte[][] getLevel(String data) .method public goToNextLevel()V → public void goToNextLevel(); • Base types – I : int / J : long / S : short – Z : boolean – D : double / F : float – C : char – V : void (when return value) • Classes: Ljava/lang/Object; • Arrays: [I, [Ljava/lang/Object;, [[I
  • 38. Dalvik::Methods • Rich meta-information is assigned to Dalvik methods • Method meta-information: – Signature – Try-catch information – Annotations – Number of registers used – Debug information • Line numbers • Local variable lifetime
  • 39. Output smali­src$ grep ­r goToFirstLevel * org/jfedor/frozenbubble/GameView$GameThread.smali:  invoke­virtual {v2},   Lorg/jfedor/frozenbubble/LevelManager;­>goToFirstLevel()V org/jfedor/frozenbubble/LevelManager.smali: .method public goToFirstLevel()V That the first argument of the method invocation is “this” as this is a non-static method.
  • 40. GameView$GameThread.smali .method public newGame()V         . . .     move­object/from16 v0, p0     iget­object v0, v0,  Lorg/jfedor/frozenbubble/GameView$GameThread;­ >mLevelManager:Lorg/jfedor/frozenbubble/LevelManager;     move­object v2, v0     invoke­virtual {v2},  Lorg/jfedor/frozenbubble/LevelManager;­>goToFirstLevel ()V Equals to Java: objLevelManager.goToFirstLevel();
  • 41. LevelManager.smali .method public goToFirstLevel()V     .registers 2 Equals to Java: public class LevelManager {     ...     .prologue     public void goToFirstLevel() {     .line 175          currentLevel = 0;     }     const/4 v0, 0x0     ... }     iput v0, p0,  Lorg/jfedor/frozenbubble/LevelManager;­>currentLevel:I Equals to Java:     .line 176 currentLevel = 0;     return­void .end method Constants to registers: const/4, const/16, const, const/high16, const-wide/16, const-wide/32, const-wide, const-wide/high16, const-string, const-class
  • 42. Modify constructor of GameView::GameThread() • Look up output in GameView$GameThread.smali .class Lorg/jfedor/frozenbubble/GameView$GameThread; .super Ljava/lang/Thread; .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x0 name = "GameThread" .end annotation # direct methods .method public constructor <init>(Lorg/jfedor/frozenbubble/GameView;Landroid/view/SurfaceHol der;[BI)V
  • 43. Modify constructor of GameView::GameThread() • Look up output in GameView$GameThread.smali # direct methods .method public constructor <init>(Lorg/jfedor/frozenbubble/GameView;Landroid/view/SurfaceHol der;[BI)V Equals to Java: class GameView ??? {     class GameThread extends Thread {         public GameThread(SurfaceHolder s,                           byte[] b,                           int I) {
  • 44. GameView.smali • Look up output in GameView.smali .class Lorg/jfedor/frozenbubble/GameView; .super Landroid/view/SurfaceView; # interfaces .implements Landroid/view/SurfaceHolder$Callback; • Look up output in GameView$GameThread.smali .class Lorg/jfedor/frozenbubble/GameView$GameThread; .super Ljava/lang/Thread; Equals to Java: class GameView extends SurfaceView                implements SurfaceHolder.Callback {   class GameThread extends Thread {
  • 45. Implementation of GameView::GameThread() • Check GameView::public GameThread(SurfaceHolder s, byte[] b, int I) const­string v3, "level" const/4 v4, 0x0 move­object/from16 v0, v25 move­object v1, v3 move v2, v4 invoke­interface {v0, v1, v2},  Landroid/content/SharedPreferences;­ >getInt(Ljava/lang/String;I)I move­result p4 Invoke constructor of LevelManager new­instance v3, Lorg/jfedor/frozenbubble/LevelManager; move­object v0, v3 move­object/from16 v1, v22 move/from16 v2, p4 invoke­direct {v0, v1, v2},  Lorg/jfedor/frozenbubble/LevelManager;­><init>([BI)V
  • 46. Register v1 related code const­string v3, "level" const/4 v4, 0x0 move­object/from16 v0, v25 move­object v1, v3 move v2, v4 invoke­interface {v0, v1, v2},  Landroid/content/SharedPreferences;­ >getInt(Ljava/lang/String;I)I move­result p4 new­instance v3,  Lorg/jfedor/frozenbubble/LevelManager; move­object v0, v3 move­object/from16 v1, v22 move/from16 v2, p4 invoke­direct {v0, v1, v2},  Lorg/jfedor/frozenbubble/LevelManager;­><init>([BI)V
  • 47. Register v2 related code const­string v3, "level" const/4 v4, 0x0 move­object/from16 v0, v25 move­object v1, v3 “0x0” is passed to LevelManager's move v2, v4 constructor as parameter invoke­interface {v0, v1, v2},  Landroid/content/SharedPreferences;­ >getInt(Ljava/lang/String;I)I move­result p4 new­instance v3,  Lorg/jfedor/frozenbubble/LevelManager; move­object v0, v3 move­object/from16 v1, v22 move/from16 v2, p4 invoke­direct {v0, v1, v2},  Lorg/jfedor/frozenbubble/LevelManager;­><init>([BI)V
  • 48. Recall the grep results smali­src$ grep ".method"  org/jfedor/frozenbubble/LevelManager.smali .method public constructor <init>([BI)V .method private getLevel(Ljava/lang/String;)[[B .method public getCurrentLevel()[[B .method public getLevelIndex()I .method public goToFirstLevel()V .method public goToNextLevel()V .method public restoreState(Landroid/os/Bundle;)V .method public saveState(Landroid/os/Bundle;)V Equals to Java: public class LevelManager {     ...     public LevelManager(byte[] b, int i)
  • 49. Register v2 related code const­string v3, "level" p4 reserve the result after method invocation. const/4 v4, 0x0 move­object/from16 v0, v25 move­object v1, v3 move v2, v4 invoke­interface {v0, v1, v2},  Landroid/content/SharedPreferences;­ >getInt(Ljava/lang/String;I)I move­result p4 new­instance v3,  Therefore, v2 has return value of method Lorg/jfedor/frozenbubble/LevelManager; android.content.Shared.Preference.getInt() move­object v0, v3 move­object/from16 v1, v22 move/from16 v2, p4 invoke­direct {v0, v1, v2},  Lorg/jfedor/frozenbubble/LevelManager;­><init>([BI)V
  • 50. Modify!!! • Check GameView::public GameThread(SurfaceHolder s, byte[] b, int I) const­string v3, "level" Change value from 0x0 to 0x4 const/4 v4, 0x0 move­object/from16 v0, v25 move­object v1, v3 move v2, v4 Remove! invoke­interface {v0, v1, v2},  Landroid/content/SharedPreferences;­>getInt(Ljava/lang/String;I)I move­result p4 new­instance v3, Lorg/jfedor/frozenbubble/LevelManager; move­object v0, v3 move­object/from16 v1, v22 Remove! move/from16 v2, p4 invoke­direct {v0, v1, v2},  Lorg/jfedor/frozenbubble/LevelManager;­><init>([BI)V
  • 52. Tasks • ODEX (Optimized DEX) – platform-specific optimizations: • specific bytecode • vtables for methods • offsets for attributes • method inlining • JNI – JNIEnv • Native Activity • Key signing
  • 53. DEX Optimizations • Before being executed by Dalvik, DEX files are optimized. – Normally it happens before the first execution of code from the DEX file – Combined with the bytecode verification – In case of DEX files from APKs, when the application is launched for the first time. • Process – The dexopt process (which is actually a backdoor of Dalvik) loads the DEX, replaces certain instructions with their optimized counterparts – Then writes the resulting optimized DEX (ODEX) file into the /data/dalvik-cache directory – It is assumed that the optimized DEX file will be executed on the same VM that optimized it. ODEX files are NOT portable across VMs.
  • 54. dexopt: Instruction Rewritten • Virtual (non-private, non-constructor, non-static methods) invoke-virtual <symbolic method name> → invoke-virtual-quick <vtable index> Before: invoke-virtual {v1,v2},java/lang/StringBuilder/append;append(Ljava/lang/String;)Ljava/lang/StringBuilder; After: invoke-virtual-quick {v1,v2},vtable #0x3b • Frequently used methods invoke-virtual/direct/static <symbolic method name> → execute-inline <method index> – Before: invoke-virtual {v2},java/lang/String/length – After: execute-inline {v2},inline #0x4 • instance fields: iget/iput <field name> → iget/iput-quick <memory offset> – Before: iget-object v3,v5,android/app/Activity.mComponent – After: iget-object-quick v3,v5,[obj+0x28]
  • 55. Meaning of DEX Optimizations • Sets byte ordering and structure alignment • Aligns the member variables to 32-bits / 64-bits • boundary (the structures in the DEX/ODEX file itself are 32-bit aligned) • Significant optimizations because of the elimination of symbolic field/method lookup at runtime. • Aid of Just-In-Time compiler
  • 56. JNI specificities can ease reversing •1- get the function signature in Java •2- use IDA to generate a TIL file from jni.h •3- assign the structure to the right variable •4- see function calls directly •5- do the same in Hex-Rays
  • 58. Further Considerations • Optimizing, Obfuscating, and Shrinking your Android Applications with ProGuard http://www.androidengineer.com/2010/07/optimizing-obfuscating-and-shrinking.html • Missions: – Obfuscation – Optimizing • ProGuard <target name="-dex" depends="compile,optimize"> <target name="-post-compile"> <antcall target="optimize"/> </target> • Google's License Verification Library (LVL) -keep class com.android.vending.licensing.ILicensingService
  • 59. Reference • Analysis of Dalvik Virtual Machine and Class Path Library, Security Engineering Research Group, Institute of Management SciencesPeshawar, Pakistan (2009) http://serg.imsciences.edu.pk • Android: forensics and reverse engineering, Raphaël Rigo – ANSSI (2010) • http://code.google.com/p/dex2jar/ • http://java.decompiler.free.fr/