SlideShare uma empresa Scribd logo
1 de 68
Baixar para ler offline
.
                                  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
Outline
1.   Intro to iOS
2.   Objective-C Primer
3. Testing Setup
4. 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 Stuff
7.   Secure coding checklist
       David Thiel (iSEC Partners)   Secure Development on iOS   SOURCE Boston 2011   2 / 68
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
Intro to iOS



Intro to iPhone
iPhone Conceptual Design




     David Thiel (iSEC Partners)   Secure Development on iOS   SOURCE Boston 2011   4 / 68
Intro to iOS



Intro to iOS
It’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
Objective-C Primer



Objective-C
How 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
Objective-C Primer



Objective-C in 1 slide
Defining Interfaces




@interface Classname : NSParentObject {
SomeType aThing; // instance variables
}
+(type)classMethod:(vartype)myVariable;
-(type)instanceMethod:(vartype)myVariable;
@end



These 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
Objective-C Primer



Objective-C in 2 slides
Alternative 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
Objective-C Primer



Objective-C in 3 slides or so
Infix and dot notation




@implementation Classname
@synthesize blorg;                              // generates set/get methods
@synthesize gurgle;


Instance *myInstance = [[Instance alloc] init];


[myInstance setGurgle:@"eep"];                  // infix notation
myInstance.gurgle = @"eep";                     // dot notation



This is the “implementation”, stored in .m files. @synthesize creates getter/setter
methods for properties.




      David Thiel (iSEC Partners)         Secure Development on iOS            SOURCE Boston 2011   9 / 68
Objective-C Primer



Objective-C Notsubclassing
Categories




        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
Objective-C Primer



Memory Management
Retain/Release




      No garbage collection in iOS
      Must track with “retain” and “release” methods


Classname *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
Testing Setup



XCode




  David Thiel (iSEC Partners)    Secure Development on iOS   SOURCE Boston 2011   12 / 68
Testing Setup



Testing Setup
Intercepting 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
Testing Setup



Stunnel config




; SSL client mode
client = yes


; service -level configuration
[https]
accept    = 127.0.0.1:80
connect = 10.10.1.50:443
TIMEOUTclose = 0




     David Thiel (iSEC Partners)    Secure Development on iOS   SOURCE Boston 2011   14 / 68
Testing Setup



Proxy Config




   David Thiel (iSEC Partners)    Secure Development on iOS   SOURCE Boston 2011   15 / 68
Testing Setup



The Sandbox Mechanism
Seatbelt



     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
Testing Setup



The Sandbox Mechanism
Jailbreaking




        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
Testing Setup



The Sandbox Mechanism
Jailbreak 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
Testing Setup



Binary 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
Testing Setup



Binary Analysis
otool



otool -toV /Applications/iCal.app/Contents/MacOS/iCal/Applications/iCal.app/
        Contents/MacOS/iCal
Objective -C segment
Module 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
Testing Setup



Binary Analysis
otx



http://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
Testing Setup



Binary Analysis
class-dump




http://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
Testing Setup



Static Analysis
XCode & 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
Testing Setup



Static Analysis
Output




     David Thiel (iSEC Partners)    Secure Development on iOS   SOURCE Boston 2011   24 / 68
App Structure   Local Storage



Keyboard 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
Security-Relevant APIs   TLS and Networking



Networking
TLS 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
Security-Relevant APIs   TLS and Networking



Networking
TLS 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
Security-Relevant APIs   TLS and Networking



Networking
NSStreams




     Good for non-HTTP traffic or going slightly lower-level


// First we define the host to be contacted
NSHost *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
Security-Relevant APIs   TLS and Networking



Networking
CFStreams




     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
Security-Relevant APIs   Data Storage



Local Data Storage
The Various Mechanisms




A 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
Security-Relevant APIs   App Layout



Anatomy 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
Security-Relevant APIs   App Layout



Cookies
NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomainOrOtherAuthoritativeSoundingPeopleByApp




     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
Security-Relevant APIs   App Layout



SQLite and SQL injection
Dynamic SQL




NSString *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
Security-Relevant APIs   App Layout



SQLite and SQL injection
Parameterized SQL




const 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
Security-Relevant APIs   App Layout



Caching



         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
Security-Relevant APIs   App Layout



Geolocation
Best 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
Security-Relevant APIs   App Layout



Geolocation
Accuracy Settings




Several 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
Security-Relevant APIs      The Keychain



The 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
Security-Relevant APIs   The Keychain



