Using SSL client in Ruby on Rails application

I am working on an application for a client that requires an SSL connection to the API. I have been provided with three files; trusted root certificate file (.cer), intermediate certificate file (.cer), and signed response file. The instructions that I was provided with for installation apply to either IIS or the Java keytool program; I am creating an application in Ruby on Rails, so there is no option (as far as I know).

The certificates are self-signed by the organization that runs the API service, and it looks like I get the provided client certificates for mutual authentication of the https connection. I'm not sure how

  • use certificates in my application to connect and use the API
  • that the signed answer file

I read “Using a Self -signed Certificate” and this article on OpenSSL in Ruby , but none of them seem to hit the mark (and both have a certain Java / JRuby dependency that confuses things).

Any pointers would be greatly appreciated.

+6
source share
1 answer

Based on your comments, I assume that the certificates are in DER format, which you can convert to PEM using the openssl x509 (see openssl x509 command :

 openssl x509 -inform DER -outform PEM -in certfile.cer -out certfile.pem 

After that, you can instruct the OpenSSL Ruby library to use a trusted root certificate to authenticate the SSL connection with something like this:

 require 'socket' require 'openssl' tcp_sock = TCPSocket.new("my.host.tld", 443) ctx = OpenSSL::SSL::SSLContext.new ctx.verify_mode = OpenSSL::SSL::VERIFY_PEER|OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT #You may need to specify the absolute path to the file ctx.ca_file = "certfile.pem" ssl_sock = OpenSSL::SSL::SSLSocket.new(tcp_sock, ctx) ssl_sock.sync_close = true ssl_sock.connect begin ssl_sock.post_connection_check('my.host.tld') rescue puts "Certificate host did not match expected hostname" end 

After that, you should be able to read and write to ssl_sock , like any other Ruby IO object. If you have been provided with a client certificate to allow the server to authenticate you, you can configure the SSL context with:

 ctx.cert = OpenSSL::X509::Certificate.new(File.read("my_cert.pem")) ctx.key = OpenSSL::PKey::RSA.new(File.read("my_key.rsa")) 

before creating ssl_sock . The OpenSSL library also supports key types other than RSA, such as DSA (see OpenSSL :: PKey module .)

Finally, the last tip, if you are accessing the RESTful API, you might want to use a gem like rest-client instead of directly handling all HTTP / S connections. Regardless of whether such a library is suitable or useful, of course, it will depend on the service you use.

+4
source

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


All Articles