Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring certificate errors with NSURLConnection

Tags:

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.

like image 396
Ideveloper Avatar asked Sep 22 '10 06:09

Ideveloper


2 Answers

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];
like image 44
BadPirate Avatar answered Sep 23 '22 00:09

BadPirate


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]];
like image 167
William Niu Avatar answered Sep 22 '22 00:09

William Niu