The Keychain
Key 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
Security-Relevant APIs   The Keychain



The Keychain
Shared 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
Security-Relevant APIs   The Keychain



The Keychain
Certificates




     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
Security-Relevant APIs   The Keychain



Data Protection
Improving 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
Security-Relevant APIs   The Keychain



Data Protection
Usage




        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
Security-Relevant APIs   The Keychain



Entropy
How does it work?




     Using Cocoa, not /dev/random
     Gathered via SecRandomCopyBytes
               Again, does not work in simulator

     Obviously, rand(), random(), arc4random() are all non-starters


int result = SecRandomCopyBytes(kSecRandomDefault , sizeof(int), (uint8_t*)&
     randomResult);




      David Thiel (iSEC Partners)             Secure Development on iOS     SOURCE Boston 2011   44 / 68
Security-Relevant APIs   Backgrounding



Backgrounding
Initiating 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
Security-Relevant APIs   Backgrounding



Backgrounding
Concerns




     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
Security-Relevant APIs   Backgrounding



Backgrounding
State 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
Security-Relevant APIs   IPC



IPC
Application 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
Security-Relevant APIs   IPC



IPC
Application 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
Security-Relevant APIs    IPC



IPC
URL 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 (for

example, “mailto”) is launched instead of your application. If a URL type registered by your application includes a scheme that conflicts with a scheme

registered 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
Security-Relevant APIs   IPC



IPC
Push 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
Security-Relevant APIs   IPC



Copy/Paste
Pasteboards




     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
Security-Relevant APIs   IPC



Copy/Paste
Pasteboards




     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
Security-Relevant APIs   IPC



Copy/Paste
Example Abuse




How 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
Security-Relevant APIs   IPC



Copy/Paste
Disabling 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
UDIDs



UDIDs
Use 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
UDIDs



UDIDs
UDIDFaker available on Cydia




      David Thiel (iSEC Partners)   Secure Development on iOS   SOURCE Boston 2011   57 / 68
UDIDs



UDIDs
Don’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
Common Attack Scenarios   Old C Stuff



Classic C Attacks
Nothing 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
Common Attack Scenarios   New Objective-C Stuff



Object 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
Common Attack Scenarios   New Objective-C Stuff



iOS & 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
Common Attack Scenarios   New Objective-C Stuff



Format Strings
Format 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
Common Attack Scenarios   New Objective-C Stuff



Format Strings
Likely culprits




       [NSString *WithFormat]
       [NSString stringByAppendingFormat]
       [NSMutableString appendFormat]
       [NSAlert alertWithMessageText]
       [NSException]
       [NSLog]




       David Thiel (iSEC Partners)               Secure Development on iOS            SOURCE Boston 2011   63 / 68
Secure coding checklist



Secure coding checklist
Or 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
Secure coding checklist



Secure coding checklist
Continued




     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
Questions




                               Q?
                              ://..




David Thiel (iSEC Partners)        Secure Development on iOS   SOURCE Boston 2011   66 / 68
Appendix     For Further Reading



For 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
Appendix     For Further Reading



For 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

Mais conteúdo relacionado

Mais procurados

