ios hacking: advanced pentest & forensic techniques

60
Author(s): Ömer Coşkun & Mark de Groot iOS Hacking: Advanced Pentest & Forensic Techniques The supreme art of war is to subdue the enemy without fighting. Sun Tzu

Upload: oemer-coskun

Post on 17-Dec-2015

57 views

Category:

Documents


7 download

DESCRIPTION

iOS Hacking: Advanced Pentest & Forensic Techniques

TRANSCRIPT

  • Author(s): mer Cokun & Mark de GrootiOS Hacking: Advanced Pentest & Forensic Techniques The supreme art of war is to subdue the enemy without fighting. Sun Tzu

  • $ whoami

    mer Cokun (@0xM3R) BEng. Computer Science Research Assistant in Quantum Cryptography & Advanced Topics in AI

    2

    Industry ExperienceKPN CISO , Ethical HackingVerizon Threat & Vulnerability ManagementIBM ISS Threat Intelligence

    Interests Algorithm Design, Programming, Cryptography, Reverse Engineering, Malware Analysis, OS Internals, Rootkits

    Mark de Groot (@markos1979) Industry ExperienceKPN CISO , Ethical Hacking

    InterestsProgramming, Cryptography, Reverse Engineering, Software Explotation, CTF, Rfid, SDR

  • Outline

    OverviewMotivationiOS Security ArchitectureApplication Sandbox and SandBox ProfilesFile System EncryptioniOS Application Reverse EngineeringiOS 64 bit App Static/Dynamic AnalysisHunting for RSA KeysiOS Application Penetration TestingApplication Communication InterceptionAtomizing PentestingQ/A

    Questions ?

    3

  • Motivations4Analyze existing security mechanism on iOS platform and circumvention techniques Automate and speed up mobile penetration testsSurveillance implants shifted focus to mobile devicesMobile applications are evolving and tied to monitory: iOS Mobile Payments, Paypal SDK etc.iOS Rootkits are not only a theory anymoreReverse Engineering on ARM Environment is Fun!

  • iOS Security Architecture5

    Every app on iOS requires signing informationSignature information within LC_CODE_SIGNATURESHA1 signature verification (memory pages)

    iOS System SecuritySecure BootChain : components signed by AppleSystem software authorization: Firmware downgrade protectionSecure Enclave: Apple A7 processors memory encryption TouchID: PassCode ReplacementKeyBags: Used for system,backup, iCloud Backups

  • iOS Security Architecture6

    http://www.cl.cam.ac.uk/techreports/UCAM-CL-TR-818.pdf

  • How does iOS SandBox Work?7

    Source: http://dl.packetstormsecurity.net/papers/general/apple-sandbox.pdf

  • How does iOS SandBox Work?8

  • How does iOS SandBox Work?9

    Sample SandBox Usage:

    iOS Sandbox Profiles (Documented)kSBXProfileNoInternet kSBXProfileNoNetworkkSBXProfileNoWrite kSBXProfileNoWriteExceptTemporarykSBXProfilePureComputation

    iOS Sandbox Profiles (Undocumented)sandbox-compilerdmDNSResponderapsdAppleDiagsPasteBoardContainerMobileSafariMobileMailMobileMaps

  • File Encyption Mechanism Every file encrypted with a unique keyData Protection engine creates each time AES CBC 256-bit key and SHA-1 hash per fileFile key stored within the file metadata Metadata of all files in the file system is encrypted with a random key (iOS 1st installation)Per file key unwrapped from Class Key, then supplied to AESengine

    iOS : File System Encryption10

  • iOS : File System Encryption (contd)11File Protector with NSData:File Protector with NSFileManager:

    File API ClassNsFileProtectionNoneNsFileProtectionCompleteNsFileProtectionCompleteUnlessOpenNsFileProtectionCompleteUntilFirstUserAuthentication

    Security AttributeskSecAttrAccessibleWhenUnlockedkSecAttrAccessibleAfterFirstUnlockkSecAttrAccessibleAlwayskSecAttrAccessibleWhenUnlockedThisDeviceOnlykSecAttrAccessibleAfterFirstUnlockThisDeviceOnlykSecAttrAccessibleAlwaysThisDeviceOnly

  • iOS : File System Encryption (contd)Passcode can be brute-forcedOpen Source and Commercial Backup Decryptors

    12

    Escrow KeyBag Location/private/var/db/lockdown/

    iTunes Backup Location~/Library/Application\ Support/MobileSync/Backup/

  • iOS : Macoff File Structure13struct segment_command_64 { uint32_t cmd; uint32_t cmdsize; char segname[16]; uint64_t vmaddr; uint64_t vmsize; uint64_t fileoff; uint64_t filesize; vm_prot_t maxprot; vm_prot_t initprot; uint32_t nsects; uint32_t flags; };https://developer.apple.com/library/mac/documentation/DeveloperTools/Conceptual/MachORuntime/index.html

  • pentestBox:/private/var/mobile/Applications/2587B469-0147-4793-86CE-B41A1C4468DC/banking.app root# otool -l BankingApp| grep cryptcryptoff 16384cryptsize 835584cryptid 1Decrypting Binaries (32-bit)14 cryptoff 16384 -> 0x4000 cryptsize 835584 -> 0xCC000 0x4000 (vm address) + 0x4000 (crypt off) = 0x8000 0x4000 (vm address) + 0x4000 (crypt off) + 0xCC000 (crypt size) = 0xD4000 (gdb) dump memory dump.bin 0x8000 0xD4000
  • pentestBox:/private/var/mobile/Applications/2587B469-0147-4793-86CE-B41A1C4468DC/banking.app root# otool -l BankingApp| grep cryptcryptoff 16384cryptsize 835584cryptid 1Decrypting Binaries (64-bit)15 cryptoff 16384 -> 0x4000 cryptsize 835584 -> 0xCC000 0x4000 (vm address) + 0x4000 (crypt off) = 0x8000 0x4000 (vm address) + 0x4000 (crypt off) + 0xCC000 (crypt size) = 0xD4000 (lldb) memory read --outfile /tmp/dump.bin binary 0x8000 0xD4000
  • Getting the Debugger running16 All you need are stored under the Xcode IDE directories Obtain the debug server binary$ hdiutil attach /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/7.1/DeveloperDiskImage.dmg

  • Create an entity file for debugserver binary signing with following contentGetting the Debugger running 17Sign your debugserver binaryand upload it to jailbroken iOS pentest device

  • Attach target binary for remote debuggingGetting the Debugger running 18Make sure correct SDK path selected and connect to device:

  • Stopped thread list available if debuggger connect is made correctlyDebugging x64 iOS App19

  • Reversing iOS should be easy in an ideal world : Malware reversers would know what I mean :)Reversing iOS Apps 20

  • IDA Pro correctly resolves the function names as well as the cross references.Reversing iOS Apps: Sainte Ida de Louvain 21

    Source: https://www.hex-rays.com/products/ida/

  • Check for interesting function calls as all the imports are correctly resolved.Reversing iOS Apps: Dealing with Crpyto22

  • It seems the application evaluates the certificate here.Reversing iOS Apps: Dealing with Crypto23https://developer.apple.com/library/mac/documentation/Security/Reference/certifkeytrustservices/index.html

    Check the function prototypes and the definition on Apple Dev.

  • Data content is being encrypted using public key before sending it to server.Reversing iOS Apps: Dealing with Crypto24

    Calling Convention : C++ObjectPointer->Function(parameters)

    Calling Convention : Objective C[ObjectPointer Function:parameters]

  • Reversing iOS Apps: Hunting for Public Key25The following function evaluates the certificate .Check the function prototypes and the definition on Apple Dev.https://developer.apple.com/library/mac/documentation/Security/Reference/certifkeytrustservices/index.html

  • 26Cross-references definitely help.So do the constants and the debug strings. Reversing iOS Apps: Hunting for Public Key

  • 27Preparation for file encryption is literally being done here.Reversing iOS Apps: Hunting for Public Key

  • Reversing iOS Apps: Hunting for Public Key28Short cheat sheet on LLDB for GDB junkies.

    LLDB Command(lldb) memory read --outfile /tmp/mem.bin --binary 0x1000 0x2000(lldb) disassemble --frame(lldb) di -f(lldb) disassemble --start-address 0x1eb8 --count 20(lldb) image list

    GDB Command(gdb) dump memory /tmp/mem.bin 0x1000 0x2000(gdb) disassemble(gdb) x/20i 0x1eb8(gdb) info shared

  • Reversing iOS Apps: Hunting for Public Key29Preparation for file encryption is literally being done here.

  • 30I hope its clear to everyone whats happening here and the purpose of the function. Reversing iOS Apps: Hunting for Public Key

  • How to Reversing on iOS Env?31

  • Reversing iOS Apps: Hunting for Public Key32Set breakpoint to target function and then run until private keys are pushed into memory.Dump the memory to a writable location by LLDB debugger .Memory dump should contain the data we were looking for.

  • iOS Apps Penetration Testing 33https://www.owasp.org/index.php/OWASP_Mobile_Security_Project#tab=Top_10_Mobile_Risks

  • iOS Apps Penetration Testing 34https://www.owasp.org/index.php/IOS_Application_Security_Testing_Cheat_Sheet

  • iOS Apps Penetration Testing: Network Traffic Analysis 35https://www.wireshark.org/

  • iOS Apps Penetration Testing: Network Traffic Analysis 36Cacoa Packet Analyzer:www.tastycocoabytes.com/cpa/Appeals to MAC funs; unlike WireShark, it doesnt require additional libraries such as Quartz to be installed.

  • SSL Interception: Function Hooks37Standard SSLRead function provided by iOS SDK .iOS Dev Center:https://developer.apple.com/library/mac/documentation/Security/Reference/secureTransportRef/

  • SSL Interception: Function Hooks38Standard SSLWrite function provided by iOS SDK .iOS Dev Center:https://developer.apple.com/library/mac/documentation/Security/Reference/secureTransportRef/

  • SSL Interception: Function Hooks39How does a simple implementation of a function hook implementation on iOS envrionment looks like ?

    MSHookFunction ((void *) SSLWrite, (void *) _ hook_SSLWrite, (void **) & call_to_REAL_SSLWrite);

    MSHookFunction ((void *) SSLRead, (void *) _ hook_SSLRead, (void **) & call_to_REAL_SSLRead);

  • SSL Interception: Function Hooks40Create a hook that will intercept the SSL communication by by hooking application level read/write operation functions .

  • Hardware/Software Interception: Captain Hook Style Hacking41Captain Hook Style Hacking: Intercepts every function, keeps a copy of the content for herself, and then let the function continue as it was supposed to

  • SSL Interception: Function Hooks42

  • SSL Interception: Function Hooks43What if some people implements hook functions not only to see SSL traffic , but rather to reach hardware resources?

  • This is beyond the conspiracy theories: for real! 44

  • Iphone Rootkit CookBook45A The following code detects the audio stream.Source Code:Tripware:http://www.tripwire.com/state-of-security/vulnerability-management/creating-iphone-rootkits-and-like-the-nsas-dropout-jeep/

  • Iphone Rootkit CookBook (contd)46A Sample hook for enabling iPhone Microphone.Source Code:Tripware:http://www.tripwire.com/state-of-security/vulnerability-management/creating-iphone-rootkits-and-like-the-nsas-dropout-jeep/

  • Burp Suite: Atomize Everything47Burp Suite: http://portswigger.net/burp/

    More than standard application communication interception.

  • Burp Extensions: InstallationSuggested and Most Preferred Way : Burp Suite >Extensions > BAppStoreSome Extensions require Pro version (not because they discriminate poor but due to API/functional limitation ) Some Extensions have 3rd party dependencies or wrapper of 3rd apllication (e.g. PhantomJS, Radamsa etc)

    48

  • How Extensions Work (contd)49

    Class Name PurposeBurpExtenderTo write our own extensionBurpExtenderCallBacksTo pass to extensions a set of callback (register actions, mark)ICookieTo retrieve the domain for which the cookie is in scopeIHTTPRequestResponseTo retrieve and update details about HTTP messages.IScanIssueTo retrieve details of Scanner issuesIScanQueueItemTo retrieve details of items in the active scan queue.IScannerInsertionPointTo define an insertion point for use by active Scanner checks.IntroderPayloadProcessorTo obtain the name of the payload processor

  • Burp Extensions in a NutShell50

    Extension Name Purpose.NET BeautifierMakes VIEWState info human readableActiveScan++Extend passive scanning , path injection, shellshock etc.Blazer Generate and fuzz custom AMF messagesBradamsaGenerate intruder payload wisely CO2Set of useful tools : sqlmapper, user generator, prettier js, ascii payload processor etc.Logger++An extension of history feature in Burp; more detailed and comprehensiveSession Auth Help to identify privilege escalation vulnsWebInspect ConnectorNewly built, share results between burp and webinspect

  • Burp Extensions : Additional Scanner ChecksAdditional passive Scanner checks: Strict-Transport-Security, X-Content-Type, X-XSS-Protection. In other words, checks the modern browser security headers. 51

  • Burp Extensions : Session Auth To Identify authentication privilege escalation vulnerabilities. 52

  • Burp Extensions : CO253 Set of useful tools : sqlmapper, user generator, prettier js, ascii payload processor etc.

  • Fully Automated XSS Verification xssValidator extension of Burp Suite could be leveraged to fully automate XSS verification process. 54

  • Fully Automated XSS Verification55 Before starting the XSS verification process, we need to install at least one wrapper to support extension . Enable the payload extension after running wrapper.

  • Fully Automated XSS Verification56Enable payload processing unit for xssVerifier. Finally, create a grep-and-match rule for intruder.

  • Fully Automated XSS Verification57Content of xss.js

  • Fully Automated XSS Verification58Let the fun begin

  • 59

    Questions ?

  • 60

    **** System security: The integrated and secure software and hardware that are the platform for iPhone, iPad, and iPod touch.

    Encryption and data protection: The architecture and design that protects user data

    if the device is lost or stolen, or if an unauthorized person attempts to use or modify it.

    App security: The systems that enable apps to run securely and without compromising

    platform integrity.

    Network security: Industry-standard networking protocols that provide secure authentication and encryption of data in transmission.

    Each step of the startup process contains components that are cryptographically signed by Apple to ensure integrity and that proceed only after verifying the chain of trust. The Boot ROM code contains the Apple Root CA public key, which is used to verify that the Low-Level Bootloader (LLB) is signed by Apple before allowing it to load.

    On a device with an A7 or later A-series processor, the Secure Enclave coprocessor also utilizes System Software Authorization to ensure the integrity of its software and prevent downgrade installations. (Secure enclave)

    The Secure Enclave uses encrypted memory and includes a hardware random number generator. Its microkernel is based on the L4 family, with modifications by Apple. Communication between the Secure Enclave and the application processor is isolated to an interrupt-driven mailbox and shared memory data buffers.

    The keys for both file and keychain Data Protection classes are collected and managed in keybagsSystem keybag is where the wrapped class keys used in normal operation of the device are stored.Backup keybag is created when an encrypted backup is made by iTunes and stored on the computer to which the device is backed up

    *The MAC Framework defines four interfaces: the KPI from kernel services to the framework, the API from policy-agnostic user commands to the framework, the KPI between the framework and access control policy modules, and an additional debugging and tracingThe MAC Framework defines four interfaces: the KPI from kernel services to the

    framework, the API from policy-agnostic user commands to the framework, the KPI between

    the framework and access control policy modules, and an additional debugging and tracingAllowns co-existance of multipe implementations *The MAC Framework defines four interfaces: the KPI from kernel services to the framework, the API from policy-agnostic user commands to the framework, the KPI between the framework and access control policy modules, and an additional debugging and tracingThe MAC Framework defines four interfaces: the KPI from kernel services to the

    framework, the API from policy-agnostic user commands to the framework, the KPI between

    the framework and access control policy modules, and an additional debugging and tracing

    interface via DTrace probes not shown in this illustration.

    **kSBXProfileNoInternet TCP/IP networking is prohibited.kSBXProfileNoNetwork All sockets-based networking is prohibited.kSBXProfileNoWrite File system writes are prohibited.kSBXProfileNoWriteExceptTemporary File system writes are restricted to the temporary folder /var/tmp and the folder specified by the confstr(3) configuration variable _CS_DARWIN_USER_TEMP_DIR.kSBXProfilePureComputation All operating system services are prohibited.* The per-file key is unwrapped with the class key, then supplied to the hardware AES engine, which

    decrypts the file as it is read from flash memory.

    Every time a file on the data partition is created, Data Protection creates a new 256-bit

    key (the per-file key) and gives it to the hardware AES engine, which uses the key to

    encrypt the file as it is written to flash memory using AES CBC mode. The initialization

    vector (IV) is calculated with the block offset into the file, encrypted with the SHA-1 hash

    of the per-file key. *

    SData constants begin with NSDataWritingFileProtection.

    None The file is not protected and can be read or written at any time. This is the default value.

    Complete Any file with this setting is protected ten seconds after the device is locked. This is the highest level of protection. Files with this setting may not be available when your program is running in the background. When the device is unlocked, these files are unprotected.

    CompleteUnlessOpen Files with this setting are protected ten seconds after the device is locked unless theyre currently open. This allows your program to continue accessing the file while running in the background. When the file is closed, it will be protected if the device is locked.

    CompleteUntilFirstUserAuthentication Files with this setting are protected only between the time the device boots and the first time the user unlocks the device. The files are unprotected from that point until the device is rebooted. This allows your application to open existing files while running in the background.NSData and its mutable subclass NSMutableData provide data objects, object-oriented wrappers for byte buffers.

    *

    SData constants begin with NSDataWritingFileProtection.

    None The file is not protected and can be read or written at any time. This is the default value.

    Complete Any file with this setting is protected ten seconds after the device is locked. This is the highest level of protection. Files with this setting may not be available when your program is running in the background. When the device is unlocked, these files are unprotected.

    CompleteUnlessOpen Files with this setting are protected ten seconds after the device is locked unless theyre currently open. This allows your program to continue accessing the file while running in the background. When the file is closed, it will be protected if the device is locked.

    CompleteUntilFirstUserAuthentication Files with this setting are protected only between the time the device boots and the first time the user unlocks the device. The files are unprotected from that point until the device is rebooted. This allows your application to open existing files while running in the background.NSData and its mutable subclass NSMutableData provide data objects, object-oriented wrappers for byte buffers.

    *****Entitlements confer specific capabilities or security permissions to your app. These file(s) define properties that provide your application access to iOS features (such as push notifications) and secure data (such as the users keychain).****************Mark should speak from this slide on***Real time traffic analysis of jailbroken IOS communication*********

    ****BurpExtenderCallBacks getScannerChecks, getIntruderPayloadProcessors, load/unload extension

    *Action Message Format (AMF) is a binary format used to serialize object graphs such as ActionScript objects and XML, or send messages between an Adobe Flash client and a remote service, usually a Flash Media Server or third party alternativesMasher - can be used to guess passwords given a word list and a known password specification.

    **It simply replaces the session identifiers and compares the results whether it yielded any different.*It comes in handy especially bruteforcing weblogins etc.*******