20

I am getting this error

The certificate for this server is invalid. You might be connecting to a server
that is pretending to be "server addres goes here" which could put your
confidential information at risk."

I am using this method:

[NSURLConnection sendSynchronousRequest:request
                      returningResponse:&response
                                  error:&error];

How can I fix this?

I tried this code:

 NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
                                                               delegate:self];

but then I get EXC_BAD_ACCESS in the didReceiveResponse method.

paulmelnikow
  • 16,895
  • 8
  • 63
  • 114
Ideveloper
  • 1,467
  • 4
  • 23
  • 44
  • *"Ignoring certificate errors with NSURLConnection"* - its better to fix the problem rather than ignoring the error. If you are not going to use PKI and SSL correctly, then why use it at all? – jww Aug 06 '14 at 15:43

6 Answers6

17

You could simply ignore the invalid certificate if you are not sending any sensitive information. This article describes how you could do that. Here is an example implementation by Alexandre Colucci for one of the methods described in that article.

Essentially you want to define a dummy interface just above the @implementation:

@interface NSURLRequest (DummyInterface)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
+ (void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString*)host;
@end

And before you call sendSynchronousRequest, invoke the private method you defined in the dummy interface:

[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[URL host]];
William Niu
  • 15,798
  • 7
  • 53
  • 93
  • This link uses private api and by using that can my app get rejected by apple? If so then I cant use it because I have to put my app on appstore. Any other way to do it? – Ideveloper Sep 22 '10 at 06:33
  • I think this post precisely answered your question: http://stackoverflow.com/questions/933331/how-to-use-nsurlconnection-to-connect-with-ssl-for-an-untrusted-cert/2033823#2033823 – William Niu Sep 22 '10 at 06:58
  • No thats not working didRecieveResponse is getting called first before canAuthenticateAgainstProtectionSpace method and its crashing in didRecieveResponse method. – Ideveloper Sep 22 '10 at 07:21
  • 1
    This has been state in apple documentation. Check this : https://developer.apple.com/library/ios/technotes/tn2232/_index.html Introduction section – Jayprakash Dubey Sep 26 '14 at 06:42
  • Good answer, works perfectly with `sendSynchronousRequest:`. Obviously should only be used when testing/debugging (and obviously any production server should have proper SSL certs to begin with), which is easily enough accomplished using a couple `#ifdef DEBUG` blocks. – aroth Nov 25 '14 at 05:45
  • *"You could simply ignore the invalid certificate if you are not sending any sensitive information"* - I think this is bad advice. Why use SSL at all? Or why not use an anonymous protocol, like ADH? With anonymous protocols, you still get the benefit of encryption without the server authentication. In the case of ADH, the server does not even send a certificate in its `ServerHello`. – jww Apr 14 '15 at 21:52
  • I can't get it to work. Is this method deprecated as of 2021? – Falaen Aug 09 '21 at 22:33
16

The correct (non deprecated, non private) way using the new:

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge

method that apple has specified should be used for NSURLConnectionDelegates is to respond to the ServerTrust method with the credential that was provided for the protection space (this will allow you to connect:

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
    {
        NSLog(@"Ignoring SSL");
        SecTrustRef trust = challenge.protectionSpace.serverTrust;
        NSURLCredential *cred;
        cred = [NSURLCredential credentialForTrust:trust];
        [challenge.sender useCredential:cred forAuthenticationChallenge:challenge];
        return;
    }

    // Provide your regular login credential if needed...
}

This method gets called multiple times once for each available authentication method, if you don't want to login using that method use:

 [challenge.sender rejectProtectionSpaceAndContinueWithChallenge:challenge];
BadPirate
  • 25,802
  • 10
  • 92
  • 123
5

I had similar issue. Got it solved by using below code snippet :

-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {

    NSLog(@"This will execute successfully!");
    if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodServerTrust) {

        [[challenge sender] useCredential:[NSURLCredential credentialForTrust:[[challenge protectionSpace] serverTrust]] forAuthenticationChallenge:challenge];
    }
}

