Diese Präsentation wurde erfolgreich gemeldet.
Die SlideShare-Präsentation wird heruntergeladen. ×

iOS secure app development

Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Nächste SlideShare
Owasp top 10
Owasp top 10
Wird geladen in …3
×

Hier ansehen

1 von 97 Anzeige

iOS secure app development

Herunterladen, um offline zu lesen

Few tips for iOS application development from security perspective.

Google docs presentation: https://docs.google.com/presentation/d/1eLQ40YCReg_pXp2as9FrbTgkNfOjOoPxDYUbFNyrT-M/pub?start=false&loop=false&delayms=3000

Few tips for iOS application development from security perspective.

Google docs presentation: https://docs.google.com/presentation/d/1eLQ40YCReg_pXp2as9FrbTgkNfOjOoPxDYUbFNyrT-M/pub?start=false&loop=false&delayms=3000

Anzeige
Anzeige

Weitere Verwandte Inhalte

Diashows für Sie (20)

Andere mochten auch (20)

Anzeige

Ähnlich wie iOS secure app development (20)

Aktuellste (20)

Anzeige

iOS secure app development

  1. 1. iOS Apps security Dušan Klinec, Faculty of Informatics, Masaryk University
  2. 2. About me • Security enthusiast • Mgr. in IT security, FI MU • Senior Software Engineer & Consultant @ EnigmaBridge.com • Co-author of the PhoneX app. 2 I
  3. 3. Outline • File System security – Encryption – Secure data storage • IPC • Certificate Pinning 3 I
  4. 4. Sandboxing recap. 4 I
  5. 5. Sandboxing • MAC, Historically Seatbelt • Based on FreeBSD’s TrustedBSD framework • Sandboxing profile what app can/cannot – Files, OS services, network, memory • Unlike Android’s UID-based segregation, apps run as one user, “mobile” • Application contained in own directory 5 I
  6. 6. Anatomy of the AppDir 6 I ● /Documents – Persistent store for application data; this data will be synced and backed up to iTunes. Can be shared via iTunes. ● /Library/Application Support – Additional app files (config files, purchased content) ● /Library/Caches – Caches, not in backup ● /Library/Caches/Snapshots – Application screenshots taken when the app is backgrounded ● /Library/Cookies – Cookie plists ● /Library/Preferences – Preference plists, NSUserDefaults. ● /Library/WebKit – Webkit local storage ● /xxxxxx.app – App resources (binary, graphics, nibs, Info.plist, localisation resources etc.) ● /tmp – temporary, can be erased between app starts
  7. 7. Data Encryption 7 I
  8. 8. Secure Enclave • Cryptographic co-processor (not Secure Element) – Apple 7+ processor (ARMv8, 64b, ARM + Apple design) – iPhone 5S+ (Required for Touch ID) • Implemented via TrustZone in Processor. • Separate trusted boot, separate software updates – Jailbreak does not compromise Secure Enclave 8 I
  9. 9. Secure Enclave 9 I Normal World Secure World Normal World User Mode Normal World User Mode Normal World User Mode Normal World User Mode Monitor
  10. 10. Secure Enclave 10 I Oscillator based random number generator AES-256 Engine UID AES-256 Engine GID
  11. 11. Secure Enclave 11 I Oscillator based random number generator AES-256 Engine UID AES-256 Engine GID Memory Key
  12. 12. Secure Enclave 12 I http://arstechnica.com/apple/2014/09/chipworks-digs-up-more-information-on-apples-new-a8-chip/ https://www.guru3d.com/articles-pages/core-i5-750-core-i7-860-870-processor-review-test,6.html http://www.wired.com/2015/10/x-ray-scans-expose-an-ingenious-chip-and-pin-card-hack/
  13. 13. FileSystem encryption • All files are encrypted – w/ or w/o passcode set – easy data wipe • Data need to be decrypted on the device (SEnc) – no Flash chip desoldering. – no parallelization with cloud, FPGAs, ASICs, ... – hard passcode bruteforcing, 80ms derivation delay – 5 second delay on wrong passcode entry by SEnc 13 I
  14. 14. NSFileProtectionComplete 14 I File contents AES-256 Encrypt AES-256 Wrap File key
  15. 15. NSFileProtectionComplete 15 I File contents AES-256 Encrypt AES-256 Wrap File key Protection class key
  16. 16. NSFileProtectionComplete 16 I File contents AES-256 Encrypt AES-256 Wrap File key Protection class key UID Passcode key
  17. 17. NSFileProtectionComplete 17 I File contents AES-256 Encrypt AES-256 Wrap File metadata File key Protection class key UID Passcode key
  18. 18. NSFileProtectionComplete 18 I File contents AES-256 Encrypt AES-256 Wrap File metadata File System key File key Protection class key UID Passcode key
  19. 19. NSFileProtectionComplete 19 I File contents AES-256 Encrypt AES-256 Wrap File metadata File System key File key Protection class key UID Passcode key
  20. 20. NSFileProtectionCompleteUntilFirstUserA uthentication 20 I File contents AES-256 Encrypt AES-256 Wrap File metadata File System key File key Protection class key UID Passcode key
  21. 21. 21 I File contents AES-256 Encrypt AES-256 Wrap File metadata File System key File key Protection class key UID NSFileProtectionNone
  22. 22. NSFileProtectionCompleteUnlessOpen 22 I File contents AES-256 Encrypt AES-256 Wrap File metadata File key fPubK, fPrvK fPubK fprvK File Create File System key
  23. 23. NSFileProtectionCompleteUnlessOpen 23 I File contents AES-256 Encrypt AES-256 Wrap File metadata File key class ECC public key fPubK, fPrvK fPubK fprvK File CreateUID File System key
  24. 24. NSFileProtectionCompleteUnlessOpen 24 I File contents AES-256 Encrypt AES-256 Wrap File metadata File key class ECC public key fPubK, fPrvK fPubK fprvK File Create ECC key agreement UID File System key
  25. 25. NSFileProtectionCompleteUnlessOpen 25 I File contents AES-256 Encrypt AES-256 Wrap File metadata File key fPubK File Create File System key
  26. 26. NSFileProtectionCompleteUnlessOpen 26 I File contents AES-256 Encrypt AES-256 Wrap File metadata File key fPubK File Open File System key
  27. 27. NSFileProtectionCompleteUnlessOpen 27 I File contents AES-256 Encrypt AES-256 Wrap File metadata File key class ECC private key fPubK File OpenUID File System key Passcode key
  28. 28. NSFileProtectionCompleteUnlessOpen 28 I File contents AES-256 Encrypt AES-256 Wrap File metadata File key class ECC private key fPubK File Open ECC key agreement UID File System key Passcode key
  29. 29. Data protection classes • NSFileProtectionComplete – e.g., password manager data container • NSFileProtectionCompleteUntilFirstUserAuthentication – e.g., contacts database, notes, messages, photos,... • NSFileProtectionCompleteUnlessOpen – e.g., background downloads, healthKit journal • NSFileProtectionNone – device without passcode, do not use. 29 I
  30. 30. Protected data availability • App Delegates – applicationProtectedDataWillBecomeUnavailable: – applicationProtectedDataDidBecomeAvailable: • NSNotificationCenter – UIApplicationProtectedDataWillBecomeUnavailable – UIApplicationProtectedDataDidBecomeAvailable • On demand check – [[UIApplication sharedApplication] protectedDataAvailable] 30 I
  31. 31. KeyChain 31 I https://materialdesignicons.com/
  32. 32. KeyChain • Place to store small sensitive data – usernames, passwords, tokens, certificates, – private keys, symmetric keys • /var/Keychains/keychain-2.db • All entries encrypted with entry-key – Protection classes. Potential Passcode dependency – *ThisDeviceOnly 32 I
  33. 33. KeyChain Usage • Original API ugly/complicated (C-style, ARC bridging) NSMutableDictionary *dict = [NSMutableDictionary dictionary]; NSData *passwordData = [@"mypassword" dataUsingEncoding:NSUTF8StringEncoding]; dict[(__bridge id) kSecClass] = (__bridge id) kSecClassGenericPassword; dict[(__bridge id) kSecAttrLabel] = @"Conglomco login"; dict[(__bridge id) kSecAttrDescription] = @"This is your password for the x service."; dict[(__bridge id) kSecAttrAccount] = @"dthiel"; dict[(__bridge id) kSecAttrService] = @"com.isecpartners.SampleKeychain"; dict[(__bridge id) kSecValueData] = passwordData; dict[(__bridge id) kSecAttrAccessible] = (__bridge id) kSecAttrAccessibleWhenUnlocked; OSStatus error = SecItemAdd((__bridge CFDictionaryRef)dict, NULL); if (error == errSecSuccess) { NSLog(@"Yay"); } 33 I
  34. 34. KeyChain Usage • Wrappers – github.com/carlbrown/PDKeychainBindingsController – github.com/granoff/Lockbox • NSUserDefaults-like API Get: PDKeychainBindings *bindings = [PDKeychainBindings sharedKeychainBindings]; [[[Model sharedModel] currentUser] setAuthToken:[bindings objectForKey:@"authToken"]]; Set: PDKeychainBindings *bindings = [PDKeychainBindings sharedKeychainBindings]; [bindings setObject:@"XYZ" forKey:@"authToken"]; 34 I
  35. 35. KeyChain & Secure Enclave • iOS 9.0+ • SecKeyGeneratePair() – Elliptic Curve P256 KeyPair – attribute kSecAttrTokenIDSecureEnclave • Public key returned • Private key stored in Keychain, protected by SEnc ACLs • Can perform SIGN operation, • Private key cannot be extracted 35 I
  36. 36. KeyChain & Backup • Unencrypted backup – Keychain items not re-encrypted – Recoverable only on the source device – Backup contains other files in plaintext • Encrypted backup – Keychain items re-encrypted (except *ThisDeviceOnly) – Recoverable on different devices – All files encrypted as well, protected backup 36 I
  37. 37. KeyChain & Jailbreak • After Jailbreak, all KeyChain entries are readable – Keychain Viewer by Sogeti, Keychain_Dumper • Jailbreaking of lost/stolen pass code-protected phone: – With Secure Enclave (Apple A7+ processor, iOS 7+) not probable – Exploit might require restart (recovery mode) → NSFileProtectionCompleteUntilFirstUserAuthentication • User can jailbreak his own phone - cannot be avoided 37 I
  38. 38. KeyChain & Jailbreak • Non-standard, multilayer precautions – Deter script kiddies, complicate automated attacks mnt. • Ideas: – Add another layer of encryption / Obfuscation – Jailbreak detection, tamper detection – User authentication (e.g., PIN lock screen, enc) – Secret sharing, server assisted encryption – Hardware security module - accessory, BT comm 38 I
  39. 39. Local storage 39 I
  40. 40. Local storage methods • Plists • NSUserDefaults • CoreData • SQLite 40 I
  41. 41. Local storage methods • NSFileProtectionCompleteUntilFirstUserAuthentication • Unencrypted backups → plaintext 41 I
  42. 42. 42 I http://www.slideshare.net/xfempx/ios-app-security-common?qid=d11914b4-0a3e-4d1b-a005-3d404064eace&v=&b=&from_search=15
  43. 43. 43 I http://www.slideshare.net/xfempx/ios-app-security-common?qid=d11914b4-0a3e-4d1b-a005-3d404064eace&v=&b=&from_search=15
  44. 44. 44 I
  45. 45. • https://github.com/sqlcipher/sqlcipher 45 I
  46. 46. Core data protection • https://github.com/project-imas/encrypted-core-data/ 46 I
  47. 47. Wiping data from SQLite • DELETE FROM … may not delete data physically • Data still present in the DB file / Write Ahead Log • → Rewrite record before removal (same length) • → From time to time, call VACUUM (warning: VACUUM rebuilds DB) 47 I
  48. 48. Injection attacks - SQL NSString *uid = [myHTTPConnection getUID]; NSString *statement = [NSString stringWithFormat: @"SELECT username FROM users where uid = '%@'",uid]; const char *sql = [statement UTF8String]; • Use prepared statements & parameter binding: 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); 48 I
  49. 49. IPC 49 I
  50. 50. IPC - URL 50 I MyApp OtherApp myApp:// NSString * url = @"myApp://user/passwd"; [[UIApplication sharedApplication] openURL:url]; • Apps can register to custom URL Schemes • Multiple registered apps to the same scheme? Undefined.
  51. 51. IPC - URL 51 I • Do not pass sensitive information via URLs • Validate incoming URLs carefully (injections) • Take URL Hijacking into account
  52. 52. IPC - Universal links - iOS 9+ 52 I • App can register to listen to web links – https://www.phone-x.net/contact-me/dusan • Entitlement is required
  53. 53. IPC - Universal links - iOS 9+ 53 I • https://www.phone-x.net/apple-app-site-association { "applinks": { "apps": [], "details": [ { "appID": "TBEJCS6FFP.com.domain.App", "paths":[ "*" ] } ] }}
  54. 54. IPC - Universal links - iOS 9+ 54 I • App delegate method: application:continueUserActivity: restorationHandler: • Prons: – Not subject to URL hijacking – If app not installed, web page is shown • Android knew it years ago… (as with copy-paste)
  55. 55. Crypto 55 I
  56. 56. Broken/weak algorithms 56 I • Kind of broken: – RC4, MD4 • Not suitable anymore: – MD5, SHA1, DES • Weak: – RSA-1024, DH-1024, ECC 128 • Do not use: – ECB mode, no padding, custom crypto!
  57. 57. Broken/weak algorithms 57 I http://www.slideshare.net/xfempx/ios-app-security-common?qid=d11914b4-0a3e-4d1b-a005-3d404064eace&v=&b=&from_search=15
  58. 58. Minimal key lengths 58 I • https://www.keylength.com/
  59. 59. Generating random numbers 59 I const int rndBuffSize = 32; NSMutableData * rnd = [NSMutableData dataWithLength:rndBuffSize]; uint8_t * rndBuff = (uint8_t*) [rnd mutableBytes]; int result = SecRandomCopyBytes(kSecRandomDefault, rndBuffSize, rndBuff); • Simulator issues • rand(), random(), arc4random() are not for crypto!
  60. 60. rand() patterns 60 I http://programmers.stackexchange.com/questions/121568/php-rand-function-or-not-so-rand http://www.scsitoolbox.com/products/cpam.asp
  61. 61. rand() patterns 61 I
  62. 62. Generating random numbers 62 I • Generate high-quality random numbers for: – IV, nonces, salts • Do not use user provided passwords as encryption keys – PBKDF2(password, salt, iterations, keyLength), use kCCPRFHmacAlgSHA256 derivation.
  63. 63. Crypto in a good way 63 I • AES-128, AES-256 – CBC, but with random IV + HMAC. ENC then MAC. – or GCM = authenticated encryption (prefered) • RSA-2048, OAEP padding • ECDSA, ECDHE • SHA-256 • PBKDF2
  64. 64. Library 64 I • https://github.com/RNCryptor/RNCryptor NSString *password = @"Secret password"; RNEncryptor *encryptor = [[RNEncryptor alloc] initWithPassword:password]; NSMutableData *ciphertext = [NSMutableData new]; // ... Each time data comes in, update the encryptor and accumulate some ciphertext ... [ciphertext appendData:[encryptor updateWithData:data]]; // ... When data is done, finish up ... [ciphertext appendData:[encryptor finalData]];
  65. 65. Memory considerations 65 I • For sensitive data, use your own allocated memory • iVars are easy to find & read in runtime analysis • Wipe the memory after use, rewrite • https://github.com/project-imas/memory-security
  66. 66. Memory considerations 66 I • For sensitive data, use your own allocated memory • iVars are easy to find & read in runtime analysis • Wipe the memory after use, rewrite • https://github.com/project-imas/memory-security http://www.slideshare.net/mgianarakis/yow-connected-developing-secure-i-os-applications?qid=6663e884-0bc0-4c89-92a1-e3ccbe1d2aa3&v=&b=&from_search=1
  67. 67. Data leakage 67 I
  68. 68. Screenshots cache 68 I http://www.slideshare.net/mgianarakis/yow-connected-developing-secure-i-os-applications?qid=6663e884-0bc0-4c89-92a1-e3ccbe1d2aa3&v=&b=&from_search=1
  69. 69. Screenshots cache 69 I • When switching to background, for task manager • /var/mobile/Applications/<app- code>/Library/Caches/Snapshots • Prevention: – Clean form contents before transition – Show window to hidden on transition – Show splash screen before transition
  70. 70. Screenshots cache 70 I http://www.slideshare.net/mgianarakis/yow-connected-developing-secure-i-os-applications?qid=6663e884-0bc0-4c89-92a1-e3ccbe1d2aa3&v=&b=&from_search=1
  71. 71. Keyboard cache 71 I http://www.slideshare.net/mgianarakis/yow-connected-developing-secure-i-os-applications?qid=6663e884-0bc0-4c89-92a1-e3ccbe1d2aa3&v=&b=&from_search=1
  72. 72. Keyboard cache 72 I • Auto-correct caching – /private/var/mobile/Library/Keyboard/dynamic-text.dat • For sensitive fields, disable: – textField.autocorrectionType = UITextAutocorrectionTypeNo; – textField.secureTextEntry = YES;
  73. 73. Logging 73 I • https://github.com/CocoaLumberjack/CocoaLumberjack • Do not log sensitive data • In production, disable logs in compile time – Occupies less memory, logging messages not included – Do not document apps behavior for an attacker • If you have to log in production, log only Errors / Warnings
  74. 74. Jailbreak cont. 74 I
  75. 75. Jailbreak detection 75 I • https://github.com/project-imas/security-check • Detection not 100% reliable • Avoid simple logic: -(BOOL) isJailbroken; • Check multiple times during execution. • Use method inlining – __attribute__((always_inline))
  76. 76. Method inlining 76 I
  77. 77. Transport Security 77 I
  78. 78. Certificate pinning 78 I http://sierraware.com/blog/wp-content/uploads/2015/04/certificate_pinning.png https://www.cigital.com/wp-content/uploads/2016/03/Certificate-Chain-Visuals-1-1_750.png
  79. 79. Certificate pinning - preface 79 I • Use secure protocols (https, smtps, imaps, ssh, …) • Never disable certificate verification, not even in debug – setAllowsAnyHTTPSCertificate – continueWithoutCredentialForAuthenticationChallenge • Use https://letsencrypt.org/ - a free CA • Some scenarios where cannot use CA – Want intermediate signing certificate (e.g., server signs) • Do pinning on self-signed certificate with true CA flag
  80. 80. Certificate pinning - manual way • Implemented by handling events in NSURLConnectionDelegate (old API) – connection:canAuthenticateAgainstProtectionSpace: – connection:didReceiveAuthenticationChallenge: • NSURLSessionTaskDelegate (new API) – URLSession:task:didReceiveChallenge:completionHandler: • Example app: https://www.owasp.org/index. php/Pinning_Cheat_Sheet 80 I
  81. 81. Certificate pinning - manual way • Devel phase: – Add trust anchors as DER encoded certificates to the application (e.g., resources, binary, obfuscation, …) • Verification phase: – Load anchors, create NSArray<SecCertificateRef> – Process challenge, get SecTrustRef – Update trust, set anchors, allow only anchors – Evaluate trust SecTrustEvaluate. OK? Return credential 81 I
  82. 82. Certificate pinning - manual way - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { if ([[challenge protectionSpace].authenticationMethod isEqualToString: NSURLAuthenticationMethodServerTrust]){ // 1. verify trust // 2. if OK, create valid credential } } 82 I
  83. 83. Certificate pinning - manual way const SecTrustRef trust = [[challenge protectionSpace] serverTrust]; // Obtain trust root CA anchors. NSArray * anchors = [PEXSecurityCenter getServerTrustAnchors]; SecTrustSetAnchorCertificates(trust, (__bridge CFArrayRef) anchors); SecTrustSetAnchorCertificatesOnly(trust, YES); // Validate certificate & trust zone against given trust anchors. SecTrustResultType res = kSecTrustResultInvalid; OSStatus sanityCheck = SecTrustEvaluate(trust, &res); return sanityCheck == noErr && [self validateResult:res]; 83 I
  84. 84. Certificate pinning - manual way NSURLCredential * const newCredential = [NSURLCredential credentialForTrust:trust]; [[challenge sender] useCredential:newCredential forAuthenticationChallenge: challenge]; 84 I
  85. 85. Certificate pinning - library • https://github.com/iSECPartners/ssl-conservatory – +(BOOL)setupSSLPinsUsingDictionnary:(NSDictionary*) domainsAndCertificates; – +(BOOL)verifyPinnedCertificateForTrust:(SecTrustRef)trust andDomain: (NSString*)domain; • Convenience delegates – ISPPinnedNSURLConnectionDelegate – ISPPinnedNSURLSessionDelegate 85 I
  86. 86. Certificate pinning - library • https://github.com/AFNetworking let securityPolicy = AFSecurityPolicy(pinningMode: AFSSLPinningMode.Certificate) let certificatePath = NSBundle.mainBundle().pathForResource("pinned-certificate", ofType: "cer")! let certificateData = NSData(contentsOfFile: certificatePath)! securityPolicy.pinnedCertificates = [certificateData]; securityPolicy.validatesCertificateChain = false self.securityPolicy = securityPolicy 86 I
  87. 87. Certificate pinning - system CA? • Include or not to include system CA list. • Trust OK ⇔ systemTrustOK && PinningOK • Good if: – your certificates are CA signed (not self-signed, $$$) – can provide you a revocation (into some extent) • Bad if: – your root certificate is self signed 87 I
  88. 88. Certificate pinning - defeating • On Jailbroken devices, certificate verification can be completely disabled • https://github.com/iSECPartners/ios-ssl-kill-switch – Hooks to verifications calls @ runtime, – patches methods to always return YES; 88 I
  89. 89. Certificate pinning - defeating • On Jailbroken devices, certificate verification can be completely disabled • https://github.com/iSECPartners/ios-ssl-kill-switch – Hooks to verifications calls @ runtime, – patches methods to always return YES; 89 I
  90. 90. TLS security - iOS 9.0+ • App Transport Security - default conn requirements • NSURLConnection, CFURL, or NSURLSession APIs. – min TLS 1.2 – forward secrecy cipher suites – certificates must be valid and signed using SHA-256 + – min 2048-bit RSA key or 256-bit elliptic curve key • If req fail → connection fails. By default ON, can override 90 I
  91. 91. Resources 91 I
  92. 92. Resources • http://damnvulnerableiosapp.com/ 92 I
  93. 93. Resources • http://highaltitudehacks.com/2013/10/26/ios-application- security-part-20-local-data-storage-nsuserdefaults/ 93 I
  94. 94. Resources • https://www.owasp.org/index. php/IOS_Application_Security_Testing_Cheat_Sheet 94 I
  95. 95. Recommended reading 95 I
  96. 96. Thank you for your attention! Q & A 96 I
  97. 97. References 1. https://www.apple.com/business/docs/iOS_Security_Guide.pdf 2. https://www.quora.com/What-is-Apple%E2%80%99s-new-Secure-Enclave-and-why-is-it-important 3. http://www.wired.com/2015/10/x-ray-scans-expose-an-ingenious-chip-and-pin-card-hack/#slide-4 4. http://www.anandtech.com/show/8562/chipworks-a8 5. http://www.darthnull.org/2014/10/06/ios-encryption 6. http://blog.cryptographyengineering.com/2014/10/why-cant-apple-decrypt-your-iphone.html 7. http://highaltitudehacks.com/2013/09/17/ios-dev-storing-info-in-keychain-with-nsuserdefaults-like- syntax/ 8. http://willowtreeapps.com/blog/enhanced-device-security-in-ios-9/ 9. https://dl.packetstormsecurity.net/papers/general/apple-sandbox.pdf 10. 97 I

×