且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何实现服务器名称指示 (SNI)

更新时间:2023-02-24 09:20:54

在客户端,您在启动 SSL 连接之前使用 SSL_set_tlsext_host_name(ssl, servername).

On the client side, you use SSL_set_tlsext_host_name(ssl, servername) before initiating the SSL connection.

在服务器端,它有点复杂:

On the server side, it's a little more complicated:

  • 为每个不同的证书设置一个额外的SSL_CTX()
  • 使用SSL_CTX_set_tlsext_servername_callback()为每个SSL_CTX()添加一个servername回调;
  • 在回调中,使用 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) 检索客户端提供的服务器名称.找出正确的 SSL_CTX 以配合该主机名,然后使用 SSL_set_SSL_CTX()SSL 对象切换到该 SSL_CTX代码>.
  • Set up an additional SSL_CTX() for each different certificate;
  • Add a servername callback to each SSL_CTX() using SSL_CTX_set_tlsext_servername_callback();
  • In the callback, retrieve the client-supplied servername with SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name). Figure out the right SSL_CTX to go with that host name, then switch the SSL object to that SSL_CTX with SSL_set_SSL_CTX().

OpenSSL 源代码分发的 apps/ 目录中的 s_client.cs_server.c 文件实现了此功能,因此它们这是一个很好的资源,可以了解应该如何完成.

The s_client.c and s_server.c files in the apps/ directory of the OpenSSL source distribution implement this functionality, so they're a good resource to see how it should be done.