[Wroclaw #2] iOS Security - 101
[Wroclaw #2] iOS Security - 101[Wroclaw #2] iOS Security - 101
[Wroclaw #2] iOS Security - 101OWASP
 
Обмен учетными данными между iOS 8 приложениями и вебом, Константин Чернухо, ...
Обмен учетными данными между iOS 8 приложениями и вебом, Константин Чернухо, ...Обмен учетными данными между iOS 8 приложениями и вебом, Константин Чернухо, ...
Обмен учетными данными между iOS 8 приложениями и вебом, Константин Чернухо, ...Yandex
 
Dark Side of iOS [SmartDevCon 2013]
Dark Side of iOS [SmartDevCon 2013]Dark Side of iOS [SmartDevCon 2013]
Dark Side of iOS [SmartDevCon 2013]Kuba Břečka
 
Octopus framework; Permission based security framework for Java EE
Octopus framework; Permission based security framework for Java EEOctopus framework; Permission based security framework for Java EE
Octopus framework; Permission based security framework for Java EERudy De Busscher
 
iOS Application Security
iOS Application SecurityiOS Application Security
iOS Application SecurityEgor Tolstoy
 
Asec r01-resting-on-your-laurels-will-get-you-pwned
Asec r01-resting-on-your-laurels-will-get-you-pwnedAsec r01-resting-on-your-laurels-will-get-you-pwned
Asec r01-resting-on-your-laurels-will-get-you-pwnedDinis Cruz
 
iOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for BeginnersiOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for BeginnersRyanISI
 
Shellcoding in linux
Shellcoding in linuxShellcoding in linux
Shellcoding in linuxAjin Abraham
 
Top Ten Proactive Web Security Controls v5
Top Ten Proactive Web Security Controls v5Top Ten Proactive Web Security Controls v5
Top Ten Proactive Web Security Controls v5Jim Manico
 
OWASP Melbourne - Introduction to iOS Application Penetration Testing
OWASP Melbourne - Introduction to iOS Application Penetration TestingOWASP Melbourne - Introduction to iOS Application Penetration Testing
OWASP Melbourne - Introduction to iOS Application Penetration Testingeightbit
 
Problems with parameters b sides-msp
Problems with parameters b sides-mspProblems with parameters b sides-msp
Problems with parameters b sides-mspMike Saunders
 
Introduction to OWASP & Web Application Security
Introduction to OWASP & Web Application SecurityIntroduction to OWASP & Web Application Security
Introduction to OWASP & Web Application SecurityOWASPKerala
 
10 Rules for Safer Code [Odoo Experience 2016]
10 Rules for Safer Code [Odoo Experience 2016]10 Rules for Safer Code [Odoo Experience 2016]
10 Rules for Safer Code [Odoo Experience 2016]Olivier Dony
 
Pentesting iOS Apps - Runtime Analysis and Manipulation
Pentesting iOS Apps - Runtime Analysis and ManipulationPentesting iOS Apps - Runtime Analysis and Manipulation
Pentesting iOS Apps - Runtime Analysis and ManipulationAndreas Kurtz
 
Odoo Code Hardening [Odoo Experience 2019]
Odoo Code Hardening [Odoo Experience 2019]Odoo Code Hardening [Odoo Experience 2019]
Odoo Code Hardening [Odoo Experience 2019]Olivier Dony
 
Reverse Engineering iOS apps
Reverse Engineering iOS appsReverse Engineering iOS apps
Reverse Engineering iOS appsMax Bazaliy
 
42 minutes to secure your code....
42 minutes to secure your code....42 minutes to secure your code....
42 minutes to secure your code....Sebastien Gioria
 
Top Ten Java Defense for Web Applications v2
Top Ten Java Defense for Web Applications v2Top Ten Java Defense for Web Applications v2
Top Ten Java Defense for Web Applications v2Jim Manico
 

Mais procurados (20)

[Wroclaw #2] iOS Security - 101
[Wroclaw #2] iOS Security - 101[Wroclaw #2] iOS Security - 101
[Wroclaw #2] iOS Security - 101
 
Обмен учетными данными между iOS 8 приложениями и вебом, Константин Чернухо, ...
Обмен учетными данными между iOS 8 приложениями и вебом, Константин Чернухо, ...Обмен учетными данными между iOS 8 приложениями и вебом, Константин Чернухо, ...
Обмен учетными данными между iOS 8 приложениями и вебом, Константин Чернухо, ...
 
Dark Side of iOS [SmartDevCon 2013]
Dark Side of iOS [SmartDevCon 2013]Dark Side of iOS [SmartDevCon 2013]
Dark Side of iOS [SmartDevCon 2013]
 
Octopus framework; Permission based security framework for Java EE
Octopus framework; Permission based security framework for Java EEOctopus framework; Permission based security framework for Java EE
Octopus framework; Permission based security framework for Java EE
 
iOS Application Security
iOS Application SecurityiOS Application Security
iOS Application Security
 
Asec r01-resting-on-your-laurels-will-get-you-pwned
Asec r01-resting-on-your-laurels-will-get-you-pwnedAsec r01-resting-on-your-laurels-will-get-you-pwned
Asec r01-resting-on-your-laurels-will-get-you-pwned
 
iOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for BeginnersiOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for Beginners
 
Shellcoding in linux
Shellcoding in linuxShellcoding in linux
Shellcoding in linux
 
Is My App Secure ?
 Is My App Secure ? Is My App Secure ?
Is My App Secure ?
 
Top Ten Proactive Web Security Controls v5
Top Ten Proactive Web Security Controls v5Top Ten Proactive Web Security Controls v5
Top Ten Proactive Web Security Controls v5
 
OWASP Melbourne - Introduction to iOS Application Penetration Testing
OWASP Melbourne - Introduction to iOS Application Penetration TestingOWASP Melbourne - Introduction to iOS Application Penetration Testing
OWASP Melbourne - Introduction to iOS Application Penetration Testing
 
Problems with parameters b sides-msp
Problems with parameters b sides-mspProblems with parameters b sides-msp
Problems with parameters b sides-msp
 
Introduction to OWASP & Web Application Security
Introduction to OWASP & Web Application SecurityIntroduction to OWASP & Web Application Security
Introduction to OWASP & Web Application Security
 
10 Rules for Safer Code [Odoo Experience 2016]
10 Rules for Safer Code [Odoo Experience 2016]10 Rules for Safer Code [Odoo Experience 2016]
10 Rules for Safer Code [Odoo Experience 2016]
 
Pentesting iOS Apps - Runtime Analysis and Manipulation
Pentesting iOS Apps - Runtime Analysis and ManipulationPentesting iOS Apps - Runtime Analysis and Manipulation
Pentesting iOS Apps - Runtime Analysis and Manipulation
 
Odoo Code Hardening [Odoo Experience 2019]
Odoo Code Hardening [Odoo Experience 2019]Odoo Code Hardening [Odoo Experience 2019]
Odoo Code Hardening [Odoo Experience 2019]
 
Reverse Engineering iOS apps
Reverse Engineering iOS appsReverse Engineering iOS apps
Reverse Engineering iOS apps
 
Secure coding-guidelines
Secure coding-guidelinesSecure coding-guidelines
Secure coding-guidelines
 
42 minutes to secure your code....
42 minutes to secure your code....42 minutes to secure your code....
42 minutes to secure your code....
 
Top Ten Java Defense for Web Applications v2
Top Ten Java Defense for Web Applications v2Top Ten Java Defense for Web Applications v2
Top Ten Java Defense for Web Applications v2
 

Semelhante a David Thiel - Secure Development On iOS

Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit TestingJames Phillips
 
ioS Einstieg und Ausblick - Mobile DevCon Hamburg 2011 - OPITZ CONSULTING - S...
ioS Einstieg und Ausblick - Mobile DevCon Hamburg 2011 - OPITZ CONSULTING - S...ioS Einstieg und Ausblick - Mobile DevCon Hamburg 2011 - OPITZ CONSULTING - S...
ioS Einstieg und Ausblick - Mobile DevCon Hamburg 2011 - OPITZ CONSULTING - S...OPITZ CONSULTING Deutschland
 
iPhone Workshop Mobile Monday Ahmedabad
iPhone Workshop Mobile Monday AhmedabadiPhone Workshop Mobile Monday Ahmedabad
iPhone Workshop Mobile Monday Ahmedabadmomoahmedabad
 
Mobile Security Assessment: 101
Mobile Security Assessment: 101Mobile Security Assessment: 101
Mobile Security Assessment: 101wireharbor
 
Poco Es Mucho: WCF, EF, and Class Design
Poco Es Mucho: WCF, EF, and Class DesignPoco Es Mucho: WCF, EF, and Class Design
Poco Es Mucho: WCF, EF, and Class DesignJames Phillips
 
iOS,From Development to Distribution
iOS,From Development to DistributioniOS,From Development to Distribution
iOS,From Development to DistributionTunvir Rahman Tusher
 
iOS Development Survival Guide for the .NET Guy
iOS Development Survival Guide for the .NET GuyiOS Development Survival Guide for the .NET Guy
iOS Development Survival Guide for the .NET GuyNick Landry
 
Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofacmeghantaylor
 
Exploring Your Apple M1 devices with Open Source Tools
Exploring Your Apple M1 devices with Open Source ToolsExploring Your Apple M1 devices with Open Source Tools
Exploring Your Apple M1 devices with Open Source ToolsKoan-Sin Tan
 
iOS Development - Offline Class for Jasakomer
iOS Development - Offline Class for JasakomeriOS Development - Offline Class for Jasakomer
iOS Development - Offline Class for JasakomerAndri Yadi
 
Chegg - iOS @ Scale
Chegg - iOS @ ScaleChegg - iOS @ Scale
Chegg - iOS @ ScaleAviel Lazar
 
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsPetr Dvorak
 
Mobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve MobileMobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve MobileKonstantin Loginov
 
Badge des bonnes pratiques OpenSSF de la CII
Badge des bonnes pratiques OpenSSF de la CIIBadge des bonnes pratiques OpenSSF de la CII
Badge des bonnes pratiques OpenSSF de la CIIOpen Source Experience
 
Ruxmon April 2014 - Introduction to iOS Penetration Testing
Ruxmon April 2014 - Introduction to iOS Penetration TestingRuxmon April 2014 - Introduction to iOS Penetration Testing
Ruxmon April 2014 - Introduction to iOS Penetration Testingeightbit
 
Protecting IIoT Endpoints - an inside look at the Industrial Internet Securit...
Protecting IIoT Endpoints - an inside look at the Industrial Internet Securit...Protecting IIoT Endpoints - an inside look at the Industrial Internet Securit...
Protecting IIoT Endpoints - an inside look at the Industrial Internet Securit...team-WIBU
 
Attacking Oracle with the Metasploit Framework
Attacking Oracle with the Metasploit FrameworkAttacking Oracle with the Metasploit Framework
Attacking Oracle with the Metasploit FrameworkChris Gates
 
Jetpack, with new features in 2021 GDG Georgetown IO Extended
Jetpack, with new features in 2021 GDG Georgetown IO ExtendedJetpack, with new features in 2021 GDG Georgetown IO Extended
Jetpack, with new features in 2021 GDG Georgetown IO ExtendedToru Wonyoung Choi
 
iOS Einstieg und Ausblick
iOS Einstieg und AusblickiOS Einstieg und Ausblick
iOS Einstieg und AusblickStefan Scheidt
 

Semelhante a David Thiel - Secure Development On iOS (20)

Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit Testing
 
ioS Einstieg und Ausblick - Mobile DevCon Hamburg 2011 - OPITZ CONSULTING - S...
ioS Einstieg und Ausblick - Mobile DevCon Hamburg 2011 - OPITZ CONSULTING - S...ioS Einstieg und Ausblick - Mobile DevCon Hamburg 2011 - OPITZ CONSULTING - S...
ioS Einstieg und Ausblick - Mobile DevCon Hamburg 2011 - OPITZ CONSULTING - S...
 
iPhone Workshop Mobile Monday Ahmedabad
iPhone Workshop Mobile Monday AhmedabadiPhone Workshop Mobile Monday Ahmedabad
iPhone Workshop Mobile Monday Ahmedabad
 
Mobile Security Assessment: 101
Mobile Security Assessment: 101Mobile Security Assessment: 101
Mobile Security Assessment: 101
 
Poco Es Mucho: WCF, EF, and Class Design
Poco Es Mucho: WCF, EF, and Class DesignPoco Es Mucho: WCF, EF, and Class Design
Poco Es Mucho: WCF, EF, and Class Design
 
iOS,From Development to Distribution
iOS,From Development to DistributioniOS,From Development to Distribution
iOS,From Development to Distribution
 
iOS Development Survival Guide for the .NET Guy
iOS Development Survival Guide for the .NET GuyiOS Development Survival Guide for the .NET Guy
iOS Development Survival Guide for the .NET Guy
 
Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofac
 
Exploring Your Apple M1 devices with Open Source Tools
Exploring Your Apple M1 devices with Open Source ToolsExploring Your Apple M1 devices with Open Source Tools
Exploring Your Apple M1 devices with Open Source Tools
 
Intro to appcelerator
Intro to appceleratorIntro to appcelerator
Intro to appcelerator
 
iOS Development - Offline Class for Jasakomer
iOS Development - Offline Class for JasakomeriOS Development - Offline Class for Jasakomer
iOS Development - Offline Class for Jasakomer
 
Chegg - iOS @ Scale
Chegg - iOS @ ScaleChegg - iOS @ Scale
Chegg - iOS @ Scale
 
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS Basics
 
Mobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve MobileMobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve Mobile
 
Badge des bonnes pratiques OpenSSF de la CII
Badge des bonnes pratiques OpenSSF de la CIIBadge des bonnes pratiques OpenSSF de la CII
Badge des bonnes pratiques OpenSSF de la CII
 
Ruxmon April 2014 - Introduction to iOS Penetration Testing
Ruxmon April 2014 - Introduction to iOS Penetration TestingRuxmon April 2014 - Introduction to iOS Penetration Testing
Ruxmon April 2014 - Introduction to iOS Penetration Testing
 
Protecting IIoT Endpoints - an inside look at the Industrial Internet Securit...
Protecting IIoT Endpoints - an inside look at the Industrial Internet Securit...Protecting IIoT Endpoints - an inside look at the Industrial Internet Securit...
Protecting IIoT Endpoints - an inside look at the Industrial Internet Securit...
 
Attacking Oracle with the Metasploit Framework
Attacking Oracle with the Metasploit FrameworkAttacking Oracle with the Metasploit Framework
Attacking Oracle with the Metasploit Framework
 
Jetpack, with new features in 2021 GDG Georgetown IO Extended
Jetpack, with new features in 2021 GDG Georgetown IO ExtendedJetpack, with new features in 2021 GDG Georgetown IO Extended
Jetpack, with new features in 2021 GDG Georgetown IO Extended
 
iOS Einstieg und Ausblick
iOS Einstieg und AusblickiOS Einstieg und Ausblick
iOS Einstieg und Ausblick
 

Mais de Source Conference

iBanking - a botnet on Android
iBanking - a botnet on AndroidiBanking - a botnet on Android
iBanking - a botnet on AndroidSource Conference
 
I want the next generation web here SPDY QUIC
I want the next generation web here SPDY QUICI want the next generation web here SPDY QUIC
I want the next generation web here SPDY QUICSource Conference
 
From DNA Sequence Variation to .NET Bits and Bobs
From DNA Sequence Variation to .NET Bits and BobsFrom DNA Sequence Variation to .NET Bits and Bobs
From DNA Sequence Variation to .NET Bits and BobsSource Conference
 
Extracting Forensic Information From Zeus Derivatives
Extracting Forensic Information From Zeus DerivativesExtracting Forensic Information From Zeus Derivatives
Extracting Forensic Information From Zeus DerivativesSource Conference
 
How to Like Social Media Network Security
How to Like Social Media Network SecurityHow to Like Social Media Network Security
How to Like Social Media Network SecuritySource Conference
 
Wfuzz para Penetration Testers
Wfuzz para Penetration TestersWfuzz para Penetration Testers
Wfuzz para Penetration TestersSource Conference
 
Security Goodness with Ruby on Rails
Security Goodness with Ruby on RailsSecurity Goodness with Ruby on Rails
Security Goodness with Ruby on RailsSource Conference
 
Securty Testing For RESTful Applications
Securty Testing For RESTful ApplicationsSecurty Testing For RESTful Applications
Securty Testing For RESTful ApplicationsSource Conference
 
Men in the Server Meet the Man in the Browser
Men in the Server Meet the Man in the BrowserMen in the Server Meet the Man in the Browser
Men in the Server Meet the Man in the BrowserSource Conference
 
Advanced Data Exfiltration The Way Q Would Have Done It
Advanced Data Exfiltration The Way Q Would Have Done ItAdvanced Data Exfiltration The Way Q Would Have Done It
Advanced Data Exfiltration The Way Q Would Have Done ItSource Conference
 
Adapting To The Age Of Anonymous
Adapting To The Age Of AnonymousAdapting To The Age Of Anonymous
Adapting To The Age Of AnonymousSource Conference
 
Are Agile And Secure Development Mutually Exclusive?
Are Agile And Secure Development Mutually Exclusive?Are Agile And Secure Development Mutually Exclusive?
Are Agile And Secure Development Mutually Exclusive?Source Conference
 
Advanced (persistent) binary planting
Advanced (persistent) binary plantingAdvanced (persistent) binary planting
Advanced (persistent) binary plantingSource Conference
 
Legal/technical strategies addressing data risks as perimeter shifts to Cloud
Legal/technical strategies addressing data risks as perimeter shifts to CloudLegal/technical strategies addressing data risks as perimeter shifts to Cloud
Legal/technical strategies addressing data risks as perimeter shifts to CloudSource Conference
 
Who should the security team hire next?
Who should the security team hire next?Who should the security team hire next?
Who should the security team hire next?Source Conference
 
The Latest Developments in Computer Crime Law
The Latest Developments in Computer Crime LawThe Latest Developments in Computer Crime Law
The Latest Developments in Computer Crime LawSource Conference
 
How To: Find The Right Amount Of Security Spend
How To: Find The Right Amount Of Security SpendHow To: Find The Right Amount Of Security Spend
How To: Find The Right Amount Of Security SpendSource Conference
 

Mais de Source Conference (20)

Million Browser Botnet
Million Browser BotnetMillion Browser Botnet
Million Browser Botnet
 
iBanking - a botnet on Android
iBanking - a botnet on AndroidiBanking - a botnet on Android
iBanking - a botnet on Android
 
I want the next generation web here SPDY QUIC
I want the next generation web here SPDY QUICI want the next generation web here SPDY QUIC
I want the next generation web here SPDY QUIC
 
From DNA Sequence Variation to .NET Bits and Bobs
From DNA Sequence Variation to .NET Bits and BobsFrom DNA Sequence Variation to .NET Bits and Bobs
From DNA Sequence Variation to .NET Bits and Bobs
 
Extracting Forensic Information From Zeus Derivatives
Extracting Forensic Information From Zeus DerivativesExtracting Forensic Information From Zeus Derivatives
Extracting Forensic Information From Zeus Derivatives
 
How to Like Social Media Network Security
How to Like Social Media Network SecurityHow to Like Social Media Network Security
How to Like Social Media Network Security
 
Wfuzz para Penetration Testers
Wfuzz para Penetration TestersWfuzz para Penetration Testers
Wfuzz para Penetration Testers
 
Security Goodness with Ruby on Rails
Security Goodness with Ruby on RailsSecurity Goodness with Ruby on Rails
Security Goodness with Ruby on Rails
 
Securty Testing For RESTful Applications
Securty Testing For RESTful ApplicationsSecurty Testing For RESTful Applications
Securty Testing For RESTful Applications
 
Esteganografia
EsteganografiaEsteganografia
Esteganografia
 
Men in the Server Meet the Man in the Browser
Men in the Server Meet the Man in the BrowserMen in the Server Meet the Man in the Browser
Men in the Server Meet the Man in the Browser
 
Advanced Data Exfiltration The Way Q Would Have Done It
Advanced Data Exfiltration The Way Q Would Have Done ItAdvanced Data Exfiltration The Way Q Would Have Done It
Advanced Data Exfiltration The Way Q Would Have Done It
 
Adapting To The Age Of Anonymous
Adapting To The Age Of AnonymousAdapting To The Age Of Anonymous
Adapting To The Age Of Anonymous
 
Are Agile And Secure Development Mutually Exclusive?
Are Agile And Secure Development Mutually Exclusive?Are Agile And Secure Development Mutually Exclusive?
Are Agile And Secure Development Mutually Exclusive?
 
Advanced (persistent) binary planting
Advanced (persistent) binary plantingAdvanced (persistent) binary planting
Advanced (persistent) binary planting
 
Legal/technical strategies addressing data risks as perimeter shifts to Cloud
Legal/technical strategies addressing data risks as perimeter shifts to CloudLegal/technical strategies addressing data risks as perimeter shifts to Cloud
Legal/technical strategies addressing data risks as perimeter shifts to Cloud
 
Who should the security team hire next?
Who should the security team hire next?Who should the security team hire next?
Who should the security team hire next?
 
The Latest Developments in Computer Crime Law
The Latest Developments in Computer Crime LawThe Latest Developments in Computer Crime Law
The Latest Developments in Computer Crime Law
 
JSF Security
JSF SecurityJSF Security
JSF Security
 
How To: Find The Right Amount Of Security Spend
How To: Find The Right Amount Of Security SpendHow To: Find The Right Amount Of Security Spend
How To: Find The Right Amount Of Security Spend
 

Último

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 

Último (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 

David Thiel - Secure Development On iOS

  • 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. Outline 1. Intro to iOS 2. Objective-C Primer 3. Testing Setup 4. 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 Stuff 7. Secure coding checklist David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 2 / 68
  • 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. Intro to iOS Intro to iPhone iPhone Conceptual Design David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 4 / 68
  • 5. Intro to iOS Intro to iOS It’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. Objective-C Primer Objective-C How 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. Objective-C Primer Objective-C in 1 slide Defining Interfaces @interface Classname : NSParentObject { SomeType aThing; // instance variables } +(type)classMethod:(vartype)myVariable; -(type)instanceMethod:(vartype)myVariable; @end These 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. Objective-C Primer Objective-C in 2 slides Alternative 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. Objective-C Primer Objective-C in 3 slides or so Infix and dot notation @implementation Classname @synthesize blorg; // generates set/get methods @synthesize gurgle; Instance *myInstance = [[Instance alloc] init]; [myInstance setGurgle:@"eep"]; // infix notation myInstance.gurgle = @"eep"; // dot notation This is the “implementation”, stored in .m files. @synthesize creates getter/setter methods for properties. David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 9 / 68
  • 10. Objective-C Primer Objective-C Notsubclassing Categories 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. Objective-C Primer Memory Management Retain/Release No garbage collection in iOS Must track with “retain” and “release” methods Classname *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. Testing Setup XCode David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 12 / 68
  • 13. Testing Setup Testing Setup Intercepting 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. Testing Setup Stunnel config ; SSL client mode client = yes ; service -level configuration [https] accept = 127.0.0.1:80 connect = 10.10.1.50:443 TIMEOUTclose = 0 David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 14 / 68
  • 15. Testing Setup Proxy Config David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 15 / 68
  • 16. Testing Setup The Sandbox Mechanism Seatbelt 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. Testing Setup The Sandbox Mechanism Jailbreaking 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. Testing Setup The Sandbox Mechanism Jailbreak 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. Testing Setup Binary 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. Testing Setup Binary Analysis otool otool -toV /Applications/iCal.app/Contents/MacOS/iCal/Applications/iCal.app/ Contents/MacOS/iCal Objective -C segment Module 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. Testing Setup Binary Analysis otx http://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. Testing Setup Binary Analysis class-dump http://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. Testing Setup Static Analysis XCode & 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. Testing Setup Static Analysis Output David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 24 / 68
  • 25. App Structure Local Storage Keyboard 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. Security-Relevant APIs TLS and Networking Networking TLS 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. Security-Relevant APIs TLS and Networking Networking TLS 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. Security-Relevant APIs TLS and Networking Networking NSStreams Good for non-HTTP traffic or going slightly lower-level // First we define the host to be contacted NSHost *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. Security-Relevant APIs TLS and Networking Networking CFStreams 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. Security-Relevant APIs Data Storage Local Data Storage The Various Mechanisms A 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. Security-Relevant APIs App Layout Anatomy 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. Security-Relevant APIs App Layout Cookies NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomainOrOtherAuthoritativeSoundingPeopleByApp 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. Security-Relevant APIs App Layout SQLite and SQL injection Dynamic SQL NSString *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. Security-Relevant APIs App Layout SQLite and SQL injection Parameterized SQL const 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. Security-Relevant APIs App Layout Caching 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. Security-Relevant APIs App Layout Geolocation Best 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. Security-Relevant APIs App Layout Geolocation Accuracy Settings Several 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. Security-Relevant APIs The Keychain The 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. Security-Relevant APIs The Keychain The Keychain Key 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. Security-Relevant APIs The Keychain The Keychain Shared 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. Security-Relevant APIs The Keychain The Keychain Certificates 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. Security-Relevant APIs The Keychain Data Protection Improving 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. Security-Relevant APIs The Keychain Data Protection Usage 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. Security-Relevant APIs The Keychain Entropy How does it work? Using Cocoa, not /dev/random Gathered via SecRandomCopyBytes Again, does not work in simulator Obviously, rand(), random(), arc4random() are all non-starters int result = SecRandomCopyBytes(kSecRandomDefault , sizeof(int), (uint8_t*)& randomResult); David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 44 / 68
  • 45. Security-Relevant APIs Backgrounding Backgrounding Initiating 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. Security-Relevant APIs Backgrounding Backgrounding Concerns 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. Security-Relevant APIs Backgrounding Backgrounding State 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. Security-Relevant APIs IPC IPC Application 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. Security-Relevant APIs IPC IPC Application 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. Security-Relevant APIs IPC IPC URL 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 (for example, “mailto”) is launched instead of your application. If a URL type registered by your application includes a scheme that conflicts with a scheme registered 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. Security-Relevant APIs IPC IPC Push 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. Security-Relevant APIs IPC Copy/Paste Pasteboards 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. Security-Relevant APIs IPC Copy/Paste Pasteboards 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. Security-Relevant APIs IPC Copy/Paste Example Abuse How 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. Security-Relevant APIs IPC Copy/Paste Disabling 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. UDIDs UDIDs Use 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. UDIDs UDIDs UDIDFaker available on Cydia David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 57 / 68
  • 58. UDIDs UDIDs Don’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. Common Attack Scenarios Old C Stuff Classic C Attacks Nothing 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. Common Attack Scenarios New Objective-C Stuff Object 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. Common Attack Scenarios New Objective-C Stuff iOS & 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. Common Attack Scenarios New Objective-C Stuff Format Strings Format 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. Common Attack Scenarios New Objective-C Stuff Format Strings Likely 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. Secure coding checklist Secure coding checklist Or 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. Secure coding checklist Secure coding checklist Continued 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. Questions Q? ://.. David Thiel (iSEC Partners) Secure Development on iOS SOURCE Boston 2011 66 / 68
  • 67. Appendix For Further Reading For 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. Appendix For Further Reading For 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