52
These are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting users’ data on the network and on the device Session 208 Securing iOS Applications Conrad Sauerwald iOS Security Snarkitect Andrew R. Whalley iOS Security Manager Michael Brouwer iOS Security Architect 1

Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

These are confidential sessions—please refrain from streaming, blogging, or taking pictures

Protecting users’ data on the network and on the device

Session 208

Securing iOS Applications

Conrad SauerwaldiOS Security Snarkitect

Andrew R. WhalleyiOS Security Manager

Michael BrouweriOS Security Architect

1

Page 2: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Introduction

• Embedded Data Security team■ Any time a key is used to protect user data

■ Data Protection, Keychain, Secure Transport, CMS■ Design and build solutions for internal clients■ High-level API for 3rd-party applications

2

Page 3: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

What We Will Demonstrate Today

• Test-drive an application through a bad neighborhood■ What can happen■ Why it matters■ How you can avoid it

• Build, test, fix, repeat

3

Page 4: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Simple device-to-device photo-sharing app

• Discover other users on the local network with Bonjour

• Take pictures on one device, have them appear on another

• Source code available

Oversharing.app

4

Page 5: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Why Secure Oversharing.app?

• Users are entrusting their data to your app■ You cannot foresee to what uses your app will be put■ Assume that people care about their data. Protect it.

• Scary and abstract terms in the news■ Brute force, man in the middle…

• Threats are very real■ Losing a device at a conference■ Connecting to a network

5

Page 6: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

How iOS APIs Can HelpWhat we will be covering

• Securing network connections• Protecting data• Protecting secrets

6

Page 7: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Securing Network Connections

7

Page 8: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Securing Network Connections

• API■ High-level API in Foundation: HTTP(S)…socket■ Low-level API in SecureTransport: DTLS/TLS, data callback

• Application■ HTTP GET to register■ HTTP POST to publish pictures

8

Page 9: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Oversharing.app Networking

NSString *server_url = @”http://1.3.3.7:1337/register/name/”;

NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString: server_url ]];

Application registers interest via GET

[[NSURLConnection alloc] initWithRequest: request delegate: self];

// @interface MainViewController : UIViewController <NSURLConnectionDelegate>

- (void)connection:(NSURLConnection *)c didReceiveData:(NSData *)data

- (void)connection:(NSURLConnection *)c didFailWithError:(NSError *)error

9

Page 10: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Oversharing.app Networking

NSString * publish_url = @”http://1.3.3.7:1334/publish/”;NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: publish_url]];[request setHTTPBody:image_data];[request setHTTPMethod:@"POST"];[[NSURLConnection alloc] initWithRequest:request delegate:self];

Publish picture via POST

10

Page 11: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Demo

11

Page 12: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Network InterceptionWhat does the attacker see?

Andrew

ConradMichael

12

Page 13: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Using Transport Layer Security (TLS) Foundation client

• One letter change, note the “https” in the URL

// “After” code

NSString *server_url = @”https://1.3.3.7:1337/{register|publish}/”;

13

Page 14: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Using Transport Layer Security (TLS)SecureTransport server—setup

• Context, callbacks, and certificates

SSLContextRef ctx = NULL;

SSLNewContext(server, &ctx)

SSLSetIOFuncs(ctx,

(SSLReadFunc)socket_read, (SSLWriteFunc)socket_write);

SSLSetConnection(ctx, (SSLConnectionRef)sock), out);

// TODO: deal with certificates later

// SSLSetCertificate(ctx, certs);

14

Page 15: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Using Transport Layer Security (TLS)SecureTransport server—operation

• Open, read/write, close

// TLS handshake negotiates authentication and encryption

status = SSLHandshake(ctx);

// Read decrypted data from peer

status = SSLRead(ctx, buffer, sizeof(buffer), &bytes_read);

// Write encrypted data to peer

status = SSLWrite(ctx, buffer, sizeof(buffer), &bytes_written);

// Shutdown TLS

SSLClose(ctx);

15

Page 16: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

TLS Without CertificatesWinning?

• No certificates, no problemSSLCipherSuite cipher = TLS_DH_anon_WITH_AES_256_CBC_SHA;

SSLSetEnabledCiphers(ctx, &cipher, 1);

• Crypto alphabet soup■ Diffie-Hellman key exchange■ AES/CBC encryption with 256-bit keys■ Secure Hash Algorithm (SHA1)

16

Page 17: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Man in the MiddleEncrypted, not secure

ConradMichaelAndrew

17

Page 18: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Certificate AuthenticationHow does it work?

• Using asymmetric keypair: Public and Private key• Private key to create a signature over data• Public key to verify signature

18

Page 19: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

CertificatesWhat are they?

Subject

Public Key

Signature

19

Page 20: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

ConradMichael

