Mobile App Certificate Pinning

Mobile App Certificate Pinning

Certificate pinning in mobile apps prevents man-in-the-middle attacks but complicates certificate updates. Implement pinning carefully with backup pins and update mechanisms.

iOS certificate pinning example:

// Swift implementation
func urlSession(_ session: URLSession, 
                didReceive challenge: URLAuthenticationChallenge, 
                completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    
    guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
          let serverTrust = challenge.protectionSpace.serverTrust,
          let certificate = SecTrustGetCertificateAtIndex(serverTrust, 0) else {
        completionHandler(.cancelAuthenticationChallenge, nil)
        return
    }
    
    // Pin certificate
    let remoteCertData = SecCertificateCopyData(certificate) as Data
    let localCertPath = Bundle.main.path(forResource: "pinned", ofType: "cer")!
    let localCertData = NSData(contentsOfFile: localCertPath)!
    
    if remoteCertData == localCertData as Data {
        completionHandler(.useCredential, URLCredential(trust: serverTrust))
    } else {
        completionHandler(.cancelAuthenticationChallenge, nil)
    }
}