How to pin the Public key of a certificate on iOS
Asked Answered
A

7

51

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?

Ambience answered 31/3, 2013 at 10:51 Comment(2)
See this if it can help jayprakashdubey.blogspot.in/2017/07/…Reheat
There's a good example at the TrustKit github: github.com/datatheorem/TrustKitMansour
A
35

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;
}

}
Ambience answered 31/3, 2013 at 10:51 Comment(1)
from where we got serverCertificateData?Tambac
H
22

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:

  1. Use a NSURLConnectionDelegate to retrieve the data, and implement willSendRequestForAuthenticationChallenge.
  2. Include a reference certificate in DER format. In the example I've used a simple resource file.
  3. Extract the public key presented by the server
  4. Extract the public key from your reference certificate
  5. Compare the two
  6. If they match, continue with the regular checks (hostname, certificate signing, etc)
  7. 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.

Hinshaw answered 24/3, 2015 at 13:49 Comment(2)
good work! allows for public key comparison without all the openSSL headachesHindsight
Anyone have this in Swift?Blaise
P
9

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.

Podite answered 28/4, 2013 at 0:57 Comment(1)
More specifically, the implementation of certificate and public key pinning is in github.com/AFNetworking/AFNetworking/blob/master/AFNetworking/…Philbrook
M
5

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).

Merlenemerlin answered 22/9, 2013 at 13:53 Comment(0)
E
3

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];
Equitation answered 22/4, 2015 at 22:16 Comment(0)
U
1

...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.

Utilitarianism answered 27/4, 2013 at 4:44 Comment(2)
The iOS project example in the OWASP doesn't really do public key pinning but certificate pinning. If you happen to go into their code you will see that the comparison they do is: const BOOL equal = [cert1 isEqualToData:cert2]; They are basically comparing the entire certificate! Well, either that, or there is something I am missing...Ambience
Yeah comparing certs has a issue where if you renew certs, you would have to update your app with the new cert. As opposed to comparing the pinned Public Keys where you'd renew your cert but keep the public key same, so there is no need for app updates.Aphis
A
0

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

Apron answered 28/2, 2017 at 3:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.