NSURLConnection fails with CocoaHTTPServer with SSL using certificate signed by custom CA

1k views Asked by At

I have a small app with CocoaHttpServer siting inside of it. I want to enable it only for loopback calls and I want to be able to make those calls only from my app. Don't ask why - I need it.

self.httpServer = [[HTTPServer alloc] init];
self.httpServer.port = HTTP_SERVER_PORT;
self.httpServer.interface = @"loopback";
self.httpServer.connectionClass = [HTTPSolFSConnection class];

NSError *error;
if([self.httpServer start:&error]) {
    DDLogInfo(@"Started HTTP Server on port %hu", [self.httpServer listeningPort]);
}
else {
    DDLogError(@"Error starting HTTP Server: %@", error);
}

The server uses custom HTTPConnection class which returns YES in isSecureServer method and uses certificate signed with custom CA.

- (BOOL)isSecureServer {
    return YES;
}

- (NSArray *)sslIdentityAndCertificates {
    NSArray *result = nil;

    NSData *serverCertificateData = [[NSData alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"server" ofType:@"p12"]];

    const void *keys[] =   { kSecImportExportPassphrase };
    const void *values[] = { CFSTR("friday_internet") };
    CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);

    CFArrayRef items = NULL;
    OSStatus securityError = SecPKCS12Import((__bridge CFDataRef) serverCertificateData, options, &items);

    if (options) {
        CFRelease(options);
    }

    if (securityError == errSecSuccess) {
        CFDictionaryRef myIdentityAndTrust = CFArrayGetValueAtIndex(items, 0);
        SecIdentityRef identity = (SecIdentityRef) CFDictionaryGetValue(myIdentityAndTrust, kSecImportItemIdentity);

        SecCertificateRef serverCertificate = NULL;
        SecIdentityCopyCertificate(identity, &serverCertificate);

        NSData *caCertificateData = [[NSData alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ca" ofType:@"der"]];
        SecCertificateRef caCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef) caCertificateData);
        NSArray *anchorCertificates = @[ (__bridge id) serverCertificate, (__bridge id) caCertificate ];

        SecTrustResultType trustResult;
        SecTrustRef trust = (SecTrustRef) CFDictionaryGetValue(myIdentityAndTrust, kSecImportItemTrust);
        SecTrustSetAnchorCertificates(trust, (__bridge CFArrayRef) anchorCertificates);
        SecTrustSetAnchorCertificatesOnly(trust, false);

        SecTrustEvaluate(trust, &trustResult);
        NSLog(@"SecTrustResultType: %d", trustResult);

        result = @[ (__bridge id) identity, (__bridge id) caCertificate, (__bridge id) serverCertificate ];

        if (serverCertificate) {
            CFRelease(serverCertificate);
        }
    }

    if (items) {
        CFRelease(items);
    }

    return result;
}

Every time I create NSURLConnection to the server, it logs SecTrustResultType: 4 and fails with error:

Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. 
You might be connecting to a server that is pretending to be “localhost” which could 
put your confidential information at risk." UserInfo=0xb93da40 
{NSErrorFailingURLStringKey=https://localhost:12345/file.txt, 
NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, 
NSErrorFailingURLKey=https://localhost:12345/file.txt, 
NSLocalizedDescription=The certificate for this server is invalid.
You might be connecting to a server that is pretending to be “localhost” which could
put your confidential information at risk., NSUnderlyingError=0xf155310 
"The certificate for this server is invalid. You might be connecting to a server
that is pretending to be “localhost” which could put your confidential information
at risk.", NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x13329720>}

I read many articles and many questions on StackOverflow but it doesn't help:

  1. How do I programatically import a certificate into my iOS app's keychain and pass the identity to a server when needed?
  2. How to make iPhoneHTTPServer secure server
  3. SecTrustEvaluate always returns kSecTrustResultRecoverableTrustFailure with SecPolicyCreateSSL
  4. Unable to trust a self signed certificate on iphone
  5. https://developer.apple.com/library/ios/technotes/tn2232/_index.html#//apple_ref/doc/uid/DTS40012884-CH1-SECCUSTOMROOT
  6. https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html

There are two "hacks" which solve the problem:

  1. I can implement connection:willSendRequestForAuthenticationChallenge: method of NSURLConnectionDelegate
  2. I can implement custom NSURLProtocol
  3. Email the CA's certificate to a device and manually trust it

The thing is that I'm using a third party library inside my app which communicates with my server. It doesn't use Foundation framework so first two methods don't work. Is there a way to do it programmatically instead of manually sending certificates?

0

There are 0 answers