100% found this document useful (1 vote)
400 views

IOS Appsec

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
400 views

IOS Appsec

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 309

Offensive Mobile

Exploitation & Reversing


Prateek Gianchandani Dinesh Shetty
[email protected] [email protected]
Twitter : @prateekg147 Twitter : @din3zh

© 2020 Prateek Gianchandani & Dinesh Shetty


WHO AM I?
• Twitter: @prateekg147
• Security Engineer @Careem

• Interested in Mobile and Embedded security

• Avid Blogger at highaltitudehacks.com

• Author of Damn Vulnerable iOS App (damnvulnerableiosapp.com)

• Spoken/Trained at Blackhat/Defcon/HIP/Phdays/Brucon etc

• GitHub: https://github.com/prateekg147

© 2020 Prateek Gianchandani & Dinesh Shetty


WHO AM I WITH?
• Twitter: @Din3zh

• Leads Mobile Security Testing CoE at Security Innovation

• Mobile and Embedded application pentesting for 10+ years

• Knowledgeable in all phases of the secure software development life


cycle (SDLC)

• GitHub: https://github.com/dineshshetty/

• Security Speaker and Trainer at multiple conferences such as BlackHat,


DefCon, OWASP, Brucon, ClubHack etc.

© 2020 Prateek Gianchandani & Dinesh Shetty


Security conferences

© 2020 Prateek Gianchandani & Dinesh Shetty


Tools we will be using
• Corellium (for iPhone emulation)
• MobileLabVM - Contains several tools and code that we will be
discussing throughout this course
• Genymotion (Android emulation)
• Frida (Dynamic instrumentation)
• Xcode with Xcode command line tools (optional) - Mac users
only
• Android Studio (optional) with platform tools installed

© 2020 Prateek Gianchandani & Dinesh Shetty


Mobile Security Introduction Mobile
Security Threat Landscape

Image Source: https://drawception.com/pub/panels/


2013/12-2/2ZaA95WLG4-8.png
© 2020 Prateek Gianchandani & Dinesh Shetty
Mobile Device
OS 3rd Party
Servers

Victim App
Remote Web Server

Remote
Other APPS Datastores

Other Devices
© 2020 Prateek Gianchandani & Dinesh Shetty
Mobile Security Introduction Mobile

Avenues of Attack
• Sensitive information stored in the APK/IPA client Binary
• Spywares (1-click or 0-click attacks)
• Vulnerabilities between APP <-> Server
• Vulnerabilities in Mobile Browsers
• Vulnerabilities related to data stored in application sandbox
• Vulnerabilities in the APP during runtime
• Vulnerabilities between APP <-> APP (IPC)
• Vulnerabilities in the Web Server
• Vulnerabilities in the Remote Datastores (AWS etc)

© 2020 Prateek Gianchandani & Dinesh Shetty


Mobile Security Introduction 

We are Here to Avoid This…

© 2020 Prateek Gianchandani & Dinesh Shetty


Mobile Security Introduction 

We are Here to Avoid This…

© 2020 Prateek Gianchandani & Dinesh Shetty


Mobile Security Introduction 

We are Here to Avoid This…

© 2020 Prateek Gianchandani & Dinesh Shetty


Mobile Security Introduction 

We are Here to Avoid This…

© 2020 Prateek Gianchandani & Dinesh Shetty


Mobile Security Introduction 

We are Here to Avoid This…

© 2020 Prateek Gianchandani & Dinesh Shetty


Course Content Walkthrough

© 2020 Prateek Gianchandani & Dinesh Shetty


WHY iOS ?
• Most popular mobile OS
• High impact for critical vulnerabilities
• iOS Security whitepaper very high-level
• Internals details mostly undocumented, except a few things
• Many undocumented daemons and Kexts
• Highest bounty offered by Zimperium for an exploit chain for
any mobile OS

© 2020 Prateek Gianchandani & Dinesh Shetty


iOS Boot sequence
• Bootrom – The first piece of code executed by the processor
on powering on. Read-only memory and embedded inside the
processor chip. A vulnerability in the Bootrom can compromise
the whole device.
• LLB – iBoot first-stage loader. Checks the signature of iBoot.
Only used in systems on or below A-9
• iBoot – Second stage loader. Responsible for signature
checking of the Kernel. Loads the kernel and OS. Code leaked
in Feb 2018 on Github.

© 2020 Prateek Gianchandani & Dinesh Shetty


iOS Boot sequence - Enforced security
• Kernel Patch Protection – For Devices below A10. Software
check enforced to check for kernel integrity protection at
random, runs at EL3. Checks the _TEXT and _DATA_const
section. Bypassed using KPPLess from @xerub and
@qwertyoruiopz by copying page tables.
• AMCC/KTRR – Hardware based Kernel integrity check.
Devices above A10. No random checks, marks memory as
read only. Works on physical memory using MMU.
• SEP – Secure enclave processor. Responsible for Touch ID
and other sensitive keys. Isolated from the Application
Processor. Used its own SEP OS. Encrypted RAM.
© 2020 Prateek Gianchandani & Dinesh Shetty
iOS Boot sequence

