iOS 使用 Swift 和 NSURLSession 固定证书

iOS certificate pinning with Swift and NSURLSession

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

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

Swift 3+ 更新:

只需为 NSURLSessionDelegate 定义一个委托 class 并实现 didReceiveChallenge 函数(此代码改编自 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 {
                let isServerTrusted = SecTrustEvaluateWithError(serverTrust, nil)

                if(isServerTrusted) {
                    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)
    }

}

(你可以找一个Gist for Swift 2 here - from the initial answer)

然后使用 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")
}

@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]

自制软件安装命令:

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

希望对您有所帮助。

这是 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/ 我构建了一个固定 public 密钥而不是整个证书的版本(如果你定期更新你的证书会更方便)。

更新:删除了强制解包并替换了 SecTrustEvaluate。

import Foundation
import CommonCrypto

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) {

    guard let serverTrust = challenge.protectionSpace.serverTrust else {
        completionHandler(.cancelAuthenticationChallenge, nil);
        return;
    }

    // Set SSL policies for domain name check
    let policies = NSMutableArray();
    policies.add(SecPolicyCreateSSL(true, (challenge.protectionSpace.host as CFString)));
    SecTrustSetPolicies(serverTrust, policies);

    var isServerTrusted = SecTrustEvaluateWithError(serverTrust, nil);

    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);

            guard trust != nil, let pubKey = SecTrustCopyPublicKey(trust!) else {
                completionHandler(.cancelAuthenticationChallenge, nil);
                return;
            }

            var error:Unmanaged<CFError>?
            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([=10=], CC_LONG(data.count), &hash)
    }
    return Data(bytes: hash).base64EncodedString();
}

}

将您网站的证书(作为 .cer 文件)保存在主包中。然后使用 this 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))
}

请注意,SecTrustEvaluate 已弃用,应替换为 SecTrustEvaluateWithError

所以这样:

var secresult = SecTrustResultType.invalid
let status = SecTrustEvaluate(serverTrust, &secresult)

if errSecSuccess == status {
   // Proceed with evaluation
   switch result {
   case .unspecified, .proceed:    return true
   default:                        return false
   }
}

我写 // Proceed with evaluation 部分的原因是因为您应该验证 secresult 以及这可能意味着证书实际上是无效的。您可以选择覆盖它并将任何提出的问题添加为例外,最好是在提示用户做出决定之后。

应该是这样的:

if SecTrustEvaluateWithError(server, nil) {
   // Certificate is valid, proceed.
}

第二个参数会捕获任何错误,但如果你对细节不感兴趣,你可以直接传递 nil.

你可以试试这个。

import Foundation
import Security

class NSURLSessionPinningDelegate: NSObject, URLSessionDelegate {

      let certFileName = "name-of-cert-file"
      let certFileType = "cer"

      func urlSession(_ session: URLSession, 
                  didReceive challenge: URLAuthenticationChallenge, 
                  completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) {

    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 certificateOne = NSData(bytes: data, length: size)
                    let filePath = Bundle.main.path(forResource: self.certFileName, 
                                                         ofType: self.certFileType)

                    if let file = filePath {
                        if let certificateTwo = NSData(contentsOfFile: file) {
                            if certificateOne.isEqual(to: certificateTwo as Data) {
                                completionHandler(URLSession.AuthChallengeDisposition.useCredential, 
                                                  URLCredential(trust:serverTrust))
                                return
                            }
                        }
                    }
                }
            }
        }
    }

    // Pinning failed
    completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
}
}

来源:https://www.steveclarkapps.com/using-certificate-pinning-xcode/