title: Ruby verify the certificate of secure ldap server
body: <p>I am using <a href="https://github.com/ruby-ldap/ruby-net-ldap" rel="nofollow">https://github.com/ruby-ldap/ruby-net-ldap</a> (net-ldap) gem to verify the authenticity of a user in my rails app. But before passing data to the ldap server, I need to verify that I am talking with the same secure server. 
  Is there a workaround which allows me to verify the certificate in ruby</p>
  
  <p>Additional details: (things I have tried)</p>
  
  <ol>
  <li><p>The certificate which is passed on to me is same as the one I see when I run </p>
  
  <pre><code>openssl s_client -showcerts -connect "&lt;host&gt;:&lt;port&gt;" &lt;/dev/null 2&gt;/dev/null|openssl x509 -outform PEM
  </code></pre></li>
  <li><p>I used <a href="http://www.ldapsoft.com/" rel="nofollow">http://www.ldapsoft.com/</a> to connect to client's server
  Unless I add the certificate file given to me in <em>Security > Manage server certificates</em>, I get a warning saying unknown security certificate</p></li>
  <li><p>I tried do it manually first in plain ruby (without gem)
  But i get following error</p>
  
  <pre><code>test-ssl.rb:23:in `connect': SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed (OpenSSL::SSL::SSLError)
  </code></pre>
  
  <p>Code:</p>
  
  <pre><code>cert_store = OpenSSL::X509::Store.new
  cert_store.add_file "server-wildcard.crt"
  io = TCPSocket.new("SECURELDAP.MYSITE.EDU","636")
  ctx = OpenSSL::SSL::SSLContext.new
  #ctx.cert = OpenSSL::X509::Certificate.new(File.read("server-wildcard.crt"))
  #ctx.client_ca = OpenSSL::X509::Certificate.new(File.read("server-wildcard.crt"))
  #ctx.ca_file = "server-wildcard.crt"
  #ctx.ca_path = "./"
  ctx.verify_mode = OpenSSL::SSL::VERIFY_PEER | OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT
  ctx.cert_store = cert_store
  conn = OpenSSL::SSL::SSLSocket.new(io, ctx)
  conn.connect
  </code></pre></li>
  </ol>