基于Ruby的SSLContext的TCP服务器SNI

ocebsuys  于 2023-02-18  发布在  Ruby
关注(0)|答案(1)|浏览(193)

我想用Ruby编写一个简单的服务器,它根据主机名返回不同的TLS证书。目前我这样做是为了用SSLContext指定一个TCPServer,并给予SSLContext证书和密钥。然后,不管主机名是什么,这个证书都用于所有连接。

context = OpenSSL::SSL::SSLContext.new

context.min_version = :TLS1_2
context.add_certificate cert, key

serv = TCPServer.new host, port
secure = OpenSSL::SSL::SSLServer.new(serv, context)

Thread.new(secure.accept) do |conn|
  # do stuff
end

因此,应根据SNI发送不同的证书。如何实现这一点?

1bqhqjot

1bqhqjot1#

您可以使用servername_cb

context.servername_cb = lambda do |_, name|
  ctx = OpenSSL::SSL::SSLContext.new

  # load certificate for name

  ctx.add_certificate cert[0], cert[1]
        
  return ctx
end

或者,您可以使用现有的上下文:

context.servername_cb = lambda do |socket, name|
  ctx = socket.context

  # load certificate for name

  ctx.add_certificate cert[0], cert[1]
        
  return ctx
end

在TLS握手过程中调用servername_cb的函数。将SSLSocket和名称作为参数传递给该函数。该函数应返回具有相应证书的SSLContext。www.example.comhttps://ruby-doc.org/3.1.2/exts/openssl/OpenSSL/SSL/SSLContext.html#attribute-i-servername_cb

相关问题