No direct API to extract the public key bits from a certificate

Originator:nabla.c0d3
Number:rdar://22205652 Date Originated:09-Aug-2015 12:12 PM
Status:Closed Resolved:
Product:iOS Product Version:
Classification: Reproducible:
 
Summary:
The technical note TN2232 mentions in "Enforcing Stricter Server Trust Evaluation" that it is possible to "implement certificate pinning by extracting the public key from the server's certificate".

However, there is no direct API on iOS to extract the public key data from a certificate (for example to hash it). 
The process is actually fairly complex:

1. Create a `SecTrustRef` trust object with the certificate, and call `SecTrustEvaluate()` on it.
2. Call `SecTrustCopyPublicKey()` on the trust object to retrieve a `SecKeyRef` of the public key.
3. Add the public key to the device's Keychain using `SecItemAdd()`.
4. Retrieve the public key from the Keychain and set `kSecReturnData` to `YES` in order to specify that the key's data should be returned (instead of a `SecKeyRef`).

On OS X, this can be achieved by just calling `SecCertificateCopyValues()` on the certificate with `kSecOIDX509V1SubjectPublicKey` as the list of oids.

I had to implement both techniques in a tool so you can see the full code here: https://github.com/datatheorem/TrustKit/blob/master/TrustKit/Pinning/public_key_utils.m#L63

Steps to Reproduce:
Try to extract the public key bits from a certificate.

Expected Results:
Having to put data in Keychain just to retrieve the public key bits of a certificate seems really complex, slow and inefficient. It would be nice to have the OS X API available for this. I know there is a private API on iOS that works exactly like SecCertificateCopyValues, but it's private...

Actual Results:
I had to add random certificates to the Keychain just to be able to get the public key bits.

Version:
iOS 8

Notes:


Configuration:
N/A

Attachments:

Comments

A function SecKeyCopyExternalRepresentation() was added to iOS 10 to implement this.

By nabla.c0d3 at June 14, 2016, 4:09 p.m. (reply...)

Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!