How to pin the Public key of a certificate on iOS - iphone

While improving the security of an iOS application that we are developing, we found the need to PIN (the entire or parts of) the SSL certificate of server to prevent man-in-the-middle attacks.
Even though there are various approaches to do this, when you searching for thisI only found examples for pinning the entire certificate. Such practice poses a problem: As soon as the certificate is updated, your application will not be able to connect anymore.
If you choose to pin the public key instead of the entire certificate you will find yourself (I believe) in an equally secure situation, while being more resilient to certificate updates in the server.
But how do you do this?

In case you are in need of knowing how to extract this information from the certificate in your iOS code, here you have one way to do it.
First of all add the security framework.
#import <Security/Security.h>
The add the openssl libraries. You can download them from https://github.com/st3fan/ios-openssl
#import <openssl/x509.h>
The NSURLConnectionDelegate Protocol allows you to decide whether the connection should be able to respond to a protection space. In a nutshell, this is when you can have a look at the certificate that is coming from the server, and decide to allow the connection to proceed or to cancel. What you want to do here is compare the certificates public key with the one you've pinned. Now the question is, how do you get such public key? Have a look at the following code:
First get the certificate in X509 format (you will need the ssl libraries for this)
const unsigned char *certificateDataBytes = (const unsigned char *)[serverCertificateData bytes];
X509 *certificateX509 = d2i_X509(NULL, &certificateDataBytes, [serverCertificateData length]);
Now we will prepare to read the public key data
ASN1_BIT_STRING *pubKey2 = X509_get0_pubkey_bitstr(certificateX509);
NSString *publicKeyString = [[NSString alloc] init];
At this point you can iterate through the pubKey2 string and extract the bytes in HEX format into a string with the following loop
for (int i = 0; i < pubKey2->length; i++)
{
NSString *aString = [NSString stringWithFormat:#"%02x", pubKey2->data[i]];
publicKeyString = [publicKeyString stringByAppendingString:aString];
}
Print the public key to see it
NSLog(#"%#", publicKeyString);
The complete code
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
const unsigned char *certificateDataBytes = (const unsigned char *)[serverCertificateData bytes];
X509 *certificateX509 = d2i_X509(NULL, &certificateDataBytes, [serverCertificateData length]);
ASN1_BIT_STRING *pubKey2 = X509_get0_pubkey_bitstr(certificateX509);
NSString *publicKeyString = [[NSString alloc] init];
for (int i = 0; i < pubKey2->length; i++)
{
NSString *aString = [NSString stringWithFormat:#"%02x", pubKey2->data[i]];
publicKeyString = [publicKeyString stringByAppendingString:aString];
}
if ([publicKeyString isEqual:myPinnedPublicKeyString]){
NSLog(#"YES THEY ARE EQUAL, PROCEED");
return YES;
}else{
NSLog(#"Security Breach");
[connection cancel];
return NO;
}
}

As far as I can tell you cannot easily create the expected public key directly in iOS, you need to do it via a certificate.
So the steps needed are similar to pinning the certificate, but additionally you need to extract the public key from the actual certificate, and from a reference certificate (the expected public key).
What you need to do is:
Use a NSURLConnectionDelegate to retrieve the data, and implement willSendRequestForAuthenticationChallenge.
Include a reference certificate in DER format. In the example I've used a simple resource file.
Extract the public key presented by the server
Extract the public key from your reference certificate
Compare the two
If they match, continue with the regular checks (hostname, certificate signing, etc)
If they don't match, fail.
Some example code:
(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
// get the public key offered by the server
SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
SecKeyRef actualKey = SecTrustCopyPublicKey(serverTrust);
// load the reference certificate
NSString *certFile = [[NSBundle mainBundle] pathForResource:#"ref-cert" ofType:#"der"];
NSData* certData = [NSData dataWithContentsOfFile:certFile];
SecCertificateRef expectedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certData);
// extract the expected public key
SecKeyRef expectedKey = NULL;
SecCertificateRef certRefs[1] = { expectedCertificate };
CFArrayRef certArray = CFArrayCreate(kCFAllocatorDefault, (void *) certRefs, 1, NULL);
SecPolicyRef policy = SecPolicyCreateBasicX509();
SecTrustRef expTrust = NULL;
OSStatus status = SecTrustCreateWithCertificates(certArray, policy, &expTrust);
if (status == errSecSuccess) {
expectedKey = SecTrustCopyPublicKey(expTrust);
}
CFRelease(expTrust);
CFRelease(policy);
CFRelease(certArray);
// check a match
if (actualKey != NULL && expectedKey != NULL && [(__bridge id) actualKey isEqual:(__bridge id)expectedKey]) {
// public keys match, continue with other checks
[challenge.sender performDefaultHandlingForAuthenticationChallenge:challenge];
} else {
// public keys do not match
[challenge.sender cancelAuthenticationChallenge:challenge];
}
if(actualKey) {
CFRelease(actualKey);
}
if(expectedKey) {
CFRelease(expectedKey);
}
}
Disclaimer: this is example code only, and not thoroughly tested.
For a full implementation start with the certificate pinning example by OWASP.
And remember that certificate pinning can always be avoided using SSL Kill Switch and similar tools.

You can do public key SSL pinning using the SecTrustCopyPublicKey function of the Security.framework. See an example at connection:willSendRequestForAuthenticationChallenge: of the AFNetworking project.
If you need openSSL for iOS, use https://gist.github.com/foozmeat/5154962 It's based on st3fan/ios-openssl, which currently doesn't work.

You could use the PhoneGap (Build) plugin mentioned here: http://www.x-services.nl/certificate-pinning-plugin-for-phonegap-to-prevent-man-in-the-middle-attacks/734
The plugin supports multiple certificates, so the server and client don't need to be updated at the same time. If your fingerprint changes every (say) 2 year, then implement a mechanism for forcing the clients to update (add a version to your app and create a 'minimalRequiredVersion' API method on the server. Tell the client to update if the app version is too low (f.i. when the new certificate is activate).

If you use AFNetworking (more specifically, AFSecurityPolicy), and you choose the mode AFSSLPinningModePublicKey, it doesn't matter if your certificates change or not, as long as the public keys stay the same. Yes, it is true that AFSecurityPolicy doesn't provide a method for you to directly set your public keys; you can only set your certificates by calling setPinnedCertificates. However, if you look at the implementation of setPinnedCertificates, you'll see that the framework is extracting the public keys from the certificates and then comparing the keys.
In short, pass in the certificates, and don't worry about them changing in the future. The framework only cares about the public keys in those certificates.
The following code works for me.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey];
[manager.securityPolicy setPinnedCertificates:myCertificate];

...for pinning the entire certificate. Such practice poses a problem...
Also, Google changes the certificate monthly (or so) but retains or re-certifies the public. So certificate pinning will result in a lot of spurious warnings, while public key pinning will pass key continuity tests.
I believe Google does it to keep CRLs, OCSP and Revocation Lists manageable, and I expect others will do it also. For my sites, I usually re-certify the keys so folks to ensure key continuity.
But how do you do this?
Certificate and Public Key Pinning. The article discusses the practice and offers sample code for OpenSSL, Android, iOS, and .Net. There is at least one problem with iOS incumbent to the framework discussed at iOS: Provide Meaningful Error from NSUrlConnection didReceiveAuthenticationChallenge (Certificate Failure).
Also, Peter Gutmann has a great treatment of key continuity and pinning in his book Engineering Security.

If you use AFNetworking, use AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey];

Related

iOS: using SecTrustEvaluate to check for presence of intermediate CA in user's keychain

We are tasked with determining inside our app whether or not a specific configuration profile is installed on an iOS device. There exists no public API to check which configuration profiles are installed on a device, but this article http://blog.markhorgan.com/?p=701 describes a workaround.
Basically one includes a root CA inside the configuration profile and signs with this root CA a second certificate. This second certificate gets bundled in the app and then a trust evaluation of this second certificate in the app will reveal whether or not the root CA is present (and this means that the configuration profile is installed).
Now, we are not able to tamper with our configuration profile in question (because it is installed on many devices already), but it does already include 2 certificates which we do have access to:
OurRootCA (issued by: OurRootCA)
OurIntermediateCA (issued by: OurRootCA)
unfortunately, OurRootCA is not only included in the configuration profile in question, but also in other configuration profiles (so a check with this method could yield false positives), but fortunately OurIntermediateCA is solely used in the configurationProfile we want to check for.
Unfortunately, for some reasons, the tests fails (it always returns kSecTrustResultRecoverableTrustFailure) if performed with a test SSL certificate that was issued by OurIntermediateCA (it works though with a test SSL certificate that was issued by OurRootCA).
Here's the validation code:
//NSString* certPath = [[NSBundle mainBundle] pathForResource:#"TestCertificateSignedByRoot" ofType:#"cer"]; //with this cert, the validation works
NSString* certPath = [[NSBundle mainBundle] pathForResource:#"TestCertificateSignedByIntermediate" ofType:#"cer"];
NSData* certData = [NSData dataWithContentsOfFile:certPath];
SecCertificateRef cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef) certData);
SecPolicyRef policy = SecPolicyCreateBasicX509();
SecTrustRef trust;
OSStatus err = SecTrustCreateWithCertificates((__bridge CFArrayRef) [NSArray arrayWithObject:(__bridge id)cert], policy, &trust);
// set trust anchor certificates to empty array as advised in http://stackoverflow.com/questions/7900896/sectrustevaluate-always-returns-ksectrustresultrecoverabletrustfailure-with-secp
SecTrustSetAnchorCertificates(trust, (__bridge CFArrayRef) [NSArray array]);
SecTrustSetAnchorCertificatesOnly(trust, NO);
SecTrustResultType trustResult = -1;
err = SecTrustEvaluate(trust, &trustResult);
CFRelease(trust);
CFRelease(policy);
CFRelease(cert);
switch(trustResult) {
case kSecTrustResultUnspecified:
case kSecTrustResultProceed: {
return YES;
// this is the result if TestCertificateSignedByRoot is used
break;
}
case kSecTrustResultRecoverableTrustFailure: {
return NO;
// this is the result if TestCertificateSignedByIntermediate is used
break;
}
default: {
return NO;
break;
}
}
So, the technique seems to work - the (self-signed) rootCA in the users keychain is used to validate our test certificate. But if the intermediate CA is checked for, the test always returns kSecTrustResultRecoverableTrustFailure. What could be the problem here and how can it be debugged?

Get host server name through email address in mail core2 framework for iOS

I want to know the default host name through the name of the email address....
I found a method in a class "MCONetService.h"....
hostnameWithEmail:
the reference link..
http://libmailcore.com/mailcore2/api/Classes/MCONetService.html
...but my problem is that i am unable to find the proper way to use this method because it is an instance method which requires the "MCONetService" class object to call that method,and i am getting null because it seems this object need some value before the use...
my code ...
MCONetService *netService=[[MCONetService alloc]init];
[netService hostnameWithEmail:#"email#gmail.com"];
This is not a good way of coding but did't found any other way to try this method...
Any help will be appreciable....
Here's how to do it:
First, make sure that you include providers.json in the resources of your app.
Here's how to get the IMAP server related to a given email address.
NSString * email = #"email#gmail.com";
MCOMailProvider * provider = [[MCOMailProvidersManager sharedManager]
providerForEmail:email];
NSString * hostname = nil;
if ([[provider imapServices] count] > 0) {
MCONetService * service = [[provider imapServices] objectAtIndex:0];
hostname = [service hostnameWithEmail:email];
}
if (hostname == nil) {
NSLog(#"no IMAP server found");
}
else {
NSLog(#"IMAP server: %#", hostname);
}

send RSA public key to iphone and use it to encrypt

I have a TCP socket server and I want to do the following w/o using SSL:
On server, make RSA key pair (I know how to do this using openssl's crypto library)
On server, send the public key to iphone and keep the private key.
On client(iphone), want to encrypt a message using the public key, using SecKeyEncrypt.
On server, decrypt the message.
The message is short enough so that the PKCS1 padded result fits into 128 bytes.
I don't know how to do 2~4. Anyone knows?
This should do what you're asking - it encrypts data with the server's public key. It's not subject to MITM attacks, unless the attacker has a copy of your private key and its password (communicating via non-SSL, however, still is, but the data you encrypt with the server's legit public key will be nearly impossible to decrypt).
I cobbled this together from Apple's docs, this site, the Apple developer forums and probably elsewhere. So thanks to everyone I cribbed code from! This code assumes several things:
You've already generated your RSA key pairs (I'm using a 4096-bit key and it seems speedy enough) and, using the private key, created a DER-encoded certificate called "cert.cer" that you put in your resource bundle of your app (obviously, you can also download the cert from your server, but then you're open to MITM attacks again). By default, OpenSSL generates a PEM encoded cert, so you have to convert it with "openssl x509 -in cert.pem -inform PEM -out cert.cer -outform DER". iOS will barf on PEM. The reason I use a cert is it's actually easier to work with, and is supported in iOS. Using just the public key isn't (though it can be done).
You've added Security.framework to your project and you #import <Security/Security.h>.
/*
Returns an NSData of the encrypted text, or nil if encryption was unsuccessful.
Takes the X.509 certificate as NSData (from dataWithContentsOfFile:, for example)
*/
+(NSData *)encryptString:(NSString *)plainText withX509Certificate:(NSData *)certificate {
SecCertificateRef cert = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)certificate);
SecPolicyRef policy = SecPolicyCreateBasicX509();
SecTrustRef trust;
OSStatus status = SecTrustCreateWithCertificates(cert, policy, &trust);
SecTrustResultType trustResult;
if (status == noErr) {
status = SecTrustEvaluate(trust, &trustResult);
}
SecKeyRef publicKey = SecTrustCopyPublicKey(trust);
const char *plain_text = [plainText UTF8String];
size_t blockSize = SecKeyGetBlockSize(publicKey);
NSMutableData *collectedCipherData = [NSMutableData data];
BOOL success = YES;
size_t cipherBufferSize = blockSize;
uint8_t *cipherBuffer = malloc(blockSize);
int i;
for (i = 0; i < strlen(plain_text); i += blockSize-11) {
int j;
for (j = 0; j < blockSize-11 && plain_text[i+j] != '\0'; ++j) {
cipherBuffer[j] = plain_text[i+j];
}
int result;
if ((result = SecKeyEncrypt(publicKey, kSecPaddingPKCS1, cipherBuffer, j, cipherBuffer, &cipherBufferSize)) == errSecSuccess) {
[collectedCipherData appendBytes:cipherBuffer length:cipherBufferSize];
} else {
success = NO;
break;
}
}
/* Free the Security Framework Five! */
CFRelease(cert);
CFRelease(policy);
CFRelease(trust);
CFRelease(publicKey);
free(cipherBuffer);
if (!success) {
return nil;
}
return [NSData dataWithData:collectedCipherData];
}
Well, I guess you would need to publish your public key to the outside world (the iPhone in your case). To do the best way is to publish a certificate conatining your public key, and the iPhone app can download it. Then the iPhone application can utilize the principle of PGP to encrypt the data with a symmetric algo (like AES) and encrypt the symmetric with the public key. The application in the server would receive the message, decrypt the symmetric key with its private key, and the then decrypt the encrypted data with the symmetric key thus obtained.
But as cobbal said, anyone can intercept the message in between the server and the iPhone and can change it, and the server would not know if its has 'actually' recieved the data from the iPHone, unless you sign it using an SSL certificate (i.e. encrypt the hash of the method with the private key of the iPhone).
My suggestion is, use availale third party application rather than doing it yourself, as they might be some falw in tghe implementation. PGP is a public available library, u can use.

Alternatives to NSHost in iPhone app

I'm currently using this code
NSHost *host = [NSHost hostWithAddress:hostname];
if (host == nil) {
host = [NSHost hostWithName:hostname];
if (host == nil) {
[self setMessage:#"Invalid IP address or hostname:"];
return;
}
}
to retrive my IP Address for a networking app I'm working on, however I'm aware that NSHost is a private API that will be rejected. Can anyone help me with working this code to produce the same results without using NSHost? I'm not really sure where to start.
EDIT:
Following suggestions that seem damn near perfect below I've added this code into my app in the place of the code above
Boolean result;
CFHostRef hostRef;
CFArrayRef addresses;
NSString *hostname = #"www.apple.com";
hostRef = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)hostname);
if (hostRef) {
result = CFHostStartInfoResolution(hostRef, kCFHostAddresses, NULL); // pass an error instead of NULL here to find out why it failed
if (result == TRUE) {
addresses = CFHostGetAddressing(hostRef, &result);
}
}
if (result == TRUE) {
NSLog(#"Resolved");
} else {
NSLog(#"Not resolved");
}
I've removed the 4th line (as I have this information from elsewhere already) but I get errors being based around CFHostRef being undeclared. How would I resolve that? It seems to be my only big hurdle, as other errors are only based upon the lack of being able to see hostRef after that.
EDIT: Scratch that I also get kCFHostAddresses undeclared.
You can use CFHost to achieve the same. On the top of the CFHost Reference is a cookbook recipe for making the lookup.
The following code does very, very basic synchronous resolution (as yours above would with NSHost). Note that you don't want to do this since it can render your app unresponsive because it doesn't return until it's resolved or the timeout hits.
Use asynchronous lookup instead (CFHostSetClient and CFHostScheduleWithRunLoop as described in the CFHost documentation above). Also, depending on what you're planning to do, you may want to look into using the reachability APIs. Check out the WWDC sessions on networking available on the iPhone developer website.
Boolean result;
CFHostRef hostRef;
CFArrayRef addresses;
NSString *hostname = #"www.apple.com";
hostRef = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)hostname);
if (hostRef) {
result = CFHostStartInfoResolution(hostRef, kCFHostAddresses, NULL); // pass an error instead of NULL here to find out why it failed
if (result == TRUE) {
addresses = CFHostGetAddressing(hostRef, &result);
}
}
if (result == TRUE) {
NSLog(#"Resolved");
} else {
NSLog(#"Not resolved");
}
// Don't forget to release hostRef when you're done with it
Look at this: http://blog.zachwaugh.com/post/309927273/programmatically-retrieving-ip-address-of-iphone
http://developer.apple.com/iphone/library/qa/qa2009/qa1652.html
Got a great little answer through the Developer Support system, this worked perfectly.

iphone programmatically read proxy settings

I'm looking at adding proxy support to my iphone svn client. When you set up a system wide vpn in the iphone settings you can add a global proxy. Is it possible for external apps to read this information through the api?
Apple has created a sample application for this purpose, called CFProxySupportTool.
CFProxySupportTool shows how to use the CFProxySupport APIs to determine whether a network connection should pass through a proxy; this is useful if you're not using Apple's high-level networking APIs (like CFNetwork and the Foundation URL loading system) but still want to interpret the system-supplied proxy settings.
It's currently available at
https://developer.apple.com/library/mac/#samplecode/CFProxySupportTool/Introduction/Intro.html
The code isn't exactly terse (more than 1000 lines), and is written in plain C. You can also look at the source code of ASIHTTPRequest's startRequest function, which seems to be based on CFProxySupportTool.
Here's a start:
systemProxySettings = [(NSDictionary *) CFNetworkCopySystemProxySettings() autorelease];
proxies = [(NSArray *) CFNetworkCopyProxiesForURL((CFURLRef) URL, (CFDictionaryRef) systemProxySettings) autorelease];
if (!proxies.count)
return;
firstProxySettings = [proxies objectAtIndex:0];
if (nil != (pacScriptURL = [firstProxySettings objectForKey:(NSString *)kCFProxyAutoConfigurationURLKey]))
{
CFErrorRef cfErrorRef = NULL;
NSError *nsError = nil;
NSString *script;
script = [NSString stringWithContentsOfURL:pacScriptURL
usedEncoding:NULL
error:&nsError];
if (nsError)
return;
proxies = [(NSArray *) CFNetworkCopyProxiesForAutoConfigurationScript((CFStringRef) script, (CFURLRef) URL, &cfErrorRef) autorelease];
if (cfErrorRef || !proxies.count)
return;
firstProxySettings = [proxies objectAtIndex:0];
}
/* Now use `firstProxySettings' */
A Swift 4 version (special thanks to mortehu for providing the initial example).
//Shown this way for clarity, you may not want to waste cycles in your production code
if let url = URL(string: "https://someurloutthere.com") {
let systemProxySettings = CFNetworkCopySystemProxySettings()?.takeUnretainedValue() ?? [:] as CFDictionary
let proxiesForTargetUrl = CFNetworkCopyProxiesForURL(url as CFURL, systemProxySettings).takeUnretainedValue() as? [[AnyHashable: Any]] ?? []
for proxy in proxiesForTargetUrl {
print("Proxy: \(String(describing: proxy))")
//Print the proxy type
print("Proxy Type: \(String(describing: proxy[kCFProxyTypeKey]))")
//There different proxy value keys depending on the type, this is an example of getting the proxy config script if the type is kCFProxyTypeAutoConfigurationURL. If the proxy type were kCFProxyTypeSOCKS you would want to access the SOCKS property keys to see/get the SOCKS proxy values
print("Proxy Autoconfig script URL: \(String(describing: proxy[kCFProxyAutoConfigurationURLKey]))"
}
}
Have you investigated using something like ASIHttpRequest, see the section in the how to document describing proxy support.
At the very least the source code should contain some helpful guidance.
Take a look at the CFProxySupport API, in particular CFNetworkCopyProxiesForURL() will let you read the proxies that are needed to get to a particular URL.