使用Swift和NSURLSession固定的​​iOS证书

如何在Swift中将证书固定添加到NSURLSession?

OWASP网站仅包含Objective-C和NSURLConnection的示例。

Swift 3更新:

只需为NSURLSessionDelegate定义一个委托类并实现NSURLSessionDelegate函数( 此代码改编自objective-c OWASP示例 ):

 class NSURLSessionPinningDelegate: NSObject, URLSessionDelegate { func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) { // Adapted from OWASP https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#iOS if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) { if let serverTrust = challenge.protectionSpace.serverTrust { var secresult = SecTrustResultType.invalid let status = SecTrustEvaluate(serverTrust, &secresult) if(errSecSuccess == status) { if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) { let serverCertificateData = SecCertificateCopyData(serverCertificate) let data = CFDataGetBytePtr(serverCertificateData); let size = CFDataGetLength(serverCertificateData); let cert1 = NSData(bytes: data, length: size) let file_der = Bundle.main.path(forResource: "certificateFile", ofType: "der") if let file = file_der { if let cert2 = NSData(contentsOfFile: file) { if cert1.isEqual(to: cert2 as Data) { completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:serverTrust)) return } } } } } } } // Pinning failed completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil) } } 

(你可以在这里找到Swift 2的要点 – 从最初的答案 )

然后使用openssl为您的网站创建.der文件

 openssl s_client -connect my-https-website.com:443 -showcerts < /dev/null | openssl x509 -outform DER > my-https-website.der 

并将其添加到xcode项目中。 仔细检查它是否存在于“ Copy Bundle Resources列表中的“ Build phases选项卡中。 否则将其拖放到此列表中。

最后在您的代码中使用它来发出URL请求:

 if let url = NSURL(string: "https://my-https-website.com") { let session = URLSession( configuration: URLSessionConfiguration.ephemeral, delegate: NSURLSessionPinningDelegate(), delegateQueue: nil) let task = session.dataTask(with: url as URL, completionHandler: { (data, response, error) -> Void in if error != nil { print("error: \(error!.localizedDescription): \(error!)") } else if data != nil { if let str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) { print("Received data:\n\(str)") } else { print("Unable to convert data to text") } } }) task.resume() } else { print("Unable to create NSURL") } 