Bootrom `````
LLB iBoot Kernel

First piece of code to be executed.


Verifies and loads the kernelcache. Can
Contains Apple Root CA public key, Only in devices on or below A9. Loads
be changed with iOS update. Takes out
verifies whether iBoot bootloader is and verifies iBoot. If failure, enter DFU Loads the OS and filesystem.
KPP binary from kernel (below iPhone7)
signed by Apple. For devices above A9, (or recovery mode).
and loads it.
directly jump to iBoot. Immutable Code.

© 2020 Prateek Gianchandani & Dinesh Shetty


PRIVILEGE LEVELS - iOS

EL3 Secure Monitor (AMCC/KTRR or KPP)

EL2 Hypervisor (Not used in iOS)

EL1 Kernel + iBoot

EL0 UserSpace

© 2020 Prateek Gianchandani & Dinesh Shetty


XNU Kernel
• The kernel used by Apple as a part of the Darwin OS
• Hybrid kernel with components takes from the Mach Kernel
and FreeBSD (Story Time !!)
• Also uses the C++ API named IOKit for creating drivers
• Encrypted until iOS 10, after which Apple decided not to
encrypt it (for performance reasons!!)
• Kernel cache can be extracted from the OTA image or
jailbroken device
• Kernelcache = Kernel + Kernel Extensions

© 2020 Prateek Gianchandani & Dinesh Shetty


XNU SOURCES

• Code can be found at https://opensource.apple.com

© 2020 Prateek Gianchandani & Dinesh Shetty


XNU SOURCES
• iOS specific comes under “#if
CONFIG_EMBEDDED” and “#if
SECURE_KERNELS”
• Some code removed
• Some code PROHIBITED with ifdef, such
as for Apple Watch

© 2020 Prateek Gianchandani & Dinesh Shetty


Task
• Open the kernel source code iOS-PreCourse▸ XNU ▸
xnu-4903.221.2
• What does the BUILD directory contain ? Does it come with the
source code ?
• What does osfmk, bsd folder contain ? Where is the Kexts
source code ?
• An example script to build the kernel by @bazad -> https://
gist.github.com/bazad/654959120a423b226dc564073b435453

© 2020 Prateek Gianchandani & Dinesh Shetty


iOS 12 Symbols
• iOS 12 got stripped of all the symbols
• Except one kernel that leaked by mistake all the symbols
• jtool2 uses those symbols to identify the symbols of other kernelcaches.

© 2020 Prateek Gianchandani & Dinesh Shetty


iOS 12 Symbols

© 2020 Prateek Gianchandani & Dinesh Shetty


jtool2 symbolication

© 2020 Prateek Gianchandani & Dinesh Shetty


jtool2 symbolication

© 2020 Prateek Gianchandani & Dinesh Shetty


List all the sections

© 2020 Prateek Gianchandani & Dinesh Shetty


Task - 10 mins
• Open the MobileLabVM
• Get the kernel cache files from the Desktop/Kernelcache
folder
• Run the commands mentioned in the previous 4 slides

© 2020 Prateek Gianchandani & Dinesh Shetty


Reversing the Kernel (Hopper demo)

© 2020 Prateek Gianchandani & Dinesh Shetty


KERNEL EXTENSIONS
• Usually not open source
• Kernel extensions are signed by Apple
• Apple Mobile File Integrity (AMFI.kext) – Responsible for
code signing and checking of entitlements, works with MACF
• Mandatory Access Control Framework (MACF.kext) – A
framework for defining policies related to various actions
• Sandbox (Sandbox.kext)– Hooks all sandboxing operations
and decide whether to allow the action or not, works with
MACF

© 2020 Prateek Gianchandani & Dinesh Shetty


SANDBOXING
• Originally referred to as “Seatbelt”
• Enforces restriction of system calls, read/write of files etc
• Implemented by a separate Kernel Extension Sandbox.kext
• This kernel extension registers a lot of policies through MACF
• In iOS it is managed in user mode through a daemon named
containermanagerd
• Restrictions are mentioned in something known as a Sandbox profile
• Profiles are encoded in the Sandbox.kext but can be decoded
• Sandboxed apps are often referred to as “containerized” application

© 2020 Prateek Gianchandani & Dinesh Shetty


ENTITLEMENTS
• Entitlements define capabilities for the app
• When the developer adds a capability, it is added in an
entitlements.plist file
• Embedded in the binary and has a special slot in the code signature
• Used extensively internally by iOS
• AMFI hooks many sensitive operations using MACF and looks for
certain entitlements
• In a jailbroken device, one can self sign the binary with their own
entitlements
• Uber had a special entitlement once which allowed it to record the
screen of the app
• jtool can be used to sign binary with custom entitlements
© 2020 Prateek Gianchandani & Dinesh Shetty
IMP ENTITLEMENTS
• get-task-allow: Makes the application debuggable
• task_for_pid-allow: Lets the application get a task port of another process
using the task_for_pid() API
• platform-application: Required by binaries to run on the device. Kernels
checks with the TF_PLATFORM flag
• com.apple.system-task-ports: Required in iOS 11 to get task port of a
process
• com.apple.private.security.no-container – Undocumented, mostly
related to sandboxing
• com.apple.private.skip-library-validation – Don’t check for proper
signatures on dynamically loaded libraries

© 2020 Prateek Gianchandani & Dinesh Shetty


SYSDIAGNOSE ENTITLEMENTS

© 2020 Prateek Gianchandani & Dinesh Shetty


J’s ENTITLEMENT DATABASE

© 2020 Prateek Gianchandani & Dinesh Shetty


ENTITLEMENTS IN CODE SIGNATURE

© 2020 Prateek Gianchandani & Dinesh Shetty


Sandbox escape < 13.5 (Entitlements parsing)

Source: https://siguza.github.io/psychicpaper/

© 2020 Prateek Gianchandani & Dinesh Shetty


Task
• Connect to the Corellium machine
• Find launchd (find / -name *launchd*) and Dump the
entitlements of launchd (jtool2 --ent /sbin/launchd). What is the
process id of launchd ?
• Dump the entitlements of sysdiagnose, why does it have so
many entitlements ?
• Dump the entitlements of any application binary running on the
device. How do you find the application binaries on the device ?

© 2020 Prateek Gianchandani & Dinesh Shetty


CODE SIGNATURE
• The origin of the code – Verifying with public key confirms that it was
signed with private key
• Authenticity of the code – Any modification would break the digital
signature
• Integration with entitlements makes it hard to defeat code signing
• Apple extended Mach-O format to add the LC_CODE_SIGNATURE
load command
• Code signature is attached to the very last
• CDHash is the mega hash of all code directory hashes
• SHA1 used in previous versions until iOS 10, now SHA 256

© 2020 Prateek Gianchandani & Dinesh Shetty


CODE SIGNATURE
• Signing the whole binary can be a costly operation
• Each binary page is hashed individually
• SHA 256 is being used since iOS 10, SHA1 deprecated
• By default, code signing only in the text segment. Gives rise to data
only attacks

© 2020 Prateek Gianchandani & Dinesh Shetty


CODE SIGNATURE

© 2020 Prateek Gianchandani & Dinesh Shetty


CODE SIGNATURE

© 2020 Prateek Gianchandani & Dinesh Shetty


VIEWING CODE SIGNATURE

© 2020 Prateek Gianchandani & Dinesh Shetty


Task
• Open the Corellium VM
• Dump the code signature of any system binary (jtool2 --sig /
sbin/launchd)
• Dump the code signature of any installed application
• Dump the code signature of kernel cache (jtool2 --sig /System/
Library/Caches/com.apple.kernelcaches/kernelcache)
• Is there anything weird that you notice ?

© 2020 Prateek Gianchandani & Dinesh Shetty


Joker demo - List mach traps

© 2020 Prateek Gianchandani & Dinesh Shetty


Joker demo - List sys calls

© 2020 Prateek Gianchandani & Dinesh Shetty


List all the Kexts - iOS 11

© 2020 Prateek Gianchandani & Dinesh Shetty


Joker demo - Extract Kext - iOS 11

© 2020 Prateek Gianchandani & Dinesh Shetty


Joker in jtool2
• Joker is deprecated for latest iOS versions and combined as
part of jtool2

• Modern reversing tools like IDA Pro etc will automatically be


able to open Kexts for reverse engineering

© 2020 Prateek Gianchandani & Dinesh Shetty


KERNELCACHE ON DEVICE
• Prelinked kernelcache is located in /System/Library/Caches/
com.apple.kernelcaches/kernelcache

• Used by doubleh3lix created by @tihmstar


• Offsets usually hardcoded in many jailbreaks (not a good idea)

© 2020 Prateek Gianchandani & Dinesh Shetty


Intro to iOS applications
Types of iOS applications

• Native applications – Developed in Objective-C or Swift.


Deliver much better performance than web applications.

• Web applications – Developed in Html, CSS and


javascript. Run using Webkit.

• Hybrid applications – Combination of a web and native


application.

© 2020 Prateek Gianchandani & Dinesh Shetty


Binary Format
• An ELF or Mach-O binary format is organised into Mach Header,
Segments and its corresponding sections. (jtool2 -h /bin/ls)
• A segment can contain 0 or more sections
• Segments tell where it should be loaded into the virtual memory
along with the permissions, also specifies how many sections it
contains
• Sections are raw data that can be loaded into the memory or just
contain metadata about other sections
• Load Commands describes position of segments, symbol table,
dynamic symbol table etc. 

© 2020 Prateek Gianchandani & Dinesh Shetty


Binary Format
• The __TEXT Segment is Read Only (protected by patch
protection)
• The __DATA Segment is Read/Write (not protected by patch
protection, constant non constant data)
• The __DATA_CONST Segment is Read Only
• Often times, sections are used to hide malicious code.

© 2020 Prateek Gianchandani & Dinesh Shetty


Binary Format

© 2020 Prateek Gianchandani & Dinesh Shetty


PageZero segment
• Used for catching Null Pointer dereference vulnerabilities
• Reserves a large section at the beginning of the memory
• Attackers can’t place shell code in this memory
• Not mapped, just reserved , can’t be used and hence
safeguarded
• No 32-bit pointer can be valid

© 2020 Prateek Gianchandani & Dinesh Shetty


Implant loading malicious section from
binary file

© 2020 Prateek Gianchandani & Dinesh Shetty


Implant loading malicious section from
binary file

© 2020 Prateek Gianchandani & Dinesh Shetty


Hopper Demo !

© 2020 Prateek Gianchandani & Dinesh Shetty


iOS App Security

© 2020 Prateek Gianchandani & Dinesh Shetty


Objective-C
• Developed in 1984 by nEXT

• Taken over by Apple for iOS and Mac OS X

• Object Oriented , superset of C

• Used by Apple for iOS/OSX and also Cocoa , Cocoa Touch etc

• Provides a dynamic runtime (via a dylib injected into the process)

• Objective-C methods can be swizzled or class methods can be added


at runtime. Uses the core principle of message sending via the
objc_msgSend() runtime function
• All objects in Obj-C are pointers

© 2020 Prateek Gianchandani & Dinesh Shetty


O
Objective-C (continued)
• The objc_msgSend() function takes a target, a selector and a list of arguments.
For e.g
• [array insertObject:foo atIndex:2];
• will convert to
• objc_msgSend(array, @selector(insertObject:atIndex:), foo, 5);
• This concept is used when applying breakpoints and manipulating functions at
runtime
• Register x0 is target, x1 is selector and x2 onwards are the arguments
• You can set breakpoint and make any modifications
• In essence, each method call leads to a objc_msgSend() function call
• This is known as message dispatching

© 2020 Prateek Gianchandani & Dinesh Shetty


Objective-C (continued)

© 2020 Prateek Gianchandani & Dinesh Shetty


Objective-C (continued)
• Files with the extension .h are header files and .m are implementation
files. Every header file has a corresponding implementation file

• Methods starting with + are class methods and those starting with - are
instance or object methods.

© 2020 Prateek Gianchandani & Dinesh Shetty


Objective-C (continued)
MyObject *o = [[MyObject alloc] init];
MyObject *o = [[MyObject alloc] initWithString:myString];
NSArray *myArray = [NSArray arrayWithObjects:object1,object2,object3,nil];

Calling Methods

[self doSomething];
[MainViewController performTaskWithID:[NSNumber numberWithInt:1]];

© 2020 Prateek Gianchandani & Dinesh Shetty


Objective-C (continued) - method analysis

© 2020 Prateek Gianchandani & Dinesh Shetty


Objective-C (continued)
• Every class has a methods list

• This list is a dictionary, where the keys are the method name and the
value is a pointer to the methods implementation in memory
• This connection is determined at runtime rather than compile time

• It is possible to change the pointer to the implementation. This


technique is known as method swizzling
• The idea is to create a method in memory and replace the pointer of an
existing method with your new method
• We will discuss method swizzling in detail later in this course

© 2020 Prateek Gianchandani & Dinesh Shetty


Introduction to Swift
• Introduced in 2014. Object Oriented and Open Source https://github.com/
apple/swift
• Will replace Objective-C for iOS development ... eventually (Sure !!)
• Even without a single line of Objective-C code, every Swift app executes
inside the Objective-C runtime.
• This may not always be the case – with the release of Swift-only system
frameworks a full Swift runtime may appear.

© 2020 Prateek Gianchandani & Dinesh Shetty


Introduction to Swift
• The important thing is that instead of objc_msgSend() method call,
Swift classes operate with vtable (which contains the table of available
methods).
• vtables are created at compile time (when objc dispatch tables are
generated dynamically). Contain function pointers accessed by index
• This table contains functions pointers accessed by index, so it doesn’t
need to bind selector to implementation.
• Called static dispatch, decision is not left until runtime to pick an
implementation opposite of dynamic dispatch.

© 2020 Prateek Gianchandani & Dinesh Shetty


Swift – Continued
• From a security testing point-of-view, most of the stuff we’ll be doing will
be the same.
• The issues arise due to poor coding and design choices rather than the
language used.
• You might use the most secure of languages, however an incorrect
implementation of the libraries will still leave your code vulnerable
• We will be taking a black box testing approach, so language will not
matter.
• Main difference during Reverse Engineering.

© 2020 Prateek Gianchandani & Dinesh Shetty


Objective-C symbols

© 2020 Prateek Gianchandani & Dinesh Shetty


Swift symbols

© 2020 Prateek Gianchandani & Dinesh Shetty


Introduction to Swift - Reversing
• TheTarget:
• __T018hello_world_swift114ViewControllerC15mainButtonClickyypFTo
• __T - Indication that it is a Swift method
• 18hello_world_swift1 – Module name with length
• 14ViewController – Class name with length
• C – Indication that it is a function of a class
• 15mainButtonClick – Function name with length
• f – Function attribute
• T – parameters (zero in this case else T_)
• T_ - Indicates the return type
© 2020 Prateek Gianchandani & Dinesh Shetty
Reversing Swift Applications
Function Attributes Parameter Types
• c – Constructor function • a – Array
• C – Allocator function • b – Boolean
• d – Destructor function • c – Unicode Scalar
• D – Deallocator function • d – Double
• g – Getter function • f – Float
• f – Normal function • i – Integer
• s – Setter function • u – Unsigned Integer
• Q – Implicitly Unwrapped Optional
• S – String
• T – Tuple
• O - enum

© 2020 Prateek Gianchandani & Dinesh Shetty


Swift-demangle using xcrun

• Hopper has in-build demangling of functions

© 2020 Prateek Gianchandani & Dinesh Shetty


Some definitions
• Delegate - An object which gets notified when the object to which it is
connected reaches certain events or states.
• AppDelegate - Connected to the App, gets when the UIApplication
object reaches certain states. Can be used for some security events as
well, for e.g clearing pasteboard data when the app goes to
background
• View Controller - Manages a portion of your app's user interface as
well as all interactions. Think as if each screen is a different view
controller.
• Storyboard - Visual representation of the user interface of an iOS
application

© 2020 Prateek Gianchandani & Dinesh Shetty


Xcode
IDE for developing native iOS applications: https://

developer.apple.com/xcode/

© 2020 Prateek Gianchandani & Dinesh Shetty


iOS security model
• All app store apps are signed using apple, and protected by code
signing.
• All apps running on the device by the developer are signed by the
developer’s certificate.
• Every application runs inside a closed environment known as an
application sandbox.
• Apps inside the sandbox cannot access data from other apps, except
through certain mechanisms like protocol handlers.
• Unsigned/modified apps cannot be installed on a non-jailbroken device.
• Access to all resources (such as files, network sockets, IPCs, and
shared memory) are managed by the sandbox

© 2020 Prateek Gianchandani & Dinesh Shetty


iOS security model - continued
• Certain system calls such as mmap and mprotect are intentionally
broken in iOS to prevent attacks, for e.g setting +w is disallowed on a
+x segment (and vice versa)
• Apps are confined to access data to its own directory

• Access to hardware drivers are done through public frameworks

• Address space layout randomization (ASLR) provide address


randomisation, prevents against overflow and return-to-libc attacks
• The eXecute Never (XN) bit is used to mitigate code execution attacks

• Pages that are writable cannot be marked executable at the same time

© 2020 Prateek Gianchandani & Dinesh Shetty


Analyzing iOS apps
• IPA files are basically a zipped version of the app

• Change name to from DVIA.ipa to DVIA.zip and unzip the folder

• It creates a folder named Payload which contains a folder DVIA.app

• Inside DVIA.app, you can find the application binary

• Open the binary in Hopper to reverse it

• To repackage the binary, just compress the Payload folder and rename
it from Payload.zip to AppName.ipa. Depending on the JB device you
install, you might need to sign the app before installing.

© 2020 Prateek Gianchandani & Dinesh Shetty


Xcode Walkthrough

© 2020 Prateek Gianchandani & Dinesh Shetty


Task - 10 mins
• Find the IPA files under the folder iOS-PreCourse -> IPA folder
provided in the Pre-course downloadables
• Unzip the DVIA.ipa and DVIA-v2-Swift.ipa files to get to the
application binary
• Open these binaries in Hopper

• Dump the symbols for these binaries using jtool2

• Have a quick look at the source code for DVIA https://github.com/


prateek147/DVIA and DVIA-v2 https://github.com/prateek147/DVIA-v2

© 2020 Prateek Gianchandani & Dinesh Shetty


Binary Analysis - Security measures
• Position independent executable (PIE) - Loads the executable at
a different address each time. Apple support PIE for iOS apps by
default. There’s no hard requirement yet and non-PIE applications
are not rejected. Having ASLR means the code can't be a part of
ROP gadgets.

• Automatic reference counting (ARC) - Enabled autorelease of


objects. Protects against memory corruption vulnerabilities,
specially object use-after-free vulnerabilities.

© 2020 Prateek Gianchandani & Dinesh Shetty


Binary Analysis
• Stack smashing protection - Adds a known value to be placed on
the stack directly before the local variables. Protects the saved base
pointer, saved instruction pointer, and function arguments to be
overwritten. Detects buffer overflow attacks when stack is corrupted,
can terminate the app on detecting this. Protects against buffer
overflow attacks.

• It is recommended to have all these settings in your application before


submitting to the App store.

© 2020 Prateek Gianchandani & Dinesh Shetty


Checking for PIE - otool

© 2020 Prateek Gianchandani & Dinesh Shetty


Checking for PIE - jtool

© 2020 Prateek Gianchandani & Dinesh Shetty


Checking for Stack Smashing protection - otool

Presence of __stack_chk_fail and __stack_chk_guard symbols


confirms that the application is compiled with stack smashing protection.

© 2020 Prateek Gianchandani & Dinesh Shetty


Checking for ARC - otool

© 2020 Prateek Gianchandani & Dinesh Shetty


rabin2 - Get Binary Info

© 2020 Prateek Gianchandani & Dinesh Shetty


rabin2 - Find imports

© 2020 Prateek Gianchandani & Dinesh Shetty


rabin2 - list symbols

© 2020 Prateek Gianchandani & Dinesh Shetty


rabin2 - list sections

© 2020 Prateek Gianchandani & Dinesh Shetty


Task - 5 mins
• On your Ubuntu VM, head under the directory Desktop/DVIA-
Decrypted-Binary
• Run the commands for rabin2 mentioned in the earlier slides
• Check any similar options provided in jtool2

© 2020 Prateek Gianchandani & Dinesh Shetty


Touch ID/ Face ID
• Electronic fingerprint or face recognition feature

• 1 in 50000 chance that someone else can unlock your phone

• After 5 unsuccessful attempts, it is required to enter Passcode

• Can be implemented in Apps as well for authentication

• Can be bypassed when using insecure APIs (canEvaluatePolicy:)

• Data protected using Secure Enclave, and never leaves the device

• Data Stored using a mathematical representation in the Secure


Enclave, and hence can’t be reverse engineered

© 2020 Prateek Gianchandani & Dinesh Shetty


Secure enclave
• Separate co-processor independent from the AP (Application processor)
• Responsible for all cryptographic operations for Data Protection key
management Includes a hardware-based key manager
• Runs its own OS called SEPOS, and has its own kernel, drivers, services, apps
etc
• Secure boot mechanism and software update mechanism independent from the
AP
• Maintains integrity even if the Kernel is compromised
• SE creates the key, stores it and performs operations with it without ever leaving
it. Much better to store key there than storing in the keychain
• No plain text key in memory like keychain

© 2020 Prateek Gianchandani & Dinesh Shetty


Setting up an iOS pen testing
environment
What do you need?
• A jailbroken iOS device (or Corellium)
• Ubuntu VM
• Some tools that need to be installed on your jailbroken device
• Some tools installed on your Ubuntu VM
• Set up the device by running the script at http://damnvulnerableiosapp.com/
setupdevice.sh (Make sure to launch Cydia first if doing this for the first time in
a device)

© 2020 Prateek Gianchandani & Dinesh Shetty


setupdevice.sh
#!/bin/sh

apt-get -y update
apt-get -y install unzip
apt-get -y install mobilesubstrate
apt-get -y install python3

echo "deb https://cydia.akemi.ai/ ./" >> /var/mobile/Library/Caches/com.saurik.Cydia/sources.list


echo "deb https://build.frida.re ./" >> /var/mobile/Library/Caches/com.saurik.Cydia/sources.list
apt-get -y update

wget http://damnvulnerableiosapp.com/t.zip
unzip t.zip
cd iOS-Device-Tools/

cp jtool2 /usr/bin/ && cp keychain_dumper /usr/bin/ && cp debugserver /usr/bin/ && cp binbag /usr/bin/ && chmod +x /usr/bin/binbag && cp rop /usr/bin/ && cp vuln /usr/bi
chmod +x /usr/bin/keychain_dumper

apt-get -y --allow-unauthenticated install re.frida.server


apt-get -y --allow-unauthenticated install net.angelxwind.appsyncunified
apt-get -y --allow-unauthenticated install com.linusyang.appinst
apt-get -y --allow-unauthenticated install com.cannathea.afc2d-arm64

appinst DamnVulnerableiOSApp.ipa
appinst DVIA-v2-swift.ipa

frida-server -l 0.0.0.0 &

killall -9 backboardd

© 2020 Prateek Gianchandani & Dinesh Shetty


Address Sanitizer - Xcode
• The Address Sanitizer feature in Xcode can be used to do an initial check
for the following vulnerabilities in the iOS application
• Use of Deallocated Memory


• Deallocation of Deallocated Memory


• Deallocation of Nonallocated Memory


• Use of Stack Memory After Function Return


• Use of Out-of-Scope Stack Memory


• Overflow and Underflow of Buffers


• Overflow of C++ Containers


© 2020 Prateek Gianchandani & Dinesh Shetty


Enabling Address Sanitizer - Xcode

https://developer.apple.com/documentation/code_diagnostics/address_sanitizer/enabling_the_address_sanitizer

© 2020 Prateek Gianchandani & Dinesh Shetty


Task - 5 mins
• Look at the different options provided by Address Sanitizer

• Recommended reading - https://medium.com/


@cristianarielbarril/finding-runtime-bugs-using-xcode-9-
tools-43c0fa61654d

© 2020 Prateek Gianchandani & Dinesh Shetty


Homework - Day 1 (Part 1)
• Look at the following video to understand more about Address
Sanitizer https://developer.apple.com/videos/play/
wwdc2015/413/

• Read about the following bug - https://awakened1712.github.io/


hacking/hacking-whatsapp-gif-rce/

© 2020 Prateek Gianchandani & Dinesh Shetty


Jailbreaking for iOS app testing
• Remove limitations imposed by Apple
• Provides root level access to the device
• Install custom applications that don’t meet Apple’s compliance
requirements
• Gives ability to run self signed apps on the device.
• All code must be signed. In case of jailbroken devices, it can be used to run
self signed applications (non CoreTrust devices).

© 2020 Prateek Gianchandani & Dinesh Shetty


Disclaimer
• Having a jailbroken device is not necessary for testing iOS Apps https://
medium.com/securing/pentesting-ios-apps-without-jailbreak-91809d23f64e
• However, it makes the job easier and it allows us to use some automation tools
much more easily
• Ideally, it is good to have one Jailbroken device and one non-jailbroken device
with the latest iOS version

© 2020 Prateek Gianchandani & Dinesh Shetty


Task - 10 mins
• SSH to your Corellium device
• Explore the directory structure of the device.
• What is the difference between logging in as mobile user and root user ?
• See a list of the processes running on the device
• Find the location where the DVIA app is installed
• Find all the sqlite and db files located on the device
• Find location of iMessage database and Contacts database (Might not work
on a virtual device)

© 2020 Prateek Gianchandani & Dinesh Shetty


Solution
ps aux to view all processes
find / -name *.db to view all database files
find / -name *.sqlite to view all sqlite files
Run DVIA and run the command ps aux | grep DamnVulnerableIOSApp to view
location of the binary

© 2020 Prateek Gianchandani & Dinesh Shetty


Solution

© 2020 Prateek Gianchandani & Dinesh Shetty


Solution

© 2020 Prateek Gianchandani & Dinesh Shetty


Important directories

Source: https://blog.elcomsoft.com/2019/11/
ios-device-acquisition-with-checkra1n-jailbreak/

© 2020 Prateek Gianchandani & Dinesh Shetty


Signing apps - iOS App Signer
• Can be done with iOS App Signer

© 2020 Prateek Gianchandani & Dinesh Shetty


Signing apps - codesign using Apple certs

© 2020 Prateek Gianchandani & Dinesh Shetty


Sideloading apps - Cydia Impactor
• Requires a valid Apple Developer account
• Need to trust the developer explicitly once the application is installed

© 2020 Prateek Gianchandani & Dinesh Shetty


Sideloading apps - Xcode
• Requires a valid Apple Developer account
• Connect your device to your Mac and launch Xcode
• In Xcode go to Window -> Devices and Simulators
• Then just drag and drop the file into the apps section

© 2020 Prateek Gianchandani & Dinesh Shetty


Sideloading apps - Altstore (altstore.io)
• Doesn’t require a developer account

© 2020 Prateek Gianchandani & Dinesh Shetty


Installing on Jailbroken devices
• Add the source https://cydia.akemi.ai/ in Cydia
• Install AppSync unified
apt-get -y --allow-unauthenticated install net.angelxwind.appsyncunified
• Install appinst
apt-get -y --allow-unauthenticated install com.linusyang.appinst
• Use appinst to install apps
appinst DVIA-v2-swift.ipa

© 2020 Prateek Gianchandani & Dinesh Shetty


iOS File system
Ref: File system programming guide

© 2020 Prateek Gianchandani & Dinesh Shetty


Understanding the iOS filesystem
• Download a good file explorer utility like iExplorer or iFunbox

© 2020 Prateek Gianchandani & Dinesh Shetty


Understanding the iOS filesystem
• /bin—Contains essential command-line binaries. Typically, you execute these binaries
from command-line scripts.
• /dev—Contains essential device files, such as mount points for attached hardware.
• /etc—Contains host-specific configuration files.
• /sbin—Contains essential system binaries.
• /tmp—Contains temporary files created by apps and the system.
• /usr—Contains non-essential command-line binaries, libraries, header files, and other
data.
• /var—Contains log files and other files whose content is variable. (Log files are typically
viewed using the Console app.)

Source: https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/
FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html#//apple_ref/doc/uid/TP40010672-CH2-SW
© 2020 Prateek Gianchandani & Dinesh Shetty
iOS partitions

Why is the root partition not read only ?

© 2020 Prateek Gianchandani & Dinesh Shetty


Important - App Bundle vs Container
• APP BUNDLE - Contains the App binaries and all the resources required to
run the app. Folder name has the .app extension
• APP CONTAINER - Contains all the data created by the app. We will check
these folders for local data storage vulnerabilities.

© 2020 Prateek Gianchandani & Dinesh Shetty


Location of iOS apps in device
• Downloaded applications bundles reside in /var/Containers/Bundle/
Application/<ID>/. Here you can find the *.app file with all the resources
included.

• The /Documents and /Library data reside in /var/mobile/Containers/Data/


Application/<ID>/. Here you can found application data, such as *.sqlite dbs or plist
files.
• Bundle vs Data -> Can be a bit Confusing
© 2020 Prateek Gianchandani & Dinesh Shetty
Location of iOS apps in device
• Many applications have different extensions (widgets). Their shared data can be found
in /var/mobile/Containers/Shared/AppGroup/<ID>.
• Every application runs in its own environment known as the application sandbox,
thereby preventing it to access resources from other applications. Such apps are said
to be “containerized”

© 2020 Prateek Gianchandani & Dinesh Shetty


Exploring device using iFunBox

© 2020 Prateek Gianchandani & Dinesh Shetty


This is what a typical application
directory looks like

© 2020 Prateek Gianchandani & Dinesh Shetty


This is what a typical shared application
directory looks like

© 2020 Prateek Gianchandani & Dinesh Shetty


Task - 5 mins
• Spend a few mins exploring the filesystem of the device
• Using the information from the previous slides, find the location
where the data for DVIA and DVIA-v2 are stored
• Hint: DVIA run (find / -name *com.highaltitudehacks.dvia*)
• Find similar command for DVIA-v2

© 2020 Prateek Gianchandani & Dinesh Shetty


Frida connection check
• On Corellium device, make sure you run the command frida-server -l 0.0.0.0 &
• It is likely it’s already running
• Connect to the WiFi-IP using the command frida-ps -H <IP address>

© 2020 Prateek Gianchandani & Dinesh Shetty


Decrypting iOS apps
• Apps downloaded from the App Store are encrypted by default
• Need to dump the apps before they can be reverse engineered
• Frida-ios-dump: https://github.com/AloneMonkey/frida-ios-dump
• Copy the working version from your Day1 Course material and move
to it to your Ubuntu-VM

© 2020 Prateek Gianchandani & Dinesh Shetty


Frida-ios-dump
• Change the config file dump.py for Corellium and put the Wifi-IP for your device

© 2020 Prateek Gianchandani & Dinesh Shetty


Frida-ios-dump
• Dump the app using dump.py script

© 2020 Prateek Gianchandani & Dinesh Shetty


Task - 10 mins Dump decrypted IPA
• Copy the frida-ios-dump folder provided in Day2 Material and
replace it with the one in your UbuntuVM under Desktop
• Connect your UbuntuVM to the VPN
• On your UbuntuVM, go to the folder Desktop/frida-ios-dump
• Edit the dump.py file to modify the username and password
(most likely it’s already setup)
• SSH to the corellium device and run the command frida-server -l
0.0.0.0 & to start the frida server (most likely it’s already setup)
• Dump the decrypted DVIA app from the device by running the
command python3 dump.py -R 10.11.0.1 "DVIA"
• Now try and dump DVIA-v2
© 2020 Prateek Gianchandani & Dinesh Shetty
Solution from Mac for YouTube - USB Device

© 2020 Prateek Gianchandani & Dinesh Shetty


Frida - Introduction
• Tool for reverse engineering and dynamic code instrumentation
• Works by injecting JavaScript engine and console into running processes
• Useful for application information gathering, dynamic manipulation
• Core written in C, inject’s Google’s v8 engine into the target process and executes
JS code with full access to memory
• Can hook functions and even call native functions
• More details on how Frida works - https://frida.re/docs/hacking/

© 2020 Prateek Gianchandani & Dinesh Shetty


Using FRIDA – iDevice Setup
• Launch Cydia.

• Manage -> Sources -> Edit -> Add

• Add https://build.frida.re to Cydia Sources

• Search and Install “Frida”

© 2020 Prateek Gianchandani & Dinesh Shetty


Using FRIDA – Mac Setup
• pip install frida

• If Error -> Use -> sudo -H


pip install frida --ignore-
installed six

• Run `frida-ps -U` to


confirm if Frida works

© 2020 Prateek Gianchandani & Dinesh Shetty


TASK
• Launch the DVIA
Application

• Find the process-id of the


DVIA application using
Frida

• Find the list of all the


applications installed on
the device using Frida

© 2020 Prateek Gianchandani & Dinesh Shetty


TASK
• Find the list of all the
applications installed
on the device using
Frida

• Find the list of all the


running applications on
the device

© 2020 Prateek Gianchandani & Dinesh Shetty


Tracing methods

© 2020 Prateek Gianchandani & Dinesh Shetty


Tracing methods

© 2020 Prateek Gianchandani & Dinesh Shetty


Tracing methods

© 2020 Prateek Gianchandani & Dinesh Shetty


Attach to the application

© 2020 Prateek Gianchandani & Dinesh Shetty


Javascript APIs

© 2020 Prateek Gianchandani & Dinesh Shetty


Using FRIDA – Dump Class Information
for (var classname in ObjC.classes)
{
if (ObjC.classes.hasOwnProperty(classname))
{
console.log(classname);
}
}

© 2020 Prateek Gianchandani & Dinesh Shetty


Using FRIDA – Dump Class Information

© 2020 Prateek Gianchandani & Dinesh Shetty


Using FRIDA – Dump Methods list
for (var classname in ObjC.classes)
{
if (ObjC.classes.hasOwnProperty(classname))
{
console.log("ClassName: "+classname);
var methodslist = ObjC.classes[classname].$ownMethods;
for (var i = 0; i < methodslist.length; i++)
{
console.log("\t Method: "+methodslist[i]);
}
}
}

© 2020 Prateek Gianchandani & Dinesh Shetty


Using FRIDA – Dump Methods list

© 2020 Prateek Gianchandani & Dinesh Shetty


Using FRIDA – Dump Specific Class
Methods
• Example for DVIA App (Make sure app is running on foreground)

var classname = "JailbreakDetectionVC";


    console.log("ClassName: "+classname);
    var methodslist = ObjC.classes[classname].$ownMethods;
    for (var i = 0; i < methodslist.length; i++)
  {
    console.log("\t Method: "+methodslist[i]);
  }

© 2020 Prateek Gianchandani & Dinesh Shetty


Using FRIDA – Dump Specific Class
Methods

© 2020 Prateek Gianchandani & Dinesh Shetty


Using FRIDA – Dump Specific Class
Methods - Function
function findMethodsFromClass(classname){
var methodslist = ObjC.classes[classname].$ownMethods;
    for (var i = 0; i < methodslist.length; i++)
  {
      console.log("\t Method: "+methodslist[i]);
  }
}

© 2020 Prateek Gianchandani & Dinesh Shetty


Using FRIDA – Dump Specific class
methods

© 2020 Prateek Gianchandani & Dinesh Shetty


Using FRIDA – Show Return Value
• Applicable for DVIA-v2 App - Jailbreak Test 2
• Frida-trace command frida-trace -m "+[JailbreakDet* *]"
DVIA-v2 -H 10.11.0.1

var classname = "JailbreakDetection";


var functionname= "isJailbroken";
var hook = ObjC.classes[classname][functionname];
Interceptor.attach(hook.implementation, {
onLeave: function(returnvalue) {
console.log("ClassName: " + classname);
console.log("FunctionName: " + functionname);
console.log("\tReturn Type: " + typeof returnvalue);
console.log("\tReturn Value: " + returnvalue);

} });

© 2020 Prateek Gianchandani & Dinesh Shetty


Using FRIDA - Show Return Value
• Applicable for DVIA-v2 App
- Jailbreak Test 2

© 2020 Prateek Gianchandani & Dinesh Shetty


Task - 20 mins
• Execute all the command shown in the previous slides using
Frida

© 2020 Prateek Gianchandani & Dinesh Shetty


Bypass Root Detection in DVIA-v2 -
Jailbreak Test 2
newreturnvalue = ptr("0x0");
returnvalue.replace(newreturnvalue );

© 2020 Prateek Gianchandani & Dinesh Shetty


Bypass Root Detection in DVIA-v2 -
Jailbreak Test 2

© 2020 Prateek Gianchandani & Dinesh Shetty


Bypass Root Detection - Change Return
Value

© 2020 Prateek Gianchandani & Dinesh Shetty


Bypass Root Detection – Frida Alternatives
• Alternatively make use of below tools based on Frida:

• NEEDLE – https://github.com/mwrlabs/needle

• APPMon - https://github.com/dpnishant/appmon

• Objection - https://github.com/sensepost/objection

© 2020 Prateek Gianchandani & Dinesh Shetty


Bypass Login Check in DVIA-v2
• Using frida-trace -m "+[LoginValidate* *]" DVIA-v2 -H
10.11.0.1, We can trace the method being called

if (ObjC.available){
var classname = "LoginValidate";
var methodname= "isLoginValidated";
var hook = ObjC.classes[classname][methodname];
Interceptor.attach(hook.implementation,
{ onLeave: function(retvalue)
{
newretvalue = ptr("0x1");
retvalue.replace(newretvalue);
console.log("\nNewReturnValue:" + retvalue + "\"]"); } });
}
© 2020 Prateek Gianchandani & Dinesh Shetty
Bypass Login Check in DVIA-v2

© 2020 Prateek Gianchandani & Dinesh Shetty


Bypass Login Check in DVIA-v2

© 2020 Prateek Gianchandani & Dinesh Shetty


Task - 15 mins
• Open DVIA, go to Runtime Manipulation -> Login Method 1
• Enter any username and password and try to Bypass the login
check

© 2020 Prateek Gianchandani & Dinesh Shetty


Solution
if (ObjC.available){
var classname = “RuntimeManipulationDetailsVC";
var methodname= “- isLoginValidated";
var hook = ObjC.classes[classname][methodname]; Interceptor.attach(hook.implementation,
{ onLeave: function(retvalue)
{ // args[0] is self
// args[1] is selector
// args[2] is the return value
newretvalue = ptr("0x1");
retvalue.replace(newretvalue);
console.log("\nNewReturnValue:" + retvalue + "\"]"); } });
}

© 2020 Prateek Gianchandani & Dinesh Shetty


Frida- Touch/Face ID Bypass
There are two ways of implementing Touch/Face ID authentication:
• Through Apple’s Local Authentication APIs.
• Through access control on the underlying system keychain.

© 2020 Prateek Gianchandani & Dinesh Shetty


Frida- Touch/Face ID Bypass - evaluatePolicy function

• App checks for response


and returns a YES or NO
• Can be hooked to return
YES

© 2020 Prateek Gianchandani & Dinesh Shetty


Frida- Touch/Face ID Bypass script
if(ObjC.available) {
var hook = ObjC.classes.LAContext["- evaluatePolicy:localizedReason:reply:"];
Interceptor.attach(hook.implementation, {
onEnter: function(args) {
send("Hooking Touch Id..")
var block = new ObjC.Block(args[4]);
const appCallback = block.implementation;
block.implementation = function (error, value) {
const result = appCallback(1, null);
return result;
};
},
});

© 2020 Prateek Gianchandani & Dinesh Shetty


Frida- Touch/Face ID secure implementation

• Data is stored in the


Keychain with a specific
access control that
requires biometric
authentication
• Without successful
authentication, data can’t
be retrieved

© 2020 Prateek Gianchandani & Dinesh Shetty


Frida- Touch/Face ID secure implementation
• Store the data in the Keychain
• The underlying system keychain is offering an access control on the
keychain using the TouchID authenticator, so when users attempt to retrieve a
secure item stored there will have first to be verified using the TouchID
successfully.
• Thus, an adversary can not hook the function and tamper the response,
because he does not know the stored value that is protected in the keychain.
• It should be noted that this value must be important for the rest of the
application authentication or business logic (similar to the user provided PIN).

© 2020 Prateek Gianchandani & Dinesh Shetty


Frida – Logging iOS Method Arguments
• Target Application – LINE

• TASK I – is to intercept the sent message and log it

• TASK 2 – is to modify the sent message

© 2020 Prateek Gianchandani & Dinesh Shetty


Frida – Logging iOS Method Arguments

Source - http://www.mopsled.com/2015/log-ios-method-arguments-with-frida/

© 2020 Prateek Gianchandani & Dinesh Shetty


Frida – Logging iOS Method Arguments

Source - http://www.mopsled.com/2015/log-ios-method-arguments-with-frida/
© 2020 Prateek Gianchandani & Dinesh Shetty
Frida – Logging iOS Method Arguments

Source - http://www.mopsled.com/2015/log-ios-method-arguments-with-frida/
© 2020 Prateek Gianchandani & Dinesh Shetty
Frida – Logging iOS Method Arguments

Source - http://www.mopsled.com/2015/log-ios-method-arguments-with-frida/

© 2020 Prateek Gianchandani & Dinesh Shetty


Frida – Logging iOS Method Arguments

Source - http://www.mopsled.com/2015/log-ios-method-arguments-with-frida/
© 2020 Prateek Gianchandani & Dinesh Shetty
Frida – Logging iOS Method Arguments

Source - http://www.mopsled.com/2015/log-ios-method-arguments-with-frida/

© 2020 Prateek Gianchandani & Dinesh Shetty


Frida – Dumping iOS Memory
• Fridump – A universal memory dumper using Frida

• https://github.com/Nightbringer21/fridump

• python fridump.py -u -s -r DVIA

© 2020 Prateek Gianchandani & Dinesh Shetty


Frida – Bypass SSL Pinning Example

var servertrusthook = ObjC.classes.OWSHTTPSecurityPolicy["-


evaluateServerTrust:forDomain:"];

Interceptor.attach(servertrusthook.implementation, {
onLeave: function(returnvalue) {
returnvalue.replace(ptr(1));
}
});

© 2020 Prateek Gianchandani & Dinesh Shetty


Protecting against Frida and other dylibs
inline void scanForInjection() __attribute__((always_inline));

void scanForInjection()
{
uint32_t count = _dyld_image_count();

char* evilLibs[] =
{
"Substrate", "cycript" , “FridaGadget”, “SSLKillSwitch2”
};

for(uint32_t i = 0; i < count; i++)
{
const char *dyld = _dyld_get_image_name(i);
int slength = strlen(dyld);
int j;
for(j = slength - 1; j>= 0; --j)
if(dyld[j] == '/') break;

char *name = strndup(dyld + ++j, slength - j);

for(int x=0; x < sizeof(evilLibs) / sizeof(char*); x++)
{
if(strstr(name, evilLibs[x]) ‖ strstr(dyld, evilLibs[x]))
fprintf(stderr,"Found injected library matching string: \
%s", evilLibs[x]);
}

free(name);
}
}
//Source: The Mobile Application Hackers’ Handbook

© 2020 Prateek Gianchandani & Dinesh Shetty


Task
• Execute all the previous command using Frida

© 2020 Prateek Gianchandani & Dinesh Shetty


Debuggers
• Allows to hook into the application during runtime and analyse each instruction
• LLDB is the debugger used for iOS device since a few years now
• Inspect each method call, set breakpoints, modify value of registers
• Can be used to modify registers during runtime
• Good knowledge of ARM assembly is preferred
• LLDB to GDB command map http://lldb.llvm.org/lldb-gdb.html
• Useful LLDB commands https://www.dropbox.com/s/9sv67e7f2repbpb/lldb-
commands-map.png?dl=0

© 2020 Prateek Gianchandani & Dinesh Shetty


LLDB setup
• Run “ps aux” to find the list of running processes on the device
• Run debugserver on the device and attach to the application of your choice

© 2020 Prateek Gianchandani & Dinesh Shetty


Reading symbols from binary

• Make sure to set the specific architecture for which the binary is compiled

© 2020 Prateek Gianchandani & Dinesh Shetty


Some basic commands
• image dump symtab - Loads the symbols
• process interrupt - stops the process
• register read - Reads all registers
• register read <register> - Reads a particular register
• register write <register> <value> - Write value into a particular register
• image list - Identifies main executable and loaded libraries
• b <method>- Sets breakpoint on a specific method
• image dump sections - Dump sections (Can be used to calculate ASLR slide)

© 2020 Prateek Gianchandani & Dinesh Shetty


Task - 10 mins
• Setup lldb on your device
• Set a breakpoint and dump the registers once the breakpoint is
hit
• Bypass Jailbreak detection challenge in DVIA-v2 using lldb
• Recommended reading - https://www.citadel.sh/blog/dvia-v2-
jailbreak-detection-solutions

© 2020 Prateek Gianchandani & Dinesh Shetty


Task
• Protection against debuggers. Add this line of code in main.m file.
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#include <stdio.h>
#import <dlfcn.h>
#import <sys/types.h>

typedef int (*ptrace_ptr_t)(int _request, pid_t _pid, caddr_t _addr, int _data);
#if !defined(PT_DENY_ATTACH)
#define PT_DENY_ATTACH 31
#endif

void disable_debugger() {
void* handle = dlopen(0, RTLD_GLOBAL | RTLD_NOW);
ptrace_ptr_t ptrace_ptr = dlsym(handle, "ptrace");
ptrace_ptr(PT_DENY_ATTACH, 0, 0, 0);
dlclose(handle);
}

int main(int argc, char * argv[]) {


disable_debugger();
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}

© 2020 Prateek Gianchandani & Dinesh Shetty


Task
• How do you bypass this mitigation ?
• Can we do it using Frida ? Is there any specific option in Frida
we need to use in order to implement this ?
• Can you use Frida to patch C calls ?

© 2020 Prateek Gianchandani & Dinesh Shetty


Binary Code Changes in main function
(0x1000065d0)

© 2020 Prateek Gianchandani & Dinesh Shetty


Reversing the anti debugging function
(0x100006580)

© 2020 Prateek Gianchandani & Dinesh Shetty


Replacing the anti debug function
• Actual address will be always different because of slide, but relative address
between functions would be same.
• relative address is (sub - main) -> (0x100006580 - 0x1000065d0 ) = -0x50
• Function at a particular pointer can be hooked and replaced with Javascript
function using NativeCallback in frida https://frida.re/docs/javascript-api/
#nativecallback

var openPtr = Module.getExportByName('libc.so', 'open');


var open = new NativeFunction(openPtr, 'int', ['pointer', 'int']);
Interceptor.replace(openPtr, new NativeCallback(function (pathPtr, flags) {
var path = pathPtr.readUtf8String();
log('Opening "' + path + '"');
var fd = open(pathPtr, flags);
log('Got fd: ' + fd);
return fd;
}, 'int', ['pointer', 'int']));
© 2020 Prateek Gianchandani & Dinesh Shetty
Replacing the anti debug function
var mainAddr = Module.findExportByName(null, 'main')
var subAddr = mainAddr.sub(0x50);
console.log("subAddr is " + subAddr.toString(16));
var debugfuncAddr = ptr(subAddr);
Interceptor.replace(debugfuncAddr, new NativeCallback(function (argc, argv){
console.log("Bypassing anti debug function!!");
return;
}, 'void', ['int', 'pointer']));

© 2020 Prateek Gianchandani & Dinesh Shetty


Frida - Bypass ptrace (recommended reading)
https://la0s.github.io/2019/03/07/anti_ptrace/

© 2020 Prateek Gianchandani & Dinesh Shetty


Frida - Manipulating registers
Interceptor.attach(functionAddress, {
onEnter: function(args) {
if(this.context.x0 == 0x01){
this.context.x0=0x00
console.log(“Register x0 changed from 1 to 0”);
}
},
});

© 2020 Prateek Gianchandani & Dinesh Shetty


Task - 15 mins
• Using your knowledge of Frida and ARM - Solve Jailbreak Test 1 challenge in DVIA-v2
• Hint: Look for all branch calls
Code:

@IBAction func jailbreakTest1Tapped(_ sender: Any) {


DVIAUtilities.showAlert(forJailbreakTestIsJailbroken: isJailbroken(),
viewController: self)
}

© 2020 Prateek Gianchandani & Dinesh Shetty


Jailbreak Test 1 - DVIA-v2

© 2020 Prateek Gianchandani & Dinesh Shetty


Solution
var targetModule = "DVIA-v2";
var addr = ptr(0x192c94);
var moduleBase = Module.getBaseAddress(targetModule);
var targetAddress = moduleBase.add(addr);
Interceptor.attach(targetAddress, {
onEnter: function(args) {
if(this.context.x0 == 0x01){
this.context.x0=0x00
console.log("Modified x0 Register value from 1 to 0");
}
},
});

© 2020 Prateek Gianchandani & Dinesh Shetty


Solution

© 2020 Prateek Gianchandani & Dinesh Shetty


Homework - Day 2 (Part 2)
• Solve the rest of the jailbreak detection challenges in DVIA-v2
• Solution: https://philkeeble.com/ios/reverse-engineering/iOS-Bypass-
Jailbreak/

© 2020 Prateek Gianchandani & Dinesh Shetty


Insecure Local Data Storage
• It is important to securely store local data on the device.
• In the event of a lost or compromised device, the data can be accessed by an
attacker.
There are many ways of storing data locally on an iOS device.
Some of these techniques are:
• Plist
• NSUserDefaults
• CoreData (Sqlite)
• Keychain

© 2020 Prateek Gianchandani & Dinesh Shetty


Plist
• Data stored in plist files is stored unencrypted in the application sandbox.
• Property lists, data is stored as key/value pair.
• Generally used to store user settings, or information about the
application.
• Most often, developers make the mistake of storing confidential data in Plist
files.

© 2020 Prateek Gianchandani & Dinesh Shetty


Plist
• Sample code for storing data in plist files.


• Location in file system is /private/var/mobile/Containers/Data/Application/
<APP ID>/Documents/userInfo.plist

© 2020 Prateek Gianchandani & Dinesh Shetty


Plist
• These files can be easily found using any simple file explorer utility like
iExplorer in the application folder.

© 2020 Prateek Gianchandani & Dinesh Shetty


Plist
• On inspecting these files, you can find the information being saved in the plist
file.

© 2020 Prateek Gianchandani & Dinesh Shetty


Plist
• Do not use plist files to store confidential information like username/
passwords.
• Do not store session ID’s , important properties etc in a plist file.
• Plist files should only be used to store information that is not important, for
e.g, a list of image names, the last launch date of the application etc.

© 2020 Prateek Gianchandani & Dinesh Shetty


NSUserDefaults
• Used for storing properties, objects that can persist even after an application
restart.
• Information is saved unencrypted inside the application sandbox in a plist file
with the name [BUNDLE_ID].plist inside the folder Library -> preferences .
• Developers make a common mistake of storing critical data using
NSUserDefaults.

© 2020 Prateek Gianchandani & Dinesh Shetty


NSUserDefaults
• All the information stored using
NSUserDefaults can be found
inside the file [BUNDLE_ID].plist
inside the folder Library ->
Preferences.
• Found in /private/var/mobile/
Library/Preferences/
com.highaltitudehacks.dvia.plist
for iOS 13.

© 2020 Prateek Gianchandani & Dinesh Shetty


NSUserDefaults
• All the key/value pairs stored using NSUserDefaults can be found in this file.

© 2020 Prateek Gianchandani & Dinesh Shetty


Core Data
• Core Data framework is used to store persistent data, manage relationships
between objects etc.
• Information is again saved unencrypted on the device in .db or .sqlite files.
• An attacker can gather information about Core data objects by using a sqlite
client.

© 2020 Prateek Gianchandani & Dinesh Shetty


Core Data
• Navigate to your application directory and look for files with the extension .db or
.sqlite.
• Use an sqlite client to access these files.

© 2020 Prateek Gianchandani & Dinesh Shetty


Core Data
• Navigate to your application directory and look for files with the extension .db or
.sqlite.
• Use an sqlite client to access these files.
• You can dump information from the tables in the database using the commands
as shown in the image below.

© 2020 Prateek Gianchandani & Dinesh Shetty


Core Data
• Sqlite browser can be used for quick analysis of sqlite databases

© 2020 Prateek Gianchandani & Dinesh Shetty


Core Data
• Core data framework should not be used to store confidential information as the
information is stored unencrypted on the device.
• If you want to use some confidential informaiton, encrypt it before saving locally
or use some wrappers over core data that store encrypted information on the
device.

© 2020 Prateek Gianchandani & Dinesh Shetty


Task - 10 mins
• Start the Corellium VM
• Run the DVIA app and fill data under all sections in the Insecure Local data storage
section
• Find the place where the application is storing data
• (find / -name *com.highaltitudehacks.dvia*)
• Solve the challenges in Insecure Data Storage for Plist, NSUserDefaults and CoreData
• Use public frida scripts, for e.g this one to read NSUserDefaults https://github.com/
noobpk/frida-ios-hook/blob/master/frida-scripts/read-nsuserdefaults.js

© 2020 Prateek Gianchandani & Dinesh Shetty


Solution

© 2020 Prateek Gianchandani & Dinesh Shetty


Solution - UserDefaults with Frida

© 2020 Prateek Gianchandani & Dinesh Shetty


Solution - UserDefaults with Frida

© 2020 Prateek Gianchandani & Dinesh Shetty


Keychain
• It is the most secure way of storing information locally on the device.
• Used by applications store sensitive information like session ID, authentication
tokens, encryption keys etc.
• Common database for all apps in a sqlite file. Data is stored outside of the
application sandbox.
• Currently, information stored in the keychain can only be dumped from a
jailbroken device using a tool named Keychain Dumper (https://github.com/
ptoomey3/Keychain-Dumper)
• Downside is that data stays even after application uninstall

© 2020 Prateek Gianchandani & Dinesh Shetty


Keychain
Can be updated by using four main operations
• SecItemAdd
• SecItemUpdate
• SecItemCopyMatching
• SecItemDelete
Data Protection for Keychain items can be configured by setting
the kSecAttrAccessible attribute key

© 2020 Prateek Gianchandani & Dinesh Shetty


Keychain accessibility values

Source: https://developer.apple.com/documentation/security/keychain_services/keychain_items/
item_attribute_keys_and_values#1679100
© 2020 Prateek Gianchandani & Dinesh Shetty
Touch ID to fetch Keychain items
Can be implemented by using LocalAuthentication or Security framework

Recommended Reading: https://developer.apple.com/documentation/


localauthentication/accessing_keychain_items_with_face_id_or_touch_id

© 2020 Prateek Gianchandani & Dinesh Shetty


Keychain wrappers
• One line implementation.
• Access group allows applications to share keychain data.
• KeychainItemWrapper *wrapper = [[KeychainItemWrapper alloc]
initWithIdentifier:@“Identifier” accessGroup:nil];
• The same access group has to be given from both the apps and both the app ID’s
have to be mentioned in the plist file for both the applications.

© 2020 Prateek Gianchandani & Dinesh Shetty


Keychain wrappers
• Using Keychain is quite simple (especially with third-party
wrappers). One of them is SSKeychain (https://github.com/soffes/
sskeychain):
• [SSKeychain setPassword:@”secretkey” forService:@”DVIA”
account:@”Admin”];
• NSString *pass = [SSKeychain passwordForService:@”DVIA”
account:@”Admin”];

© 2020 Prateek Gianchandani & Dinesh Shetty


Storing Data in Keychain
• Using Keychain is quite simple (especially with third-party wrappers). One of
them is SSKeychain (https://github.com/soffes/sskeychain):
• [SSKeychain setPassword:@”secretkey” forService:@”DVIA” account:@”Admin”];
• NSString *pass = [SSKeychain passwordForService:@”DVIA” account:@”Admin”];

© 2020 Prateek Gianchandani & Dinesh Shetty


Keychain dumper demo
Keychain information dumped for the application Damn Vulnerable iOS app
can be clearly found in the image below.

Even though keychain is one of the most secure places to store information,
consider adding an extra layer of encryption before saving data in the
application to make the job for the attacker more difficult.
© 2020 Prateek Gianchandani & Dinesh Shetty
Keychain dumper in iOS 13
Need to sign with the following entitlements.xml file

Build instructions at https://github.com/ptoomey3/Keychain-Dumper

© 2020 Prateek Gianchandani & Dinesh Shetty


Keychain dumper in iOS 13

Build instructions at https://github.com/ptoomey3/Keychain-Dumper


© 2020 Prateek Gianchandani & Dinesh Shetty
Task
• Start the Corellium VM
• Run the following command to dump the keychain:
keychain_dumper
• Can you dump all the keychain contents for the whole device using
Frida by hooking into only one app ?

© 2020 Prateek Gianchandani & Dinesh Shetty


keychain_dumper
• Explore the different options in Keychain Dumper

© 2020 Prateek Gianchandani & Dinesh Shetty


Realm
• Realm is a popular third-party cross-platform mobile database built on a
custom C++ core.
• Just like in all other cases information is stored unencrypted in the /
Documents folder, in the *.realm files.
• Realm is a replacement for SQLite & Core Data
• An attacker can gather information using the default Realm Browser:
https://github.com/realm/realm-cocoa/tree/master/tools/
RealmBrowser

© 2020 Prateek Gianchandani & Dinesh Shetty


Firebase
• Another popular SDK used to create apps without the need to write backend
code.
• Data is written in Firebase databases.
• In the past, there have been issues with misconfigured Firebase databases.
• PROJECT_ID key in the GoogleService-Info.plist contains the Project Name.
• One can then use FireBase scanner to scan for misconfigured databases.

python FirebaseScanner.py -f <commaSeperatedFirebaseProjectNames>

© 2020 Prateek Gianchandani & Dinesh Shetty


Apple Watch
• Apple Watch is the wearable device from Apple.
• Most of the Apple Watch apps are simply extensions of native iOS
applications.

© 2020 Prateek Gianchandani & Dinesh Shetty


Apple Watch
• The running app extension and containing app have no direct
access to each other’s containers, so they use a shared data
directory for data syncing.
• Their shared data can be found in /var/mobile/Containers/
Shared/AppGroup/<ID>
• So, all the Insecure Data Storage vulnerabilities can be applied to
Apple Watch extensions.

© 2020 Prateek Gianchandani & Dinesh Shetty


Side Channel Data leakage
There are many different ways in which data can be leaked from the application
without the awareness of the developer.
• Device Logs
• Application snapshots
• Pasteboard
• Keystroke logging
• Cookies

© 2020 Prateek Gianchandani & Dinesh Shetty


Device Logs
• Some developer use logs while debugging their applications but forget to
remove them while releasing the application.
• To see the device logs while you are running an application, make sure that
the device is connected to your computer.
• In Xcode, go to Window -> Organizer -> Device -> Your Device -> Console
• In Recent iOS versions , data is logged with the os_log command
• On your UbuntuVM, you can use the command idevicesyslog to view the logs
from a USB connected device

© 2020 Prateek Gianchandani & Dinesh Shetty


Device Logs

• Device logs should only be enabled for DEBUG mode in the application, this
will ensure that the logs are disabled when the application is downloaded
from the App store and run on a user’s device.
© 2020 Prateek Gianchandani & Dinesh Shetty
Disabling Device Logs
Add the following code in the Precompiled header file , usually with the name
PrefixHeader.pch

#ifdef DEBUG
# define NSLog (...) NSLog(__VA_ARGS__)
#else
# define NSLog (...)
#endif

© 2020 Prateek Gianchandani & Dinesh Shetty


Application Snapshots
• iOS by default takes a screenshot of your application when you take the application to
background by pressing the home button.
• This screenshot is shown to the user when he opens the app again while the app is loaded in
the background.
• Provides a seamless experience.
• The problem is that the screenshot is stored without any protection in the application folder.
• Sometimes, these screenshots can contain confidential information that might be leaked to an
attacker.
• Location is ./private/var/mobile/Containers/Data/Application/<APP-ID>/Library/
SplashBoard/Snapshots for iOS 13

© 2020 Prateek Gianchandani & Dinesh Shetty


Application Snapshots
• The following image shows the application snapshot stored in the application
folder

© 2020 Prateek Gianchandani & Dinesh Shetty


Pasteboard
• Data copied using the cut/copy features in iOS goes inside a buffer known
inside a pasteboard item.
• It is possible for other applications to access the content of this pasteboard.
• If the pasteboard item contains some confidential information, it might lead to
information leakage
• Fixed in iOS 14 - User sees each copy/paste notification

© 2020 Prateek Gianchandani & Dinesh Shetty


Pasteboard
• Data can be copied using the Copy feature
in iOS.
• Once it is copied, it remains in the buffer.

© 2020 Prateek Gianchandani & Dinesh Shetty


Pasteboard
Using the following code in any app you can dump out the contents of the
pasteboard.

[UIPasteboard generalPasteboard].items[0] -> Objective-C


UIPasteboard.general.string -> Swift

© 2020 Prateek Gianchandani & Dinesh Shetty


Pasteboard
• For text fields that might contain secure information, make sure the Secure
property is set.

• Clear pasteboard contents when the application enters background.

• Use pasteboard with specific identifiers, this makes it difficult for other
applications to fetch data from this pasteboard item.

© 2020 Prateek Gianchandani & Dinesh Shetty


Pasteboard

Source: https://www.macrumors.com/2020/07/06/reddit-app-
clipboard-snooping-fix-coming/

© 2020 Prateek Gianchandani & Dinesh Shetty


Pasteboard

Source: https://www.infoq.com/news/2020/07/ios-clipboard-bug/

© 2020 Prateek Gianchandani & Dinesh Shetty


Keystroke logging
• iOS by default logs every input that you enter in any text field unless the
secure flag is not set.
• This helps in autocorrecting the user later.
• All the keystroke logs can be easily fetched out from a device.
• These logs might contain information that is important.
• Logs remain stored on the device for a long time hence making it even
more insecure.
• Logs are stored in a file with the extension .dat in the location
“/var/mobile/Library/Keyboard/“

© 2020 Prateek Gianchandani & Dinesh Shetty


Keystroke logging
• The prefix of the file denotes the language in which the keystroke logs are
stored.
• Here is how a part of the logs file look like.

© 2020 Prateek Gianchandani & Dinesh Shetty


Cookies
• Some applications create persistance cookies and store them in
cookies.binarycookies file in application’s home directory.
• The sample code for storing cookies:
• [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
• The path to cookies is:
• /Library/Cookies/Cookies.binarycookies (iOS 7)
• /User/Data/Application/<APP-ID>/Library/Cookies (iOS 8)

© 2020 Prateek Gianchandani & Dinesh Shetty


Cookies
• Revealing cookies is quite easy:
• Download the python script BinaryCookieReader.py from http://
securitylearn.net/wp-content/uploads/tools/iOS/BinaryCookieReader.py
• Download the Cookies.binarycookies file from your device.
• Run binarycookiereader.py /file-path-to-cookies

© 2020 Prateek Gianchandani & Dinesh Shetty


Cookies
This is the example from Aeroflot mobile application:

© 2020 Prateek Gianchandani & Dinesh Shetty


Task
• Dump the pasteboard contents using this Frida script https://
github.com/noobpk/frida-ios-hook/blob/master/frida-scripts/
pasteboard-monitoring.js
• Find the location of the Application Snapshot stored on the device for
DVIA or DVIA-v2
• You can also Dump Binary Cookies using this Frida script https://
github.com/noobpk/frida-ios-hook/blob/master/frida-scripts/
show_binarycookies.js

© 2020 Prateek Gianchandani & Dinesh Shetty


Solution - Pasteboard

© 2020 Prateek Gianchandani & Dinesh Shetty


Solution - Application Snapshot

© 2020 Prateek Gianchandani & Dinesh Shetty


Analysing network traffic over HTTP/
HTTPs
• It is important to analyze the network traffic that flows between the client/server in
an application.
• Look for credentials, authentication tokens, API keys being transmitted over
unsecured http channel.
• Check for the entropy in Session ID’s.
• Traffic can be analyzed using a simple proxy tool like Burp proxy.
• Try to manipulate the request/response using Burp and see how the client side
application responds to it.

© 2020 Prateek Gianchandani & Dinesh Shetty


Analyzing traffic over HTTP
• Configure Burp Proxy to start listening for traffic. Make sure it is listening on all
interfaces.

© 2020 Prateek Gianchandani & Dinesh Shetty


Analyzing traffic over HTTP
• Configure your iOS device to use your computer as a proxy.

© 2020 Prateek Gianchandani & Dinesh Shetty


Analyzing traffic over HTTP
• You can now intercept the traffic as it goes to the server.

© 2020 Prateek Gianchandani & Dinesh Shetty


Analyzing traffic over HTTPS
• This will require you to install Burp’s
CA certificate as a trusted root on
your device.
• Configure your browser to relay
traffic over Burp proxy.

© 2020 Prateek Gianchandani & Dinesh Shetty


Analyzing traffic over HTTPS
• You will get a warning, click on Add Exception.

© 2020 Prateek Gianchandani & Dinesh Shetty


Analyzing traffic over HTTPS
• Click on View.

© 2020 Prateek Gianchandani & Dinesh Shetty


Analyzing traffic over HTTPS
• Go to Details, select the
topmost certificate, click on
Export and save the file with
extension as .crt
• Optionally, you can setup
the proxy on your device
and go to http://burp and
click on CA Certificate to
download the certificate
© 2020 Prateek Gianchandani & Dinesh Shetty
Analyzing traffic over HTTPS
• Send this file to your device via email, click on it
and Install it. Accept all the instructions and click on
Done.

• Explicitly Trust the Certificate by Going to Settings


-> General -> About -> Certificate Trust Settings

• https://support.apple.com/en-ae/HT204477

© 2020 Prateek Gianchandani & Dinesh Shetty


Analyzing traffic over HTTPS
• Quit and restart the application you want to sniff traffic for. You will now be
able to see the traffic even if it is over HTTPs

© 2020 Prateek Gianchandani & Dinesh Shetty


Certificate pinning
• The server’s certificate is hardcoded in the application bundle and checked
while exchanging data with the server.
• Provides protection against MITM attacks.
• Used by applications like Twitter, Square etc.

© 2020 Prateek Gianchandani & Dinesh Shetty


Certificate pinning
• Certificate pinning can be bypassed by hooking into some low level
methods during runtime.
• iOS SSL kill switch was released in Blackhat to demonstrate this.
• https://github.com/nabla-c0d3/ssl-kill-switch2

© 2020 Prateek Gianchandani & Dinesh Shetty


Certificate pinning bypass
• Once it is enabled, user can see the traffic through applications like Twitter
as well.

© 2020 Prateek Gianchandani & Dinesh Shetty


App Transport Security

© 2020 Prateek Gianchandani & Dinesh Shetty


App Transport Security

© 2020 Prateek Gianchandani & Dinesh Shetty


Certificate pinning bypass
• Once it is enabled, user can see the traffic through applications like Twitter
as well.

© 2020 Prateek Gianchandani & Dinesh Shetty


Task - 15 mins
• Try to capture traffic over HTTP/HTTPs for the Facebook app or
any app of your choosing
• Bypass SSL Pinning in the Twitter app
• Try and use some SSL pinning bypass frida scripts from
codeshare https://codeshare.frida.re/browse

© 2020 Prateek Gianchandani & Dinesh Shetty


Scanning Server side vulnerabilities

• Same logic as testing for


web application
vulnerabilities
• Includes both manual and
automated testing

© 2020 Prateek Gianchandani & Dinesh Shetty


Scanning Server side vulnerabilities
• Perform a scan on the
vulnerable web application
via OWASP Zap or
Burpsuite.

© 2020 Prateek Gianchandani & Dinesh Shetty


WebViews
• WebViews are used to display web content
• By default, Javascript is enabled
• Attacks like Cross-Site scripting are possible
• Some popular classes are UIWebView, WkWebView and
SFSafariViewController
• UIWebView has been deprecated and not recommended to be used
• Javascript can’t be disabled in UIWebView

© 2020 Prateek Gianchandani & Dinesh Shetty


WKWebView security advantages
• Javascript can be turned off by using the javaScriptEnabled property
• The JavaScriptCanOpenWindowsAutomatically property can be used to
disable new windows such as popups
• The hasOnlySecureContent ensures resources loaded are through secure
channels.
• WKWebView implements out-of-process rendering. Memory corruption
bugs like JIT optimisation bugs such as UaF etc will not affect the main
app process.

© 2020 Prateek Gianchandani & Dinesh Shetty


UIWebView vs WKWebView

https://medium.com/ios-os-x-development/security-flaw-with-uiwebview-95bbd8508e3c

© 2020 Prateek Gianchandani & Dinesh Shetty


SfSafariViewController
• Isolated from the app context itself
• Shares cookies and other website data with Safari
• Recommended if you want to open random links inside the app, but without
any interactions with the link and their content itself

Source: https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller

© 2020 Prateek Gianchandani & Dinesh Shetty


Testing for WebViews
• grep for symbols starting with UIWebView, WKWebView etc
• SFSafariViewcontroller doesn’t have any security implications
• Make sure the javascript settings and configurations are properly enabled,
in some cases having javascript enabled would be a requirement, in other
cases not.

© 2020 Prateek Gianchandani & Dinesh Shetty


Jailbreak Detection
• For critical applications like banking applications etc, it is important that you
ensure that the application doesn’t work on a jailbroken device.
• With a copy of your app’s binary and tools like Cycript at his disposal, an
attacker is in complete control.
• It is therefore important to check for a jailbroken device and disable certain
features of the application or quit the application in order to protect it.

© 2020 Prateek Gianchandani & Dinesh Shetty


Jailbreak Detection
• There are many ways to check for a jailbroken device.
• Checking for specific files that exist on a jailbroken device is one of the most
common techniques being used.
• Another way is to check if the application is able to modify a file outside it’s own
sandbox.
• Most than 80% of the jailbroken devices have Cydia installed, so check if you can
open a url that starts with Cydia’s URL scheme, i.e cydia://
• Using C code, we can check for open ports, fork command etc
• It is important to note that no that there is no foolproof technique to detect a
jailbroken device, however a combination of checks can make the job difficult for
even a skilled hacker. © 2020 Prateek Gianchandani & Dinesh Shetty
Jailbreak Detection
• Combining all these techniques, we get this method.
+(BOOL)isJailbroken{

#if !(TARGET_IPHONE_SIMULATOR)

if ([[NSFileManager defaultManager] fileExistsAtPath:@"/Applications/Cydia.app"]){

return YES;

}else if([[NSFileManager defaultManager] fileExistsAtPath:@"/Library/MobileSubstrate/MobileSubstrate.dylib"]){

return YES;

}else if([[NSFileManager defaultManager] fileExistsAtPath:@"/bin/bash"]){

return YES;

}else if([[NSFileManager defaultManager] fileExistsAtPath:@"/usr/sbin/sshd"]){

return YES;

}else if([[NSFileManager defaultManager] fileExistsAtPath:@"/etc/apt"]){

return YES;
}

NSError *error;

NSString *stringToBeWritten = @"This is a test.";

[stringToBeWritten writeToFile:@"/private/jailbreak.txt" atomically:YES

encoding:NSUTF8StringEncoding error:&error];

if(error==nil){

//Device is jailbroken

return YES;

} else {

[[NSFileManager defaultManager] removeItemAtPath:@"/private/jailbreak.txt" error:nil];

if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"cydia://package/com.example.package"]]){

//Device is jailbroken

return YES;

#endif

//All checks have failed. Most probably, the device is not jailbroken

return NO; © 2020 Prateek Gianchandani & Dinesh Shetty


}
Jailbreak Detection
• The problem is that the signature of this method gives everything away.
• Attacker can use Frida to use bypass the check for jailbreak detection.

© 2020 Prateek Gianchandani & Dinesh Shetty


Swift 4 JB Detection
https://github.com/TheSwiftyCoder/JailBreak-Detection/blob/master/JailBreak.swift

© 2020 Prateek Gianchandani & Dinesh Shetty


Jailbreak Detection
• It is better to rename the method to something that doesn’t look
important.
• Something like +(BOOL)isDefaultColour
• Yeah I know, we do ignore the coding guidelines, but in this case, the
guidelines are something that gives everything away.
• After analyzing the class-dump output of the application, the hacker is
most likely to ignore this method.
• He can always reverse engineer this method to see what’s going on
inside, so this method is also not foolproof.

© 2020 Prateek Gianchandani & Dinesh Shetty


Broken Cryptography
• Occurs when data stored on the device is not encrypted properly.
• One of the most common vulnerabilities found in iOS
applications.
• Can occur by use of deprecated or weak algorithms.
• Sometimes the key while encryption is hardcoded in the app
thereby making it much easier for the attacker to break the
application.
• Related article: http://www.andreas-kurtz.de/2013/07/how-to-
easily-spot-broken-cryptography.html

© 2020 Prateek Gianchandani & Dinesh Shetty


Task Broken Cryptography - 40 mins
• Open the Broken Cryptography challenge in DVIA and set a password, use reversing and
Frida in the application to find out the following
a) Which encryption library is being used ? And Which function is responsible for
encryption ?
b) Which encryption algorithm is being used ?
c) Where is the encryption key being stored ?
d) Which file stores the encrypted data ?
e) How will you decrypt the encrypted data ?
f) Post Solution in the Slack Channel #Labs

© 2020 Prateek Gianchandani & Dinesh Shetty


Code obfuscation
• Difficult to do because of the way iOS application are compiled and
executed.
• For hiding class information - iOS class guard https://github.com/Polidea/
ios-class-guard
• For sqlite databases - SQLCipher - https://www.zetetic.net/sqlcipher/
• For many other things - iMAS - https://github.com/project-imas/memory-
security/

© 2020 Prateek Gianchandani & Dinesh Shetty


Code obfuscation
• Add bogus code
• Changes names of important classes, methods
• Use string encryption. Encrypt the key as well
• Generate the key at runtime, for e.g by adding 2 different strings

© 2020 Prateek Gianchandani & Dinesh Shetty


Patching iOS applications
• Patching an application changes its login permanently.
• This is better that making a change in cycript where you have to
repeat the same process over and over again.
• Often used to disable checks like Jailbreak detection, piracy check
etc.
• Tools used for patching iOS application: radare, IDA Pro, Hexfiend
and Hopper.

© 2020 Prateek Gianchandani & Dinesh Shetty


Task
• Analyze an iOS application using Hopper
• Find the class information about the application
• Understand to see Pseudo code and CFP graph for a particular method

© 2020 Prateek Gianchandani & Dinesh Shetty


Patching iOS applications
• Hopper is one of the best tools available for patching iOS applications.
• Not free, but the value for money is very good.
• Patching iOS applications with Hopper: http://highaltitudehacks.com/
2014/01/17/ios-application-security-part-28-patching-ios-application-
with-hopper/
• Patching iOS applications with IDA Pro and Hex fiend:http://
highaltitudehacks.com/2013/12/17/ios-application-security-part-26-
patching-ios-applications-using-ida-pro-and-hex-fiend

© 2020 Prateek Gianchandani & Dinesh Shetty


Patching iOS applications
• To modify any instruction in Hopper, click on it and click on Modify ->
Assemble Instruction.

© 2020 Prateek Gianchandani & Dinesh Shetty


Patching iOS applications
• Make the change and click on Assemble and Go Next

© 2020 Prateek Gianchandani & Dinesh Shetty


Patching iOS applications
• Once the change has been made, click on File -> Produce new executable
and overwrite the existing one.

© 2020 Prateek Gianchandani & Dinesh Shetty


Patching iOS applications
• To deploy the application back to your device, resign the application binary
using Impactor and deploy it to the device
• Let’s use r2 to patch an application since its free
• Let’s solve the first challenge in “Application patching” section in DVIA-v2

© 2020 Prateek Gianchandani & Dinesh Shetty


Challenge - DVIA-v2 Application Patching ->Login
method 1

© 2020 Prateek Gianchandani & Dinesh Shetty


Hopper view
• Replace the instruction with b loc_1001ac1bc

© 2020 Prateek Gianchandani & Dinesh Shetty


radare2
• To deploy the application back to your device, resign the application
binary using Impactor and deploy it to the device
• Let’s patch the same instruction using r2 since its free
• Or you can use the command line utility appinst to install the IPA file

© 2020 Prateek Gianchandani & Dinesh Shetty


Steps
• Unzip DVIA-v2 from the IPA folder cd Desktop/IPA
• Find the application binary and run the following commands

r2 -Aw DVIA-v2 - Open with write mode and analyse (takes some time)
i - Show info of current file
iz - Print strings in the data section
izz - Print strings in the whole binary
s main - Seek to the main function
pdf - Print disassembled version of the main function

© 2020 Prateek Gianchandani & Dinesh Shetty


Task - Patch DVIA-v2 to solve Login Method 1
challenge
is - Show all the sections
s 0x1001ac198 - Jump to the instruction to be changed
pdf - Print disassembled function
wa b 0x1001ac1bc - Write the following opcode in that specific address
q - Quit
• Compress the folder again such that the folder name is Payload.zip, now
rename it to App.ipa and install on the device using Corellium’s app
installer or the command line appinst. The app should run and the login
check should show Success now
© 2020 Prateek Gianchandani & Dinesh Shetty
Automated testing
• Automating tests while doing an iOS penetration test can help you save a lot
of time.
• Though not all tests can be automated, there are some tools that do a very
good job at this.
• Objection - https://github.com/sensepost/objection
• Needle - https://github.com/mwrlabs/needle
• PassionFruit - https://github.com/chaitin/passionfruit

© 2020 Prateek Gianchandani & Dinesh Shetty


MobSF

Source: https://github.com/MobSF/Mobile-Security-Framework-MobSF
© 2020 Prateek Gianchandani & Dinesh Shetty
Objection

© 2020 Prateek Gianchandani & Dinesh Shetty


Objection

© 2020 Prateek Gianchandani & Dinesh Shetty


Needle

© 2020 Prateek Gianchandani & Dinesh Shetty


Needle

© 2020 Prateek Gianchandani & Dinesh Shetty


PassionFruit

© 2020 Prateek Gianchandani & Dinesh Shetty


PassionFruit

© 2020 Prateek Gianchandani & Dinesh Shetty


Static Analysis of iOS
applications

© 2020 Prateek Gianchandani & Dinesh Shetty


© 2020 Prateek Gianchandani & Dinesh Shetty
© 2020 Prateek Gianchandani & Dinesh Shetty
© 2020 Prateek Gianchandani & Dinesh Shetty
© 2020 Prateek Gianchandani & Dinesh Shetty
Further practice

Try out all the challenges in Damn


Vulnerable iOS App v2
(http://damnvulnerableiosapp.com)

© 2020 Prateek Gianchandani & Dinesh Shetty

You might also like