Using TLS with Self-Signed Certificates or Custom Root Certificates in iOS
Transport Layer Security (TLS), formerly Secure Sockets Layer (SSL), is the standard for encrypting and authenticating messages and identifying users and servers, all of which you do when you make an online purchase. For example, if you want to buy something from Amazon, you connect to a server that your Domain Name System (DNS) server says is amazon.com and send them your order with your credit card. However, in this simple transaction, a number of failures could occur: you might not be connected to the real Amazon server, someone might be watching packets for your order to steal your credit card number, or someone might rewrite your order to have your order shipped to their house. Using TLS, you can be sure that the server to which you are connected is Amazon’s, that no one sees the contents of your order, and that Amazon can verify that the order they received is the one that you sent. This article uses code examples to show how Apple’s mobile operating system, iOS, supports TLS and what you need to do to add it to your iPhone/iPad application.
iOS supports TLS with built-in commonly trusted root certificate authorities (CAs). However, if you must talk to a server whose certificate cannot be validated with those root CAs or is self-signed, you must manually validate the server’s certificate.
You have two options available: add your server’s certificate to the keychain or perform validation manually. Regardless of your approach, you’ll need to include a DER-encoded X.509 public certificate in your app. In the example below, it is named “ios-trusted-cert.der”) and create a SecCertificateRef with it. (If your server’s certificate is part of a chain to a root certificate authority, you should install the root certificate authority rather than your server’s certificate.)
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSData *iosTrustedCertDerData =
[NSData dataWithContentsOfFile:[bundle pathForResource:@"ios-trusted-cert"
ofType:@"der"]];
SecCertificateRef certificate =
SecCertificateCreateWithData(NULL,
(CFDataRef) iosTrustedCertDerData);
Remember that SecCertificateCreateWithData follows the create rule of memory ownership, so you must CFRelease it when you no longer need it to avoid memory leaks.
Next, you can add your cert to your app’s keychain. This is appropriate when you want iOS to trust your cert for every new socket you create.
- (void) useKeychain: (SecCertificateRef) certificate {
OSStatus err =
SecItemAdd((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
(id) kSecClassCertificate, kSecClass,
certificate, kSecValueRef,
nil],
NULL);
if ((err == noErr) || // success!
(err == errSecDuplicateItem)) { // the cert was already added. Success!
// create your socket normally.
// This is oversimplified. Refer to the CFNetwork Guide for more details.
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL,
(CFStringRef)@"localhost",
8443,
&readStream,
&writeStream);
CFReadStreamSetProperty(readStream,
kCFStreamPropertySocketSecurityLevel,
kCFStreamSocketSecurityLevelTLSv1);
CFReadStreamOpen(readStream);
CFWriteStreamOpen(writeStream);
} else {
// handle the error. There is probably something wrong with your cert.
}
}
If you only want to verify the cert for the socket you are creating and for no other sockets in your app, you can verify your trust in the cert manually. First, create a socket (assuming your server is listening on port 8443 on the same machine as your client) and disable its certificate chain validation in its ssl settings:
- (void) verifiesManually: (SecCertificateRef) certificate {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL,
(CFStringRef)@"localhost",
8443,
&readStream,
&writeStream);
// Set this kCFStreamPropertySocketSecurityLevel before
// setting kCFStreamPropertySSLSettings.
// Setting kCFStreamPropertySocketSecurityLevel
// appears to override previous settings in kCFStreamPropertySSLSettings
CFReadStreamSetProperty(readStream,
kCFStreamPropertySocketSecurityLevel,
kCFStreamSocketSecurityLevelTLSv1);
// this disables certificate chain validation in ssl settings.
NSDictionary *sslSettings =
[NSDictionary dictionaryWithObjectsAndKeys:
(id)kCFBooleanFalse, (id)kCFStreamSSLValidatesCertificateChain,
nil];
CFReadStreamSetProperty(readStream,
kCFStreamPropertySSLSettings,
sslSettings);
NSInputStream *inputStream = (NSInputStream *)readStream;
NSOutputStream *outputStream = (NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
CFReadStreamOpen(readStream);
CFWriteStreamOpen(writeStream);
}
Then, when you receive a callback that your socket is ready to write data, you should verify trust in the certificate your server included before writing any data to or reading any data from the server. First (1), create a client SSL policy with the hostname of the server to which you connected. The hostname is included in the server’s cert to authenticate that the server to which DNS directed you is the server you trust. Next (2), you grab the actual server certificates from the socket. There may be multiple certificates associated with the server if the server’s certificate is part of a certificate chain. When you have the actual server certificates, you can (3) create a trust object. The trust object represents a local context for trust evaluations. It isolates individual trust evaluations whereas the keychain certificates apply to all trusted sockets. After you have a trust object, you can (4) set the anchor certificates, which are the certificates you trust. Finally (5), you can evaluate the trust object and discover whether the server can be trusted.
#pragma mark -
#pragma mark NSStreamDelegate
- (void)stream:(NSStream *)aStream
handleEvent:(NSStreamEvent)eventCode {
switch (eventCode) {
case NSStreamEventNone:
break;
case NSStreamEventOpenCompleted:
break;
case NSStreamEventHasBytesAvailable:
break;
case NSStreamEventHasSpaceAvailable:
// #1
// NO for client, YES for server. In this example, we are a client
// replace "localhost" with the name of the server to which you are connecting
SecPolicyRef policy = SecPolicyCreateSSL(NO, CFSTR("localhost"));
SecTrustRef trust = NULL;
// #2
CFArrayRef streamCertificates =
[aStream propertyForKey:(NSString *) kCFStreamPropertySSLPeerCertificates];
// #3
SecTrustCreateWithCertificates(streamCertificates,
policy,
&trust);
// #4
SecTrustSetAnchorCertificates(trust,
(CFArrayRef) [NSArray arrayWithObject:(id) self.certificate]);
// #5
SecTrustResultType trustResultType = kSecTrustResultInvalid;
OSStatus status = SecTrustEvaluate(trust, &trustResultType);
if (status == errSecSuccess) {
// expect trustResultType == kSecTrustResultUnspecified
// until my cert exists in the keychain see technote for more detail.
if (trustResultType == kSecTrustResultUnspecified) {
NSLog(@"We can trust this certificate! TrustResultType: %d", trustResultType);
} else {
NSLog(@"Cannot trust certificate. TrustResultType: %d", trustResultType);
}
} else {
NSLog(@"Creating trust failed: %d", status);
[aStream close];
}
if (trust) {
CFRelease(trust);
}
if (policy) {
CFRelease(policy);
}
break;
case NSStreamEventErrorOccurred:
NSLog(@"unexpected NSStreamEventErrorOccurred: %@", [aStream streamError]);
break;
case NSStreamEventEndEncountered:
break;
default:
break;
}
}
That’s all! You now have a trusted, secured connection.

Nice blog.
Well if i only want to add certificate to keychain (same as u did), then i request the server async with NSURLConnection and go along the flow, no need for canAuthenticateAgainstProtectionSpace… or didReceiveAuthenticationChallenge.
In ur opinion, would that work?
I’m adding a cert to the keychain. I’m creating a SecTrust object and using it to authenticate the connection. You can only add certs to the keychain with the iPhone Configuration Utility. Unless you add a cert to the keychain, I doubt NSURLConnection would work properly.
Sorry, the last comment was erroneous.
I’m _NOT_ adding a cert to the keychain. I’m creating a SecTrust object and using it to authenticate the connection. You can only add certs to the keychain with the iPhone Configuration Utility. Unless you add a cert to the keychain, I doubt NSURLConnection would work properly.
Is there a way to explore the iPhone’s keychain to see what certificates are installed which are taken into account by NSURLConnection etc?