【问题标题】:iOS: Having problems with self-signed certificate. SSL Handshake Error (-9824)iOS:自签名证书有问题。 SSL 握手错误 (-9824)
【发布时间】:2016-02-06 17:09:22
【问题描述】:

我有一个应用程序,我需要执行某种两步验证,长话短说,我从服务器获取每用户 base64 编码的 pem 格式证书,并在每个请求中使用它们。

首先我生成一个密钥对,创建一个 CSR,给他们 CSR,他们给我证书,这是我必须使用它但失败的地方。对于每个单独的请求,我都会在控制台中收到以下错误:

CFNetwork SSLHandshake 失败 (-4)

CFNetwork SSLHandshake 失败 (-9824)

CFNetwork SSLHandshake 失败 (-9824)

NSURLConnection/CFURLConnection HTTP 加载失败(kCFStreamErrorDomainSSL,-9824)

我的方法如下:

-从他们发送给我的 PEM 格式签名证书中获取 DER 编码数据

-制作一个我添加到钥匙串中的 SecCertificateRef

-通过标签查询钥匙串中的SecIdentityRef

-然后我会做一些大部分不必要的事情,例如从身份中获取 SecCertificateRef 和私钥,主要是为了确定发生了什么

-我还插入了一个我从服务器获得的 CA 证书,并从钥匙串中获取对它的引用(不确定我是否需要将它用于凭证,但我尝试使用或不使用它 - 结果是相同的)

-然后我使用身份和我的证书初始化凭据,并在我获得 NSURLAuthenticationMethodClientCertificate 身份验证方法时使用它(我不进行检查,但除了服务器信任之外,这就是我得到的全部)。

所以到目前为止,没有什么是 NULL,一切都被初始化并且看起来不错,但是请求没有成功。当我尝试在所有请求上使用服务器信任凭证时,我通过并且没有收到错误,但我的服务器给了我一个安全错误,因为它应该。一旦我将自定义凭据用于任何挑战,我就会收到上述错误。

注意:我知道代码很乱,我不应该在每个请求上都插入证书,但它仍处于早期工作中,这不是问题,因为 refs 已正确实例化 p>

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
    SSLConnectionWrapper *wrapper = [self wrapperForConnection:connection];


    NSString *certStringBase64 = [[NSUserDefaults standardUserDefaults] SSLCertificateForUserWithID:wrapper.userID];
    NSData *certData = [[NSData alloc] initWithBase64EncodedString:certStringBase64 options:0];
    NSString *certString = [[NSString alloc] initWithData:certData encoding:NSUTF8StringEncoding];

    certString = [certString stringByReplacingOccurrencesOfString:@"-----BEGIN CERTIFICATE-----" withString:@""];
    certString = [certString stringByReplacingOccurrencesOfString:@"-----END CERTIFICATE-----" withString:@""];
    certString = [[certString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@""];
    //at this point certString contains the DER encoded certificate data

    SecCertificateRef cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)([[NSData alloc] initWithBase64EncodedString:certString options:kNilOptions]));

    OSStatus err = SecItemAdd((__bridge CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
                                                          (__bridge id) kSecClassCertificate, kSecClass,
                                                          cert, kSecValueRef,
                                                          kCFBooleanTrue, kSecReturnPersistentRef,
                                                          [NSString stringWithFormat:@"CertLabel_UserID_%@", wrapper.userID], kSecAttrLabel,
                                                          nil], NULL);

    const void *keys[] =   { kSecClass, kSecReturnRef,  kSecAttrLabel };

    const void *values[] = { kSecClassIdentity, kCFBooleanTrue, (__bridge const void *)([NSString stringWithFormat:@"CertLabel_UserID_%@", wrapper.userID]) };

    CFDictionaryRef queryForIdentityDict = CFDictionaryCreate(NULL, keys, values,
                                                              3, NULL, NULL);

    SecIdentityRef identityKeychainRef = NULL;
    OSStatus s = SecItemCopyMatching(queryForIdentityDict, (CFTypeRef *)&identityKeychainRef);

    SecCertificateRef certKeychainRef = NULL;
    OSStatus s2 = SecIdentityCopyCertificate(identityKeychainRef, &certKeychainRef);

    SecKeyRef privateKey;
    SecIdentityCopyPrivateKey(identityKeychainRef, &privateKey);

    NSString *stringForCACert = [self stringForCACert];

    SecCertificateRef caCert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)([[NSData alloc] initWithBase64EncodedString:stringForCACert options:kNilOptions]));
    OSStatus s3 = SecItemAdd((__bridge CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
                                                          (__bridge id) kSecClassCertificate, kSecClass,
                                                          caCert, kSecValueRef,
                                                           @"CACert", kSecAttrLabel,
                                                          nil], NULL);

    const void *keys1[] =   { kSecClass, kSecReturnRef,  kSecAttrLabel };

    const void *values1[] = { kSecClassCertificate, kCFBooleanTrue, @"CACert" };

    CFDictionaryRef queryForCACert = CFDictionaryCreate(NULL, keys1, values1,
                                                              3, NULL, NULL);

    SecCertificateRef caCertKeychainRef = NULL;
    OSStatus s4 = SecItemCopyMatching(queryForCACert, (CFTypeRef *)&caCertKeychainRef);

    NSURLCredential *credential = [[NSURLCredential alloc] initWithIdentity:identityKeychainRef certificates:@[ (__bridge id)certKeychainRef, (__bridge id) caCertKeychainRef] persistence:NSURLCredentialPersistencePermanent];

    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {

        [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
    }else{
        [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
    }

}

【问题讨论】:

    标签: ios ssl certificate self-signed


    【解决方案1】:

    这是服务器面临的身份验证挑战。您可以通过以下代码绕过(使用 NSURLCONnection)

    + (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host {
        return YES;
    }
    

    注意:如果您在应用商店上传应用,请勿使用上述方法。

    iOS 9 以上无法使用,请编辑 plist 如下

    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>
    

    【讨论】:

    • 我已经启用了 AllowsArbitraryLoads。我也尝试了该类别,但没有成功。它被调用,但并不能阻止握手错误的发生。它也与 iOS 9 的 TLS 1.2 政策无关。
    猜你喜欢
    • 2018-02-18
    • 1970-01-01
    • 2015-04-06
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-06
    相关资源
    最近更新 更多