Securing SSL on iOS

To improve the security of my application and protect the user from MITM attacks, I am trying to bind SSL with my self-signed certificate, following the contents of this post .

So, I use the following code to compare the certificate that I get from the server with the one that was added to the application.

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { SecTrustRef serverTrust = challenge.protectionSpace.serverTrust; SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, 0); NSData *remoteCertificateData = CFBridgingRelease(SecCertificateCopyData(certificate)); NSLog(@"Remote Certificate Data Length: %d",[remoteCertificateData length]); NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"apache" ofType:@"crt"]; NSData *localCertData = [NSData dataWithContentsOfFile:cerPath]; NSLog(@"Local Certificate Data Length: %d",[localCertData length]); if ([remoteCertificateData isEqualToData:localCertData]) { NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust]; [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; } else { [[challenge sender] cancelAuthenticationChallenge:challenge]; } } 

The only thing that is different from my code and one of the blog posts I linked is the name and extension (.cer to.crt) for the resource representing my certificate, and two added NSLogs that will be useful later to show what is the problem.

In fact, when this code is executed, I get this output:

 2013-05-22 16:08:53.331 HTTPS Test[5379:c07] Remote Certificate Data Length: 880 2013-05-22 16:09:01.346 HTTPS Test[5379:c07] Local Certificate Data Length: 1249 

Obviously, the comparison between local and remote certificates fails because the data length is different, and therefore it also fails.

Why is this happening and how can I solve this problem?

+6
source share
1 answer

I had the same problem. The problem is probably due to the fact that you did not convert your .crt file to the correct format. iOS and OSX are looking for your certificate in format . der . To convert it, you must use openssl . Here is a very useful article on this topic. My public certificate came from the Apache server (I assume yours did too). By looking at the openssl documentation, I was able to figure out how to make this work.

1) Open a terminal and change the directory to the address of your .crt.

2) Run the following command:

 openssl x509 -in your_cert.crt -outform der -out your_output_name.der 

This will create an output file named 'your_output_file.der'. You must import this into your xCode project and reference it in

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

for your implementation of NSURLConnectionDelegate .

Hope this helps!

+5
source

Source: https://habr.com/ru/post/945598/


All Articles