.                                  Secure Development on iOS                             Advice for developers and penetra...
Outline1.   Intro to iOS2.   Objective-C Primer3. Testing Setup4. Security-Relevant APIs       TLS and Networking       Da...
Intro    My perspective is that of a penetration tester (not developer)    Info here is ideally of use to both testers and...
Intro to iOSIntro to iPhoneiPhone Conceptual Design     David Thiel (iSEC Partners)   Secure Development on iOS   SOURCE B...
Intro to iOSIntro to iOSIt’s an OS, but with an i      High-level API, “Cocoa Touch”      Development in XCode            ...
Objective-C PrimerObjective-CHow to spot it from a very long way away     C + Smalltalk…ish     Uses “infix” notation:     ...
Objective-C PrimerObjective-C in 1 slideDefining Interfaces@interface Classname : NSParentObject {SomeType aThing; // insta...
Objective-C PrimerObjective-C in 2 slidesAlternative interface declaration#import "NSParentClass.h"@interface Classname : ...
Objective-C PrimerObjective-C in 3 slides or soInfix and dot notation@implementation Classname@synthesize blorg;           ...
Objective-C PrimerObjective-C NotsubclassingCategories        Simple method for adding functionality to classes without su...
Objective-C PrimerMemory ManagementRetain/Release      No garbage collection in iOS      Must track with “retain” and “rel...
Testing SetupXCode  David Thiel (iSEC Partners)    Secure Development on iOS   SOURCE Boston 2011   12 / 68
Testing SetupTesting SetupIntercepting secure communications     Standard proxy intercept won’t work     Cert errors are a...
Testing SetupStunnel config; SSL client modeclient = yes; service -level configuration[https]accept    = 127.0.0.1:80connec...
Testing SetupProxy Config   David Thiel (iSEC Partners)    Secure Development on iOS   SOURCE Boston 2011   15 / 68
Testing SetupThe Sandbox MechanismSeatbelt     aka “Seatbelt”     Based upon TrustedBSD MAC framework     Unlike Android’s...
Testing SetupThe Sandbox MechanismJailbreaking        On jailbroken devices, sandbox no longer applies        However, dev...
Testing SetupThe Sandbox MechanismJailbreak Detection      No more official Apple jailbreak detection API      If you must d...
Testing SetupBinary Analysis       Useful for black box testing or self-testing       Disassembly of Mach-O binary format ...
Testing SetupBinary Analysisotoolotool -toV /Applications/iCal.app/Contents/MacOS/iCal/Applications/iCal.app/        Conte...
Testing SetupBinary Analysisotxhttp://otx.osxninja.com/-(BOOL)[NSString(NSStringExtras) isFeedURLString]+0 00003488 55    ...
Testing SetupBinary Analysisclass-dumphttp://iphone.freecoder.org/classdump_en.html (or via Cydia)class-dump-x /Developer/...
Testing SetupStatic AnalysisXCode & Clang     Clang analyzer merged into XCode     “Build & Analyze” option     Identifies ...
Testing SetupStatic AnalysisOutput     David Thiel (iSEC Partners)    Secure Development on iOS   SOURCE Boston 2011   24 ...
App Structure   Local StorageKeyboard Caching   Keyboard cache used for form autocompletion   /root/Library/Keyboard/dynam...
Security-Relevant APIs   TLS and NetworkingNetworkingTLS and NSURL Handling     Standard method for working with URLs     ...
Security-Relevant APIs   TLS and NetworkingNetworkingTLS and NSURL Handling        Check for NSURLRequest verification bypa...
Security-Relevant APIs   TLS and NetworkingNetworkingNSStreams     Good for non-HTTP traffic or going slightly lower-level//...
Security-Relevant APIs   TLS and NetworkingNetworkingCFStreams     Slightly lower-level still     Security defined by kCFSt...
Security-Relevant APIs   Data StorageLocal Data StorageThe Various MechanismsA few ways data is stored (and potentially ex...
Security-Relevant APIs   App LayoutAnatomy of an App     ˜/Library/Application Support/iPhone Simulator/Applications/(appI...
Security-Relevant APIs   App LayoutCookiesNSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomainOrOtherAuthoritativeSoundingPe...
Security-Relevant APIs   App LayoutSQLite and SQL injectionDynamic SQLNSString *uid = [myHTTPConnection getUID];NSString *...
Security-Relevant APIs   App LayoutSQLite and SQL injectionParameterized SQLconst char *sql = "SELECT username FROM users ...
Security-Relevant APIs   App LayoutCaching         HTTP & HTTPS requests cached by default         Can be prevented by NSU...
Security-Relevant APIs   App LayoutGeolocationBest Practices      Use least degree of accuracy necessary      Check for gr...
Security-Relevant APIs   App LayoutGeolocationAccuracy SettingsSeveral accuracy constants:CLLocationAccuracy kCLLocationAc...
Security-Relevant APIs      The KeychainThe Keychain   Keychain is where secret stuff goes            Argh! Do not store th...
Security-Relevant APIs   The KeychainThe KeychainKey protection      Pass an appropriate kSecAttrAccessible value to SecIt...
Security-Relevant APIs   The KeychainThe KeychainShared keychains        For using the same keychain among different apps5 ...
Security-Relevant APIs   The KeychainThe KeychainCertificates     On device, can be installed via e-mail, Safari or iTunes ...
Security-Relevant APIs   The KeychainData ProtectionImproving file and keychain protection     By default, data encrypted w...
Security-Relevant APIs   The KeychainData ProtectionUsage        2 methods for enabling        Pass NSDataWritingFileProte...
Security-Relevant APIs   The KeychainEntropyHow does it work?     Using Cocoa, not /dev/random     Gathered via SecRandomC...
Security-Relevant APIs   BackgroundingBackgroundingInitiating Background Tasks      Probably most security-relevant API in...
Security-Relevant APIs   BackgroundingBackgroundingConcerns     Note: app is snapshotted upon backgrounding     Prior to t...
Security-Relevant APIs   BackgroundingBackgroundingState Transitions      Detect state transitions      Key state transiti...
Security-Relevant APIs   IPCIPCApplication URL Schemes      Apps can register their own URL handlers — added by editing th...
Security-Relevant APIs   IPCIPCApplication URL Schemes      Deprecated delegation method:      - (BOOL)application:(UIAppl...
Security-Relevant APIs    IPCIPCURL handler conflicts         What happens if two apps use the same handler?               ...
Security-Relevant APIs   IPCIPCPush Notifications      Registering for notifications:[[UIApplication sharedApplication] regi...
Security-Relevant APIs   IPCCopy/PastePasteboards     Obligatory dig at Apple re: copy/paste debacle     2 system UIPasteb...
Security-Relevant APIs   IPCCopy/PastePasteboards     Also “private” application pasteboards, which (in true Objective-C f...
Security-Relevant APIs   IPCCopy/PasteExample AbuseHow not to pasteboard: Twitter OAuth library7- (void) pasteboardChanged...
Security-Relevant APIs   IPCCopy/PasteDisabling it             Possible mitigation: For fields with sensitive data, disable...
UDIDsUDIDsUse and Abuse        Unique identifier derived from hardware information        Often abused as a user tracking m...
UDIDsUDIDsUDIDFaker available on Cydia      David Thiel (iSEC Partners)   Secure Development on iOS   SOURCE Boston 2011  ...
UDIDsUDIDsDon’t use them.Summary:     Don’t rely on UDID for anything ever     Don’t use it for tracking, it gets you bad ...
Common Attack Scenarios   Old C StuffClassic C AttacksNothing new here     Still has the same classic issues     Buffer over...
Common Attack Scenarios   New Objective-C StuffObject use after release        Exploitable! Under some circumstances.10    ...
Common Attack Scenarios   New Objective-C StuffiOS & Format Strings   withFormat/appendingFormat family   %x works — %n doe...
Common Attack Scenarios   New Objective-C StuffFormat StringsFormat string confusion      Found on pentest:      NSString m...
Common Attack Scenarios   New Objective-C StuffFormat StringsLikely culprits       [NSString *WithFormat]       [NSString s...
Secure coding checklistSecure coding checklistOr penetration tester’s hit list       HTTPS used and correctly configured (i...
Secure coding checklistSecure coding checklistContinued     UIPasteBoards not leaking sensitive data     Correct object de...
Questions                               Q?                              ://..David Thiel (i...
Appendix     For Further ReadingFor Further Reading I   H. Dwivedi, C. Clark, D. Thiel   Mobile Application Security.   Mc...
Appendix     For Further ReadingFor Further Reading II   Other resources   http://culater.net/wiki/moin.cgi/CocoaReverseEn...
Upcoming SlideShare
Loading in...5
×

David Thiel - Secure Development On iOS

9,514

Published on

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

No Downloads
Views
Total Views
9,514
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
160
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

David Thiel - Secure Development On iOS

  1. 1. . Secure Development on iOS Advice for developers and penetration testers. David Thiel SOURCE Boston 2011 David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 1 / 68
  2. 2. Outline1. Intro to iOS2. Objective-C Primer3. Testing Setup4. Security-Relevant APIs TLS and Networking Data Storage The Keychain Backgrounding IPC App URLs Copy/Paste .5 UDIDs .6 Common Attack Scenarios Old C Stuff New Objective-C Stuff7. Secure coding checklist David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 2 / 68
  3. 3. Intro My perspective is that of a penetration tester (not developer) Info here is ideally of use to both testers and developers Assumes little to no iOS knowledge Focus is app security, not OS security Takeaways: be able fix or break your own or others’ iOS apps David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 3 / 68
  4. 4. Intro to iOSIntro to iPhoneiPhone Conceptual Design David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 4 / 68
  5. 5. Intro to iOSIntro to iOSIt’s an OS, but with an i High-level API, “Cocoa Touch” Development in XCode So yes, you need a Mac iOS Simulator (not emulator) Compiles iOS apps to native code to run locally Applications written primarily in Objective-C David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 5 / 68
  6. 6. Objective-C PrimerObjective-CHow to spot it from a very long way away C + Smalltalk…ish Uses “infix” notation: [Object messagePassedToObject:argument]; It is not to everyone’s tastes Some of us have very refined tastes David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 6 / 68
  7. 7. Objective-C PrimerObjective-C in 1 slideDefining Interfaces@interface Classname : NSParentObject {SomeType aThing; // instance variables}+(type)classMethod:(vartype)myVariable;-(type)instanceMethod:(vartype)myVariable;@endThese go in .h files, and define the structure of objects (like C structs). David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 7 / 68
  8. 8. Objective-C PrimerObjective-C in 2 slidesAlternative interface declaration#import "NSParentClass.h"@interface Classname : NSParentClass { @public NSURL *blorg; @private NSString *gurgle;}@property(readonly) NSURL *blorg;@property(copy) NSString *gurgle;This is the “2.0” way to declare interfaces. David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 8 / 68
  9. 9. Objective-C PrimerObjective-C in 3 slides or soInfix and dot notation@implementation Classname@synthesize blorg; // generates set/get methods@synthesize gurgle;Instance *myInstance = [[Instance alloc] init];[myInstance setGurgle:@"eep"]; // infix notationmyInstance.gurgle = @"eep"; // dot notationThis is the “implementation”, stored in .m files. @synthesize creates getter/settermethods for properties. David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 9 / 68
  10. 10. Objective-C PrimerObjective-C NotsubclassingCategories Simple method for adding functionality to classes without subclassing Just define a new @interface and implementation with new methods@implementation NSURL (CategoryName)- (BOOL) isPurple;{ if ([self isColor:@"purple"]) return YES; else return NO;}@end David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 10 / 68
  11. 11. Objective-C PrimerMemory ManagementRetain/Release No garbage collection in iOS Must track with “retain” and “release” methodsClassname *myClass = [[Classname alloc] init]; // Retain count: 1... // Can be shortened to // [Classname new];[myClass release]; David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 11 / 68
  12. 12. Testing SetupXCode David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 12 / 68
  13. 13. Testing SetupTesting SetupIntercepting secure communications Standard proxy intercept won’t work Cert errors are a hard failure Options: Change source to use HTTP Use device + cert for proxy Use simulator with → proxy → real site David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 13 / 68
  14. 14. Testing SetupStunnel config; SSL client modeclient = yes; service -level configuration[https]accept = 127.0.0.1:80connect = 10.10.1.50:443TIMEOUTclose = 0 David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 14 / 68
  15. 15. Testing SetupProxy Config David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 15 / 68
  16. 16. Testing SetupThe Sandbox MechanismSeatbelt aka “Seatbelt” Based upon TrustedBSD MAC framework Unlike Android’s UID-based segregation, apps run as one user Seatbelt policies provide needed segregation. Probably. Sandbox policies now compiled and rolled into the kernel On jailbroken devices, sandbox no longer applies David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 16 / 68
  17. 17. Testing SetupThe Sandbox MechanismJailbreaking On jailbroken devices, sandbox no longer applies However, devs for sideloaded apps can voluntarily hop into one1 Documented profiles for OSX:kSBXProfileNoNetwork (= "nonet")kSBXProfileNoInternet (= "nointernet")kSBXProfilePureComputation (= "pure-computation")kSBXProfileNoWriteExceptTemporary (= "write-tmp-only")kSBXProfileNoWrite (= "nowrite") 1 http://iphonedevwiki.net/index.php/Seatbelt David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 17 / 68
  18. 18. Testing SetupThe Sandbox MechanismJailbreak Detection No more official Apple jailbreak detection API If you must determine whether a device is jailbroken, some possible checks: /bin/bash /bin/ssh /private/var/lib/apt But discriminating against jailbroken devices is not necessarily a great idea And Apple app review may flag it David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 18 / 68
  19. 19. Testing SetupBinary Analysis Useful for black box testing or self-testing Disassembly of Mach-O binary format quite clean Several useful tools: otool, otx, class-dump Use for reversing other applications, or finding what info would be available to a third party Obfuscation is generally pretty futile, but especially in ObjC Encrypted binaries easily dumped2 2 http://www.246tnt.com/iPhone/ David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 19 / 68
  20. 20. Testing SetupBinary Analysisotoolotool -toV /Applications/iCal.app/Contents/MacOS/iCal/Applications/iCal.app/ Contents/MacOS/iCalObjective -C segmentModule 0x22b52c ... Class Definitions defs[0] 0x00204360 isa 0x0020a560 super_class 0x001a5f44 CALCanvasItem name 0x001c6574 CALCanvasAttributedText ... ivars 0x00224300 ivar_count 13 ivar_name 0x001a54e2 _text ivar_type 0x001a53d0 @"NSMutableAttributedString" ivar_offset 0x0000012c ivar_name 0x001a54e8 David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 20 / 68
  21. 21. Testing SetupBinary Analysisotxhttp://otx.osxninja.com/-(BOOL)[NSString(NSStringExtras) isFeedURLString]+0 00003488 55 pushl %ebp+1 00003489 89e5 movl %esp,%ebp+3 0000348b 53 pushl %ebx+4 0000348c 83ec14 subl $0x14 ,%esp+7 0000348f 8b5d08 movl 0x08(%ebp),%ebx+10 00003492 c744240844430700 movl $0x00074344 ,0x08(%esp)feed:+18 0000349a a180a00700 movl 0x0007a080 ,%eax _web_hasCaseInsensitivePrefix:+23 0000349f 89442404 movl %eax,0x04(%esp)+27 000034a3 891c24 movl %ebx,(%esp)+30 000034a6 e850420800 calll 0x000876fb -[(%esp,1) _web_hasCaseInsensitivePrefix:] David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 21 / 68
  22. 22. Testing SetupBinary Analysisclass-dumphttp://iphone.freecoder.org/classdump_en.html (or via Cydia)class-dump-x /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/ iPhoneSimulator3.0.sdk/Applications/MobileSafari.app < snip > @protocol CALCanvasTextProtocol - (id)attributes; - (id)foregroundColor; - (float)fontSize; @end @protocol CALDetachmentDelegate - (int) decideDetachmentFor:(id)fp8 withOccurrence:(id)fp12; @end David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 22 / 68
  23. 23. Testing SetupStatic AnalysisXCode & Clang Clang analyzer merged into XCode “Build & Analyze” option Identifies memory leakage, use-after-free, etc. Note: in some recent XCode versions, Analyzer results only show for device SDK builds. Meh David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 23 / 68
  24. 24. Testing SetupStatic AnalysisOutput David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 24 / 68
  25. 25. App Structure Local StorageKeyboard Caching Keyboard cache used for form autocompletion /root/Library/Keyboard/dynamic-text.dat Already disabled for password fields Should be disabled for any potentially sensitive fields Set UITextField property autocorrectionType = UITextAutocorrectionNo David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 25 / 68
  26. 26. Security-Relevant APIs TLS and NetworkingNetworkingTLS and NSURL Handling Standard method for working with URLs SSL/TLS handled properly! Bypassing failed verification not allowed by default. So, of course, people turn it off David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 26 / 68
  27. 27. Security-Relevant APIs TLS and NetworkingNetworkingTLS and NSURL Handling Check for NSURLRequest verification bypass via setAllowsAnyHTTPSCertificate SSL verification bypass via NSURLConnection delegation Search for continueWithoutCredentialForAuthenticationChallenge3 Extra bonus stupid: Define category method to slip by Apple’s private API checks4 3 http://stackoverflow.com/questions/933331/ 4 http://stackoverflow.com/questions/2001565/ David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 27 / 68
  28. 28. Security-Relevant APIs TLS and NetworkingNetworkingNSStreams Good for non-HTTP traffic or going slightly lower-level// First we define the host to be contactedNSHost *myhost = [NSHost hostWithName:[@"www.conglomco.com"]];// Then we create[NSStream getStreamsToHost:myhost port:443 inputStream:&MyInputStream outputStream:&MyOutputStream];[MyInputStream setProperty:NSStreamSocketSecurityLevelTLSv1 // Note forKey:NSStreamSocketSecurityLevelKey]; David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 28 / 68
  29. 29. Security-Relevant APIs TLS and NetworkingNetworkingCFStreams Slightly lower-level still Security defined by kCFStreamPropertySSLSettings Has sad set of constants ⌢ ¨CFStringRef kCFStreamSSLLevel;CFStringRef kCFStreamSSLAllowsExpiredCertificates;CFStringRef kCFStreamSSLAllowsExpiredRoots;CFStringRef kCFStreamSSLAllowsAnyRoot;CFStringRef kCFStreamSSLValidatesCertificateChain;CFStringRef kCFStreamSSLPeerName; David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 29 / 68
  30. 30. Security-Relevant APIs Data StorageLocal Data StorageThe Various MechanismsA few ways data is stored (and potentially exposed): SQLite Core Data Internally, SQLite Cookie management Caches plists David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 30 / 68
  31. 31. Security-Relevant APIs App LayoutAnatomy of an App ˜/Library/Application Support/iPhone Simulator/Applications/(appID)./Documents → properties, logs./Library/Caches → cachey things./Library/Caches/Snapshots → screenshots of your app./Library/Cookies → cookie plists./Library/Preferences → various preference plists./Library/WebKit → WebKit local storage./Appname.app → app resources: binary, graphics, nibs, Info.plist./tmp → tmp David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 31 / 68
  32. 32. Security-Relevant APIs App LayoutCookiesNSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomainOrOtherAuthoritativeSoundingPeopleByApp Manipulated by the URL loading system Can alter cookieAcceptPolicy to: NSHTTPCookieAcceptPolicyNever NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain Note that this may affect other running applications In OS X, cookies and cookie policy are shared among apps In iOS, only cookie policy is shared David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 32 / 68
  33. 33. Security-Relevant APIs App LayoutSQLite and SQL injectionDynamic SQLNSString *uid = [myHTTPConnection getUID];NSString *statement = [NSString StringWithFormat:@"SELECT username FROM users where uid = %@",uid];const char *sql = [statement UTF8String]; David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 33 / 68
  34. 34. Security-Relevant APIs App LayoutSQLite and SQL injectionParameterized SQLconst char *sql = "SELECT username FROM users where uid = ?";sqlite3_prepare_v2(db, sql, -1, &selectUid , NULL);sqlite3_bind_int(selectUid , 1, uid);int status = sqlite3_step(selectUid); David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 34 / 68
  35. 35. Security-Relevant APIs App LayoutCaching HTTP & HTTPS requests cached by default Can be prevented by NSURLConnection delegate-(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse{ NSCachedURLResponse *newCachedResponse=cachedResponse; if ([[[[cachedResponse response] URL] scheme] isEqual:@"https"]) { newCachedResponse=nil; } return newCachedResponse;} David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 35 / 68
  36. 36. Security-Relevant APIs App LayoutGeolocationBest Practices Use least degree of accuracy necessary Check for graceful handling of locationServicesEnabled and authorizationStatus method responses If you don’t want to handle subpoenas from divorce lawyers: Don’t log locally Anonymize server-side data Prune logs David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 36 / 68
  37. 37. Security-Relevant APIs App LayoutGeolocationAccuracy SettingsSeveral accuracy constants:CLLocationAccuracy kCLLocationAccuracyBestForNavigation;CLLocationAccuracy kCLLocationAccuracyBest;CLLocationAccuracy kCLLocationAccuracyNearestTenMeters;CLLocationAccuracy kCLLocationAccuracyHundredMeters;CLLocationAccuracy kCLLocationAccuracyKilometer;CLLocationAccuracy kCLLocationAccuracyThreeKilometers; David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 37 / 68
  38. 38. Security-Relevant APIs The KeychainThe Keychain Keychain is where secret stuff goes Argh! Do not store this data in NSUserDefaults! Encrypted with device-specific key Apps “can’t read”, not included in backups Simpler API than OS X: SecItemAdd, SecItemUpdate, SecItemCopyMatching Not available in simulator for pre-4.0 ← cause it’s got keys in it, see David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 38 / 68
  39. 39. Security-Relevant APIs The KeychainThe KeychainKey protection Pass an appropriate kSecAttrAccessible value to SecItemAdd:CFTypeRef kSecAttrAccessibleWhenUnlocked;CFTypeRef kSecAttrAccessibleAfterFirstUnlock;CFTypeRef kSecAttrAccessibleAlways;CFTypeRef kSecAttrAccessibleWhenUnlockedThisDeviceOnly;CFTypeRef kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly;CFTypeRef kSecAttrAccessibleAlwaysThisDeviceOnly; David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 39 / 68
  40. 40. Security-Relevant APIs The KeychainThe KeychainShared keychains For using the same keychain among different apps5 Used by setting kSecAttrAccessGroup on init Apps must have same keychain-access-groups Apps can only have one access group On jailbroken phone…all bets off 5 http://useyourloaf.com/blog/2010/4/3/keychain-group-access.html David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 40 / 68
  41. 41. Security-Relevant APIs The KeychainThe KeychainCertificates On device, can be installed via e-mail, Safari or iTunes sync On older simulators, no such luck Certs still verified, but no way to install new ones Since they’re stored in the Keychain Stubs necessary for detecting simulator vs. device David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 41 / 68
  42. 42. Security-Relevant APIs The KeychainData ProtectionImproving file and keychain protection By default, data encrypted with “hardware” key In iOS 4, “hardware” key can supplemented with PIN Developers can also mark files as “protected” Files encrypted, unreadable while device is locked David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 42 / 68
  43. 43. Security-Relevant APIs The KeychainData ProtectionUsage 2 methods for enabling Pass NSDataWritingFileProtectionComplete to writeToFile method of NSData object Set NSFileProtectionKey to NSFileProtectionComplete on NSFileManager object Again, data not accessible when device is locked Check for data availability before use6 Clean up when UIApplicationProtectedDataWillBecomeUnavailable 6 http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/StandardBehaviors/StandardBehaviors.html David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 43 / 68
  44. 44. Security-Relevant APIs The KeychainEntropyHow does it work? Using Cocoa, not /dev/random Gathered via SecRandomCopyBytes Again, does not work in simulator Obviously, rand(), random(), arc4random() are all non-startersint result = SecRandomCopyBytes(kSecRandomDefault , sizeof(int), (uint8_t*)& randomResult); David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 44 / 68
  45. 45. Security-Relevant APIs BackgroundingBackgroundingInitiating Background Tasks Probably most security-relevant API in iOS 4.0 Use beginBackgroundTaskWithExpirationHandler method to initiate background tasks Needs matching endBackgroundTask method Remaining task time stored in backgroundTimeRemaining property David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 45 / 68
  46. 46. Security-Relevant APIs BackgroundingBackgroundingConcerns Note: app is snapshotted upon backgrounding Prior to this, application should remove any sensitive data from view Use splash screen or set hidden or alpha properties of UIWindow David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 46 / 68
  47. 47. Security-Relevant APIs BackgroundingBackgroundingState Transitions Detect state transitions Key state transition methods:application:didFinishLaunchingWithOptions:applicationDidBecomeActive:applicationWillResignActive:applicationDidEnterBackground:applicationWillEnterForeground:applicationWillTerminate: David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 47 / 68
  48. 48. Security-Relevant APIs IPCIPCApplication URL Schemes Apps can register their own URL handlers — added by editing the plist, usually from XCode Called just like any URL, with multiple parameters, e.g. openURL:[NSURL URLWithString:@"myapp://?foo=urb&blerg=gah"]; Can be called by app or web page Without user confirmation… Params accessible to receiving app via a delegate David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 48 / 68
  49. 49. Security-Relevant APIs IPCIPCApplication URL Schemes Deprecated delegation method: - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url New method: - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id) annotation Allows for determining calling application, receives data in plist form Obviously, sanitization is key here, especially given… David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 49 / 68
  50. 50. Security-Relevant APIs IPCIPCURL handler conflicts What happens if two apps use the same handler? If an Apple app uses it: Apple app launches Third-party apps: “Undefined”“If your URL type includes a scheme that is identical to one defined by Apple, the Apple-provided application that handles a URL with that scheme (forexample, “mailto”) is launched instead of your application. If a URL type registered by your application includes a scheme that conflicts with a schemeregistered by another third-party application, the application that launches for a URL with that scheme is undefined.” May go to the last claiming app…ew. Hence: be wary of passing private data in app URLs David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 50 / 68
  51. 51. Security-Relevant APIs IPCIPCPush Notifications Registering for notifications:[[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)]; Receiving notifications:- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions Check for validation of userInfo and launchOptions David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 51 / 68
  52. 52. Security-Relevant APIs IPCCopy/PastePasteboards Obligatory dig at Apple re: copy/paste debacle 2 system UIPasteboard access methods: UIPasteboardNameGeneral & UIPasteboardNameFind Pasteboards marked “persistent” will be kept in local storage David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 52 / 68
  53. 53. Security-Relevant APIs IPCCopy/PastePasteboards Also “private” application pasteboards, which (in true Objective-C form) are not in any way “private” Occasionally used as IPC hack Migrating data from free → paid app I saw one suggestion to transfer private keys with the pasteboard ⌢ ¨ Bottom line: avoid sensitive data here & clean up after yourself Clear pasteboard on applicationWillTerminate pasteBoard.items = nil David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 53 / 68
  54. 54. Security-Relevant APIs IPCCopy/PasteExample AbuseHow not to pasteboard: Twitter OAuth library7- (void) pasteboardChanged: (NSNotification *) note { UIPasteboard *pb = [UIPasteboard generalPasteboard]; if ([note.userInfo objectForKey:UIPasteboardChangedTypesAddedKey] == nil) return; NSString *copied = pb.string; if (copied.length != 7 || !copied.oauthtwitter_isNumeric) return; [self gotPin:copied];} 7 3rd-party library, not by Twitter David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 54 / 68
  55. 55. Security-Relevant APIs IPCCopy/PasteDisabling it Possible mitigation: For fields with sensitive data, disable copy/paste menu-(BOOL)canPerformAction:(SEL)action withSender:(id)sender { UIMenuController *menuController = [UIMenuController sharedMenuController]; if (menuController) { [UIMenuController sharedMenuController].menuVisible = NO; }return NO;} Can also disable menu items individually8 8 http://stackoverflow.com/questions/1426731/ David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 55 / 68
  56. 56. UDIDsUDIDsUse and Abuse Unique identifier derived from hardware information Often abused as a user tracking mechanism9 Occasionally abused as an authenticator See: Tapulous Contrary to popular belief, this is mutable 9 http://www.pskl.us/wp/wp-content/uploads/2010/09/iPhone-Applications-Privacy-Issues.pdf David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 56 / 68
  57. 57. UDIDsUDIDsUDIDFaker available on Cydia David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 57 / 68
  58. 58. UDIDsUDIDsDon’t use them.Summary: Don’t rely on UDID for anything ever Don’t use it for tracking, it gets you bad press If you really need to track users, use hash of UDID + salt Check code for use of [[UIDevice currentDevice] uniqueIdentifier] David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 58 / 68
  59. 59. Common Attack Scenarios Old C StuffClassic C AttacksNothing new here Still has the same classic issues Buffer overflows Integer issues, especially with malloc() Why are you malloc’ing, grandpa? We are in the future here Sanitize int calculations with checkint(3) Double-frees Format strings David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 59 / 68
  60. 60. Common Attack Scenarios New Objective-C StuffObject use after release Exploitable! Under some circumstances.10 Procedure: Release object Release some other object Allocate space of same size as first object Write your code to the new buffer … Send message or release to original object 10 http://felinemenace.org/~nemo/slides/eusecwest-STOP-objc-runtime-nmo.pdf David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 60 / 68
  61. 61. Common Attack Scenarios New Objective-C StuffiOS & Format Strings withFormat/appendingFormat family %x works — %n does not ⌢ ¨ %n does still work with regular C code… David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 61 / 68
  62. 62. Common Attack Scenarios New Objective-C StuffFormat StringsFormat string confusion Found on pentest: NSString myStuff = @"Here is my stuff."; myStuff = [myStuff stringByAppendingFormat:[UtilityClass formatStuff: unformattedStuff.text]]; Bzzt. NSString objects aren’t magically safe. NSString myStuff = @"Here is my stuff."; myStuff = [myStuff stringByAppendingFormat:@"%@", [UtilityClass formatStuff :unformattedStuff.text]]; David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 62 / 68
  63. 63. Common Attack Scenarios New Objective-C StuffFormat StringsLikely culprits [NSString *WithFormat] [NSString stringByAppendingFormat] [NSMutableString appendFormat] [NSAlert alertWithMessageText] [NSException] [NSLog] David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 63 / 68
  64. 64. Secure coding checklistSecure coding checklistOr penetration tester’s hit list HTTPS used and correctly configured (i.e. not bypassed by delegation or setAllowsAnyHTTPSCertificate) All format strings properly declared General C issues (malloc(), str*, etc.) Any third-party C/C++ code is suspect Entropy gathered correctly Secure backgrounding David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 64 / 68
  65. 65. Secure coding checklistSecure coding checklistContinued UIPasteBoards not leaking sensitive data Correct object deallocation, no use-after-release URL handler parameters sanitized Secure keychain usage No inappropriate data stored on local filesystem CFStream, NSStream, NSURL inputs sanitized/encoded No direct use of UDID David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 65 / 68
  66. 66. Questions Q? ://..David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 66 / 68
  67. 67. Appendix For Further ReadingFor Further Reading I H. Dwivedi, C. Clark, D. Thiel Mobile Application Security. McGraw Hill, 2010 Neil Archibald STOP!!! Objective-C Run-TIME. http: //felinemenace.org/~nemo/slides/eusecwest-STOP-objc-runtime-nmo.pdf Apple, Inc. iOS Application Programming Guide http://developer.apple.com/library/ios/#documentation/iPhone/ Conceptual/iPhoneOSProgrammingGuide/Introduction/Introduction.html David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 67 / 68
  68. 68. Appendix For Further ReadingFor Further Reading II Other resources http://culater.net/wiki/moin.cgi/CocoaReverseEngineering http://www.musicalgeometry.com/archives/872 http://www.pskl.us/wp/wp-content/uploads/2010/09/ iPhone-Applications-Privacy-Issues.pdf David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 68 / 68
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×