Since below methods are deprecated :

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)space { ... }

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { ... }
Jayprakash Dubey
  • 35,723
  • 18
  • 170
  • 177
  • 1
    This is good, but it does not handle a [CA that's *not* preloaded](https://support.apple.com/en-us/HT204132) or added to the store by the user. But using the preloaded CA list is dangerous since any CA in the CA Zoo can claim to certify the site (even the wrong ones, like those who issue certificates for interception). I think its better to specify the CA that is supposed to certify the site so bad CAs cannot break the channel. – jww Apr 14 '15 at 21:57
3

You've set the delegate as self, so you can fix this by implementing part of NSURLConnectionDelegate in the class sending that request.

Implement this:

-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;

By doing this:

[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];

Note: this is NOT a solution to use in production. Certificates exist for a reason! :)

William Power
  • 686
  • 7
  • 12
3

This does not answer your question of "how to ignore errors". That's being irresponsible.

Rather, it shows you how to load the CA that certifies the server so the connection can proceed as expected. Below, the CA is bundled with the app and is called ca-cert.der. Its a DER (as opposed to PEM) encoded certificate.

Also, you might want to have a look at Apple's Technical Note TN2232 HTTPS Server Trust Evaluation. kSecTrustResultUnspecified is success, see Technical Q&A QA1360 Describing the kSecTrustResultUnspecified error.

-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:
(NSURLProtectionSpace*)space
{        
    return [[space authenticationMethod] isEqualToString: NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:
(NSURLAuthenticationChallenge *)challenge
{        
    if ([[[challenge protectionSpace] authenticationMethod] isEqualToString: NSURLAuthenticationMethodServerTrust])
    {
        do
        {
            SecTrustRef serverTrust = [[challenge protectionSpace] serverTrust];
            NSCAssert(serverTrust != nil, @"serverTrust is nil");
            if(nil == serverTrust)
                break; /* failed */

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

            SecCertificateRef caRef = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)caCert);
            NSCAssert(caRef != nil, @"caRef is nil");
            if(nil == caRef)
                break; /* failed */

            NSArray* caArray = [NSArray arrayWithObject:(__bridge id)(caRef)];
            NSCAssert(caArray != nil, @"caArray is nil");
            if(nil == caArray)
                break; /* failed */

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

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

            NSLog(@"Result: %d", result);

            /* This test looks for a "SUCCESS" */
            /* kSecTrustResultUnspecified and kSecTrustResultProceed are success */
            if(result != kSecTrustResultUnspecified && result != kSecTrustResultProceed)
                break; /* failed */

#if 0
            /* Alternate test looks for a "NOT FAILURE" */
            /* Treat kSecTrustResultConfirm and kSecTrustResultRecoverableTrustFailure as success */
            /*   since the user will likely tap-through to see the dancing bunnies */
            if(result == kSecTrustResultDeny || result == kSecTrustResultFatalTrustFailure || result == kSecTrustResultOtherError)
                break; /* failed to trust cert (good in this case) */
#endif

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

        } while(0);
    }

    // Bad dog
    return [[challenge sender] cancelAuthenticationChallenge: challenge];
}
jww
  • 97,681
  • 90
  • 411
  • 885
  • Good references and example. Here's the [newer documentation](https://developer.apple.com/documentation/foundation/url_loading_system/handling_an_authentication_challenge/performing_manual_server_trust_authentication) which describes using the newer URLSessionDelegate methods. – jk7 Oct 09 '18 at 18:47
1

Are you using an HTTPS url. If so go to the url in a browser and check the certificate. Ensure the certificate is valid for the domain or sub domain that you are trying to use, and that all the intermediate certificates have been installed on your server. I had a problem similar to this, and the solution was to install the intermediate certificates.

Jonathan
  • 1,592
  • 1
  • 14
  • 28