MugunthKumar/MKNetworkKit — pull request #241 by Wirsing84 (2012-12-05 16:25:07+00:00)
Title: Added block-based CertificateHandler to validate own SSL Certificate (issue #192)

This adds an optional block-based handler, e.g., for users to implement their own SSL-certificate validation.

Scenario:
Server sends SSL-certificate, App should verify SSL-certificate by comparing it with SSL-certificate saved in its bundle. This is especially useful to counteract the threat of a mocked server / API.

- - -
Usage example with the SSL-certificate as a .cer-file in the application's main bundle:

operation.certificateHandler = ^(NSURLAuthenticationChallenge *challenge, NSURLConnection *connection){

SecTrustRef trust = [[challenge protectionSpace] serverTrust];

SecCertificateRef certificate = SecTrustGetCertificateAtIndex(trust, 0);

NSData* ServerCertificateData = (__bridge NSData*) SecCertificateCopyData(certificate);

// Check if the certificate returned from the server is identical to the saved certificate in
// the main bundle
NSData *bundleCertificateData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"certificate" ofType:@"cer"]];

BOOL areCertificatesEqual = ([ServerCertificateData
isEqualToData:bundleCertificateData]);

if (!areCertificatesEqual)
{
NSLog(@"Bad Certificate, canceling request");
[connection cancel];
}else{
NSLog(@"OK Certificate!");
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}
};