title: OpenSSL Verify Peer (Client) Certificate in C++
body: <p>I have a working application that establishes an SSL connection to a server.  The server uses a self-signed certificate and the client loads a certificate authority chain to tell it that the server is OK to trust.  I did that with code like this on the client:</p>
  
  <pre><code>SSL_METHOD* method = TLSv1_client_method();
  _ctx = SSL_CTX_new(method);
  if ( SSL_CTX_load_verify_locations(_ctx, "ca-all.crt", NULL) != 1 )
  {
      return false;
  }
  _ssl = SSL_new(_ctx);
  int val = SSL_set_fd(_ssl, _socket-&gt;GetFD());
  if ( val != SSL_SUCCESS )
  {
      int err = SSL_get_error(_ssl, val);
      return false;
  }
  val = SSL_connect(_ssl);
  </code></pre>
  
  <p>And on the server:</p>
  
  <pre><code>  if ( SSL_CTX_use_certificate_chain_file( g_ctx, "ca-chain1.crt" ) &lt;= 0 ) {
      return 1;
    }
    ppem_file = getenv( "PEM_FILE" );
    if ( ppem_file == NULL ) {
      ppem_file = pem_file;
    }
    if ( SSL_CTX_use_certificate_file( g_ctx, ppem_file,
                                       SSL_FILETYPE_PEM ) &lt;= 0 ) {
      return 1;
    }
    if ( SSL_CTX_use_PrivateKey_file( g_ctx, ppem_file,
                                      SSL_FILETYPE_PEM ) &lt;= 0 ) {
      return 2;
    }
  </code></pre>
  
  <p>I'm trying to modify this code so that the server also verifies the client's peer certificate (self-signed, using same issuer as the server) and having a bit of trouble.  I haven't found good "conceptual overview" documentation anywhere, and that seems to be a typical hurdle with the OpenSSL libraries.</p>
  
  <p>On the client I added this after the SSL_CTX_load_verify_locations() call:</p>
  
  <pre><code>if ( SSL_CTX_use_certificate_file(_ctx, "generic_client.pem", SSL_FILETYPE_PEM ) != 1 )
  {
      return false;
  }
  </code></pre>
  
  <p>On the server I added this after the SSL_CTX_use_PrivateKey_file() call:</p>
  
  <pre><code>  STACK_OF(X509_NAME) *list;
    list = SSL_load_client_CA_file( "ca_chain2.crt" );
    if( list == NULL ) {
      return 4;
    }
    SSL_CTX_set_client_CA_list( g_ctx, list );
    SSL_CTX_set_verify( g_ctx, SSL_VERIFY_PEER, NULL );
  </code></pre>
  
  <p>The connection fails because the certificate doesn't validate.  The client seems to load the certificate fine and if I comment out the SSL_CTX_set_verify line, the client connects without trouble (because its certificate is never verified).</p>
  
  <p>It seems that the server doesn't think that the client's certificate authority chain is good.  What am I missing here?</p>
  
  <p>From the commandline I can run:
  openssl verify -CAfile ca-chain2.crt generic_client.pem
  And it passes, so I have the right certificate data available, I must just be using it wrong somehow.</p>