How to answer
Pinning means the app trusts only specific keys for its own servers, on top of normal certificate validation, so a mis-issued certificate or a user-installed root CA can't be used to intercept its traffic. The simplest option is declarative: NSPinnedDomains in Info.plist (covered in the certificate pinning question). When you need logic in code, for example pins fetched with the app config or reporting failures, you implement the session delegate's async urlSession(_:didReceive:) challenge handler: run the system's evaluation first (SecTrustEvaluateWithError), then hash the SubjectPublicKeyInfo (SPKI) of the certificates in the chain and accept only if one matches a pinned hash. Pin public keys rather than whole certificates so routine renewals with the same key don't break the app, and always ship a backup pin.
Key points
- Handle
NSURLAuthenticationMethodServerTrustonly;.performDefaultHandlingfor everything else - Default validation first, then the pin check; never skip
SecTrustEvaluateWithError SecTrustCopyCertificateChain→SecCertificateCopyKey→SecKeyCopyExternalRepresentationgives the raw key, not the SPKI; prepend the algorithm's ASN.1 header before hashing so the hash matches whatopenssland other tools produce- Pin the leaf key, an intermediate's key (more resilient), or both; include at least one backup key
- The delegate must be the session's delegate (or a per-task delegate), so
URLSession.sharedcan't pin - Network framework:
sec_protocol_options_set_verify_blockon the TLS options
If they dig deeper
Rotation strategy (backup keys generated in advance, remote kill switch, app updates in the field for months). Certificate vs public-key vs CA pinning trade-offs. Pinning and debugging proxies (disable in debug builds). Certificate Transparency, which ATS already enforces for many CAs. Why pinning alone doesn't stop a jailbroken device from bypassing it. Libraries such as TrustKit wrap the same logic.
Common pitfalls
Hashing SecKeyCopyExternalRepresentation output directly and never matching server-side pins. Only one pin, so a key rotation bricks networking. Returning .useCredential without evaluating the trust (accepting anything). Pinning third-party domains you don't control. Forgetting WebSockets and other sessions that also need the delegate.
How to use it
import CryptoKit
import Foundation
// nonisolated: trust evaluation can block, so keep it off the main actor
nonisolated final class PinningDelegate: NSObject, URLSessionDelegate, Sendable {
let pinnedSPKIHashes: Set<String> // base64 SHA-256; include a backup key
init(pinnedSPKIHashes: Set<String>) { self.pinnedSPKIHashes = pinnedSPKIHashes }
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge)
async -> (URLSession.AuthChallengeDisposition, URLCredential?) {
guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
let trust = challenge.protectionSpace.serverTrust else {
return (.performDefaultHandling, nil)
}
guard SecTrustEvaluateWithError(trust, nil), // normal chain + hostname
let chain = SecTrustCopyCertificateChain(trust) as? [SecCertificate],
chain.contains(where: { spkiHash(of: $0).map(pinnedSPKIHashes.contains) ?? false })
else {
return (.cancelAuthenticationChallenge, nil)
}
return (.useCredential, URLCredential(trust: trust))
}
}import CryptoKit
/// ASN.1 SPKI prefixes for the key types you pin (add others as needed).
nonisolated let rsa2048SPKIHeader: [UInt8] = [0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48,
0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00]
nonisolated let p256SPKIHeader: [UInt8] = [0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d,
0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00]
/// SHA-256 of the DER SubjectPublicKeyInfo, the value `openssl ... -pubkey | sha256` gives.
nonisolated func spkiHash(of certificate: SecCertificate) -> String? {
guard let key = SecCertificateCopyKey(certificate),
let raw = SecKeyCopyExternalRepresentation(key, nil) as Data?,
let attributes = SecKeyCopyAttributes(key) as? [CFString: Any], // Security returns a CFDictionary
let type = attributes[kSecAttrKeyType] as? String,
let bits = attributes[kSecAttrKeySizeInBits] as? Int else { return nil }
let header: [UInt8]
if type == kSecAttrKeyTypeRSA as String, bits == 2048 {
header = rsa2048SPKIHeader
} else if type == kSecAttrKeyTypeECSECPrimeRandom as String, bits == 256 {
header = p256SPKIHeader
} else {
return nil
}
return Data(SHA256.hash(data: Data(header) + raw)).base64EncodedString()
}
// let session = URLSession(configuration: .default,
// delegate: PinningDelegate(pinnedSPKIHashes: [primaryPin, backupPin]),
// delegateQueue: nil)Best practices
- Prefer
NSPinnedDomainswhen static pins are enough; use code only when you need logic - Evaluate the trust normally, then compare SPKI hashes from the chain
- Ship backup pins and a plan for rotation
- Disable pinning only in debug builds, never through a runtime flag an attacker can flip
- Apply the delegate to every session that talks to pinned hosts
Related concepts
- Certificate pinning (
NSPinnedDomains), app transport security, URLSession delegates, proxy configuration, CryptoKit, OAuth 2.0