I Want More Ninja – iOS Security Testing
-
Upload
jason-haddix -
Category
Internet
-
view
1.168 -
download
2
Transcript of I Want More Ninja – iOS Security Testing
iOS Application Testing
@jhaddix I work at Fortify On Demand
We assess a lot of mobile apps
http://goo.gl/cjd3JF
Me
iDevice apps are downloaded via the appstore or given to you by
the customer. They are an extension .ipa which is just a zip file. Your idevice unzips them,
handles crypto and signing magic and deploys them to their own
sandboxed directory.
ZOMG 2hrs!?!!???!?
A jailbroken iDevice? SSHed into their device before? Proxied a mobile app or used
Burp Suite before?
Lets Play “Who has?”
Setting Up Your Lab
• Hardware o MacBook o PC o iPad / Iphone o Bluetooth KB (useful but not necessary)
Ninjas Need Tools
• Software for MacBook o Xcode with developer utils o USBMux Python package o iTunes o Burp Suite o Wireshark o Hopper Disassembler o iFunBox o Filezilla o libimobiledevice
MacBook Software
• Software for PC o iFunBox o iExplorer o Apple Configuration Utility o USBMux Python package o iTunes o Burp Suite o SSH/SCP Client (I use Bitvise) o Plist editor pro o SQL Database Browser o SQLite Expert Professional o Wireshark ++ Tshark o Python o Java o IDA Pro
PC Software
Look Ma, Exploits!
Setting up your
iPad
Jailbreaking
Fanc
y ha
rdw
are�
Objective-C �
Core Services + Cocoa (Media & UI APIs) �
iOS (fork of Darwin (fork of BSD)) �
Opera'ng System
Language
ARM Executables
• Get us a shell! o A jailbreak is a set of exploits designed to give us full control over
the device. Also installs the Cydia appstore. o A combination of userland exploits ,kernel exploits, and iOS API
trickery. o Current JB is Evasion 7.1 or Pangu 7.1.2
Jailbreaking
1. Open and update cydia 2. Install OpenSSH
• In safari - apptapp://package/openssh
Then
Post Jailbreak
• Install from cydia – APT 0.7 Strict – Afc2add – Cycript – Appsync – IPA installer – Appcake – ClutchPatched
• Useful packages (packages.txt) • apt-get install $(<packages.txt) • reboot
iPad Software
1. Get USB mux installed 1. This way you don’t need a network
Not iPad Software
ECHO OFF ::CMD will no longer show us what command it’s execu<ng(cleaner) ECHO USB MUX Connec<on! \Python27\python.exe \usbmuxd-‐1.0.8\python-‐client\tcprelay.py -‐t 22:2222
1. Now you have a functioning *nix environment on your iPad.
2. A Lab Mac 3. A Lab PC
Let talk about what we are looking for!
Now you have *NIX
Apps and Vulns
1. We live in userland 2. We still have fun 3. Remember, it’s for the customer
We test Apps
On the iDevice, once installed, the IPA file (remember just a zip) is extracted to the applications sandboxed folder:
/var/mobile/Applications/APPGUID/
Where Apps live
Use the IPA Installer Console (or appcake) to install apps that you have IPAs for: Appcake IPAs must be dropped in: /var/mobile/Media/Appcake/Imported
Installing IPAs
Ender:~ root# ipainstaller -‐c TargetApp.ipa Clean installa<on enabled. Will not restore any saved documents and other resources. Analyzing TargetApp.ipa... Installing TargetApp (v1.0)... Installed TargetApp (v1.0) successfully. Cleaning old contents of TargetApp...
listapps
#!/bin/sh ls -‐d /var/mobile/Applica<ons/*/*.app | sort -‐f -‐t \/ -‐k 6
Place in /usr/bin/ :
listapps
running
#!/bin/bash ps aux |grep mobile| awk -‐F" " '{print $2, $11}'|grep /var/mobile
Place in /usr/bin/ :
running
Process ID
Appname.app/ Lets explore an app bundle directory, inside it are the barebones pieces of the app once installed:
Ls –alX <appPath/appName.app>
$Appname.app/
Other files inside of the bundle (.app/) • Image files • Info.plist • Hard coded certs • Pre configured SQLite dbs
More on the content of the app directory later
$appguid/ Up one directory from your apps .app folder is its sandbox directory folders (the apps “container”). Upon 1st run things will get copied here and the important storage, settings and caches files live here.
Ls –alX $appPath/
• /var/mobile/Applica'ons/<long string here>/
App Directories
Looking for Vulns
OWASP Mobile Top 10 Risks
M1 – Weak Server Side Controls
M2 – Insecure Data Storage
M3 -‐ Insufficient Transport Layer
Protec'on M4 -‐ Unintended Data Leakage
M5 -‐ Poor Authoriza'on and Authen'ca'on
M6 -‐ Broken Cryptography
M7 -‐ Client Side Injec'on
M8 -‐ Security Decisions Via
Untrusted Inputs
M9 -‐ Improper Session Handling
M10 -‐ Lack of Binary Protec'ons
Client-Side
OWASP Mobile Top 10 Risks
M1 – Weak Server Side Controls
M2 – Insecure Data Storage
M3 -‐ Insufficient Transport Layer
Protec'on M4 -‐ Unintended Data Leakage
M5 -‐ Poor Authoriza'on and Authen'ca'on
M6 -‐ Broken Cryptography
M7 -‐ Client Side Injec'on
M8 -‐ Security Decisions Via
Untrusted Inputs
M9 -‐ Improper Session Handling
M10 -‐ Lack of Binary Protec'ons
What are we looking for?
• Usernames • Authentication tokens • Passwords • Cookies • Location data • Sensitive Images • UDID/EMEI • Device Name • Network Names
• DoB • Address • Social • Card Data • Stored application logs • Debug information • Cached messages • Transaction histories • PIN numbers
What are we looking for? Many apps will encode sensitive data, not encrypt. Look for (this is “password”): • Base64
– cGFzc3dvcmQ= • Hex
– 70617373776f7264
• Decimal – 112 97 115 115 119 111 114 100
• Md5 – 5f4dcc3b5aa765d61d8327deb882cf99
• SHA1 – 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
Logs, SQLite, Plists, Caches, oh my!
Logs, SQLite, Plists, Caches, oh my!
M2 – Insecure Data Storage
• All of the last slide will be stored by one app or another.
• Some are OK to store as long as the file is protected by encryption.
• Others are usually bad to store all the time and should be handled: – In memory – Crypted in the keychain – On the server exclusively
Working with data storage files
• Most data stores can be inspected easily with a text editor, except:
– Plists
• XML • Binary
– SQLite Databases
Plists Data storage via:
NSUserDefualts Tool On Mac
§ Xcode plist editor will read both formats
§ Plutil will convert a binary plist to an xml one
Tool On Windows § Plist editor Pro will read and
save either format § Notepad++
SQLite
• iOS supports SQLite for data storage using NSManagedObject (core data)
• Tools: – SQLite Database Browser for Win (GUI)\ – SQLite on the command line
Checking the encryption level of files
• Most files can be assigned a Data Protection API level (NOT NSuserdefaults)
• This designates when the file is accessible and unencrypted
NSFileProtec'onComplete Encrypted unless device is on and unlocked.
NSFileProtec'onCompleteUnlessOpen Encrypted unless device is on and unlocked, or the file is already open.
NSFileProtec'onCompleteUn'lFirstUserAuthen'ca'on Encrypted un'l user first unlocks the device, un'l device shutdown. (default on iOS 7)
NSFileProtec'onNone Unencrypted (default on iOS 6)
Checking the encryption level of files
Tool FileDP: No DPAPI
FileDP -‐d $app_path 2>&1 | grep -‐v "\.dll\|\.nib\|\.png\|\.jpeg\|\.jpg\|\.css\|\.gif" |
grep NSFileProtec'onNone|sed 's/^.*is://'|sed 's/ -‐ protec'on.*$//'
NSFileProtec<onCompleteUn<lFirstUserAuthen<ca<on DPAPI
FileDP -‐d $app_path 2>&1 | grep -‐v "\.dll\|\.nib\|\.png\|\.jpeg\|\.jpg\|\.css\|\.gif" |grep NSFileProtec'onCompleteUn'lFirstUserAuthen'ca'on|sed 's/^.*is://'|sed 's/ -‐
protec'on.*$//'
Logs
• iOS supports logging for applications using NSLog Tools: – Apple Configuration Utility for Win (GUI) – Syslog on the command line (*nix)
Looking at ASL Start: tail -‐f /var/log/syslog | tee /private/var/root/SYSLOG.log 2>&1 &
Stop: ps aux | grep -‐ie tail | awk '{print $2}' | xargs kill -‐9 > /dev/null 2>&1
Tool keychain dumper:
Keychain
keychain_dumper 2>/dev/null | grep -‐i -‐B 3 -‐A 5 "yahoo"
Keychain
Finding strings
credsearch.sh
Data Storage LABs
• Damn Vulnerable iOS App – Install DVIA – Lab Coredata – Lab NSUserDefaults – Lab Find Weak DPAPI levels – Lab Logging – Lab keychain
Web
Proxy the device
• HTTP Traffic: • Fire up burp • Go to you phone and navigate to: • Settings -> Wi-Fi -> Network name -> HTTP
Proxy -> Manual • Enter in the IP address of your machine
running Burp and the external port burp is listening on.
Proxy the device
HTTPS
• Once proxied, go to http://burp/cert in safari • Install SSL cert
SSL Headaches
• Cert Pinning!
– SSLkillswitch - hooks functions within the Secure Transport API
In /tools
Webservices
• REST – http://bank.com/accntdetails/12345
• REST Params – http://bank.com/accntdetails?id=12345
• SOAP
Fuzz strings
• Several payload sets for fuzzing available in seclists:
• Use Burp Intruder for these.
Fuzz strings
3rd Party Tools
iNalyzer
• Static/bin analysis tool • Cracks app • Creates doxygen graph out of classdump-z
data • Offers web gui, finding plists, dbs etc • Has a cycript console in it’s web gui allowing
you to proxy the web gui via burp for fuzzing. • https://appsec-labs.com/iNalyzer
iNalyzer
Introspy • Runtime hooking and monitoring tool using
mobile substrate • Will log API calls for crypto, data storage,
network connections , ++ , to an SQLite db. • Separate tool parses the db, offers some
automated security checks. • Bad XML parsing, bad cert pinning, bad
keychain usage, pasteboard, http traffic, bad data storage, crypto flaws.
• http://isecpartners.github.io/Introspy-iOS/
idb
• Ruby based GUI Tool to instrument and automate some testing
• GUI for SSH/USBmux, Log viewer, checks imported libs, check for ASLR, SS, PIE (otool checks), pasteboard viewer, URL scheme fuzzer, keychain
• https://github.com/dmayer/idb/wiki/Manual-and--Walk-Through
iret
• Web based GUI instrumentation tool • Pretty much the same as idb • Has a function to create theos tweaks
Snoop-it
• Web GUI • Runtime monitoring, debugging, tracing tool. • GUI for classes, methods, objects and can
invoke views and methods via web gui. • https://code.google.com/p/snoop-it/
XSecurity
• Xcode plugin that extends clang analyzer • hops://github.com/XSecurity/XSecurity
Binary + Source
Grep your way to $profit!
• Un-encrypt a ios app and the strings table can reveal a lot… (clutch works well)
• Classdump-z + otool gives more! • Whole companies are built on this =(
Unencrypting
• Cracking the app to view data: – Clutchpatched from cydia – Cracked app to be analyzed ends up in – /var/root/Documents/Cracked/
Grep Your way to $ecurity
hops://github.com/jhaddix/ios_sh/blob/master/ios.sh
Issue Bin or Source Grep string
Web Comms (secure or unsecure)
hop OR hops openUrl, handleOpenURL, NSUrl, writeToUrl, CFStream, NSStreamin
Weak Cert management or SSL
setAllowsAnyHTTPSCer'ficate\|kCFStreamSSLAllowsExpiredRoots\|kCFStreamSSLAllowsExpiredCer'ficates\|kCFStreamSSLAllowsAnyRoot
Exploit mi'ga'ons (PIE, StackProt, ARC)
otool -‐Ivm "$app_binary_path" |grep stack_chk
otool -‐hvm "$app_binary_path” | grep PIE
otool -‐Ivm "$app_binary_path" | grep _objc | sort | sed -‐n '1,10p
Grep Your way to $ecurity Issue Bin or Source grep string
Possible Format string bugs grep -‐i "NSLog \|stringWithFormat\|initWithFormat\|appendFormat\|informa'veTextWithFormat\|predicateWithFormat\|stringByAppendingFormat\|alertWithMessageText\|NSExcep'on +format\|NSRunAlertPanel" | grep "%@"
App checks for JB status or has JB protec'on (common ones)
grep "^/bin/bash$\|^/Applica'ons/Cydia.app$\|/cydia.log$"
Pasteboard enabled generalpasteboard
SQL from dynamic input (possible client/server SQLi)
grep -‐i "^begin transac'on\|^select .* from \|^update .* set \|^delete from \|^insert into " | grep "%@" | grep -‐v "SELECT id,access_token FROM test_account WHERE app_id"
Registered URL Schemes (for info only)
grep -‐oE "[a-‐zA-‐Z][a-‐zA-‐Z0-‐9\+\-‐\.]*://[^[:space:]\<\>\#\"\']+"|grep -‐v "hop://\|hops://\|radr://”
Grep Your way to $Privacy Issue Bin + Source
Privacy API’s
App uses address book ABAddressBookCopyArrayOfAllPeople\|ABAddressBook
App uses ad or analy'cs (some) GADBannerView\|GADRequest\|GADInters''al\|kGADAd\|GADSearch\|GoogleConversionPin\|adwhirl
App has logging enabled _NSLog$
App uses Bluetooth GKSession\|MCSession\|CBCentralManager
App uses Calendar EKEventStore
Possible Weak or Guessable Hash/crypto
CC_MD2\|CC_MD4\|CC_MD5\|CC_SHA1\|kCCAlgorithmDES
App uses geoloaca'on clloca'on
App stores photos world accessible UIImageWriteToSavedPhotosAlbum
App uses Push No'fica'ons registerForRemoteNo'fica'onTypes
Grep Your way to $Privacy Issue Bin + Source
Privacy API’s
App uses address book ABAddressBookCopyArrayOfAllPeople\|ABAddressBook
App uses ad or analy'cs (some) GADBannerView\|GADRequest\|GADInters''al\|kGADAd\|GADSearch\|GoogleConversionPin\|adwhirl
App has logging enabled _NSLog$
App uses Bluetooth GKSession\|MCSession\|CBCentralManager
App uses Calendar EKEventStore
Possible Weak or Guessable Hash/crypto
CC_MD2\|CC_MD4\|CC_MD5\|CC_SHA1\|kCCAlgorithmDES
App uses geoloaca'on clloca'on
App stores photos world accessible UIImageWriteToSavedPhotosAlbum
App uses Push No'fica'ons registerForRemoteNo'fica'onTypes
Bin Analysis w/Hopper
• http://www.hopperapp.com/ DVIA Challenges
• Binary Patching • Broken Cryptography • Security Via Untrusted Inputs
Common Findings (some)
Client Side Vulns Vuln Notes
Format String Injec'on
Image Cache Disclosure Saving priv photos to the global photoroll instead of sandbox
Client side SQL injec'on Low risk Sensi've data over unauthen'cated Web Service
Encryp'on Using ECB Mode Failure to Validate Source Applica'on from openURL
General Pasteboard Use
iOS Keyboard Cache Exposure
Weak Cryptographic Hash: Hardcoded Salt
Keychain entry unencrypted
Client Side Vulns Vuln Notes
Cryptographic Keys Stored in Client Usually in binary or sqlitedb Applica'on Compiled Without Stack-‐Smashing Protec'on
Found using otool
Applica'on Compiled Without PIE Protec'on
Found using otool
Applica'on Creden'als Stored Clear Text in Memory
Applica'on Logs Leak Sensi've Info (NSLog) Found by monitoring ASL Sensi've data storage using a binary sqlite database (NSManagedObjects) Sensi've data storage using binary plists (NSUserDefaults)
Authoriza'on Bypass On pin/pass screens, Usually using cycript
Transport and Web Vulns Vuln Notes
No SSL Preoy much all sensi've info should be over HTTPS
Weak Cer'ficate Management See slide 54
HTTPS can be downgraded to HTTP Anyone in the middle can use SSLstrip to do this, or burp -‐ hop://goo.gl/DnP4GA
Account Enumera'on via Response Usernames mostly
Sensi've data sent to ad or analy'cs endpoint (hop or hops)
Baking in a ad/analy'cs framework can o}en do things devs don’t even know about
Arbitrary file upload Self explanatory; try old tricks here -‐ hop://goo.gl/HqMDeY
Web Service Data Exposure A lot of these mobile WS will return a ton data, and the app will only parse out some of it. An aoacker will get it all.
Transport and Web Vulns Vuln
SSL/Cert Pinning implementa'on Defeatable sslkillswitch
CSRF
Open Redirec'on
XML En'ty Expansion Injec'on
Weak Serverside SSL Implementa'on SSLabs or SSLAudit -‐ hop://goo.gl/5CtFBq
Logout does not destroy session serverside (cookie reuse a}er logout)
Transport and Web Vulns Vuln
Applica'on accepts message switch (GET/POST)
Verbose Errors
SQL Injec'on Burp scanner or Generic_SQLi.txt fuzz list
XSS
Creden'als/session tokens Sent In URL Query String
Lack of Account Lockout
Web service does not use correct content type Make sure all web service calls return non javascript executable content types
UDID Leakage
Directory Traversal
Logout Does Not Clear Saved Creden'als / Destroy Session
Copy cookies, logout, replace cookies
Things we didn’t talk about due to time constraints:
1. Manually decryp'ng apps 2. Classdump-‐z 3. Otool 4. MobileSubstrate or Theos or CaptainHook frameworks 5. Flex patching for beginners 6. XML Parsing vulns 7. KB cache 8. Snapshot caching 9. Copy paste buffer / UI pasteboard 10. URL Scheme fuzzing (can be done easily with idb) 11. URL Scheme spoofing 12. Capturing non-‐hop(s) traffic 13. Cookie parsing 14. Filemon 15. Sqlite injec'on 16. Shared keychain access
Runtime
Cycript
• Labs – DVIA Jialbreak test 1 – DVIA Login Method 1
• Practical reading: – /resources/cycript and GDB/
Special Thanks
James Fitts Daniel Miessler
Dawn Isabell Brad Wolfe
Prateek Gianchandani
Sources: Sep 12, 2013 -‐ How to Assess and Secure iOS apps by NCC Group May 2, 2012 -‐ iOSApplica'on (In)Securityby Dominic Chell October 2, 2012 – iOS Security by Apple April 21, 2011 -‐ Secure Development on iOS by David Thiel (NCC Group) Aug 11, 2011 – Audi�ng iPhone and iPad applica'ons by Ilja Van Sprundel iOS Reverse engineering blog content by Prateek Gianchandani of Highal'tudehacks.com Tool Demos: Daniel Mayer – idb Sa'sh Bomse� -‐ FileDP Auxiliary reading: My Old class hops://dl.dropboxusercontent.com/u/37776965/Sources_external.rar
Collage of #FAIL
Screenshots aka iOS Backgrounding
Logging
3rd party analy'cs companies are sent your age, zip, loca'on, UDID, etc
Library/Preferences/com.kik.chat.plist: -‐ Username -‐ Password -‐ Email
Documents/kik.sqlite: –Chat history