ios - 加载自己的 ca 证书时,Swift 2.0 中 SecTrustEvaluate 调用上的 EXC_BAD_ACCESS

标签 ios swift https certificate tls1.2

我正在加载自己的根证书作为我的应用程序的锚定证书,但我总是在 SecTrustEvaluate(trust!, &trustResult) 上获得 EXC_BAD_ACCESS线。 谁能看出我做错了什么?

我看过Always EXC_BAD_ACCESS on SecTrustEvaluate ,但它并没有解决我的问题,因为我认为我的问题可能是特定于 Swift 的问题。

public func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
    if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
        // First load our extra root-CA to be trusted from the app bundle.
        let trust = challenge.protectionSpace.serverTrust

        let rootCa = "SSLcomDVCA_2_DER"
        if let rootCaPath = NSBundle.mainBundle().pathForResource(rootCa, ofType: "cer") {
            if let rootCaData = NSData(contentsOfFile: rootCaPath) {

                let cfData = CFDataCreate(kCFAllocatorDefault, UnsafePointer<UInt8>(rootCaData.bytes), rootCaData.length)

                let rootCert = SecCertificateCreateWithData(nil, cfData)

                let certs: [CFTypeRef] = [rootCert!]
                let certPointer = UnsafeMutablePointer<UnsafePointer<Void>>(certs)
                let certArrayRef = CFArrayCreate(nil, certPointer
                    , certs.count, nil)
                SecTrustSetAnchorCertificates(trust!, certArrayRef)
                SecTrustSetAnchorCertificatesOnly(trust!, false) // also allow regular CAs.
            }
        }

        var trustResult: SecTrustResultType = 0
        SecTrustEvaluate(trust!, &trustResult)

        if (Int(trustResult) == kSecTrustResultUnspecified ||
            Int(trustResult) == kSecTrustResultProceed) {
                // Trust certificate.
                let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)
                challenge.sender!.useCredential(credential, forAuthenticationChallenge: challenge)
        } else {
            NSLog("Invalid server certificate.")
            challenge.sender!.cancelAuthenticationChallenge(challenge)
        }
    } else {
        NSLog("Got unexpected authentication method \(challenge.protectionSpace.authenticationMethod)");
        challenge.sender!.cancelAuthenticationChallenge(challenge)
    }
}

最佳答案

使用Certificate and Public Key Pinning作为指导,我想出了这个作为 Swift 中的证书固定实现。它与您的方法不同,但在我的测试中有效。

可以使用 Firefox 下载 .der 格式的证书,方法是访问该网站,单击地址栏中的挂锁 > 更多信息 > 查看证书 > 详细信息选项卡 > 导出(从格式列表中选择 DER)。

func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {

    if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {

        guard let serverTrust = challenge.protectionSpace.serverTrust else {
            print("serverTrust is nil")
            return
        }

        guard errSecSuccess == SecTrustEvaluate(serverTrust, nil) else {
            print("SecTrustEvaluate is not errSecSuccess")
            return
        }

        guard let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) else {
            print("serverCertificate is nil")
            return
        }

        let serverCertificateData = SecCertificateCopyData(serverCertificate)
        let data = CFDataGetBytePtr(serverCertificateData)
        let size = CFDataGetLength(serverCertificateData)
        let dataPtr = unsafeBitCast(data, UnsafeMutablePointer<Void>.self)

        let cert1 = NSData(bytes: dataPtr, length: size)

        guard let file = NSBundle.mainBundle().pathForResource("facebook.com", ofType: "der"), cert2 = NSData(contentsOfFile: file) else {
            print("Failed to open .der file")
            return
        }

        guard cert1 == cert2 else {
            print("Certificate pinning failed, certs unequal")
            return
        }

        // Good exit point. 
        print("PASSED Cert Pinning")
        return challenge.sender!.useCredential(NSURLCredential(forTrust: serverTrust), forAuthenticationChallenge: challenge)
    }

    print("FAILED Cert Pinning, authenticationMethod not ServerTrust")
}

关于ios - 加载自己的 ca 证书时,Swift 2.0 中 SecTrustEvaluate 调用上的 EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35699915/

相关文章:

java - Android 与 iOS 中 View 的位置?

ios - 编辑时tableView中没有didSelectRowAtIndexPath()

amazon-web-services - aws ubuntu 16.04 服务器上的 HTTPS

typescript - 在 Firebase 中获取状态为 : 405. 的方法不允许使用 POST 的 URL

ios - 如何从 URLSession 获取数组

ios - 如何指定多种类型供委托(delegate)引用?

iphone - 构建时我不断收到弧形错误

ios - Swift:点击标签栏时关闭模态呈现的 View Controller

ios - 在 xcode 12 中创建通用框架时出现 Lipo 错误

java - httpclientandroidlib 上的 TLS 1.1 @ TLS 1.2