ossl-guide-quic-client-block.7ossl 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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-QUIC-CLIENT-BLOCK 7ossl"
  58. .TH OSSL-GUIDE-QUIC-CLIENT-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\-quic\-client\-block
  65. \&\- OpenSSL Guide: Writing a simple blocking QUIC client
  66. .SH "SIMPLE BLOCKING QUIC CLIENT EXAMPLE"
  67. .IX Header "SIMPLE BLOCKING QUIC CLIENT EXAMPLE"
  68. This page will present various source code samples demonstrating how to write
  69. a simple blocking QUIC client application which connects to a server, sends an
  70. HTTP/1.0 request to it, and reads back the response. Note that HTTP/1.0 over
  71. QUIC is non-standard and will not be supported by real world servers. This is
  72. for demonstration purposes only.
  73. .PP
  74. We assume that you already have OpenSSL installed on your system; that you
  75. already have some fundamental understanding of OpenSSL concepts, TLS and QUIC
  76. (see \fBossl\-guide\-libraries\-introduction\fR\|(7), \fBossl\-guide\-tls\-introduction\fR\|(7)
  77. and \fBossl\-guide\-quic\-introduction\fR\|(7)); and that you know how to
  78. write and build C code and link it against the libcrypto and libssl libraries
  79. that are provided by OpenSSL. It also assumes that you have a basic
  80. understanding of UDP/IP and sockets. The example code that we build in this
  81. tutorial will amend the blocking TLS client example that is covered in
  82. \&\fBossl\-guide\-tls\-client\-block\fR\|(7). Only the differences between that client and
  83. this one will be discussed so we also assume that you have run through and
  84. understand that tutorial.
  85. .PP
  86. For this tutorial our client will be using a single QUIC stream. A subsequent
  87. tutorial will discuss how to write a multi-stream client (see
  88. \&\fBossl\-guide\-quic\-multi\-stream\fR\|(7)).
  89. .PP
  90. The complete source code for this example blocking QUIC client is available in
  91. the \f(CW\*(C`demos/guide\*(C'\fR directory of the OpenSSL source distribution in the file
  92. \&\f(CW\*(C`quic\-client\-block.c\*(C'\fR. It is also available online at
  93. <https://github.com/openssl/openssl/blob/master/demos/guide/quic\-client\-block.c>.
  94. .SS "Creating the SSL_CTX and SSL objects"
  95. .IX Subsection "Creating the SSL_CTX and SSL objects"
  96. In the TLS tutorial (\fBossl\-guide\-tls\-client\-block\fR\|(7)) we created an \fBSSL_CTX\fR
  97. object for our client and used it to create an \fBSSL\fR object to represent the
  98. TLS connection. A QUIC connection works in exactly the same way. We first create
  99. an \fBSSL_CTX\fR object and then use it to create an \fBSSL\fR object to represent the
  100. QUIC connection.
  101. .PP
  102. As in the TLS example the first step is to create an \fBSSL_CTX\fR object for our
  103. client. This is done in the same way as before except that we use a different
  104. "method". OpenSSL offers two different QUIC client methods, i.e.
  105. \&\fBOSSL_QUIC_client_method\fR\|(3) and \fBOSSL_QUIC_client_thread_method\fR\|(3).
  106. .PP
  107. The first one is the equivalent of \fBTLS_client_method\fR\|(3) but for the QUIC
  108. protocol. The second one is the same, but it will additionally create a
  109. background thread for handling time based events (known as "thread assisted
  110. mode", see \fBossl\-guide\-quic\-introduction\fR\|(7)). For this tutorial we will be
  111. using \fBOSSL_QUIC_client_method\fR\|(3) because we will not be leaving the QUIC
  112. connection idle in our application and so thread assisted mode is not needed.
  113. .PP
  114. .Vb 10
  115. \& /*
  116. \& * Create an SSL_CTX which we can use to create SSL objects from. We
  117. \& * want an SSL_CTX for creating clients so we use OSSL_QUIC_client_method()
  118. \& * here.
  119. \& */
  120. \& ctx = SSL_CTX_new(OSSL_QUIC_client_method());
  121. \& if (ctx == NULL) {
  122. \& printf("Failed to create the SSL_CTX\en");
  123. \& goto end;
  124. \& }
  125. .Ve
  126. .PP
  127. The other setup steps that we applied to the \fBSSL_CTX\fR for TLS also apply to
  128. QUIC except for restricting the TLS versions that we are willing to accept. The
  129. QUIC protocol implementation in OpenSSL currently only supports TLSv1.3. There
  130. is no need to call \fBSSL_CTX_set_min_proto_version\fR\|(3) or
  131. \&\fBSSL_CTX_set_max_proto_version\fR\|(3) in an OpenSSL QUIC application, and any such
  132. call will be ignored.
  133. .PP
  134. Once the \fBSSL_CTX\fR is created, the \fBSSL\fR object is constructed in exactly the
  135. same way as for the TLS application.
  136. .SS "Creating the socket and BIO"
  137. .IX Subsection "Creating the socket and BIO"
  138. A major difference between TLS and QUIC is the underlying transport protocol.
  139. TLS uses TCP while QUIC uses UDP. The way that the QUIC socket is created in our
  140. example code is much the same as for TLS. We use the \fBBIO_lookup_ex\fR\|(3) and
  141. \&\fBBIO_socket\fR\|(3) helper functions as we did in the previous tutorial except that
  142. we pass \fBSOCK_DGRAM\fR as an argument to indicate UDP (instead of \fBSOCK_STREAM\fR
  143. for TCP).
  144. .PP
  145. .Vb 6
  146. \& /*
  147. \& * Lookup IP address info for the server.
  148. \& */
  149. \& if (!BIO_lookup_ex(hostname, port, BIO_LOOKUP_CLIENT, family, SOCK_DGRAM, 0,
  150. \& &res))
  151. \& return NULL;
  152. \&
  153. \& /*
  154. \& * Loop through all the possible addresses for the server and find one
  155. \& * we can connect to.
  156. \& */
  157. \& for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {
  158. \& /*
  159. \& * Create a TCP socket. We could equally use non\-OpenSSL calls such
  160. \& * as "socket" here for this and the subsequent connect and close
  161. \& * functions. But for portability reasons and also so that we get
  162. \& * errors on the OpenSSL stack in the event of a failure we use
  163. \& * OpenSSL\*(Aqs versions of these functions.
  164. \& */
  165. \& sock = BIO_socket(BIO_ADDRINFO_family(ai), SOCK_DGRAM, 0, 0);
  166. \& if (sock == \-1)
  167. \& continue;
  168. \&
  169. \& /* Connect the socket to the server\*(Aqs address */
  170. \& if (!BIO_connect(sock, BIO_ADDRINFO_address(ai), 0)) {
  171. \& BIO_closesocket(sock);
  172. \& sock = \-1;
  173. \& continue;
  174. \& }
  175. \&
  176. \& /* Set to nonblocking mode */
  177. \& if (!BIO_socket_nbio(sock, 1)) {
  178. \& BIO_closesocket(sock);
  179. \& sock = \-1;
  180. \& continue;
  181. \& }
  182. \&
  183. \& break;
  184. \& }
  185. \&
  186. \& if (sock != \-1) {
  187. \& *peer_addr = BIO_ADDR_dup(BIO_ADDRINFO_address(ai));
  188. \& if (*peer_addr == NULL) {
  189. \& BIO_closesocket(sock);
  190. \& return NULL;
  191. \& }
  192. \& }
  193. \&
  194. \& /* Free the address information resources we allocated earlier */
  195. \& BIO_ADDRINFO_free(res);
  196. .Ve
  197. .PP
  198. You may notice a couple of other differences between this code and the version
  199. that we used for TLS.
  200. .PP
  201. Firstly, we set the socket into nonblocking mode. This must always be done for
  202. an OpenSSL QUIC application. This may be surprising considering that we are
  203. trying to write a blocking client. Despite this the \fBSSL\fR object will still
  204. have blocking behaviour. See \fBossl\-guide\-quic\-introduction\fR\|(7) for further
  205. information on this.
  206. .PP
  207. Secondly, we take note of the IP address of the peer that we are connecting to.
  208. We store that information away. We will need it later.
  209. .PP
  210. See \fBBIO_lookup_ex\fR\|(3), \fBBIO_socket\fR\|(3), \fBBIO_connect\fR\|(3),
  211. \&\fBBIO_closesocket\fR\|(3), \fBBIO_ADDRINFO_next\fR\|(3), \fBBIO_ADDRINFO_address\fR\|(3),
  212. \&\fBBIO_ADDRINFO_free\fR\|(3) and \fBBIO_ADDR_dup\fR\|(3) for further information on the
  213. functions used here. In the above example code the \fBhostname\fR and \fBport\fR
  214. variables are strings, e.g. "www.example.com" and "443".
  215. .PP
  216. As for our TLS client, once the socket has been created and connected we need to
  217. associate it with a BIO object:
  218. .PP
  219. .Vb 1
  220. \& BIO *bio;
  221. \&
  222. \& /* Create a BIO to wrap the socket */
  223. \& bio = BIO_new(BIO_s_datagram());
  224. \& if (bio == NULL) {
  225. \& BIO_closesocket(sock);
  226. \& return NULL;
  227. \& }
  228. \&
  229. \& /*
  230. \& * Associate the newly created BIO with the underlying socket. By
  231. \& * passing BIO_CLOSE here the socket will be automatically closed when
  232. \& * the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which
  233. \& * case you must close the socket explicitly when it is no longer
  234. \& * needed.
  235. \& */
  236. \& BIO_set_fd(bio, sock, BIO_CLOSE);
  237. .Ve
  238. .PP
  239. Note the use of \fBBIO_s_datagram\fR\|(3) here as opposed to \fBBIO_s_socket\fR\|(3) that
  240. we used for our TLS client. This is again due to the fact that QUIC uses UDP
  241. instead of TCP for its transport layer. See \fBBIO_new\fR\|(3), \fBBIO_s_datagram\fR\|(3)
  242. and \fBBIO_set_fd\fR\|(3) for further information on these functions.
  243. .SS "Setting the server's hostname"
  244. .IX Subsection "Setting the server's hostname"
  245. As in the TLS tutorial we need to set the server's hostname both for SNI (Server
  246. Name Indication) and for certificate validation purposes. The steps for this are
  247. identical to the TLS tutorial and won't be repeated here.
  248. .SS "Setting the ALPN"
  249. .IX Subsection "Setting the ALPN"
  250. ALPN (Application-Layer Protocol Negotiation) is a feature of TLS that enables
  251. the application to negotiate which protocol will be used over the connection.
  252. For example, if you intend to use HTTP/3 over the connection then the ALPN value
  253. for that is "h3" (see
  254. <https://www.iana.org/assignments/tls\-extensiontype\-values/tls\-extensiontype\-values.xml#alpn\-protocol\-ids>).
  255. OpenSSL provides the ability for a client to specify the ALPN to use via the
  256. \&\fBSSL_set_alpn_protos\fR\|(3) function. This is optional for a TLS client and so our
  257. simple client that we developed in \fBossl\-guide\-tls\-client\-block\fR\|(7) did not use
  258. it. However QUIC mandates that the TLS handshake used in establishing a QUIC
  259. connection must use ALPN.
  260. .PP
  261. .Vb 1
  262. \& unsigned char alpn[] = { 8, \*(Aqh\*(Aq, \*(Aqt\*(Aq, \*(Aqt\*(Aq, \*(Aqp\*(Aq, \*(Aq/\*(Aq, \*(Aq1\*(Aq, \*(Aq.\*(Aq, \*(Aq0\*(Aq };
  263. \&
  264. \& /* SSL_set_alpn_protos returns 0 for success! */
  265. \& if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn)) != 0) {
  266. \& printf("Failed to set the ALPN for the connection\en");
  267. \& goto end;
  268. \& }
  269. .Ve
  270. .PP
  271. The ALPN is specified using a length prefixed array of unsigned chars (it is not
  272. a NUL terminated string). Our original TLS blocking client demo was using
  273. HTTP/1.0. We will use the same for this example. Unlike most OpenSSL functions
  274. \&\fBSSL_set_alpn_protos\fR\|(3) returns zero for success and nonzero for failure.
  275. .SS "Setting the peer address"
  276. .IX Subsection "Setting the peer address"
  277. An OpenSSL QUIC application must specify the target address of the server that
  278. is being connected to. In "Creating the socket and BIO" above we saved that
  279. address away for future use. Now we need to use it via the
  280. \&\fBSSL_set1_initial_peer_addr\fR\|(3) function.
  281. .PP
  282. .Vb 5
  283. \& /* Set the IP address of the remote peer */
  284. \& if (!SSL_set1_initial_peer_addr(ssl, peer_addr)) {
  285. \& printf("Failed to set the initial peer address\en");
  286. \& goto end;
  287. \& }
  288. .Ve
  289. .PP
  290. Note that we will need to free the \fBpeer_addr\fR value that we allocated via
  291. \&\fBBIO_ADDR_dup\fR\|(3) earlier:
  292. .PP
  293. .Vb 1
  294. \& BIO_ADDR_free(peer_addr);
  295. .Ve
  296. .SS "The handshake and application data transfer"
  297. .IX Subsection "The handshake and application data transfer"
  298. Once initial setup of the \fBSSL\fR object is complete then we perform the
  299. handshake via \fBSSL_connect\fR\|(3) in exactly the same way as we did for the TLS
  300. client, so we won't repeat it here.
  301. .PP
  302. We can also perform data transfer using a default QUIC stream that is
  303. automatically associated with the \fBSSL\fR object for us. We can transmit data
  304. using \fBSSL_write_ex\fR\|(3), and receive data using \fBSSL_read_ex\fR\|(3) in the same
  305. way as for TLS. The main difference is that we have to account for failures
  306. slightly differently. With QUIC the stream can be reset by the peer (which is
  307. fatal for that stream), but the underlying connection itself may still be
  308. healthy.
  309. .PP
  310. .Vb 10
  311. \& /*
  312. \& * Get up to sizeof(buf) bytes of the response. We keep reading until the
  313. \& * server closes the connection.
  314. \& */
  315. \& while (SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) {
  316. \& /*
  317. \& * OpenSSL does not guarantee that the returned data is a string or
  318. \& * that it is NUL terminated so we use fwrite() to write the exact
  319. \& * number of bytes that we read. The data could be non\-printable or
  320. \& * have NUL characters in the middle of it. For this simple example
  321. \& * we\*(Aqre going to print it to stdout anyway.
  322. \& */
  323. \& fwrite(buf, 1, readbytes, stdout);
  324. \& }
  325. \& /* In case the response didn\*(Aqt finish with a newline we add one now */
  326. \& printf("\en");
  327. \&
  328. \& /*
  329. \& * Check whether we finished the while loop above normally or as the
  330. \& * result of an error. The 0 argument to SSL_get_error() is the return
  331. \& * code we received from the SSL_read_ex() call. It must be 0 in order
  332. \& * to get here. Normal completion is indicated by SSL_ERROR_ZERO_RETURN. In
  333. \& * QUIC terms this means that the peer has sent FIN on the stream to
  334. \& * indicate that no further data will be sent.
  335. \& */
  336. \& switch (SSL_get_error(ssl, 0)) {
  337. \& case SSL_ERROR_ZERO_RETURN:
  338. \& /* Normal completion of the stream */
  339. \& break;
  340. \&
  341. \& case SSL_ERROR_SSL:
  342. \& /*
  343. \& * Some stream fatal error occurred. This could be because of a stream
  344. \& * reset \- or some failure occurred on the underlying connection.
  345. \& */
  346. \& switch (SSL_get_stream_read_state(ssl)) {
  347. \& case SSL_STREAM_STATE_RESET_REMOTE:
  348. \& printf("Stream reset occurred\en");
  349. \& /* The stream has been reset but the connection is still healthy. */
  350. \& break;
  351. \&
  352. \& case SSL_STREAM_STATE_CONN_CLOSED:
  353. \& printf("Connection closed\en");
  354. \& /* Connection is already closed. Skip SSL_shutdown() */
  355. \& goto end;
  356. \&
  357. \& default:
  358. \& printf("Unknown stream failure\en");
  359. \& break;
  360. \& }
  361. \& break;
  362. \&
  363. \& default:
  364. \& /* Some other unexpected error occurred */
  365. \& printf ("Failed reading remaining data\en");
  366. \& break;
  367. \& }
  368. .Ve
  369. .PP
  370. In the above code example you can see that \fBSSL_ERROR_SSL\fR indicates a stream
  371. fatal error. We can use \fBSSL_get_stream_read_state\fR\|(3) to determine whether the
  372. stream has been reset, or if some other fatal error has occurred.
  373. .SS "Shutting down the connection"
  374. .IX Subsection "Shutting down the connection"
  375. In the TLS tutorial we knew that the server had finished sending data because
  376. \&\fBSSL_read_ex\fR\|(3) returned 0, and \fBSSL_get_error\fR\|(3) returned
  377. \&\fBSSL_ERROR_ZERO_RETURN\fR. The same is true with QUIC except that
  378. \&\fBSSL_ERROR_ZERO_RETURN\fR should be interpreted slightly differently. With TLS
  379. we knew that this meant that the server had sent a "close_notify" alert. No
  380. more data will be sent from the server on that connection.
  381. .PP
  382. With QUIC it means that the server has indicated "FIN" on the stream, meaning
  383. that it will no longer send any more data on that stream. However this only
  384. gives us information about the stream itself and does not tell us anything about
  385. the underlying connection. More data could still be sent from the server on some
  386. other stream. Additionally, although the server will not send any more data to
  387. the client, it does not prevent the client from sending more data to the server.
  388. .PP
  389. In this tutorial, once we have finished reading data from the server on the one
  390. stream that we are using, we will close the connection down. As before we do
  391. this via the \fBSSL_shutdown\fR\|(3) function. This example for QUIC is very similar
  392. to the TLS version. However the \fBSSL_shutdown\fR\|(3) function will need to be
  393. called more than once:
  394. .PP
  395. .Vb 11
  396. \& /*
  397. \& * Repeatedly call SSL_shutdown() until the connection is fully
  398. \& * closed.
  399. \& */
  400. \& do {
  401. \& ret = SSL_shutdown(ssl);
  402. \& if (ret < 0) {
  403. \& printf("Error shutting down: %d\en", ret);
  404. \& goto end;
  405. \& }
  406. \& } while (ret != 1);
  407. .Ve
  408. .PP
  409. The shutdown process is in two stages. In the first stage we wait until all the
  410. data we have buffered for sending on any stream has been successfully sent and
  411. acknowledged by the peer, and then we send a CONNECTION_CLOSE to the peer to
  412. indicate that the connection is no longer usable. This immediately closes the
  413. connection and no more data can be sent or received. \fBSSL_shutdown\fR\|(3) returns
  414. 0 once the first stage has been completed.
  415. .PP
  416. In the second stage the connection enters a "closing" state. Application data
  417. cannot be sent or received in this state, but late arriving packets coming from
  418. the peer will be handled appropriately. Once this stage has completed
  419. successfully \fBSSL_shutdown\fR\|(3) will return 1 to indicate success.
  420. .SH "FURTHER READING"
  421. .IX Header "FURTHER READING"
  422. See \fBossl\-guide\-quic\-multi\-stream\fR\|(7) to read a tutorial on how to modify the
  423. client developed on this page to support multiple streams.
  424. .SH "SEE ALSO"
  425. .IX Header "SEE ALSO"
  426. \&\fBossl\-guide\-introduction\fR\|(7), \fBossl\-guide\-libraries\-introduction\fR\|(7),
  427. \&\fBossl\-guide\-libssl\-introduction\fR\|(7), \fBossl\-guide\-tls\-introduction\fR\|(7),
  428. \&\fBossl\-guide\-tls\-client\-block\fR\|(7), \fBossl\-guide\-quic\-introduction\fR\|(7)
  429. .SH COPYRIGHT
  430. .IX Header "COPYRIGHT"
  431. Copyright 2023 The OpenSSL Project Authors. All Rights Reserved.
  432. .PP
  433. Licensed under the Apache License 2.0 (the "License"). You may not use
  434. this file except in compliance with the License. You can obtain a copy
  435. in the file LICENSE in the source distribution or at
  436. <https://www.openssl.org/source/license.html>.