How to implement Server Name Indication (SNI)
28,752
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:
- Set up an additional
SSL_CTX()
for each different certificate; - Add a servername callback to each
SSL_CTX()
usingSSL_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 rightSSL_CTX
to go with that host name, then switch theSSL
object to thatSSL_CTX
withSSL_set_SSL_CTX()
.
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.
Related videos on Youtube
Comments
-
2.8a8a_G over 3 years
How to implement Server Name Indication(SNI) on OpenSSL in C or C++?
Are there any real world examples available?
-
jww over 10 yearsAlso see Serving multiple domains in one box with SNI for some code examples and using
s_client
to test your server.
-
-
2.8a8a_G over 13 yearss_client.c and s_server.c are good examples. I am trying to implement SNI on a client who acts as a load generator(network) and hammers a server with http/https requests. And server already has server side SNI implemented.
-
chacham15 about 10 yearsDo the server calls hold up in a multithreaded context? It seems like the SSL_set_SSL_CTX is innately not threadsafe (i.e. if you have two different inbound connections with two different certs, youll have a problem).
-
caf about 10 years@chacham15: One way to make it thread-safe is to allocate one
SSL_CTX()
per certificate, per thread (and always handle the sameSSL
andSSL_CTX
objects from the same thread). The other way is to set thread callbacks withCRYPTO_set_id_callback()
andCRYPTO_set_locking_callback()
, in which case OpenSSL will make the right calls to the locking callback to makeSSL_set_SSL_CTX()
thread-safe. -
mat almost 8 yearsThat's a very nice high-level write up, thank you! jww has illustrated exactly this approach with a code example in another answer. Could one or both of you please augment these answers with the issue raised in the comments regarding multiple threads? For example, how is
SSL_set_SSL_CTX
innately not thread safe? It seems to only affect the SSL connection specified in the first argument. -
Ben D over 6 yearsDo you know how I can implement SNI support on a server using boost::asio as a socket ? I can't find any example.. I also don't see how I can add multiple ssl context, as the ssl socket takes the context in the constructor
-
user2610053 over 6 years> a little more complicated
-
PYK over 4 yearsYou saved me 3 hard working days on this \o/ ... Thanks ;-)