CertificatesHonest Abe’s Lightly Used Bicycles and Cheap Certificates

20

Page 21: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Certificate AuthenticationServer vs. client authentication

ConradMichael

Andrew

21

Page 22: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Certificate AuthenticationClient authentication to peer

- (void)connection:(NSURLConnection *)c didReceiveAuthenticationChallenge: (NSURLAuthenticationChallenge *)challenge {

if ([[[challenge protectionSpace] authenticationMethod] isEqualToString: NSURLAuthenticationMethodClientCertificate])

{

NSURLCredential * credential = [NSURLCredential

credentialWithIdentity: identity

certificates: nil

persistence: NSURLCredentialPersistenceNone];

[[challenge sender] useCredential: credential

forAuthenticationChallenge: challenge];

}

}

22

Page 23: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Certificate AuthenticationAccept the challenge

- (BOOL)connection:(NSURLConnection *)connection

canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)

protectionSpace

{

if ([[protectionSpace authenticationMethod] isEqualToString:

NSURLAuthenticationMethodClientCertificate])

return YES;

}

23

Page 24: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Demo

24

Page 25: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Certificate AuthenticationOther things to consider

• Rule out “Man in the Middle”

• Trust the right certificates

• Limit Root Certificates (i.e., not Honest Abe’s)

25

Page 26: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Authentication Using Certificates (Client)Accept the challenge

- (BOOL)connection:(NSURLConnection *)connection

canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)

protectionSpace

{

else if ([[protectionSpace authenticationMethod] isEqualToString:

NSURLAuthenticationMethodServerTrust])

return YES;

}

26

Page 27: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Custom Trust EvaluationLimit valid anchors as a client

if ([[[challenge protectionSpace] authenticationMethod] isEqualToString:

NSURLAuthenticationMethodServerTrust]) {

SecTrustRef trust = [[challenge protectionSpace] serverTrust];

SecTrustSetAnchorCertificates(trust, oversharing_root);

SecTrustEvaluate(trust, &trust_result);

if (trust_result == kSecTrustResultUnspecified) {

NSURLCredential * credential =

[NSURLCredential credentialForTrust: trust];

[[challenge sender] useCredential: credential

forAuthenticationChallenge: challenge];

}

}

27

Page 28: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Securing Network ConnectionsSummary

• HTTPS is easy to use from high-level API• Requires some setup work, but provides simple experience• Lot of options under the hood, so watch the sharp edges

28

Page 29: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Demo

29

Page 30: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Protecting Data on the DeviceLast line of defense

• Data Protection allows data to be tied to the user’s passcode• Provides protection in case a device is lost or stolen

■ Widely available hacking tools allow filesystem access

30

Page 31: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

File Meta Data

File Key

Protected fileData Protection Key Hierarchy

Class Key

User Passcode Key

Device Key

31

Page 32: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

APIs Offering Data Protection

NSFileManager

CoreData

NSData

sqlite3

SecItem

NSFileProtectionKey NSFileProtection…

NSFileProtectionKey NSFileProtection…

NSDataWritingOptions NSDataWritingFileProtection…

sqlite3_open_v2 option SQLITE_OPEN_FILEPROTECTION_…

kSecAttrAccessible kSecAttrAccessible…

32

Page 33: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Data Protection for All FilesForeground-only apps

• Add “DataProtectionClass” entitlement• Use “NSFileProtectionComplete” as its value• Profit!

33

Page 34: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Data Only Available When UnlockedFileProtectionComplete

-(BOOL)writeImage:(UIImage *)image toPath:path error:(NSError **)error

{

NSData *data = UIImageJPEGRepresentation(image, 1.0);

return [data writeToFile:path options:

NSDataWritingFileProtectionComplete error:error];

}

34

Page 35: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Data Only Available When UnlockedConsiderations

• Only as good as the passcode• Cannot access when locked

■ Use NSFileProtectionCompleteUnlessOpen ■ Upgrade to NSFileProtectionComplete when unlocked

35

Page 36: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Data DropboxFileProtectionCompleteUnlessOpen

-(BOOL)writeImageWhileLocked:(UIImage *)image toPath:path

error:(NSError **)error

{

NSData *data = UIImageJPEGRepresentation(image, 1.0);

return [data writeToFile: path

options: NSDataWritingFileProtectionComplete

error: error]

|| [data writeToFile: path

options: NSDataWritingFileProtectionCompleteUnlessOpen

error: error];

}

36

Page 37: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Upgrade to FileProtectionComplete-(void)upgradeImagesInDir:(NSString *)dir error:(NSError **)error {

NSFileManager *fm = [NSFileManager defaultManager];

NSDirectoryEnumerator *de = [fm enumeratorAtPath: dir];

for (NSString *path in de) {

NSDictionary *attrs = [de fileAttributes];

if (![[attrs objectForKey: NSFileProtectionKey]

isEqual: NSFileProtectionComplete]) {

attrs = [NSDictionary dictionaryWithObject:

NSFileProtectionComplete forKey: NSFileProtectionKey];

[fm setAttributes: attrs ofItemAtPath: path error: error];

}

}

}

