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.
The add the openssl libraries. You can download them from https://github.com/st3fan/ios-openssl
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)
Now we will prepare to read the public key data
At this point you can iterate through the pubKey2 string and extract the bytes in HEX format into a string with the following loop
Print the public key to see it
The complete code
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:
willSendRequestForAuthenticationChallenge
.Some example code:
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.