ADAM MEYERS
Introduction Disclaimer Types of Mobile Devices Platform Models ARM Primer Malware on Mobile Static Analysis Dynamic Analysis Conclusion Q&A
Adam
Director of Intelligence 10 years at SRA International - Defense Contractor Security Consultant/Penetration Test Team/Forensic Technician/Security Architect Reverse Code Analysis
Goal
Learn about ARM/RISC processors, assembly, nuances versus x86 Learn about different mobile operating system architectures Learn approaches for static and dynamic reverse engineering Have fun!
Hacker Fail
Fall 2008 a promise is made Meet JK Benites This genius left his name (unobfuscated) in the malware he wrote to steal banking credentials and ended up at a certain US Government Agency
i'm JK Benites. I like the music, i love the rock N metal, i'm a person that like stranges things, like adredaline, be good with friends, make new things... i play the guitar, my guitar is my life, with she i can show that i feel. i like the Pcs, too. ... Visit my prol in Hi5: http:// jkprotection.hi5.com City: Piura Hometown: Piura
Compliance
Angry Birds
lulz
Kill Chain
DFIR
Cyberwar
APT
Introduction Disclaimer Types of Mobile Devices Platform Architectures ARM Primer Malware on Mobile Static Analysis Dynamic Analysis Conclusion Q&A
Disclaimer
Standard legal-mumbo jumbo. You have the right to remain silent. Anything you say or do can and will be used against you in a court of law. You have the right to an attorney. If you cannot afford an attorney, one will be appointed to you. Prohibition on Reverse Engineering, Decompilation, and Disassembly. You may not reverse engineer, decompile, or disassemble the SOFTWARE PRODUCT, except and only to the extent that such activity is expressly permitted by applicable law notwithstanding this limitation. The right of the people to be secure in their persons, houses, papers, and effects, against unreasonable searches and seizures, shall not be violated, and no Warrants shall issue, but upon probable cause, supported by Oath or affirmation, and particularly describing the place to be searched, and the persons or things to be seized. (2) Intentionally accesses a computer without authorization or exceeds authorized access, and thereby obtains (A) information contained in a nancial record of a nancial institution, or of a card issuer as dened in section 1602 (n) of title 15, or contained in a le of a consumer reporting agency on a consumer, as such terms are dened in the Fair Credit Reporting Act (15 U.S.C. 1681 et seq.); (B) information from any department or agency of the United States; or (C) information from any protected computer; I pledge allegiance to the ag of the United States of America, and to the republic for which it stands, one nation under God, indivisible, with liberty and justice for all Energy can be transformed (changed from one form to another), but cannot be created or destroyed.
Introduction Disclaimer Types of Mobile Devices Platform Architectures ARM Primer Malware on Mobile Static Analysis Dynamic Analysis Conclusion Q&A
Different Flavors
Blackberry
Q2 2011
Windows Mobile
Different Platforms
Same OS
Similar Platforms
Different OS
Introduction Disclaimer Types of Mobile Devices Platform Architectures ARM Primer Malware on Mobile Static Analysis Dynamic Analysis Conclusion Q&A
About
Platform Architecture is a high level overview of the way a complex system is implemented Understanding mobile system architecture is important to understanding how to Reverse Engineer on that platform
Android Architecture
IOS Architecture
IOS Frameworks
Cocoa UI Framework
Address Book UI Eventkit UI Gamekit iAd MapKit Message UI UIKit
Media Frameworks Assets Library AV Foundation Core Audio Core Graphics Core MIDI Core Text
Core Video
Image I/O
Media Player
OpenAL
OpenGL
Quartz Core
Core Services Frameworks Address Book CFNetwork Core Data Core Foundation Core Location Core Media
Core Telephony
Event Kit
Foundation
Mobile Core
Quick Look
Store Kit
SysConf
IOS Layer
Cocoa Touch Multitasking Printing Data Protection Push Notication File Sharing
Local Notication
Push Notication
P2P
View Controller
External Display
Core Services Layer Block Objects Grand Central Dispatch In-App Purchase SQLite XLM Support
Windows Mobile
Windows Mobile
Symbian
Blackberry
Blackberry classes net.rim.device.api.system
Application Interfaces Hardware Interfaces (SMS, Radio, Etc) Events Etc
Java classes
Error Handling Memory JVM MIDP CLDC etc
19
Error Handling
Introduction Disclaimer Types of Mobile Devices Platform Architectures ARM Primer Malware on Mobile Static Analysis Dynamic Analysis Conclusion Q&A
What is ARM
Most mobile and embedded devices run on a CPU architecture called ARM Advanced Risc Machine (ARM) (a/k/a Acorn RISC Machine)
Reduced Instruction Set Computer RISC emerged in the 1970s, the concept was simpler CPU instructions would increase performance Made possible by higher (than assm) level languages First chips emerged 1987
NE Not Equal CS Carry Set HS Unsigned High CC Carry Clear LO Unsigned Lower MI Minus or Negative Result PL Positive or Zero Result VS Overow VC No Overow HI Unsigned Higher LS Unsigned Lower GE Signed Greater or Equal LT Signed Less Than GT Signed Greater Than LE Signed Less Than or Equal LA Always
Memory Alignment
ARM/RISC requires aligned memory (impacts on exploit dev) Aligned memory requires padding
Conditional Execution
Top 4 bits of each instruction contain a condition code**
Thumb-State
Thumb state is designed to optimize code density by allowing the processor to enter a state that uses xed instructions of 16 bit size Thumb == 16bit mode Several different implementations of Thumb modes exist depending on processor
Thumb Thumb2 (additional features/instructions)
32bit unconditional instructions
Jazelle
Direct Bytecode eXecution (DBX) feature supporting Java byte code execution Initiated using the Branch and eXchange to Java (BXJ) instruction
ARM Registers
ARM 16 general purpose registers Named R
R0 - R15 R0 - Argument1/Return Value/Temporary Register R1 - Argument2/second 32 bits of return value (optional)/Temporary Register R2/R3 - Arguments/Temporary Registers R4-R10 Permanent Registers R11 ARM Frame Pointer/Permanent Register R12 Temporary Register R13 Stack Pointer/Permanent Register R14 Link Register/Permanent Register (Return Address stored here) R15 Program Counter CPSR Current Program Status Register
Upper four bits contain conditional ags: Negative, Zero, Carry, oVerow Additional control codes in lower 8 eg: Thumb Instruction Set, Operating Mode Etc SPSR Saved Program Status Register (Exception modes)
CPSR
31 30 29 28
M 4
M 3
M 2
M 1
M 0
Operating Mode
Operating Modes
User: This mode is used to run the application code. Once in user mode the CPSR cannot be written to and modes can only be changed when an exception is generated. FIQ: (Fast Interrupt reQuest) This supports high speed interrupt handling. Generally it is used for a single critical interrupt source in a system IRQ: (Interrupt ReQuest) This supports all other interrupt sources in a system Supervisor: A protected mode for running system level code to access hardware or run OS calls. Abort: If an instruction or data is fetched from an invalid memory region, an abort exception will be generated Undened Instruction: If a FETCHED opcode is not an ARM instruction, an undened instruction exception will be generated.
Exception Modes
Exceptions occur for three possible reasons
Executing an Instruction (e.g.: Bad Instruction) Side effect of executing and instruction (e.g.: fetching from invalid memory) Exception unrelated to execution (e.g.: Interrupt)
Exception Flow
Switch to Processor to Privileged Mode PC+4 -> LR SPSR == CPSR Interrupts Disabled PC == Exception Vector Address
ARM Instructions
Branching Instructions
B, BL, BX, BLX, BXJ
Arithmetic
ADD, ADC, SUB, RSB, SBC, RSC
Bitwise Operations
ASR, LSR, LSL, ROR, RRX
Logical Operations
AND, ORR, EOR, BIC, ORN
Comparisons
CMP, CMN
Data manipulation
MOV, MVN, MOVT
Branching
B = Branch Branch can include condition BL - Branch with Link
Calling a routine PC+4 -> LR SubRoutine Address -> PC Return PC -> LR
BX/BLX = Branch eXchange Instruction (Switch between Thumb and ARM Mode)
SUBS R11, SP, #0x12 ; Status Flags Set SUBS <Destination> Operand1, Operand2 (optional)
Introduction Disclaimer Types of Mobile Devices Platform Architectures ARM Primer Malware on Mobile Static Analysis Dynamic Analysis Conclusion Q&A
Malware On Mobile
Lots of devices out there and malware is beginning to target these devices which in addition to everyday life are quickly invading the corporate network - Oh noes! Malware on mobile has a few places to live
Mobile Application (User land) Mobile Platform/OS (Kernel land) Other (SIM chip, Bootloader, Baseband, etc)
Detection/Prevention is difficult do to limited security tools (Mobile Device Management) So many different platforms this makes malware tracking and analysis a moving target
Attacker Vectors
Mobile malware can originate in different locations
AppStore Malware
Google Appstore 3rd Party Appstores iTunes AppStore etc
Attack Payload
Drive-by (Web attack) Spearphish/Social Engineering mdot seeding (m.mydomain.com)
Flashlight App
July 2010 Handy Light 15 Year Old Nick Lee Standard ash light app
if you include tethering
Nickispy
July 2011 Nickispi trojan is detected with low occurance SMS Command and control Records all voice calls to: /sdcard/shangzhou/callrecord/ Exls calls to jin.56mo.com
Dog Wars
August 2011 Kage games releases Dog Wars Beta code circulated on Warez sites Modied apk contains class rabbies Rabbies generates SMS message to contacts
"I take pleasure in hurting small animals, just thought you should know that"
SandBoxes
Access Control System/Proles == Sandbox ...in computing, sandboxes should be applied broadlyto all apps, ideally ensuring that they cannot cause much harm if they get compromised. -Apple
User Land
My Application
SandBox SubSystem
System
User Mode Calls
Kernel
Sandbox Kernel Component
No Kernel Land
yes
Code Signing
Ensure that if an app is signed and this is validated by the appstore, it *should* be safe Asymmetric Cryptographic Systems Reverse Engineering Challenge
Primarily impacts IOS due to iTunes distribution mechanism IPA - more on static analysis
Sample Collections
Contagio Mobile Malware Mini-dump
http://contagiominidump.blogspot.com/
Searching google: site:.cn letype:apk == win Searching google: site:.cn letype:jad Etc
Mobile Packages
Blackberry - JAD/COD WinMo - CAB (Cabinet Archive) Android APK Contains: AndroidManifest.xml META-INF classes.dex res/ resources.arsc iPhone/iPod/iPad IPA Contains: iTunesMetadata.plist iTunesArtwork Payload/<Application Name>.app Symbian SiS/SiSX Contains: private/ resource/ sys (/bin/(application name>.exe) iOS Malware packages may be designed for jailbroken phones, this is typically a more realistic attack vector to avoid vendor detection - this will be manifested as a gzipped package Typically these les are compressed and contain a manifest of some form and binary executable code
Device Forensics
Device forensics can assist in identifying malicious applications Blackberry - Look for .cod les that shouldnt be there IOS - Most malware requires jailbreak, this will generally leave forensics artifacts such as Cydia Android - Harvest apk les from OS, unfortunately the location of an APK can vary based on a number of factors Symbian/WinMo/etc
Introduction Disclaimer Types of Mobile Devices Platform Architectures ARM Primer Malware on Mobile Static Analysis Dynamic Analysis Conclusion Q&A
About
Static analysis analyzes something in a non-executing state Little danger of compromise Different approaches depending on system
Meta Data Extraction:
Strings Dump Manifest File
Android: DeCompilation, different approach due to Davlik EXecutable (DEX), this can reproduce nearly compilable code IOS/Symbian/WinMO: IDA Pro/Hex-Rays DeCompiler BBerry:Coddec (Good luck)
Tools
IDA Pro (www.hex-rays.com/) HexRays ARM Decompiler (www.hex-rays.com/) Dex2jar (code.google.com/p/dex2jar/) Sisxplorer (www.symbian-toys.com/sisxplorer.aspx) AXMLPrinter2.jar Apktool.jar Coddec
Cheat Sheet
Operating System iOS Android Symbian WinMO Blackberry Static Analysis Tool Strings, IDA Pro AAPT, Dex2Jar, JD-GUI Strings, IDA Pro Strings, IDA Pro Coddec
Encryption/Signing
Android Applications are signed by the developer Apple applications are signed by the developer, applications obtained via iTunes generally have an encrypted component courtesy of FairPlay DRM
Detection can be accomplished by unpacking the ipa and using the Apple object tool (otool)
Symbian packages may be signed, in some cases they are not and the user can sign using something like Symbiansigned.com Blackberry .cod les are signed and utilize the Rimm cryptographic package Windows Mobile has two different signing mechanisms depending on distribution method
Windows Marketplace Method Windows Mobile Code Signing via Verisign
Obfuscation
Various obfuscation techniques are available for mobile applications
Proguard (http://proguard.sourceforge.net/#) - Java Obfuscator Android and probably Blackberry Objective C (iOS) manual techniques, which might be optimized out by compiler dotfuscator, a commercial solution from PreEmptive Solutions is typically used for obfuscating Windows Mobile Not very common
Obfuscation varies on the available platforms and is not widely used, though increasingly Android malware seems to be using it Developer.Android.Com recommends the use of ProGuard and mentions it is integrated into build system
Package Contents
Packages in general contain graphics images resourced by the application Various conguration les either in a binary format or text
The conguration les contain lots of useful information about the application you are reversing
Binary executables (The application) may be spread across different les depending on the mobile platform
WinMo may have an installer exe and several executables The application functions may be spread across different binaries to limit memory footprint
Package Analysis
Most packages can be decompressed and analyzed with zip or other commerical open source compression utilities Windows Mobile uses Cabinet les thus requiring cabextract Symbian .sis les requires special tools to extract (e.g.: sisxplorer)
Registration
Resource Files
$ strings malware.exe EPOC *}OK 15XLeaveException 11CSMSHandler 19MMsvSessionObserver 15CCommController 19MNotifyCommObserver 19CGpsPositionRequest 15CContactManager 18MContactDbObserver 8CIMEIApp 8CIMSIApp 12CCallHandler 17CRemoteSmsReciver c:\data\loc.txt 15CDeviceLocation APGRFX{000a0000}[10003a3c].DLL CNTMODEL{000a0000}[10003a71].DLL COMMSDAT{000a0000}[10204ddb].DLL ESTLIB{000a0000}[10003b0b].DLL ... http://***REDACTED***/servicerequest.php Malware Client 17MHTTPDataSupplier 24MHTTPTransactionCallback 8CIMEIApp 8CIMSIApp 21TRegistrationItemdata
Binary Files
$ strings *.0* !This program cannot be run in DOS mode. RichA .text `.rdata @.data .pdata @.rsrc @.reloc J",K =L9o< FRSDSO> c:\Dev\malware\Windows Mobile 5.0 Pocket PC SDK (ARMV4I)\Release\IE.pdb COREDLL.dll CoTaskMemAlloc ...
Resource Files
Binary Files
otool -l malware.app |grep LC_ENCRYPTION_INFO cmd LC_ENCRYPTION_INFO cmdsize 20 cryptoff 4096 cryptsize 434176 cryptid 1 -o~*h cmd LC_ENCRYPTION_INFO AOQa cmdsize 20 qtLw cryptoff 4096 x1)k cryptsize 442368 ^^S' cryptid 1 6L`j ^Lo+8 6,(p& Aa0W << Encrypted 1`7$_9f [F];3 Bd@b Ee ^FJ0 EYC/ <^LhT iDV!q {'L+H ^k)+ ...
:(
Plist Files
Binary Files
MyApp
MyApp
MyApp
:)
Plist Files
Binary Files
Plist Files
Binary Files
Disassembly
Remember that our disassembly will be for ARM Beyond the difference in the instruction set the primary thing to be cognizant of is when the application has switched to Thumb-mode
MOVLS R0, R4 MOVLS R1, SP BLS sub_BF40 CMP R4, #4 BNE sub_8000 MOV R0, SP LDR R4, [SP,#arg_10] TST R4, #0x20 LDRNE R1, [SP,#arg_50]
Decompilation - HexRays
Works as expected :D Automatic Thumbswitch (you may need to go manual if something looks wrong)
int __fastcall sub_8010(int a1, int a2) { int v2; // r4@1 int v3; // r5@1 int v4; // r0@1 v2 = a2; v3 = a1; *(_DWORD *)(a2 + 60) = 0; v4 = UserHeap::SetupThreadHeap(); if ( !v4 ) v4 = sub_BF38(*(_DWORD *)(v2 + 8), *(_DWORD *)(v2 + 12), v3); return User::Exit(v4); }
myHandle = Loadlibrary(DLL.dll)
IOS
Objective C is detected by IDA This can be a little off putting at rst but the analysis by IDA is very nice to have for parsing the structures
objc_msgSend(*(void **)&v2->UIViewController_opaque[*(_DWORD *)dword_7860], "setHidden:", 1); objc_msgSend(*(void **)&v2->UIViewController_opaque[*(_DWORD *)dword_7880], "setHidden:", 1); objc_msgSend(*(void **)&v2->UIViewController_opaque[*(_DWORD *)dword_788C], "setHidden:", 1);
DeCompiling Android
Different approaches are possible, this is one Tools:
Dex2Jar (http://code.google.com/p/dex2jar/) multiple tools for converting DEX to Java Class Eclipse (http://www.eclipse.org) - Opensource Integrated Development Environment (IDE) Android SDK (http://developer.android.com/sdk/) - Android toolchain for developers JD-GUI (http://java.decompiler.free.fr/?q=jdgui) - Java DeCompiler Other decompilers: JAD, Mocha, JadClipse, etc
Basic premise:
Unpack APK (Not required to DeCompile but contents may be interesting) Convert DEX to Java using Dex2Jar Decompile using JD-GUI
Dex2Jar
$ sh ../dex2jar.sh malware.apk dex2jar version: translator-0.0.9.7 dex2jar malware.apk -> malware_dex2jar.jar Done. $
JD-GUI
Where to start?
Depends Android Asset Packaging Tool (AAPT) - from SDK will decode the contents of the AndroidManifest.xml inside of the APK launchable-activity: name= package: name='kagegames.apps.DWBeta' versionCode='18' versionName='0.981'
sdkVersion:'4' targetSdkVersion:'9' uses-permission:'android.permission.VIBRATE' uses-permission:'android.permission.INTERNET' uses-permission:'android.permission.ACCESS_COARSE_LOCATION' uses-permission:'android.permission.READ_PHONE_STATE' uses-permission:'android.permission.SEND_SMS' uses-permission:'android.permission.WRITE_SMS' uses-permission:'android.permission.READ_CONTACTS' uses-permission:'android.permission.RECEIVE_BOOT_COMPLETED' application-label:'Dog Wars - Beta' application-icon-160:'res/drawable-hdpi/icon.png' application-icon-240:'res/drawable-hdpi/icon.png' application: label='Dog Wars - Beta' icon='res/drawable-hdpi/icon.png' launchable-activity: name='kagegames.apps.DWBeta.DogWars' label='Dog Wars - Beta' icon='' uses-feature:'android.hardware.location' uses-feature:'android.hardware.location.network' uses-feature:'android.hardware.telephony' uses-feature:'android.hardware.touchscreen' uses-feature:'android.hardware.screen.landscape' uses-feature:'android.hardware.screen.portrait' main app-widget other-activities other-receivers other-services supports-screens: 'normal' 'large' 'xlarge' supports-any-density: 'true' locales: '--_--' densities: '160' '240'
Introduction Disclaimer Types of Mobile Devices Platform Architectures ARM Primer Malware on Mobile Static Analysis Dynamic Analysis Conclusion Q&A
About
Dynamic analysis on mobile platforms is difficult Options for analysis are emulator or real hardware device
Emulators are clunky and detectable Real Hardware is expensive Either way potentially detectable that the device is being debugged
Emulators
iOS
Simulator package comes with xTools Limited capability to install Application and difficult to jailbreak iEmu is Qemu emulator for iOS (http://www.iemu.org/index.php/Main_Page) supports debugging :D
Android
Android SDK contains very functional emulator Supports control from host including installation of arbitrary packages, and fuzzing user input/ behavior Possible to build automated sandbox very easily (Ive done this in python)
Windows Mobile
Requires Visual Studio (denitely works with VS10) and platform SDK Supports debugging via Visual Studio
Symbian
Depends on hardware platform targeted S60/N97 Part of SDK IDA supports
Blackberry
Emulator is part of the SDK (painful on non-windows) Supports on-device debugging or emulator debugging
Theory
Dynamic analysis on mobile platforms is dependent on the platform and target Analysis
Fire up an emulator in a controlled environment install package (via web/appstore/manual) attach debugger launch targeted application simulate input from user dump logs (capture traffic if network enabled) refresh the emulator*
Demo time
Introduction Disclaimer Types of Mobile Devices Platform Architectures ARM Primer Malware on Mobile Static Analysis Dynamic Analysis Conclusion Q&A
Conclusion
Reversing on mobile is not too different than on conventional platforms ARM instruction set is very different than what we may be used to Plenty of (mal)code sources out there with some creative googling Static analysis is more or less the same
iOS Fairplay exception
Dynamic analysis requires a little more effort than ring up a windows virtual machine Instrumentation of debugger is a little harder Reverse engineering mobile applications is fun :D
Introduction Disclaimer Types of Mobile Devices Platform Architectures ARM Primer Malware on Mobile Static Analysis Dynamic Analysis Conclusion Q&A
Questions?
Adam Meyers
Resources
http://developer.apple.com/library/ios/#documentation/Miscellaneous/Conceptual/iPhoneOSTechOverview/Introduction/ Introduction.html#//apple_ref/doc/uid/TP40007898-CH1-SW1 http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0489c/Cihjffga.html http://infocenter.arm.com/help/topic/com.arm.doc.qrc0001l/QRC0001_UAL.pdf http://simplemachines.it/doc/arm_inst.pdf ftp://ftp.cs.man.ac.uk/pub/apt/peve/PEVE05/Slides/05_Thumb.pdf http://developer.apple.com/library/ios/#documentation/Security/Conceptual/Security_Overview/SecuritySvcs/ SecuritySvcs.html#//apple_ref/doc/uid/TP40002650-SW1 http://dl.packetstormsecurity.net/papers/general/apple-sandbox.pdf http://developer.android.com/guide/topics/security/security.html http://apttech.wordpress.com/2011/12/30/ipa-les-apples-proprietary-format-for-archive-les-for-iphone-applications-usesapples-fairplay-drm-technology/ http://developer.android.com/guide/appendix/glossary.html http://code.google.com/p/dex2jar/wiki/Faq http://hackulo.us/wiki/IOS_Cracking http://www.slideshare.net/JBollinger/code-obfuscation-for-android-wp7 http://msdn.microsoft.com/en-us/windowsmobile/dd569132 http://www.jetbrains.com/decompiler/ http://developer.apple.com/library/ios/#documentation/Xcode/Conceptual/ios_development_workow/00About_the_iOS_Application_Development_Workow/introduction.html http://library.developer.nokia.com/index.jsp?topic=/Java_Developers_Library/GUID-42DE9C15-99C4-42BAA436-8595AF265CE7.html