Post on 14-Apr-2017
iOS Apps security
Dušan Klinec, Faculty of Informatics, Masaryk University
About me
• Security enthusiast
• Mgr. in IT security, FI MU
• Senior Software Engineer & Consultant
@ EnigmaBridge.com
• Co-author of the PhoneX app.
2 I
Outline
• File System security
– Encryption
– Secure data storage
• IPC
• Certificate Pinning
3 I
Sandboxing recap.
4 I
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
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
Data Encryption
7 I
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
Secure Enclave
9 I
Normal World Secure World
Normal WorldUser Mode
Normal WorldUser Mode
Normal WorldUser Mode
Normal WorldUser Mode
Monitor
Secure Enclave
10 I
Oscillator based random number generator
AES-256 Engine
UID
AES-256 Engine
GID
Secure Enclave
11 I
Oscillator based random number generator
AES-256 Engine
UID
AES-256 Engine
GID Memory Key
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.htmlhttp://www.wired.com/2015/10/x-ray-scans-expose-an-ingenious-chip-and-pin-card-hack/
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
NSFileProtectionComplete
14 I
File contents
AES-256 EncryptAES-256 Wrap
File key
NSFileProtectionComplete
15 I
File contents
AES-256 EncryptAES-256 Wrap
File keyProtection class key
NSFileProtectionComplete
16 I
File contents
AES-256 EncryptAES-256 Wrap
File keyProtection class key
UID
Passcodekey
NSFileProtectionComplete
17 I
File contents
AES-256 EncryptAES-256 Wrap
File metadata
File keyProtection class key
UID
Passcodekey
NSFileProtectionComplete
18 I
File contents
AES-256 EncryptAES-256 Wrap
File metadata
File System key
File keyProtection class key
UID
Passcodekey
NSFileProtectionComplete
19 I
File contents
AES-256 EncryptAES-256 Wrap
File metadata
File System key
File keyProtection class key
UID
Passcodekey
NSFileProtectionCompleteUntilFirstUserAuthentication
20 I
File contents
AES-256 EncryptAES-256 Wrap
File metadata
File System key
File keyProtection class key
UID
Passcodekey
21 I
File contents
AES-256 EncryptAES-256 Wrap
File metadata
File System key
File keyProtection class key
UID
NSFileProtectionNone
NSFileProtectionCompleteUnlessOpen
22 I
File contents
AES-256 EncryptAES-256 Wrap
File metadata
File key
fPubK, fPrvK
fPubK
fprvK
File Create File System
key
NSFileProtectionCompleteUnlessOpen
23 I
File contents
AES-256 EncryptAES-256 Wrap
File metadata
File key
class ECC public key
fPubK, fPrvK
fPubK
fprvK
File Create UID
File System key
NSFileProtectionCompleteUnlessOpen
24 I
File contents
AES-256 EncryptAES-256 Wrap
File metadata
File key
class ECC public key
fPubK, fPrvK
fPubK
fprvK
File Create
ECC key agreement
UIDFile System
key
NSFileProtectionCompleteUnlessOpen
25 I
File contents
AES-256 EncryptAES-256 Wrap
File metadata
File key
fPubK
File Create File System
key
NSFileProtectionCompleteUnlessOpen
26 I
File contents
AES-256 EncryptAES-256 Wrap
File metadata
File key
fPubK
File Open File System
key
NSFileProtectionCompleteUnlessOpen
27 I
File contents
AES-256 EncryptAES-256 Wrap
File metadata
File key
class ECC private key
fPubK
File Open UID
File System key
Passcodekey
NSFileProtectionCompleteUnlessOpen
28 I
File contents
AES-256 EncryptAES-256 Wrap
File metadata
File key
class ECC private key
fPubK
File Open
ECC key agreement
UIDFile System
key
Passcodekey
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
Protected data availability
• App Delegates
– applicationProtectedDataWillBecomeUnavailable:
– applicationProtectedDataDidBecomeAvailable:
• NSNotificationCenter
– UIApplicationProtectedDataWillBecomeUnavailable
– UIApplicationProtectedDataDidBecomeAvailable
• On demand check
– [[UIApplication sharedApplication] protectedDataAvailable]
30 I
KeyChain
31 I
https://materialdesignicons.com/
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
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
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
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 extracted35 I
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 backup36 I
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 avoided37 I
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 comm38 I
Local storage
39 I
Local storage methods
• Plists
• NSUserDefaults
• CoreData
• SQLite
40 I
Local storage methods
• NSFileProtectionCompleteUntilFirstUserAuthentication
• Unencrypted backups → plaintext
41 I
42 I
http://www.slideshare.net/xfempx/ios-app-security-common?qid=d11914b4-0a3e-4d1b-a005-3d404064eace&v=&b=&from_search=15
43 Ihttp://www.slideshare.net/xfempx/ios-app-security-common?qid=d11914b4-0a3e-4d1b-a005-3d404064eace&v=&b=&from_search=15
44 I
• https://github.com/sqlcipher/sqlcipher
45 I
Core data protection
• https://github.com/project-imas/encrypted-core-data/
46 I
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
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
IPC
49 I
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.
IPC - URL
51 I
• Do not pass sensitive information via URLs
• Validate incoming URLs carefully (injections)
• Take URL Hijacking into account
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
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":[ "*" ] } ] }}
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)
Crypto
55 I
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!
Broken/weak algorithms
57 Ihttp://www.slideshare.net/xfempx/ios-app-security-common?qid=d11914b4-0a3e-4d1b-a005-3d404064eace&v=&b=&from_search=15
Minimal key lengths
58 I
• https://www.keylength.com/
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!
rand() patterns
60 I
http://programmers.stackexchange.com/questions/121568/php-rand-function-or-not-so-randhttp://www.scsitoolbox.com/products/cpam.asp
rand() patterns
61 I
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.
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
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]];
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
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
Data leakage
67 I
Screenshots cache
68 Ihttp://www.slideshare.net/mgianarakis/yow-connected-developing-secure-i-os-applications?qid=6663e884-0bc0-4c89-92a1-e3ccbe1d2aa3&v=&b=&from_search=1
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
Screenshots cache
70 Ihttp://www.slideshare.net/mgianarakis/yow-connected-developing-secure-i-os-applications?qid=6663e884-0bc0-4c89-92a1-e3ccbe1d2aa3&v=&b=&from_search=1
Keyboard cache
71 Ihttp://www.slideshare.net/mgianarakis/yow-connected-developing-secure-i-os-applications?qid=6663e884-0bc0-4c89-92a1-e3ccbe1d2aa3&v=&b=&from_search=1
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;
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
Jailbreak cont.
74 I
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))
Method inlining
76 I
Transport Security
77 I
Certificate pinning
78 I
http://sierraware.com/blog/wp-content/uploads/2015/04/certificate_pinning.pnghttps://www.cigital.com/wp-content/uploads/2016/03/Certificate-Chain-Visuals-1-1_750.png
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
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
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 credential81 I
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
Certificate pinning - manual wayconst 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
Certificate pinning - manual wayNSURLCredential * const newCredential = [NSURLCredential
credentialForTrust:trust];
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:
challenge];
84 I
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
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
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
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
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
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
Resources
91 I
Resources
• http://damnvulnerableiosapp.com/
92 I
Resources
• http://highaltitudehacks.com/2013/10/26/ios-application-
security-part-20-local-data-storage-nsuserdefaults/
93 I
Resources
• https://www.owasp.org/index.
php/IOS_Application_Security_Testing_Cheat_Sheet
94 I
Recommended reading
95 I
Thank you for your attention!
Q & A
96 I
References1. https://www.apple.com/business/docs/iOS_Security_Guide.pdf2. https://www.quora.com/What-is-Apple%E2%80%99s-new-Secure-Enclave-and-why-is-it-important3. http://www.wired.com/2015/10/x-ray-scans-expose-an-ingenious-chip-and-pin-card-hack/#slide-44. http://www.anandtech.com/show/8562/chipworks-a85. http://www.darthnull.org/2014/10/06/ios-encryption6. http://blog.cryptographyengineering.com/2014/10/why-cant-apple-decrypt-your-iphone.html7. 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