iOS NSURLErrorDomain Code=-1005与ClientCertificate验证挑战



我试图在iOS与NSURLSession实现https客户端证书认证。下面是我正在做的:

-(void) httpPostWithCustomDelegate :(NSDictionary *) params
{
    NSString *ppyRequestURL = [NSString stringWithFormat:@"%@/fetchcountryCities", PPBaseURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:ppyRequestURL]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
       Log(@"ASDAD");
    }];
    [postDataTask resume]; 
}

我在挑战处理程序中提供客户端证书,像这样:

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler{
    if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){
        NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
    }
    else    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodClientCertificate]) {
               NSURLCredential *credential = [self provideClientCertificate];
                completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
            }
}

这是我如何加载我的客户端证书,

- (SecIdentityRef)findClientCertificate {
    SecIdentityRef clientCertificate = NULL;
    if (clientCertificate) {
        CFRelease(clientCertificate);
        clientCertificate = NULL;
    }
    NSString *pkcs12Path = [[NSBundle mainBundle] pathForResource:@"johndoe" ofType:@"p12"];
    NSData *pkcs12Data = [[NSData alloc] initWithContentsOfFile:pkcs12Path];
    CFDataRef inPKCS12Data = (__bridge CFDataRef)pkcs12Data;
    CFStringRef password = CFSTR("password");
    const void *keys[] = { kSecImportExportPassphrase };
    const void *values[] = { password };
    CFDictionaryRef optionsDictionary = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
    CFArrayRef items = NULL;
    OSStatus err = SecPKCS12Import(inPKCS12Data, optionsDictionary, &items);
    CFRelease(optionsDictionary);
    CFRelease(password);
    if (err == errSecSuccess && CFArrayGetCount(items) > 0) {
        CFDictionaryRef pkcsDict = CFArrayGetValueAtIndex(items, 0);
        SecTrustRef trust = (SecTrustRef)CFDictionaryGetValue(pkcsDict, kSecImportItemTrust);
        if (trust != NULL) {
            clientCertificate = (SecIdentityRef)CFDictionaryGetValue(pkcsDict, kSecImportItemIdentity);
            CFRetain(clientCertificate);
        }
    }
    if (items) {
        CFRelease(items);
    }
    return clientCertificate;
}
- (NSURLCredential *)provideClientCertificate {
    SecIdentityRef identity = [self findClientCertificate];
    if (!identity) {
        return nil;
    }
    SecCertificateRef certificate = NULL;
    SecIdentityCopyCertificate (identity, &certificate);
    const void *certs[] = {certificate};
    CFArrayRef certArray = CFArrayCreate(kCFAllocatorDefault, certs, 1, NULL);
    NSURLCredential *credential = [NSURLCredential credentialWithIdentity:identity certificates:(__bridge NSArray *)certArray persistence:NSURLCredentialPersistencePermanent];
    CFRelease(certArray);
    return credential;
}

现在当API被调用时,我得到这个错误:

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."UserInfo={NSUnderlyingError=0x7f8428df4d40{错误域=kCFErrorDomainCFNetwork Code=-1005 "(null)"用户信息= {_kCFStreamErrorCodeKey = 4, _kCFStreamErrorDomainKey = 4}}

我在模拟器和设备上得到相同的错误。我完全被困住了。我不知道哪里出了问题。

* * * * * * * * * *更新我跟查尔斯的代理人确认了更多细节。令我惊讶的是,当我将客户端证书添加到查尔斯代理时,我得到了服务器的响应,所以我在plist中缺少一些设置或加载p12的问题?

从plist设置,

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSExceptionDomains</key>
        <dict>
            <key>test.mydomain.com</key>
            <dict>
                <key>NSExceptionAllowsInsecureHTTPLoads</key>
                <true/>
                <key>NSExceptionMinimumTLSVersion</key>
                <string>TLSv1.2</string>
                <key>NSExceptionRequiresForwardSecrecy</key>
                <true/>
                <key>NSIncludesSubdomains</key>
                <true/>
                <key>NSRequiresCertificateTransparency</key>
                <false/>
                <key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
                <false/>
                <key>NSThirdPartyExceptionMinimumTLSVersion</key>
                <string>TLSv1.2</string>
                <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
                <true/>
            </dict>
        </dict>
    </dict>

乍一看,我发现了三个问题:

  • 你正在发送一个POST请求而没有提供请求体。这可能会导致请求立即失败,甚至没有发送到服务器。

  • 你的服务器信任处理,如所写,有效地删除了任何保护,否则你会通过告诉操作系统盲目信任它(我认为)从TLS获得。

    你应该A.告诉NSURLSession在服务器信任情况下执行默认处理或B.自己检查证书并然后告诉它使用证书

  • 您的身份仅包括客户端证书,而不包括服务器信任它所需的任何中间证书。

    你可能应该结合这两种方法,使用你找到的第一个身份,但采取你在身份文件中找到的每个证书,并将它们全部添加到证书数组中(可能与客户端证书本身一起,但我模糊地记得你不应该在那里添加它;两种方法都试一试,看看哪一种会失败)。

请注意,如果您知道您的用户身份都不会有证书链,那么第三个身份可能无关紧要。

相关内容

  • 没有找到相关文章

最新更新