020Transport Security using SSL

suggest change

iOS apps need to be written in a way that protects data transported over the network.

SSL is the common way to do it.

Whenever app tries to call web services to pull or push data to servers, it should use SSL over HTTP, i.e. HTTPS.

To do this, app must call https://server.com/part such web services and not http://server.com/part.

In this case, app needs to trust the server server.com using SSL certificate.

Here is an example of validating server trust.

Implement URLSessionDelegate as:

func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    
    if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
        let serverTrust:SecTrust = challenge.protectionSpace.serverTrust!

        func acceptServerTrust() {
            let credential = URLCredential(trust: serverTrust)
            // URLSession expects only the completion handler, not challenge.sender.
            completionHandler(.useCredential, credential)
        }
        
        let success = SSLTrustManager.shouldTrustServerTrust(serverTrust, forCert: "Server_Public_SSL_Cert")
        if success {
            acceptServerTrust()
            return
        }
    }
    else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate {
        completionHandler(.rejectProtectionSpace, nil);
        return
    }
    completionHandler(.cancelAuthenticationChallenge, nil)
}

Here is the trust manager (Swift equivalent not shown):

@implementation SSLTrustManager
+ (BOOL)shouldTrustServerTrust:(SecTrustRef)serverTrust forCert:(NSString*)certName {
// Load up the bundled certificate.
NSString *certPath = [[NSBundle mainBundle] pathForResource:certName ofType:@"der"];
NSData *certData = [[NSData alloc] initWithContentsOfFile:certPath];
CFDataRef certDataRef = (__bridge_retained CFDataRef)certData;
SecCertificateRef cert = SecCertificateCreateWithData(NULL, certDataRef);

// Establish a chain of trust anchored on our bundled certificate.
CFArrayRef certArrayRef = CFArrayCreate(NULL, (void *)&cert, 1, NULL);
SecTrustSetAnchorCertificates(serverTrust, certArrayRef);

// Verify that trust.
SecTrustResultType trustResult;
SecTrustEvaluate(serverTrust, &trustResult);

// Clean up.
CFRelease(certArrayRef);
CFRelease(cert);
CFRelease(certDataRef);

// Did our custom trust chain evaluate successfully?
return trustResult == kSecTrustResultUnspecified;
}
@end

Server_Public_SSL_Cert.der is the server's public SSL certificate.

Using this approach our app can make sure that it is communicating to the intended server and no one is intercepting the app-server communication.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents