How to protect SecIdentity with biometrics/kSecAttrAccessControl? - ios

Here's the repo where this can be easily reproduced: https://github.com/haemi/SecIdentityBiometrics
What I try to achieve is generating a RSA 2048bit key pair, where the public key is sent to the server. The server sends a x.509 certificate back.
With my private key and the certificate, I need to create a SecIdentity (used for URLAuthChallenge). This works when I do not use biometrics to protect the private key.
But as soon as I add biometrics, I'm unable to fetch the SecIdentity. I tried with two variants:
enum Variant {
case writeIdentityWithBiometrics
case writePrivateKeyWithBiometrics
}
writeIdentityWithBiometrics
Here I add kSecAttrAccessControl to the private key directly and try to read the SecIdentity in the end.
writePrivateKeyWithBiometrics
Here I first add the keypair, then the certificate to the keychain - everything without biometrics. Then I read the SecIdentity and try to add it with kSecAttrAccessControl.

Related

iOS TLS/SSL Pinning using NSRequiresCertificateTransparency key in Info.plist

I want to secure my app against man-in-the-middle (mitm) attacks using SSL Pinning.
By default it is possible to use a proxy like Charles or mitmproxy to intercept traffic, and decrypt it using a self-signed certificate.
After extensive research, I found several options:
Adding NSPinnedDomains > MY_DOMAIN > NSPinnedLeafIdentities to Info.plist
Apple Documentation: Identity Pinning
Guardsquare: Leveraging Info.plist Based Certificate Pinning
Pros: Simple
Cons: App becomes unusable once Certificate/Private Key is renewed (typically after a few months)
Adding NSPinnedDomains > MY_DOMAIN > NSPinnedCAIdentities to Info.plist
Apple Documentation: same as above
Pros: Simple. No failure on Leaf Certificate renewal because Root CAs are pinned instead (expiration dates decades out)
Cons: Seems redundant as most root CAs are already included in the OS
Checking certificates in code URLSessionDelegate > SecTrustEvaluateWithError (or Alamofire wrapper)
Ray Wenderlich: Preventing Man-in-the-Middle Attacks in iOS with SSL Pinning
Apple Documentation: Handling an Authentication Challenge
Medium article: Everything you need to know about SSL Pinning
Medium article: Securing iOS Applications with SSL Pinning
Pros: More flexibility. Potentially more secure. Recommended by Apple (see Apple-link above).
Cons: A more laborious version of (1) or (2). Same Cons as (1) and (2) regarding leaf expirations / root CA redundancies. More complicated.
Adding NSExceptionDomains > MY_DOMAIN > NSRequiresCertificateTransparency to Info.plist
Apple documentation: Section Info.plist keys 'Certificate Transparency'
Pros: Very simple. No redundant CA integration.
Cons: Documentation is unclear whether this should be used for ssl pinning
After evaluation I came to the following conclusion:
Not suitable for a production app because of certificate expiration
Probably best balance between simplicity, security and sustainability – but I don't like the duplication of adding root CAs the system already knows
Too complicated, too risky, any implementation error may lock the app
My preferred way. Simple. Works in my tests but – unclear documentation.
I am tempted to use option (4) but I am not sure if this is really meant for ssl pinning.
In the documentation it says:
Certificate Transparency (CT) is a protocol that ATS can use to identify mistakenly or maliciously issued X.509 certificates. Set the value for the NSRequiresCertificateTransparency key to YES to require that for a given domain, server certificates are supported by valid, signed CT timestamps from at least two CT logs trusted by Apple. For more information about Certificate Transparency, see RFC6962.
and in the linked RFC6962:
This document describes an experimental protocol for publicly logging the existence of Transport Layer Security (TLS) certificates [...]
The terms "experimental protocol" and "publicly logging" raise flags for me and although flipping the feature on in the Info.plist seems to solve SSL pinning I am not sure if I should use it.
I am by no means a security expert and I need a dead simple solution that gives me decent protection while protecting me from choking my own app through possible expired / changed certificates.
My question:
Should I use NSRequiresCertificateTransparency for ssl pinning and preventing mitm-attacks on my app?
And if not:
What should I use instead?
PS:
This same question was essentially already asked in this thread:
https://developer.apple.com/forums/thread/675791
However the answer was vague about NSRequiresCertificateTransparency (4. in my list above):
Right, Certificate Transparency is great tool for verifying that a provided leaf does contain a set of SCTs (Signed Certificate Timestamp) either embedded in the certificate (RFC 6962), through a TLS extension (which can be seen in a Packet Trace), or by checking the OCSP logs of the certificate. When you make a trust decision in your app, I would recommend taking a look at is property via the SecPolicyRef object.
Additional side note:
My expectation from Apple as a security-aware company would have been, that pinning to root CAs was enabled by default, and that I would have to add exceptions manually, e.g. allow proxying with Charles on debug builds.
I hear Android does it that way.
I'm using SecTrustEvaluateWithError to evaluate the certificate. In case if certificate expired or any another case where evaluate return an error, I getting new one from the server. Certificate is stored and received witch keychain. One of the problem I faced with this solution was updating existing certificate at keychain because in apple documentation way to do it, is by using kSecValueRef but that one returns error whenever you try to update it. Instead cert is saved with kSecValueData.
So solution nr 3 (kind of) is used here, but in my case there is a socket connection instead.
First I connect to the socket with settings using CocoaAsyncSocket library
GCDAsyncSocketManuallyEvaluateTrust: NSNumber(value: true),
kCFStreamSSLPeerName as String: NSString("name")
next I use delegate to receive trust object
public func socket(_ sock: GCDAsyncSocket, didReceive trust: SecTrust, completionHandler: #escaping (Bool) -> Void)
next evaluate with existing one (from keychain), or update cert and repeat evaluation
if let cert = CertificateManager.shared.getServerCertificate() {
SecTrustSetAnchorCertificates(trust, [cert] as NSArray)
SecTrustSetAnchorCertificatesOnly(trust, true)
var error: CFError?
let evaluationSucceeded = SecTrustEvaluateWithError(trust, &error)
guard evaluationSucceeded else {
CertificateManager.shared.updateCertificate()
return
}
completionHandler(evaluationSucceeded)
} else {
CertificateManager.shared.updateCertificate()
}
Method for getting certificate is just a regular URLSession dataTask on domain that has certificate with URLSessionDelegate I get a URLAuthenticationChallenge from that object you can retrieve certificate and save it to keychain.
There is info from apple documentation how to store certificate
Best if you read thru it, but how I mentioned above I faced problems with that solution with updating existing one so there there are methods that I use for saving and retrieving certificate
add as data:
public func saveServerCertificate(_ certificate: SecCertificate, completion: #escaping () -> Void) throws {
let query: [String: Any] = [kSecClass as String: kSecClassCertificate,
kSecAttrLabel as String: attribute]
let status = SecItemCopyMatching(query as CFDictionary, nil)
switch status {
case errSecItemNotFound:
let certData = SecCertificateCopyData(certificate) as Data
let saveQuery: [String: Any] = [kSecClass as String: kSecClassCertificate,
kSecAttrLabel as String: attribute,
kSecValueData as String: certData]
let addStatus = SecItemAdd(saveQuery as CFDictionary, nil)
guard addStatus == errSecSuccess else { throw KeychainError.unhandledError(status: status) }
completion()
case errSecSuccess:
let certData = SecCertificateCopyData(certificate) as Data
let attributes: [String: Any] = [kSecValueData as String: certData]
let updateStatus = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)
guard updateStatus == errSecSuccess else { throw KeychainError.unhandledError(status: status) }
completion()
default:
throw KeychainError.unhandledError(status: status)
}
}
get and create certificate with data:
public func getServerCertificate(completion: #escaping (SecCertificate) -> Void) throws {
let query: [String: Any] = [kSecClass as String: kSecClassCertificate,
kSecAttrLabel as String: attribute,
kSecReturnAttributes as String: true,
kSecMatchLimit as String: kSecMatchLimitOne,
kSecReturnData as String: true]
var item: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &item)
switch status {
case errSecItemNotFound:
throw KeychainError.noCertificate
case errSecSuccess:
guard let existingItem = item as? [String : Any],
let certData = existingItem[kSecValueData as String] as? Data
else {
throw KeychainError.unexpectedCertificateData
}
if let certificate = SecCertificateCreateWithData(nil, certData as CFData) {
completion(certificate)
} else {
throw KeychainError.unexpectedCertificateData
}
default:
throw KeychainError.unhandledError(status: status)
}
}
Additional resource for you is OWASP. It is good to follow their recommendations for all of your platforms.
https://owasp.org/www-community/controls/Certificate_and_Public_Key_Pinning
As for your points:
The public key does not always change when the certificates change (leaf certs are usualy rotated yearly?). This is one of the advantages of pinning against the public key.
'Cons: Seems redundant as most root CAs are already included in the OS'
As you said here, pinning against the root cert is pointless, as the certificate is likely already trusted by the OS.
However, from the doc you linked to: 'A pinned CA public key must appear in a certificate chain either in an intermediate or root certificate. Pinned keys are always associated with a domain name, and the app will refuse to connect to that domain unless the pinning requirement is met.'
You would be pinning against the intermediate certificate here. For peace of mind you can do a test to print out the public key of your root certs + intermediate certs and prove they don't match.
'Too complicated, too risky, any implementation error may lock the app.' Apple provides an implementation in their tech note, and you can test all the codepaths yourself manually. Also, as owasp recommends, you can look into trust kit. I seems it has an implementation of this, and again here you have the option to just pin against the intermediate certificate (NOT ROOT) vs leaf node certs. Intermediate certificates typically last for 5-10 years.
I would hold off on this as personally I am not sure, I think this might just be an additional check you might want to use in addition to cert pinning. There also does not seem to be mention of this in the owasp document.
Personally, if I was writing a new app, I would go with option 1. Since android N, the OS provides a similar approach, which means you can also stay in sync with your android counterparts and they will also only have to update when you do and vice versa. https://developer.android.com/training/articles/security-config.html#CertificatePinning
I am not a security expert, but I am giving my thoughts based on my experience working for large coorperations that have their applications penetration tested. If you are really working on an app that requires high security, you really should have a penetration tester test your application. If you are in a big company, you may have a cyber team that can help.
No, you can’t do ssl certificate pining by using NSRequiresCertificateTransparency, it’s uses for client side TLS. If you want to implement pinning ,you can use server certificate pining to prevent MITM attacks.
Certificate pining
The difference is bellow
1) Client-side certificate transparency
For iOS apps, turning on client-side certificate transparency check is rather simple – you do nothing! Certificate transparency is enforced by default on devices running iOS 12.1.1 and higher. For devices running earlier versions of the iOS, you will need to set the NSRequiresCertificateTransparency option to YES in your Info.plist file.
2) Server-side certificate transparency
Certificate transparency has two aspects:
Pin the certificate: You can download the server’s certificate and bundle it into your app. At runtime, the app compares the server’s certificate to the one you’ve embedded.
Pin the public key: You can retrieve the certificate’s public key and include it in your code as a string. At runtime, the app compares the certificate’s public key to the one hard-coded in your code.
An SSL certificate with an SCT is definitely required. Make sure your server certificate is one with a valid SCT. Almost every CA these days issue certificates with SCTs

How to verify X.509 certificate was signed by another certificate?

The story: I call a request where I am getting a JWS token which I parse with the JOSESwift library. In the response I have a x5u parameter, which is a URL pointing to a certificate, which was used to sign the payload. I download the certificate and using JOSESwift I verify that. With some simplification I am doing the following:
let serverCert = // Getting the downloaded certificate as a SecCertificate object
var publicKey: SecKey!
publicKey = SecCertificateCopyKey(serverCert)
let rsaVerifier = RSAVerifier(algorithm: .ES256, publicKey: publicKey)
if let headerVerifier = Verifier(verifyingAlgorithm: .RS256, publicKey: rsaVerifier.publicKey) {
do {
_ = try jws.validate(using: headerVerifier)
print("Verifying success")
} catch {
print("Verifying failed with error:", error)
}
}
Question1: This is working nice so far. Now I want to verify that the downloaded certificate was indeed signed by a specific certificate I store locally in my application. And that's where I am stuck, that I am unable to find out how it could be done.
Question2: A requirement for the functionality is that the locally stored certificate can be self-signed, but also it can be some other certificate from a chain. So basically I should trust the locally stored certificate regardless it is self-signed or not. Is it doable, or when verifying we should always know about the root certificate ?
[rootCert] <--signed by-- [localCert] <--signed by-- [receivedCert] // We have only the local and receivedCert
My thoughts/ What I tried: My first thought was to use a SecTrust object, with setting the locally stored certificate as the trust anchor, and use the SecTrustEvaluateWithError(_:_:) to check if it's is a correct chain(what I conclude eventually will check also if the received certificate was signed by the one I store locally). I have seen working this in SSLPinning implementations, but somehow it is returning me false, even though I double checked that the certificates are correct. Here is what I am doing:
let serverCert = // Getting my server cert as a SecCertificate object
let localCert = // Getting my server cert as a SecCertificate object
let policy = SecPolicyCreateBasicX509()
var optionalTrust: SecTrust?
let status = SecTrustCreateWithCertificates([serverCert] as AnyObject,
policy,
&optionalTrust)
guard status == errSecSuccess else { return }
let trust = optionalTrust! // Safe to force unwrap now
SecTrustSetAnchorCertificates(trust, [localCert] as CFArray)
var error: CFError?
print("Veryfing result: ", SecTrustEvaluateWithError(trust, &error))
print(error)
Is it a good approach to verify that the received certification was signed by the local one ? If yes than what I am doing wrong that I am getting false ? If the approach is bad, what else can I try here ?
I found a similar question, but it is in Java(but maybe can give a hint what I am trying to accomplish): Verify x509 signature Java. However it also mentions the root certificate, so it again rises me the Question2 if it's doable without the root/self-signed certificate.
Update
As suggested in the comments, I am printing the error I am getting from SecTrustEvaluateWithError:
Error Domain=NSOSStatusErrorDomain Code=-25318 "“AuthInfoKey:18”
certificate is not trusted"
UserInfo={NSLocalizedDescription=“AuthInfoKey:18” certificate is not
trusted, NSUnderlyingError=0x280efb9c0 {Error
Domain=NSOSStatusErrorDomain Code=-25318 "Certificate 0
“AuthInfoKey:18” has errors: Unable to build chain to root (possible
missing intermediate);" UserInfo={NSLocalizedDescription=Certificate 0
“AuthInfoKey:18” has errors: Unable to build chain to root (possible
missing intermediate);}}}
The issues seems reasonable as I do not have access to the root certificate as mentioned above, I want to verify an intermediate certificate.
So again my question is: it possible to check the serverCert(an intermediate certificate) was signed by my local certificate(an other intermediate certificate) with SecTrustEvaluateWithError ? For me it seems it is working only if one has also the root certificate.

Does the flag kSecAttrAccessControl has an effect on the public key when generating the key pair using SecKeyGeneratePair?

I am creating a private/public key pair using the SecKeyGeneratePair method.
To be able to do that I create a parameter dictionary with kSecPrivateKeyAttrs and kSecPublicKeyAttrs.
In the kSecPrivateKeyAttrs and kSecPublicKeyAttrs (both a dictionary) I add kSecAttrAccessControl to set the protection level of the key (eg. kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly).
var publicKey, privateKey: SecKey?
let status = SecKeyGeneratePair(params as CFDictionary, &publicKey, &privateKey)
The generation of the keys succeeds but it seams that adding the kSecAttrAccessControl only affects the private key.
Is this documented somewhere?
I couldn't find any documentation but what you observe makes sense based on a few things:
Keychain APIs store secrets on Apple's platforms. The public key is not a secret. Only the private key is. So it makes sense that data protection would only apply to the private key.
The keychain on iOS is similar to Keychain Access on macOS. In Keychain Access, only private keys have access controls. See attached. That's my for my distribution private key.

Apple, iOS 13, CryptoKit, Secure Enclave - Enforce biometric authentication ahead of private key usage

I am working with Apple's new cryptokit library and am trying to get a basic use case to work.
Goal: I would like to create a private key in the secure enclave via the cryptokit, store the key's reference in the iOS device's key chain and ensure that the key can only be reinitialized in the secure enclave after the user has authenticated himself via some biometric authentication method.
Current state: So far, I am able to initialize a private key in the secure enclave via the following code:
var privateKeyReference = try CryptoKit.SecureEnclave.P256.KeyAgreement.PrivateKey.init();
Furthermore, I can store and retrieve the corresponding private key's reference from the key chain. After retrieving the reference, I can reinitialize the private key in the secure enclave with the following code:
var privateKeyReference = getPrivateKeyReferenceFromKeyChain();
var privateKey = try CryptoKit.SecureEnclave.P256.KeyAgreement.PrivateKey.init(
dataRepresentation: privateKeyReference
);
So far everything works as expected and all cryptographic operations with the private key succeed.
Now, as far as I understand the spare documentation by Apple, I should be able to modify the first initialization of the private key to something as follows.
let authContext = LAContext();
let accessCtrl = SecAccessControlCreateWithFlags(
kCFAllocatorDefault,
kSecAttrAccesibleWhenUnlockedThisDeviceOnly,
[.privateKeyUsage, .userPresence, .biometryCurrentSet],
nil
);
var privateKeyReference = try CryptoKit.SecureEnclave.P256.KeyAgreement.PrivateKey.init(
accessControl: accessCtrl!,
authenticationContext: authContext
);
Thereby, ensuring that the private key can only be reinitialized, when the user authenticates himself via some biometric authentication method. The initial initialization stil works without any errors.
Problem: However, adding the previous code, I do not get any biometric authentication prompt and can not use the private key at all after reinitialization. The following error is logged whenever I try to execute some cryptographic operation with the reinitialized key, here for example some signing:
Error Domain=CryptoTokenKit Code=-9 "setoken: unable to sign digest" UserInfo={NSLocalizedDescription=setoken: unable to sign digest})
As far as I could guess from here, I think that Code=-9 refers to the "authenticationNeeded" error.
Question: Can someone point me to some documentation or tutorial how to achieve what I am looking for or explain to me what I am missing?
Thanks!
Cross-Post: https://forums.developer.apple.com/message/387746
After a couple of days of patience I was able to obtain an answer from the Apple development support. They suggested the following method which only differs a little bit from my approach:
var error: Unmanaged<CFError>? = nil;
let accessCtrl = SecAccessControlCreateWithFlags(
nil,
kSecAttrAccesibleAfterFirstUnlockThisDeviceOnly,
[.privateKeyUsage, .biometryCurrentSet],
&error
);
var privateKeyReference = try CryptoKit.SecureEnclave.P256.KeyAgreement.PrivateKey.init(
accessControl: accessCtrl
);
Additionally, in the meantime iOS version 13.1.3 was released and, after upgrading my device, the above code started working. So either there is a subtle difference between mine and Apple's code or it is related to the update. Nevertheless, it is working now.

Temporarily store relevant public and private keys (after a successful key-exchange) in a WebAPI scenario

I have written an API to implement the Diffie Hellman key exchange and now wanted to store my "server" private/public keys in a secure and expirable way so that I can access them on the subsequent api calls.
The idea is to have the client initiate the exchange of the keys, then have the client send me an encrypted message based on his privatekey that I can decrypt on the server because I have my related privateKey.
My problem is where to store securely the list of various public/private server keys in a way that I could reuse it when referenced at later stage.
My initial idea would be to have some sort of static list that contains
KeyID (Guid - autogenerated)
Expiration Date (DateTime - now + 20 seconds)
ServerPublicKey (byte[] - resulted from successful key exchange)
ServerPrivateKey (byte[] - resulted from successful key exchange)
On completion of the KeyExchange I could return a KeyID to the client caller and then on subsequent API calls, he should pass an encrypted message using his clientPrivate key. By also passing me the KeyID, I could quickly identify what is the related serverPrivateKey and Decrypt the message.
Is this the right and most secure approach?

Resources