w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
iOS connect with self-signed TLS/SSL certificate not working

The iOS code you linked to expects the server's certificate to be in the device's trusted root certificate store, or at least signed by a trusted root certificate authority. The error you are getting suggests that this is not the case.

That error means the certificate is not trusted. By definition, a self-signed certificate is not trusted because it isn't signed by a trusted root certificate authority (so there's no way to verify that the signer of the certificate is who they say they are).

If you just want the benefits of SSL encryption without the protection from MITM attacks, you can bypass the server check by doing something like the following in the NSURLConnection delegate's didReceiveAuthenticationChallenge method:

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

{
    if ([challenge.protectionSpace.authenticationMethod
isEqualToString:NSURLAuthenticationMethodServerTrust])
        [challenge.sender useCredential:[NSURLCredential
credentialForTrust:challenge.protectionSpace.serverTrust]
forAuthenticationChallenge:challenge];

    [challenge.sender
continueWithoutCredentialForAuthenticationChallenge:challenge];
}

Note that this will not prevent MITM attacks, since you are now allowing a connection to any SSL host, but if you truly want that kind of protection you shouldn't use a self-signed certificate. If you just want the encryption offered by SSL, a self-signed certificate is fine.

That said, you can do server authentication if you are bundling the server certificate in with your application - this is known as certificate pinning. You would need to add code in the didReceiveAuthenticationChallenge method above to compare the server's certificate with the one that's embedded in your application and have it trust ONLY that specific certificate and no other. This of course means that if the certificate on your server ever expires or changes, your clients will no longer be able to connect (until you rebuild and redistribute your application with the new certificate). It also means that if your server's private key is ever stolen or compromised, you won't be able to revoke it and issue a new one, and the Bad Guys will be able to impersonate your server to any clients that try to connect using the compromised key. Using a certificate issued by a trusted root CA avoids both problems, and is still the recommended way to go if you truly need server authentication. That way you can revoke the certificate if you ever need to, issue a new one, and everything will still work.





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.