Hacking for Fun and Profit (Mostly for Fun). AnDevCon Boston

1,751 views

Published on

Dive deep into the internals of Android in this two-part, 150-minute class. You will explore the wonders of Dalvik bytecode, smali syntax, decompilation tools, patching techniques, and common methods you can use to (try to) protect your apps.

Extremely hands-on, you'll be downloading a very popular app, modifying it, and messing around with its behavior. Even if you're not that interested in APK hacking, you'll leave this class with the sort of deep appreciation for Dalvik that makes good Android developers great.

Published in: Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,751
On SlideShare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
90
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide
  • META-INF contains keys
  • META-INF contains keys
  • META-INF contains keys
  • META-INF contains keys
  • META-INF contains keys
  • META-INF contains keys
  • META-INF contains keys
  • Hacking for Fun and Profit (Mostly for Fun). AnDevCon Boston

    1. 1. HACKINGAPKS FOR FUNAND FOR PROFIT(MOSTLYFOR FUN)DAVIDTEITELBAUMMAY2013@davtbaum
    2. 2. 2 © 2013 Apkudo LLC. www.apkudo.comOBJECTIVESAndroidappdisassemblyFundamentalsofcodeinjectionSmali/BaksmaliandreadingDalvikbytecodeBestpracticesinhardeningyourappExpect to learn:
    3. 3. 3 © 2013 Apkudo LLC. www.apkudo.comROADMAPPART I - CLASS PART II – DEMO/HACKApproachtohackingTools–apktool,baksmali,smaliTheAPKAllthingsbytecodeSnapchatdeepdiveAppdisassemblyandanalysisCodeinjectionRecap
    4. 4. 4 © 2013 Apkudo LLC. www.apkudo.comPART I - CLASS
    5. 5. 5 © 2013 Apkudo LLC. www.apkudo.com1. UnzipAPK and disassemble classes.dex (baksmali)2. Analyze – what is the application doing?3. Inject byte code into the application to modify execution4. Reassemble classes.dex (smali) and rezip/signAPKAPK HACKINGApproachDisassemble(baksmali).smaliStatic analysisReassemble(smali)Code injection
    6. 6. 6 © 2013 Apkudo LLC. www.apkudo.comCODE INJECTION Write patches in Java, compile, then use theSmali/Baksmali tools to disassemble into Dalvik byte code Stick to public static methods in Dalvik byte code whichhave no register dependencies. Let the compiler do the work - this hack was achievedwith only one line of code injection!Best Practices:
    7. 7. 7 © 2013 Apkudo LLC. www.apkudo.comTOOLS Access to a terminal environment (preferably Linux or Macosx) Android SDK keytool and jarsigner Smali/Baksmali - http://code.google.com/p/smali/ Apktool - http://code.google.com/p/android-apktool/ Editor of choice (emacs!)You’ll need…
    8. 8. 8 © 2013 Apkudo LLC. www.apkudo.comSMALI/BAKSMALI Baksmali disassembles Dalvik executable (.dex) intoreadable Dalvik byte code (.smali) Smali re-assembles .smali files back into .dex Dalvikexecutable Gives developers the ability to modify execution of anAPKwithout having access to source codeDalvik Assembler/Disassembler
    9. 9. 9 © 2013 Apkudo LLC. www.apkudo.comAPKTOOL Wraps smali/baksmali andAndroid asset packaging tool(aapt) Decodes resources and decompresses xml Great for manifest introspection Buggy :/All in one reverser
    10. 10. 10 © 2013 Apkudo LLC. www.apkudo.comTHE APKA container for your app Zipped file formatted based on JARMETA-INF/AndroidManifest.xmlclasses.dexlib/res/resources.arsc
    11. 11. 11 © 2013 Apkudo LLC. www.apkudo.comEXAMPLES$unzipfoobar.apk–dfoobar$cd./foobar$lsAndroidManifest.xml META-INF classes.dex resresources.arsc lib$baksmali–a10–d~/boot_class_pathclasses.dexbaksmaliAPI level boot class path dex file
    12. 12. 12 © 2013 Apkudo LLC. www.apkudo.comEXAMPLES$lsAndroidManifest.xml META-INF classes.dex resresources.arsc libout$smali –a10./out–oclasses.dex$zip–r~/hacked.apk./*smaliAPI level output dex filerecursive
    13. 13. 13 © 2013 Apkudo LLC. www.apkudo.comEXAMPLES$apktooldfoobar.apk foobar$cd./foobar$lsAndroidManifest.xml apktool.yml assets res smali$cd../$apktoolb./foobarapktooldecode out directorybuild
    14. 14. 14 © 2013 Apkudo LLC. www.apkudo.comEXAMPLES$keytool-genkeypair-v -aliasdefault–keystore~/.keystore–storepasspassword$jarsigner–keystore~/.keystore ./foobar.apkdefaultkeytool and jarsigneralias
    15. 15. 15 © 2013 Apkudo LLC. www.apkudo.comSMALI FILESclass representation in byte code.class public Lcom/apkudo/util/Serializer;.super Ljava/lang/Object;.source "Serializer.java”# static fields.field public static final TAG:Ljava/lang/String; = "ApkudoUtils”# direct methods.method public constructor <init>()V.registers 1.prologue.line 5invoke-direct {p0}, Ljava/lang/Object;-><init>()Vreturn-void.end methodClass informationStatic fieldsMethodsDirectVirtual
    16. 16. 16 © 2013 Apkudo LLC. www.apkudo.comSYNTAXV voidZ booleanB byteS shortC charF floatI intJ longD double[ arraytypes .method private doSomething()V64 bit – special instructions
    17. 17. 17 © 2013 Apkudo LLC. www.apkudo.comSYNTAX• full name space slash separated• prefixed with L• suffixed with ;Lcom/apkudo/util/Serializer;classesconst-string v0, "ApkudoUtils"new-instance v1, Ljava/lang/StringBuilder;invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()Vconst-string v2, "docId: ["invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;move-result-object v1
    18. 18. 18 © 2013 Apkudo LLC. www.apkudo.comSYNTAX Method definitions .method <[keyword]> <name>(<[param]>)<return type> Method invocations invoke-static – any method that is static invoke-virtual– any method that isn‟t private, static, orfinal invoke-direct – any non-static direct method invoke-super – any superclasss virtual method Invoke-interface– any interface method Virtual methods require their class instance as a parameter!.method private doSomething()Vmethods
    19. 19. 19 © 2013 Apkudo LLC. www.apkudo.comSYNTAX.method private doSomething()Vmethods.method private delayedAnimationFrame(J)Z.registers 8.parameter "currentTime”keyword method name parameters/return# Static invocationinvoke-static {p2}, Landroid/text/TextUtils;->isEmpty(Ljava/lang/CharSequence;)Z# Virtual invocationinvoke-virtual {v0, v1}, Lcom/google/android/finsky/FinskyApp;->drainAllRequests(I)V
    20. 20. 20 © 2013 Apkudo LLC. www.apkudo.comSYNTAX All registers are 32 bits Declaration .registers – total number of registers .locals – total minus method parameter registers Naming scheme Pregisters – parameter registers implicit p0 = „this‟instance (non-static) V registers – local registers Pregisters are always at the end of the register list.locals 16.registers 18Registers
    21. 21. 21 © 2013 Apkudo LLC. www.apkudo.comSYNTAX.method public onCreate()V.registers 7...Register Examplev0 First local registerv1 Second local registerv2 …v3 …v4 …v5 …v6 p0 First param – ‘this’p0 == v6
    22. 22. 22 © 2013 Apkudo LLC. www.apkudo.comSYNTAX.method public doIt(Ljava/lang/String;II)V.registers 7Register Example 2v0 First local registerv1 Second local registerv2 …v3 p0 ‘this’v4 p1 Stringv5 p2 intv6 p3 intp3 == v6p2 == v5p1 == v4p0 == v3
    23. 23. 23 © 2013 Apkudo LLC. www.apkudo.comSYNTAX.method public doIt(JI)V.registers 7# hint, j == longRegister Example 3v0 First local registerv1 Second local registerv2v3v4v5v6Third local registerp0 ‘this’ instancep1 longp2 longp3 intv3 - is it…A) Fourth local register?B) This instance?C) Long?D) Int?v4 - is it…A) Fourth local register?B) This instance?C) Long?D) Int?v5 - is it…A) Fourth local register?B) This instance?C) Long?D) Int?v6 - is it…A) Fourth local register?B) This instance?C) Long?D) Int?
    24. 24. 24 © 2013 Apkudo LLC. www.apkudo.comSYNTAX.method public static doIt(IJ)V.registers 7Register Example 4v0 First local registerv1 Second local registerv2v3v4v5v6Third local registerFourth local registerp0 Intp1 Longp2 Longv3 - is it…A) Fourth local register?B) This instance?C) Long?D) Int?v4 - is it…A) Fourth local register?B) This instance?C) Long?D) Int?v5 - is it…A) Fourth local register?B) This instance?C) Long?D) Int?v6 - is it…A) Fourth local register?B) This instance?C) Long?D) Int?
    25. 25. 25 © 2013 Apkudo LLC. www.apkudo.comSYNTAX jumps goto <offset>jumping.method public doIt(JI)V.registers 7...goto :goto_31...:goto_31return-void
    26. 26. 26 © 2013 Apkudo LLC. www.apkudo.comSYNTAX Conditionals If-eq If-ne If-le If-lt If-ge If-gt Add z for zero If-eqz If-nezconditionalsmethod public foobar()V.registers 2const/4 v0, 0x0if-eqz v0, :cond_6return-void:cond_6# Do something.end method
    27. 27. 27 © 2013 Apkudo LLC. www.apkudo.comPUTTING IT ALLTOGETHERExample - Javapackage com.google.android.finsky;import android.app.Application;import android.accounts.Account;public class FinskyApp() extends Application {Account mCurrentAccount;public String getCurrentAccountName() {if (mCurrentAccount != null) {return mCurrentAccount.name;} else {return null;}}}
    28. 28. 28 © 2013 Apkudo LLC. www.apkudo.comPUTTING IT ALLTOGETHERSame example - smali.method public getCurrentAccountName()Ljava/lang/String;.registers 2.prologue.line 617iget-object v0, p0, Lcom/google/android/finsky/FinskyApp;->mCurrentAccount:Landroid/accounts/Account;if-nez v0, :cond_6const/4 v0, 0x0:goto_5return-object v0:cond_6iget-object v0, v0, Landroid/accounts/Account;->name:Ljava/lang/String;goto :goto_5.end methodv0 First local registerv1 p0 ‘this’ instanceGetting this field! of type …into this reg
    29. 29. 29 © 2013 Apkudo LLC. www.apkudo.comONE FINALSTEPObfuscation!• Renames classes, class members and and method• Preserves OS entry points and java namespace classes• Slows down the static analysis process• Not a silver bullet, but an easy first line of defenseiget-object v0, p0, Lcom/a/a/g;->a:Lcom/a/a/f;invoke-static {v0}, Lcom/a/a/f;->a(Lcom/a/a/f;)Landroid/webkit/WebView;
    30. 30. 30 © 2013 Apkudo LLC. www.apkudo.comPART II - DEMOhttps://github.com/davtbaum/adc-demo
    31. 31. 31 © 2013 Apkudo LLC. www.apkudo.comHACKINGSNAPCHAT
    32. 32. 32 © 2013 Apkudo LLC. www.apkudo.com1. Picture messenger with a catch…2. Self-destructive pictures!3. Pictures only last up to 10 seconds, ensures the receiver cannotsave them4. Alerts the sender if the receiver tries to take a screenshot5. Net-worth $70M – over 20M snaps sent a day!1WHAT ISSNAPCHAT?Real-time picture messenger1. http://techcrunch.com/2012/12/12/sources-snapchat-raising-north-of-10m-at-around-70m-valuation-led-by-benchmarks-mitch-lasky/
    33. 33. 33 © 2013 Apkudo LLC. www.apkudo.comSNAPCHATIN ACTION
    34. 34. 34 © 2013 Apkudo LLC. www.apkudo.com1. UnzipAPK and disassemble classes.dex2. Analyze for target resource (snapchat pictureAKA„snap‟)3. Inject code to store or transmit resource4. Reassemble classes.dex and rezip/resignAPKHACKINGSNAPCHATApproachDisassemble(baksmali).smaliStatic analysis/Code InjectionReassemble(smali)
    35. 35. 35 © 2013 Apkudo LLC. www.apkudo.comTOOLS Access to a terminal environment (preferably Linux or Macosx) Android SDK keytool and jarsigner Smali/Baksmali - http://code.google.com/p/smali/ Apktool - http://code.google.com/p/android-apktool/ Editor of choice (emacs!)You’ll need…
    36. 36. 36 © 2013 Apkudo LLC. www.apkudo.comSTEP 1 Query device for list of applications and associated file paths adbshellpm listpackages–f (optional)|grep–si“snapchat” Pull the files adbpull<file>~/snapchat/snapchat.apkGET THE APP
    37. 37. 37 © 2013 Apkudo LLC. www.apkudo.comSTEP 2 Extract classes.dexand remove keys unzipsnapchat.apk rm–r ./META-INF Disassemble: baksmali-a 10–d<framework_path> ./classes.dex -a=api-level -d=bootclasspathdir „adbpull/system/framework/ ./framework‟DECOMPRESS ANDDISASSEMBLE
    38. 38. 38 © 2013 Apkudo LLC. www.apkudo.comSTEP 3 apktool dump and inspectAndroidManifest.xmlfor activities apktooldsnapchat.apk emacsAndroidManifest.xml Find the resource Use tools uiautomator to retrieve view hierarchy(buggy) adbshelldumpsyswindow|grep–si“mCurrentFocus” Resolve resource in codeANDROID FORENSICS
    39. 39. 39 © 2013 Apkudo LLC. www.apkudo.comSTEP 3 Resource located! Now we need to retrieve it… Don‟t write everything in byte code- build an applicationthat contains the resource retrieval code. Disassemble donor application and copy appropriatemethods into target app Easy enough, right?RESOURCE RETRIEVALJavaresourceretrievalcodeBuild Bytecode
    40. 40. 40 © 2013 Apkudo LLC. www.apkudo.comDONOR APPRESOURCE RETRIEVALpackage com.apkudo.util;import android.app.Activity;import android.graphics.Bitmap;import java.io.FileOutputStream;Import android.os.Bundle;public class HackUtils extends Activity {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);}public void saveSnap(Bitmap bmp) {try {FileOutputStream out = new FileOutputStream(“/sdcard/test.png”);bmp.compress(Bitmap.CompressFormat.PNG, 90, out);} catch (Exception e) {e.printStackTrace();}}}
    41. 41. 41 © 2013 Apkudo LLC. www.apkudo.comSTEP 4CODE INJECTION .method private showImage()V Isolate Bitmap Pass into resource retrieval methodinvoke-virtual{v1,v2},Lcom/snapchat/android/model/ReceivedSnap;->getImageBitmap(Landroid/content/Context;)Landroid/graphics/Bitmap;move-result-objectv0#Patchesinvoke-static{v0},Lcom/apkudo/util/HackUtils;->saveSnap(Landroid/graphics/Bitmap;)V#EndofPatches
    42. 42. 42 © 2013 Apkudo LLC. www.apkudo.comSTEP 5 Re-assemble smali–a10./out–oclasses.dex Compress zip–z0–r../snapchat.apk./* SignAPK jarsigner-verbose -keystore my-release-key.keystore./snapchat.apkalias_nameREBUILD APK
    43. 43. 43 © 2013 Apkudo LLC. www.apkudo.comSTEP 6 Install adb install –r ../snapchat.apk Run the app!INSTALLAND EXECUTE
    44. 44. 44 © 2013 Apkudo LLC. www.apkudo.comRECAP Obfuscate? Very simple to navigate using method name E.g. “showSnap()”. Push images to native layer OpenGL? Native code is much harder to reverse. Dynamic signature verification? There is no silver bullet!ROOM FOR IMPROVEMENTS
    45. 45. Thankyou.DAVID@ .COM@davtbaum

    ×