37

Page 38: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Background Read…ProtectionCompleteUntilFirstUserAuthentication

• Also solves the problem of data access when unlocked• Protects data from reboot until first unlock

■ Then not at all■ Better than default of none against attacks that require a reboot

38

Page 39: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Background Readable Database…ProtectionCompleteUntilFirstUserAuthentication

-(int)openDatabase(const char *filename, sqlite3 **pdb)

{

return sqlite3_open_v2(filename, pdb,

SQLITE_OPEN_FILEPROTECTION_COMPLETEUNTILFIRSTUSERAUTHENTICATION,

NULL);

}

39

Page 40: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Demo

40

Page 41: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

KeychainIntroduction

• What belongs in the keychain• Keychain Items are protected just like files

■ Migratability can be controlled

41

Page 42: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Uploading to a Website

• Username and password

• Do not want to prompt the user each time

• Need to store securely on the device

42

Page 43: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Availability NSFileProtection kSecAttrAccessible

When unlocked

While locked

After first unlock

Always

…Complete …WhenUnlocked

…CompleteUnlessOpen N/A

…CompleteUntilFirstUserAuthentication …AfterFirstUnlock

…None …Always

Keychain vs. Data Protection Classes

43

Page 44: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Availability NSFileProtection kSecAttrAccessible

When unlocked

While locked

After first unlock

Always

…Complete …WhenUnlockedThisDeviceOnly

…CompleteUnlessOpen N/A

…CompleteUntilFirstUserAuthentication …AfterFirstUnlockThisDeviceOnly

…None …AlwaysThisDeviceOnly

Nonmigrating Keychain Classes

44

Page 45: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Keychain Item lookup

- (NSMutableDictionary *) queryForAccount:(NSString *)account {

return [NSMutableDictionary dictionaryWithObjectsAndKeys:

kSecClassGenericPassword, kSecClass,

@”Oversharing”, kSecAttrService, account, kSecAttrAccount, nil];

}

- (NSData *) passwordForAccount:(NSString *)account found:(BOOL *)found {

NSMutableDictionary *query = [self queryForAccount: account];

[query setObject: kCFBooleanTrue forKey: kSecReturnData];

NSData *data = NULL;

OSStatus status = SecItemCopyMatching(query, &data);

*found = status != errSecItemNotFound;

return data;

}

45

Page 46: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Keychain Item create

- (BOOL)setPassword: (NSData *)password forAccount:(NSString *)account {

NSMutableDictionary *attrs = [self queryForAccount: account];

[attrs setObject: password forKey: kSecValueData];

[attrs setObject: kSecAttrAccessibleWhenUnlocked

forKey: kSecAttrAccessible];

OSStatus status = SecItemAdd(attrs, NULL);

return status == noErr;

}

46

Page 47: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Keychain Item update

- (BOOL)updatePassword: (NSData *)password forAccount:(NSString *)account {

NSMutableDictionary *query = [self queryForAccount: account];

NSMutableDictionary *attrs = [NSMutableDictionary dictionary];

[attrs setObject: password forKey: kSecValueData];

[attrs setObject: kSecAttrAccessibleWhenUnlocked

forKey: kSecAttrAccessible];

OSStatus status = SecItemUpdate(query, attrs);

return status == noErr;

}

47

Page 48: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Keychain High-level Keychain usage sample

-(BOOL) login: (NSString *) account {

BOOL found = NO;

NSData *pw = [self passwordForAccount: account found: &found];

if ([self login: account password: pw]) return YES;

pw = [self queryUserForPassword];

if ([self login: account password: pw]) {

if (found) [self updatePassword: pw forAccount: account];

else [self setPassword: pw forAccount: account];

return YES;

}

return NO;

}

48

Page 49: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Summary

• Protect your customers’ data■ Store secrets in the Keychain■ Protect files with the best possible Data Protection class■ Encrypt and authenticate network traffic

49

Page 50: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Keychain Services Reference

Certificate, Key, and Trust Services Reference

NSFileManager Class Reference

NSData Class Reference

CoreData Framework Reference

CFNetwork Framework Reference

Secure Transport Reference

More Information

50

Page 51: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

Security Lab Core OS Lab BThursday 11:30AM

Labs

Security Lab Core OS Lab BFriday 11:30AM

51

Page 52: Securing iOS Applications - Freejan0.free.fr/208_securing_ios_applications.pdfThese are confidential sessions—please refrain from streaming, blogging, or taking pictures Protecting

52