如何在iOS中验证(和要求)自签名证书

9
我希望能够使用自签名证书在iOS中创建SSL连接到我的服务器,以此方式就不必担心更为复杂的中间人攻击,其中某人可以访问高级“受信任”证书机构。我正在尝试使用我认为是苹果标准方式来解决这个问题,但遇到了一些问题。
通过这里找到的程序生成证书。
# Create root CA & private key
openssl req -newkey rsa:4096 -sha512 -days 9999 -x509 -nodes -out root.pem.cer
# Create a certificate signing request
openssl req -newkey rsa:4096 -sha512 -nodes -out ssl.csr -keyout ssl.key
# Create an OpenSSL Configuration file from http://svasey.org/projects/software-usage-notes/ssl_en.html
vim openssl.conf
# Create the indexes
touch certindex
echo 000a > certserial
echo 000a > crlnumber
# Generate SSL certificate 
openssl ca -batch -config openssl.conf -notext -in ssl.csr -out ssl.pem.cer
# Create Certificate Revocation List
openssl ca -config openssl.conf -gencrl -keyfile privkey.pem -cert root.pem.cer -out root.crl.pem
openssl crl -inform PEM -in root.crl.pem -outform DER -out root.crl && rm root.crl.pem

而iOS的代码:

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
  NSURLProtectionSpace *protectionSpace = [challenge protectionSpace];
  if ([protectionSpace authenticationMethod] == NSURLAuthenticationMethodServerTrust) {
    // Load anchor cert.. also tried this with both certs and it doesn't seem to matter
    NSString *path = [[NSBundle mainBundle] pathForResource:@"root.der" ofType:@"crt"];
    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
    SecCertificateRef anchorCert = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)data);
    CFMutableArrayRef anchorCerts = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
    CFArrayAppendValue(anchorCerts, anchorCert);

    // Set anchor cert
    SecTrustRef trust = [protectionSpace serverTrust];
    SecTrustSetAnchorCertificates(trust, anchorCerts);
    SecTrustSetAnchorCertificatesOnly(trust, YES); // only use that certificate
    CFRelease(anchorCert);
    CFRelease(anchorCerts);

    // Validate cert
    SecTrustResultType secresult = kSecTrustResultInvalid;
    if (SecTrustEvaluate(trust, &secresult) != errSecSuccess) {
      [challenge.sender cancelAuthenticationChallenge:challenge];
      return;
    }

    switch (secresult) {
      case kSecTrustResultInvalid:
      case kSecTrustResultDeny:
      case kSecTrustResultFatalTrustFailure:
      case kSecTrustResultOtherError:
      case kSecTrustResultRecoverableTrustFailure: { 
        // !!! It's always kSecTrustResultRecoverableTrustFailure, aka 5
        NSLog(@"Failing due to result: %lu", secresult);
        [challenge.sender cancelAuthenticationChallenge:challenge];
        return;
      }

      case kSecTrustResultUnspecified: // The OS trusts this certificate implicitly.
      case kSecTrustResultProceed: { // The user explicitly told the OS to trust it.
        NSURLCredential *credential = [NSURLCredential credentialForTrust:trust];
        [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
        return;
      }
      default: ;
        /* It's somebody else's key. Fall through. */
    }
    /* The server sent a key other than the trusted key. */
    [connection cancel];

    // Perform other cleanup here, as needed.
  } else {
    NSLog(@"In weird space... not handling authentication method: %@", [protectionSpace authenticationMethod]);
    [connection cancel];
  }
}

我总是得到 kSecTrustResultRecoverableTrustFailure 的结果。我认为这不是本地主机的问题,因为我也尝试过使用苹果提供的代码来更改。应该怎么做呢?

谢谢!


你需要重写 canAuthenticateAgainstProtectionSpacedidReceiveAuthenticationChallenge 两个方法。TrustResultRecoverableTrustFailure 表示你可以改变服务器验证的结果。同时,你也可以参考 OWASP 的 iOS 公钥固定示例,链接为 Public Key Pinning - jww
2个回答

0
请确保您的证书有效。我认为它的名称不应该是root.der.crt。您可以从这里查看证书类型。以下代码适用于p12证书,希望能对您有所帮助。
NSData *PKCS12DataQA = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"CERTIFICATE NAME" ofType:@"CERTIFICATE TYPE"]];

BOOL result = [self extractIdentity:&identity andTrust:&trust fromPKCS12Data:PKCS12DataQA];


- (BOOL)extractIdentity:(SecIdentityRef *)outIdentity andTrust:(SecTrustRef*)outTrust fromPKCS12Data:(NSData *)inPKCS12Data
{
    OSStatus securityError = errSecSuccess;
    //testtest is the passsword for the certificate.
    NSDictionary *optionsDictionary = [NSDictionary dictionaryWithObject:@"testtest" forKey:(id)CFBridgingRelease(kSecImportExportPassphrase)];

    CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
    securityError = SecPKCS12Import((__bridge CFDataRef)(inPKCS12Data),(CFDictionaryRef)CFBridgingRetain(optionsDictionary),&items);

    if (securityError == 0) {
        CFDictionaryRef myIdentityAndTrust = CFArrayGetValueAtIndex (items, 0);
        const void *tempIdentity = NULL;
        tempIdentity = CFDictionaryGetValue (myIdentityAndTrust, kSecImportItemIdentity);
        *outIdentity = (SecIdentityRef)tempIdentity;
        const void *tempTrust = NULL;
        tempTrust = CFDictionaryGetValue (myIdentityAndTrust, kSecImportItemTrust);
        *outTrust = (SecTrustRef)tempTrust;

    } else {
        NSLog(@"Failed with error code %d",(int)securityError);
        return NO;
    }

    return YES;
}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接