ossl-guide-tls-server-block.7ossl 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. .\" -*- mode: troff; coding: utf-8 -*-
  2. .\" Automatically generated by Pod::Man 5.01 (Pod::Simple 3.43)
  3. .\"
  4. .\" Standard preamble:
  5. .\" ========================================================================
  6. .de Sp \" Vertical space (when we can't use .PP)
  7. .if t .sp .5v
  8. .if n .sp
  9. ..
  10. .de Vb \" Begin verbatim text
  11. .ft CW
  12. .nf
  13. .ne \\$1
  14. ..
  15. .de Ve \" End verbatim text
  16. .ft R
  17. .fi
  18. ..
  19. .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
  20. .ie n \{\
  21. . ds C` ""
  22. . ds C' ""
  23. 'br\}
  24. .el\{\
  25. . ds C`
  26. . ds C'
  27. 'br\}
  28. .\"
  29. .\" Escape single quotes in literal strings from groff's Unicode transform.
  30. .ie \n(.g .ds Aq \(aq
  31. .el .ds Aq '
  32. .\"
  33. .\" If the F register is >0, we'll generate index entries on stderr for
  34. .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
  35. .\" entries marked with X<> in POD. Of course, you'll have to process the
  36. .\" output yourself in some meaningful fashion.
  37. .\"
  38. .\" Avoid warning from groff about undefined register 'F'.
  39. .de IX
  40. ..
  41. .nr rF 0
  42. .if \n(.g .if rF .nr rF 1
  43. .if (\n(rF:(\n(.g==0)) \{\
  44. . if \nF \{\
  45. . de IX
  46. . tm Index:\\$1\t\\n%\t"\\$2"
  47. ..
  48. . if !\nF==2 \{\
  49. . nr % 0
  50. . nr F 2
  51. . \}
  52. . \}
  53. .\}
  54. .rr rF
  55. .\" ========================================================================
  56. .\"
  57. .IX Title "OSSL-GUIDE-TLS-SERVER-BLOCK 7ossl"
  58. .TH OSSL-GUIDE-TLS-SERVER-BLOCK 7ossl 2025-01-17 3.4.0 OpenSSL
  59. .\" For nroff, turn off justification. Always turn off hyphenation; it makes
  60. .\" way too many mistakes in technical documents.
  61. .if n .ad l
  62. .nh
  63. .SH NAME
  64. ossl\-guide\-tls\-server\-block
  65. \&\- OpenSSL Guide: Writing a simple blocking TLS server
  66. .SH "SIMPLE BLOCKING TLS SERVER EXAMPLE"
  67. .IX Header "SIMPLE BLOCKING TLS SERVER EXAMPLE"
  68. This page will present various source code samples demonstrating how to write a
  69. simple, non-concurrent, TLS "echo" server application which accepts one client
  70. connection at a time, echoing input from the client back to the same client.
  71. Once the current client disconnects, the next client connection is accepted.
  72. .PP
  73. Both the acceptor socket and client connections are "blocking". A more typical
  74. server might use nonblocking sockets with an event loop and callbacks for I/O
  75. events.
  76. .PP
  77. The complete source code for this example blocking TLS server is available in
  78. the \fBdemos/guide\fR directory of the OpenSSL source distribution in the file
  79. \&\fBtls\-server\-block.c\fR. It is also available online at
  80. <https://github.com/openssl/openssl/blob/master/demos/guide/tls\-server\-block.c>.
  81. .PP
  82. We assume that you already have OpenSSL installed on your system; that you
  83. already have some fundamental understanding of OpenSSL concepts and TLS (see
  84. \&\fBossl\-guide\-libraries\-introduction\fR\|(7) and \fBossl\-guide\-tls\-introduction\fR\|(7));
  85. and that you know how to write and build C code and link it against the
  86. libcrypto and libssl libraries that are provided by OpenSSL. It also assumes
  87. that you have a basic understanding of TCP/IP and sockets.
  88. .SS "Creating the SSL_CTX and SSL objects"
  89. .IX Subsection "Creating the SSL_CTX and SSL objects"
  90. The first step is to create an \fBSSL_CTX\fR object for our server. We use the
  91. \&\fBSSL_CTX_new\fR\|(3) function for this purpose. We could alternatively use
  92. \&\fBSSL_CTX_new_ex\fR\|(3) if we want to associate the \fBSSL_CTX\fR with a particular
  93. \&\fBOSSL_LIB_CTX\fR (see \fBossl\-guide\-libraries\-introduction\fR\|(7) to learn about
  94. \&\fBOSSL_LIB_CTX\fR). We pass as an argument the return value of the function
  95. \&\fBTLS_server_method\fR\|(3). You should use this method whenever you are writing a
  96. TLS server. This method will automatically use TLS version negotiation to select
  97. the highest version of the protocol that is mutually supported by both the
  98. server and the client.
  99. .PP
  100. .Vb 9
  101. \& /*
  102. \& * An SSL_CTX holds shared configuration information for multiple
  103. \& * subsequent per\-client SSL connections.
  104. \& */
  105. \& ctx = SSL_CTX_new(TLS_server_method());
  106. \& if (ctx == NULL) {
  107. \& ERR_print_errors_fp(stderr);
  108. \& errx(res, "Failed to create server SSL_CTX");
  109. \& }
  110. .Ve
  111. .PP
  112. We would also like to restrict the TLS versions that we are willing to accept to
  113. TLSv1.2 or above. TLS protocol versions earlier than that are generally to be
  114. avoided where possible. We can do that using
  115. \&\fBSSL_CTX_set_min_proto_version\fR\|(3):
  116. .PP
  117. .Vb 9
  118. \& /*
  119. \& * TLS versions older than TLS 1.2 are deprecated by IETF and SHOULD
  120. \& * be avoided if possible.
  121. \& */
  122. \& if (!SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION)) {
  123. \& SSL_CTX_free(ctx);
  124. \& ERR_print_errors_fp(stderr);
  125. \& errx(res, "Failed to set the minimum TLS protocol version");
  126. \& }
  127. .Ve
  128. .PP
  129. Next we configure some option flags, see \fBSSL_CTX_set_options\fR\|(3) for details:
  130. .PP
  131. .Vb 6
  132. \& /*
  133. \& * Tolerate clients hanging up without a TLS "shutdown". Appropriate in all
  134. \& * application protocols which perform their own message "framing", and
  135. \& * don\*(Aqt rely on TLS to defend against "truncation" attacks.
  136. \& */
  137. \& opts = SSL_OP_IGNORE_UNEXPECTED_EOF;
  138. \&
  139. \& /*
  140. \& * Block potential CPU\-exhaustion attacks by clients that request frequent
  141. \& * renegotiation. This is of course only effective if there are existing
  142. \& * limits on initial full TLS handshake or connection rates.
  143. \& */
  144. \& opts |= SSL_OP_NO_RENEGOTIATION;
  145. \&
  146. \& /*
  147. \& * Most servers elect to use their own cipher preference rather than that of
  148. \& * the client.
  149. \& */
  150. \& opts |= SSL_OP_CIPHER_SERVER_PREFERENCE;
  151. \&
  152. \& /* Apply the selection options */
  153. \& SSL_CTX_set_options(ctx, opts);
  154. .Ve
  155. .PP
  156. Servers need a private key and certificate. Though anonymous ciphers (no
  157. server certificate) are possible in TLS 1.2, they are rarely applicable, and
  158. are not currently defined for TLS 1.3. Additional intermediate issuer CA
  159. certificates are often also required, and both the server (end-entity or EE)
  160. certificate and the issuer ("chain") certificates are most easily configured in
  161. a single "chain file". Below we load such a chain file (the EE certificate
  162. must appear first), and then load the corresponding private key, checking that
  163. it matches the server certificate. No checks are performed to check the
  164. integrity of the chain (CA signatures or certificate expiration dates, for
  165. example).
  166. .PP
  167. .Vb 10
  168. \& /*
  169. \& * Load the server\*(Aqs certificate *chain* file (PEM format), which includes
  170. \& * not only the leaf (end\-entity) server certificate, but also any
  171. \& * intermediate issuer\-CA certificates. The leaf certificate must be the
  172. \& * first certificate in the file.
  173. \& *
  174. \& * In advanced use\-cases this can be called multiple times, once per public
  175. \& * key algorithm for which the server has a corresponding certificate.
  176. \& * However, the corresponding private key (see below) must be loaded first,
  177. \& * *before* moving on to the next chain file.
  178. \& */
  179. \& if (SSL_CTX_use_certificate_chain_file(ctx, "chain.pem") <= 0) {
  180. \& SSL_CTX_free(ctx);
  181. \& ERR_print_errors_fp(stderr);
  182. \& errx(res, "Failed to load the server certificate chain file");
  183. \& }
  184. \&
  185. \& /*
  186. \& * Load the corresponding private key, this also checks that the private
  187. \& * key matches the just loaded end\-entity certificate. It does not check
  188. \& * whether the certificate chain is valid, the certificates could be
  189. \& * expired, or may otherwise fail to form a chain that a client can validate.
  190. \& */
  191. \& if (SSL_CTX_use_PrivateKey_file(ctx, "pkey.pem", SSL_FILETYPE_PEM) <= 0) {
  192. \& SSL_CTX_free(ctx);
  193. \& ERR_print_errors_fp(stderr);
  194. \& errx(res, "Error loading the server private key file, "
  195. \& "possible key/cert mismatch???");
  196. \& }
  197. .Ve
  198. .PP
  199. Next we enable session caching, which makes it possible for clients to more
  200. efficiently make additional TLS connections after completing an initial full
  201. TLS handshake. With TLS 1.3, session resumption typically still performs a fresh
  202. key agreement, but the certificate exchange is avoided.
  203. .PP
  204. .Vb 7
  205. \& /*
  206. \& * Servers that want to enable session resumption must specify a cache id
  207. \& * byte array, that identifies the server application, and reduces the
  208. \& * chance of inappropriate cache sharing.
  209. \& */
  210. \& SSL_CTX_set_session_id_context(ctx, (void *)cache_id, sizeof(cache_id));
  211. \& SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER);
  212. \&
  213. \& /*
  214. \& * How many client TLS sessions to cache. The default is
  215. \& * SSL_SESSION_CACHE_MAX_SIZE_DEFAULT (20k in recent OpenSSL versions),
  216. \& * which may be too small or too large.
  217. \& */
  218. \& SSL_CTX_sess_set_cache_size(ctx, 1024);
  219. \&
  220. \& /*
  221. \& * Sessions older than this are considered a cache miss even if still in
  222. \& * the cache. The default is two hours. Busy servers whose clients make
  223. \& * many connections in a short burst may want a shorter timeout, on lightly
  224. \& * loaded servers with sporadic connections from any given client, a longer
  225. \& * time may be appropriate.
  226. \& */
  227. \& SSL_CTX_set_timeout(ctx, 3600);
  228. .Ve
  229. .PP
  230. Most servers, including this one, do not solicit client certificates. We
  231. therefore do not need a "trust store" and allow the handshake to complete even
  232. when the client does not present a certificate. Note: Even if a client did
  233. present a trusted ceritificate, for it to be useful, the server application
  234. would still need custom code to use the verified identity to grant nondefault
  235. access to that particular client. Some servers grant access to all clients
  236. with certificates from a private CA, this then requires processing of
  237. certificate revocation lists to deauthorise a client. It is often simpler and
  238. more secure to instead keep a list of authorised public keys.
  239. .PP
  240. Though this is the default setting, we explicitly call the
  241. \&\fBSSL_CTX_set_verify\fR\|(3) function and pass the \fBSSL_VERIFY_NONE\fR value to it.
  242. The final argument to this function is a callback that you can optionally
  243. supply to override the default handling for certificate verification. Most
  244. applications do not need to do this so this can safely be set to NULL to get
  245. the default handling.
  246. .PP
  247. .Vb 12
  248. \& /*
  249. \& * Clients rarely employ certificate\-based authentication, and so we don\*(Aqt
  250. \& * require "mutual" TLS authentication (indeed there\*(Aqs no way to know
  251. \& * whether or how the client authenticated the server, so the term "mutual"
  252. \& * is potentially misleading).
  253. \& *
  254. \& * Since we\*(Aqre not soliciting or processing client certificates, we don\*(Aqt
  255. \& * need to configure a trusted\-certificate store, so no call to
  256. \& * SSL_CTX_set_default_verify_paths() is needed. The server\*(Aqs own
  257. \& * certificate chain is assumed valid.
  258. \& */
  259. \& SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
  260. .Ve
  261. .PP
  262. That is all the setup that we need to do for the \fBSSL_CTX\fR. Next we create an
  263. acceptor BIO on which to accept client connections. This just records the
  264. intended port (and optional "host:" prefix), without actually creating the
  265. socket. This delayed processing allows the programmer to specify additional
  266. behaviours before the listening socket is actually created.
  267. .PP
  268. .Vb 10
  269. \& /*
  270. \& * Create a listener socket wrapped in a BIO.
  271. \& * The first call to BIO_do_accept() initialises the socket
  272. \& */
  273. \& acceptor_bio = BIO_new_accept(hostport);
  274. \& if (acceptor_bio == NULL) {
  275. \& SSL_CTX_free(ctx);
  276. \& ERR_print_errors_fp(stderr);
  277. \& errx(res, "Error creating acceptor bio");
  278. \& }
  279. .Ve
  280. .PP
  281. Servers almost always want to use the "SO_REUSEADDR" option to avoid startup
  282. failures if there are still lingering client connections, so we do that before
  283. making the \fBfirst\fR call to \fBBIO_do_accept\fR\|(3) which creates the listening
  284. socket, without accepting a client connection. Subsequent calls to the same
  285. function will accept new connections.
  286. .PP
  287. .Vb 6
  288. \& BIO_set_bind_mode(acceptor_bio, BIO_BIND_REUSEADDR);
  289. \& if (BIO_do_accept(acceptor_bio) <= 0) {
  290. \& SSL_CTX_free(ctx);
  291. \& ERR_print_errors_fp(stderr);
  292. \& errx(res, "Error setting up acceptor socket");
  293. \& }
  294. .Ve
  295. .SS "Server loop"
  296. .IX Subsection "Server loop"
  297. The server now enters a "forever" loop handling one client connection at a
  298. time. Before each connection we clear the OpenSSL error stack, so that any
  299. error reports are related to just the new connection.
  300. .PP
  301. .Vb 2
  302. \& /* Pristine error stack for each new connection */
  303. \& ERR_clear_error();
  304. .Ve
  305. .PP
  306. At this point the server blocks to accept the next client:
  307. .PP
  308. .Vb 5
  309. \& /* Wait for the next client to connect */
  310. \& if (BIO_do_accept(acceptor_bio) <= 0) {
  311. \& /* Client went away before we accepted the connection */
  312. \& continue;
  313. \& }
  314. .Ve
  315. .PP
  316. On success the accepted client connection has been wrapped in a fresh BIO and
  317. pushed onto the end of the acceptor BIO chain. We pop it off returning the
  318. acceptor BIO to its initial state.
  319. .PP
  320. .Vb 3
  321. \& /* Pop the client connection from the BIO chain */
  322. \& client_bio = BIO_pop(acceptor_bio);
  323. \& fprintf(stderr, "New client connection accepted\en");
  324. .Ve
  325. .PP
  326. Next, we create an \fBSSL\fR object by calling the \fBSSL_new\|(3)\fR function and
  327. passing the \fBSSL_CTX\fR we created as an argument. The client connection BIO is
  328. configured as the I/O conduit for this SSL handle. SSL_set_bio transfers
  329. ownership of the BIO or BIOs involved (our \fBclient_bio\fR) to the SSL handle.
  330. .PP
  331. .Vb 8
  332. \& /* Associate a new SSL handle with the new connection */
  333. \& if ((ssl = SSL_new(ctx)) == NULL) {
  334. \& ERR_print_errors_fp(stderr);
  335. \& warnx("Error creating SSL handle for new connection");
  336. \& BIO_free(client_bio);
  337. \& continue;
  338. \& }
  339. \& SSL_set_bio(ssl, client_bio, client_bio);
  340. .Ve
  341. .PP
  342. And now we're ready to attempt the SSL handshake. With a blocking socket
  343. OpenSSL will perform all the read and write operations required to complete the
  344. handshake (or detect and report a failure) before returning.
  345. .PP
  346. .Vb 7
  347. \& /* Attempt an SSL handshake with the client */
  348. \& if (SSL_accept(ssl) <= 0) {
  349. \& ERR_print_errors_fp(stderr);
  350. \& warnx("Error performing SSL handshake with client");
  351. \& SSL_free(ssl);
  352. \& continue;
  353. \& }
  354. .Ve
  355. .PP
  356. With the handshake complete, the server loops echoing client input back to the
  357. client:
  358. .PP
  359. .Vb 9
  360. \& while (SSL_read_ex(ssl, buf, sizeof(buf), &nread) > 0) {
  361. \& if (SSL_write_ex(ssl, buf, nread, &nwritten) > 0 &&
  362. \& nwritten == nread) {
  363. \& total += nwritten;
  364. \& continue;
  365. \& }
  366. \& warnx("Error echoing client input");
  367. \& break;
  368. \& }
  369. .Ve
  370. .PP
  371. Once the client closes its connection, we report the number of bytes sent to
  372. \&\fBstderr\fR and free the SSL handle, which also frees the \fBclient_bio\fR and
  373. closes the underlying socket.
  374. .PP
  375. .Vb 2
  376. \& fprintf(stderr, "Client connection closed, %zu bytes sent\en", total);
  377. \& SSL_free(ssl);
  378. .Ve
  379. .PP
  380. The server is now ready to accept the next client connection.
  381. .SS "Final clean up"
  382. .IX Subsection "Final clean up"
  383. If the server could somehow manage to break out of the infinite loop, and
  384. be ready to exit, it would first deallocate the constructed \fBSSL_CTX\fR.
  385. .PP
  386. .Vb 5
  387. \& /*
  388. \& * Unreachable placeholder cleanup code, the above loop runs forever.
  389. \& */
  390. \& SSL_CTX_free(ctx);
  391. \& return EXIT_SUCCESS;
  392. .Ve
  393. .SH "SEE ALSO"
  394. .IX Header "SEE ALSO"
  395. \&\fBossl\-guide\-introduction\fR\|(7), \fBossl\-guide\-libraries\-introduction\fR\|(7),
  396. \&\fBossl\-guide\-libssl\-introduction\fR\|(7), \fBossl\-guide\-tls\-introduction\fR\|(7),
  397. \&\fBossl\-guide\-tls\-client\-non\-block\fR\|(7), \fBossl\-guide\-quic\-client\-block\fR\|(7)
  398. .SH COPYRIGHT
  399. .IX Header "COPYRIGHT"
  400. Copyright 2024 The OpenSSL Project Authors. All Rights Reserved.
  401. .PP
  402. Licensed under the Apache License 2.0 (the "License"). You may not use
  403. this file except in compliance with the License. You can obtain a copy
  404. in the file LICENSE in the source distribution or at
  405. <https://www.openssl.org/source/license.html>.