这是Swift 3的更新版本

 import Foundation import Security class NSURLSessionPinningDelegate: NSObject, URLSessionDelegate { func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) { // Adapted from OWASP https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#iOS if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) { if let serverTrust = challenge.protectionSpace.serverTrust { var secresult = SecTrustResultType.invalid let status = SecTrustEvaluate(serverTrust, &secresult) if(errSecSuccess == status) { if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) { let serverCertificateData = SecCertificateCopyData(serverCertificate) let data = CFDataGetBytePtr(serverCertificateData); let size = CFDataGetLength(serverCertificateData); let cert1 = NSData(bytes: data, length: size) let file_der = Bundle.main.path(forResource: "name-of-cert-file", ofType: "cer") if let file = file_der { if let cert2 = NSData(contentsOfFile: file) { if cert1.isEqual(to: cert2 as Data) { completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:serverTrust)) return } } } } } } } // Pinning failed completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil) } } 

感谢此站点中的示例: https : //www.bugsee.com/blog/ssl-certificate-pinning-in-mobile-applications/我构建了一个固定公钥而不是整个证书的版本(更方便如果您定期续订证书)。

 import Foundation class SessionDelegate : NSObject, URLSessionDelegate { private static let rsa2048Asn1Header:[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 ]; private static let google_com_pubkey = ["4xVxzbEegwDBoyoGoJlKcwGM7hyquoFg4l+9um5oPOI="]; private static let google_com_full = ["KjLxfxajzmBH0fTH1/oujb6R5fqBiLxl0zrl2xyFT2E="]; func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { let serverTrust = challenge.protectionSpace.serverTrust; // Set SSL policies for domain name check let policies = NSMutableArray(); policies.add(SecPolicyCreateSSL(true, (challenge.protectionSpace.host as CFString))); SecTrustSetPolicies(serverTrust!, policies); // Evaluate server certificate var result = SecTrustResultType.invalid; SecTrustEvaluate(serverTrust!, &result) var isServerTrusted = result == .unspecified || result == .proceed ? true : false; if(isServerTrusted && challenge.protectionSpace.host == "www.google.com") { let certificate = SecTrustGetCertificateAtIndex(serverTrust!, 0); //Compare public key if #available(iOS 10.0, *) { let policy = SecPolicyCreateBasicX509(); let cfCertificates = [certificate] as CFArray; var trust: SecTrust? SecTrustCreateWithCertificates(cfCertificates, policy, &trust); let pubKey = SecTrustCopyPublicKey(trust!); var error:Unmanaged? if let pubKeyData = SecKeyCopyExternalRepresentation(pubKey!, &error) { var keyWithHeader = Data(bytes: SessionDelegate.rsa2048Asn1Header); keyWithHeader.append(pubKeyData as Data); let sha256Key = sha256(keyWithHeader); if(!SessionDelegate.google_com_pubkey.contains(sha256Key)) { isServerTrusted = false; } } else { isServerTrusted = false; } } else { //Compare full certificate let remoteCertificateData = SecCertificateCopyData(certificate!) as Data; let sha256Data = sha256(remoteCertificateData); if(!SessionDelegate.google_com_full.contains(sha256Data)) { isServerTrusted = false; } } } if(isServerTrusted) { let credential = URLCredential(trust: serverTrust!); completionHandler(.useCredential, credential); } else { completionHandler(.cancelAuthenticationChallenge, nil); } } func sha256(_ data : Data) -> String { var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) data.withUnsafeBytes { _ = CC_SHA256($0, CC_LONG(data.count), &hash) } return Data(bytes: hash).base64EncodedString(); } } 

将主页中的网站证书(如.cer文件)保存。 然后使用此 URLSessionDelegate方法:

 func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, let serverTrust = challenge.protectionSpace.serverTrust, SecTrustEvaluate(serverTrust, nil) == errSecSuccess, let serverCert = SecTrustGetCertificateAtIndex(serverTrust, 0) else { reject(with: completionHandler) return } let serverCertData = SecCertificateCopyData(serverCert) as Data guard let localCertPath = Bundle.main.path(forResource: "shop.rewe.de", ofType: "cer"), let localCertData = NSData(contentsOfFile: localCertPath) as Data?, localCertData == serverCertData else { reject(with: completionHandler) return } accept(with: serverTrust, completionHandler) } 

 func reject(with completionHandler: ((URLSession.AuthChallengeDisposition, URLCredential?) -> Void)) { completionHandler(.cancelAuthenticationChallenge, nil) } func accept(with serverTrust: SecTrust, _ completionHandler: ((URLSession.AuthChallengeDisposition, URLCredential?) -> Void)) { completionHandler(.useCredential, URLCredential(trust: serverTrust)) } 

@ lifeisfoo的答案中的openssl命令会在OS X中为某些使用较新密码(如ECDSA)的SSL证书出错。

如果在@lifeisfoo的答案中运行openssl命令时出现以下错误:

  write:errno=54 unable to load certificate 1769:error:0906D06C:PEM routines:PEM_read_bio:no start line:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL09 8-59.60.1/src/crypto/pem/pem_lib.c:648:Expecting: TRUSTED CERTIFICATE 

您的网站SSL证书可能使用的是OS X默认的openssl版本(v0.9.X,不支持ECDSA等)中不支持的算法。

这是修复:

要获得正确的.der文件,您必须先刷新brew install openssl ,然后用@lifeisfoo的答案替换openssl命令:

/usr/local/Cellar/openssl/1.0.2h_1/bin/openssl [rest of the above command]

Homebrew安装命令:

 /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" 

希望有所帮助。