14

I need to establish a TCP connection with my server which has a SSL enabled port, that I need to access.

I need to send a XML file and get the response from the server.

Before the SSL was enabled, I was able to get the data from the server using the below mentioned code.

require 'socket'
myXML = 'test_xml' 
host = 'myhost.com'   
port = 12482               

socket = TCPSocket.open(host,port)  # Connect to server  
socket.send(myXML, 0)
response = socket.recvfrom(port)
puts response
socket.close

Now I have a 'certi.pfx' with which I need to establish a connection, Send my_xml data and get the response. How can this be done.

I would also like to know if I have the 'pem' and 'key' file, how can I establish a connection, Send my_xml data and get the response.

Please help.

Amal Kumar S
  • 15,555
  • 19
  • 56
  • 88

2 Answers2

22
require 'socket'
require 'openssl'

myXML = 'my_sample_data'
host = 'my_host.com'
port = my_port                

socket = TCPSocket.open(host,port)
ssl_context = OpenSSL::SSL::SSLContext.new()
ssl_context.cert = OpenSSL::X509::Certificate.new(File.open("certificate.crt"))
ssl_context.key = OpenSSL::PKey::RSA.new(File.open("certificate.key"))
ssl_context.ssl_version = :SSLv23
ssl_socket = OpenSSL::SSL::SSLSocket.new(socket, ssl_context)
ssl_socket.sync_close = true
ssl_socket.connect

ssl_socket.puts(myXML)
while line = ssl_socket.gets
  p line
end
ssl_socket.close
Amal Kumar S
  • 15,555
  • 19
  • 56
  • 88
6

Like this:

  sock = TCPSocket.new('hostname', 443)
  ctx = OpenSSL::SSL::SSLContext.new
  ctx.set_params(verify_mode: OpenSSL::SSL::VERIFY_PEER)
  @socket = OpenSSL::SSL::SSLSocket.new(sock, ctx).tap do |socket|
    socket.sync_close = true
    socket.connect
  end
Roman
  • 13,100
  • 2
  • 47
  • 63
  • Roman - thanks for your reply. But one thing is where do I need to specify the certificate files. Actually I am new to socket programming. When I used the above code I got an error like "connect: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed (OpenSSL::SSL::SSLError)" – Amal Kumar S Oct 11 '12 at 10:20
  • I have a specific port 12482. To which I need to connect – Amal Kumar S Oct 11 '12 at 10:22
  • You need to specify the ca bundle (ca_path: '/path', ca_file: 'ca-bundle.crt') and you need to specify the certificate (cert) in PEM form. Check ri OpenSSL::SSL::SSLContext – Roman Oct 11 '12 at 10:22
  • Currently I am having only a 'certi.pfx' file. How can I connect with help of that – Amal Kumar S Oct 11 '12 at 10:27
  • If it's a PKCS12 container, you can extract the certificate and the key using the openssl commands line utility, probably using the pkcs12 command. – Roman Oct 11 '12 at 10:28
  • I was able to get the crt and key files – Amal Kumar S Oct 11 '12 at 10:38