Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify a website certificate in Cocoa Touch?

I currently open an https connection to a web server using NSURLConnection. Everything works as it should and I am able to retrieve the page content I am after. The certificate is issued by VeriSign and I assume NSURLConnection does some work to verify the authenticity of the certificate to some extent? If I connected to the same website through mobile safari it would extract from the certificate, and display the Organization (of the website) in the navigation bar. Is it possibly to extract these same details in Cocoa Touch as I too would like to present them to the user? Also would verifying the server’s host name against that certificate be reasonable enough to assume website is legitimate?

like image 395
dbotha Avatar asked Aug 09 '09 10:08

dbotha


1 Answers

NSURLConnection will give you an error (NSURLErrorDomain) if you attempt to connect to a server with an invalid certificate (e.g. it's self signed, out of date, has the wrong host etc.). So you don't actually need to do any verification yourself, because it's all handled for you.

If you really want/need to display an SSL certificate summary in your UI, you'll need to drop down a layer from NSURLConnection and use low-level CFNetwork API instead. Once you have a CFReadStreamRef that's in the kCFStreamEventEndEncountered state, you should be able to do the following (assuming your stream handle is called readStream):

NSArray* certificates = [(NSArray*)CFReadStreamCopyProperty(readStream, kCFStreamPropertySSLPeerCertificates) autorelease]; 
if ([certificates count] > 0) { 
  SecCertificateRef certificate = (SecCertificateRef)[certificates objectAtIndex:0]; 
  NSString* description = [(NSString*)SecCertificateCopySubjectSummary(certificate) autorelease]; 
  NSData* data = [(NSData*)SecCertificateCopyData(certificate) autorelease]; 
}

You'll need to decode the information held in data if you want to access the various properties of the certificate, but the summary held in description might be enough for your purposes.

like image 162
Nathan de Vries Avatar answered Nov 13 '22 10:11

Nathan de Vries