SecTrustEvaluate未按预期失败?

时间:2014-04-25 03:23:35

标签: objective-c macos cocoa ssl

我已经获得了一些代码,可以在example.com上执行HTTPS抓取。

问题是,我正在插入下面的假CA(@"ca-rsa-cert.der"),因此SecTrustEvaluate会失败。 (或者我很幸运并生成了与真正的example.com签署证书相同的公钥/私钥对。)

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:
(NSURLAuthenticationChallenge *)challenge
{
    do
    {
        SecTrustRef serverTrust = [[challenge protectionSpace] serverTrust];
        if(nil == serverTrust)
            break; /* failed */

        NSData* caCert = [NSData dataWithContentsOfFile:@"ca-rsa-cert.der"];
        if(nil == caCert)
            break; /* failed */

        SecCertificateRef caRef = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)caCert);
        if(nil == caRef)
            break; /* failed */

        NSArray* caArray = [NSArray arrayWithObject:(__bridge id)(caRef)];
        if(nil == caArray)
            break; /* failed */

        OSStatus status = SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)caArray);
        if(!(errSecSuccess == status))
            break; /* failed */

        status = SecTrustEvaluate(serverTrust, NULL);
        if(!(errSecSuccess == status))
            break; /* failed */

        // The only good exit point
        return [[challenge sender] useCredential: [NSURLCredential credentialForTrust: serverTrust]
                      forAuthenticationChallenge: challenge];

    } while(0);

    // Bad dog
    return [[challenge sender] cancelAuthenticationChallenge: challenge];
}

基本上,这些步骤与iOS HTTPS requests 101中概述的步骤相同(问题是关于加载CA证书)。我还审核了Apple TN2232 HTTPS Server Trust EvaluationOverriding TLS Chain Validation Correctly,但我没有看到我的错误。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我应该更加关注TN2232 HTTPS Server Trust EvaluationQA1360 Describing the kSecTrustResultUnspecified error中的详细信息。

status = SecTrustEvaluate(serverTrust, NULL);
if(!(errSecSuccess == status))
    break; /* failed */

我没有正确使用API​​。 OSStatus仅在SecTrustEvaluate的调用成功(或失败)时提供。要获得评估结果:

SecTrustResultType result
status = SecTrustEvaluate(serverTrust, &result);
if(!(errSecSuccess == status))
    break; /* failed */

if(result != kSecTrustResultUnspecified && result != kSecTrustResultProceed)
    break; /* failed */

...