title: Making HTTPS request in iOS 9 with self-signed certificate
body: <p>I want to make an HTTPS request to custom server with self-signed certificate. I'm using NSURLConnection class and processing authentication challenges, but always receive error message in a console:</p>
  
  <pre><code>NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)
  </code></pre>
  
  <p>then method "connection:didFailWithError:" gets called with the following error:</p>
  
  <pre><code>Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=&lt;SecTrustRef: 0x150094100&gt;, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, NSErrorPeerCertificateChainKey=&lt;CFArray 0x1500ddd90 [0x19f6dab68]&gt;{type = immutable, count = 1, values = (
      0 : &lt;cert(0x14e6fb370) s: (server certificate name) i: (custom CA name)&gt;
  )}, NSUnderlyingError=0x1504ae170 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSErrorFailingURLStringKey=https://217.92.80.156:9090/(method name and parameters), NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFNetworkCFStreamSSLErrorOriginalValue=-9802, kCFStreamPropertySSLPeerCertificates=&lt;CFArray 0x1500ddd90 [0x19f6dab68]&gt;{type = immutable, count = 1, values = (
      0 : &lt;cert(0x14e6fb370) s: (server certificate name) i: (custom CA name)&gt;
  )}, _kCFStreamPropertySSLClientCertificateState=2, kCFStreamPropertySSLPeerTrust=&lt;SecTrustRef: 0x150094100&gt;, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., _kCFStreamPropertySSLClientCertificates=&lt;CFArray 0x14e5ee8e0 [0x19f6dab68]&gt;{type = mutable-small, count = 2, values = (
      0 : &lt;SecIdentityRef: 0x15012cd40&gt;
      1 : &lt;cert(0x15014aa70) s: (client certificate name) i: (custom CA name)&gt;
  )}, _kCFStreamErrorDomainKey=3, NSErrorFailingURLKey=https://217.92.80.156:9090/(method name and parameters), _kCFStreamErrorCodeKey=-9802}}, NSErrorClientCertificateChainKey=&lt;CFArray 0x14e5ee8e0 [0x19f6dab68]&gt;{type = mutable-small, count = 2, values = (
      0 : &lt;SecIdentityRef: 0x15012cd40&gt;
      1 : &lt;cert(0x15014aa70) s: (client certificate name) i: (custom CA name)&gt;
  )}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://217.92.80.156:9090/(method name and parameters), NSErrorFailingURLStringKey=https://217.92.80.156:9090/(method name and parameters), NSErrorClientCertificateStateKey=2}
  </code></pre>
  
  <p>App receives two authentication challenges (NSURLAuthenticationMethodClientCertificate and NSURLAuthenticationMethodServerTrust) and processes them in a following manner:</p>
  
  <pre><code>- (void) connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
  {
      if(challenge.proposedCredential &amp;&amp; !challenge.error)
      {
          [challenge.sender useCredential:challenge.proposedCredential forAuthenticationChallenge:challenge];
  
          return;
      }
  
      NSString *strAuthenticationMethod = challenge.protectionSpace.authenticationMethod;
      NSLog(@"authentication method: %@", strAuthenticationMethod);
  
      NSURLCredential *credential = nil;
      if([strAuthenticationMethod isEqualToString:NSURLAuthenticationMethodClientCertificate])
      {
          // get identity and certificate from p.12
          NSData *PKCS12Data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"client" ofType:@"p12"]];
  
          NSDictionary *optionsDictionary = [NSDictionary dictionaryWithObject:@"password" forKey:(__bridge id)kSecImportExportPassphrase];
          CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
          OSStatus securityError = SecPKCS12Import((__bridge CFDataRef)PKCS12Data,(__bridge CFDictionaryRef)optionsDictionary, &amp;items);
  
          SecIdentityRef identity = NULL;
          SecCertificateRef certificate = NULL;
          if(securityError == errSecSuccess)
          { 
              CFDictionaryRef myIdentityAndTrust = CFArrayGetValueAtIndex(items, 0);
              identity = (SecIdentityRef)CFDictionaryGetValue (myIdentityAndTrust, kSecImportItemIdentity);
  
              CFArrayRef array = (CFArrayRef)CFDictionaryGetValue(myIdentityAndTrust, kSecImportItemCertChain);
              certificate = (SecCertificateRef)CFArrayGetValueAtIndex(array, 0);
          }
  
          credential = [NSURLCredential credentialWithIdentity:identity certificates:[NSArray arrayWithObject:(__bridge id)(certificate)] persistence:NSURLCredentialPersistenceNone];
  
          CFRelease(items);
      }
      else if([strAuthenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
      {       
          int trustCertificateCount = (int)SecTrustGetCertificateCount(challenge.protectionSpace.serverTrust);
          NSMutableArray *trustCertificates = [[NSMutableArray alloc] initWithCapacity:trustCertificateCount];
          for(int i = 0; i &lt; trustCertificateCount; i ++)
          {
              SecCertificateRef trustCertificate =  SecTrustGetCertificateAtIndex(challenge.protectionSpace.serverTrust, i);
              [trustCertificates addObject:(__bridge id) trustCertificate];
          }            
  
          SecPolicyRef policyRef = NULL;
          policyRef = SecPolicyCreateSSL(YES, (__bridge CFStringRef) challenge.protectionSpace.host);
  
          SecTrustRef trustRef = NULL;
          if(policyRef)
          {
              SecTrustCreateWithCertificates((__bridge CFArrayRef) trustCertificates, policyRef, &amp;trustRef);
              CFRelease(policyRef);
          }
  
          if(trustRef)
          {
  //          SecTrustSetAnchorCertificates(trustRef, (__bridge CFArrayRef) [NSArray array]);
  //          SecTrustSetAnchorCertificatesOnly(trustRef, NO);
  
              SecTrustResultType result;
              OSStatus trustEvalStatus = SecTrustEvaluate(trustRef, &amp;result);
              if(trustEvalStatus == errSecSuccess)
              {
                  // just temporary attempt to make it working.
                  // i hope, there is no such problem, when we have final working version of certificates.
                  if(result == kSecTrustResultRecoverableTrustFailure)
                  {
                      CFDataRef errDataRef = SecTrustCopyExceptions(trustRef);
                      SecTrustSetExceptions(trustRef, errDataRef);
  
                      SecTrustEvaluate(trustRef, &amp;result);
                  }
  
                  if(result == kSecTrustResultProceed || result == kSecTrustResultUnspecified)
                      credential = [NSURLCredential credentialForTrust:trustRef];
              }
  
              CFRelease(trustRef);
          }
      }
      else
      {
          DDLogWarn(@"Unexpected authentication method. Cancelling authentication ...");
          [challenge.sender cancelAuthenticationChallenge:challenge];
      }
  
      if(credential)
          [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
      else
          [challenge.sender cancelAuthenticationChallenge:challenge];
  }
  </code></pre>
  
  <p>In CFNetwork diagnostic log i can see that Handshake procedure is about to be started. At least app sends "ClientHello" message, then server sends its "ServerHello" message and requires for authentication. And here app tries to send authentication response, but immediately receives error. (At the same time, in server logs i don't see any messages about handshake at all). Here is part of diagnostic log:</p>
  
  <pre><code>Sep 15 10:51:49  AppName[331] &lt;Notice&gt;: CFNetwork Diagnostics [3:49] 10:51:49.185 {
      Authentication Challenge
         Loader: &lt;CFURLRequest 0x1501931c0 [0x19f6dab68]&gt; {url = https://217.92.80.156:9090/(method name and parameters), cs = 0x0}
      Challenge: challenge space https://217.92.80.156:9090/, ServerTrustEvaluationRequested (Hash f9810ad8165b3620)
      } [3:49]
  Sep 15 10:51:49  AppName[331] &lt;Notice&gt;: CFNetwork Diagnostics [3:50] 10:51:49.189 {
      Use Credential
          Loader: &lt;CFURLRequest 0x1501931c0 [0x19f6dab68]&gt; {url = https://217.92.80.156:9090/(method name and parameters), cs = 0x0}
      Credential: Name: server, Persistence: session
      } [3:50]
  Sep 15 10:51:49  AppName[331] &lt;Notice&gt;: CFNetwork Diagnostics [3:51] 10:51:49.190 {
       touchConnection
                Loader: &lt;CFURLRequest 0x1501931c0 [0x19f6dab68]&gt; {url = https://217.92.80.156:9090/(method name and parameters), cs = 0x0}
      Timeout Interval: 60.000 seconds
      } [3:51]
  Sep 15 10:51:49  AppName[331] &lt;Notice&gt;: CFNetwork Diagnostics [3:52] 10:51:49.192 {
      Response Error
      Request: &lt;CFURLRequest 0x14e5d02a0 [0x19f6dab68]&gt; {url = https://217.92.80.156:9090/(method name and parameters), cs = 0x0}
        Error: Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFNetworkCFStreamSSLErrorOriginalValue=-9802, kCFStreamPropertySSLPeerCertificates=&lt;CFArray 0x1500ddd90 [0x19f6dab68]&gt;{type = immutable, count = 1, values = (
                  0 : &lt;cert(0x14e6fb370) s: (server certificate name) i: (custom CA name)&gt;
               )}, _kCFStreamPropertySSLClientCertificateState=2, kCFStreamPropertySSLPeerTrust=&lt;SecTrustRef: 0x150094100&gt;, _kCFStreamPropertySSLClientCertificates=&lt;CFArray 0x14e5ee8e0 [0x19f6dab68]&gt;{type = mutable-small, count = 2, values = (
                  0 : &lt;SecIdentityRef: 0x15012cd40&gt;
                  1 : &lt;cert(0x15014aa70) s: (client certificate name) i: (custom CA name)&gt;
               )}, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802}
      } [3:52]
  </code></pre>
  
  <p>Our back-end instance can be installed on customer side, so i can't set any domain exception in Info.plist file. Also app may request server by IP address in IPv4 form, but not by domain name (as it is in my example).</p>
  
  <p>What have i tried:</p>
  
  <ul>
  <li>used NSURLSession instead of NSURLConnection, but without any success;</li>
  <li>checked Apple's ATS requirements for server implementation <a href="https://developer.apple.com/library/prerelease/ios/technotes/App-Transport-Security-Technote/index.html#//apple_ref/doc/uid/TP40016240" rel="nofollow noreferrer">here</a> (back-end developer is sure that his implementation meets all of them);</li>
  <li>played with setting anchor certificates for trust validation in accordance with various solved issues from stackoverflow and Apple's developer forums;</li>
  <li>paid attention particularly to <a href="https://stackoverflow.com/questions/31662134/https-request-in-ios-9-nsurlsession-nsurlconnection-http-load-failed-kcfstrea">similar</a> post and its related <a href="https://forums.developer.apple.com/thread/6452" rel="nofollow noreferrer">solution</a> at developer forums;</li>
  </ul>
  
  <p>I'm testing https request on iPad Air 2 with iOS 9 GM Seed (Build 13A340) and xCode 7 GM Seed (Build 7A218). Important note: this functionality works fine with iOS 8. Taking that into account i may assume, that problem is in our server, but our back-end developer assured me that there everything is fine.</p>
  
  <p>Now i'm out of ideas. I would appreciate if anyone can give me a hint, or at least suggest some other diagnostic, which would reveal particular error, more specific than "fatal alert".</p>
  
  <p>Thanks.</p>
  
  <p>EDIT 1: SecTrustEvaluate always returns kSecTrustResultRecoverableTrustFailure, that is why i had to find some kind of workaround.</p>