quic-client-block.c 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. /*
  2. * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. /*
  10. * NB: Changes to this file should also be reflected in
  11. * doc/man7/ossl-guide-quic-client-block.pod
  12. */
  13. #include <string.h>
  14. /* Include the appropriate header file for SOCK_DGRAM */
  15. #ifdef _WIN32 /* Windows */
  16. # include <winsock2.h>
  17. #else /* Linux/Unix */
  18. # include <sys/socket.h>
  19. #endif
  20. #include <openssl/bio.h>
  21. #include <openssl/ssl.h>
  22. #include <openssl/err.h>
  23. /* Helper function to create a BIO connected to the server */
  24. static BIO *create_socket_bio(const char *hostname, const char *port,
  25. BIO_ADDR **peer_addr)
  26. {
  27. int sock = -1;
  28. BIO_ADDRINFO *res;
  29. const BIO_ADDRINFO *ai = NULL;
  30. BIO *bio;
  31. /*
  32. * Lookup IP address info for the server.
  33. */
  34. if (!BIO_lookup_ex(hostname, port, BIO_LOOKUP_CLIENT, 0, SOCK_DGRAM, 0,
  35. &res))
  36. return NULL;
  37. /*
  38. * Loop through all the possible addresses for the server and find one
  39. * we can connect to.
  40. */
  41. for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {
  42. /*
  43. * Create a UDP socket. We could equally use non-OpenSSL calls such
  44. * as "socket" here for this and the subsequent connect and close
  45. * functions. But for portability reasons and also so that we get
  46. * errors on the OpenSSL stack in the event of a failure we use
  47. * OpenSSL's versions of these functions.
  48. */
  49. sock = BIO_socket(BIO_ADDRINFO_family(ai), SOCK_DGRAM, 0, 0);
  50. if (sock == -1)
  51. continue;
  52. /* Connect the socket to the server's address */
  53. if (!BIO_connect(sock, BIO_ADDRINFO_address(ai), 0)) {
  54. BIO_closesocket(sock);
  55. sock = -1;
  56. continue;
  57. }
  58. /* Set to nonblocking mode */
  59. if (!BIO_socket_nbio(sock, 1)) {
  60. BIO_closesocket(sock);
  61. sock = -1;
  62. continue;
  63. }
  64. break;
  65. }
  66. if (sock != -1) {
  67. *peer_addr = BIO_ADDR_dup(BIO_ADDRINFO_address(ai));
  68. if (*peer_addr == NULL) {
  69. BIO_closesocket(sock);
  70. return NULL;
  71. }
  72. }
  73. /* Free the address information resources we allocated earlier */
  74. BIO_ADDRINFO_free(res);
  75. /* If sock is -1 then we've been unable to connect to the server */
  76. if (sock == -1)
  77. return NULL;
  78. /* Create a BIO to wrap the socket */
  79. bio = BIO_new(BIO_s_datagram());
  80. if (bio == NULL) {
  81. BIO_closesocket(sock);
  82. return NULL;
  83. }
  84. /*
  85. * Associate the newly created BIO with the underlying socket. By
  86. * passing BIO_CLOSE here the socket will be automatically closed when
  87. * the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which
  88. * case you must close the socket explicitly when it is no longer
  89. * needed.
  90. */
  91. BIO_set_fd(bio, sock, BIO_CLOSE);
  92. return bio;
  93. }
  94. /* Server hostname and port details. Must be in quotes */
  95. #ifndef HOSTNAME
  96. # define HOSTNAME "www.example.com"
  97. #endif
  98. #ifndef PORT
  99. # define PORT "443"
  100. #endif
  101. /*
  102. * Simple application to send a basic HTTP/1.0 request to a server and
  103. * print the response on the screen. Note that HTTP/1.0 over QUIC is
  104. * non-standard and will not typically be supported by real world servers. This
  105. * is for demonstration purposes only.
  106. */
  107. int main(void)
  108. {
  109. SSL_CTX *ctx = NULL;
  110. SSL *ssl = NULL;
  111. BIO *bio = NULL;
  112. int res = EXIT_FAILURE;
  113. int ret;
  114. unsigned char alpn[] = { 8, 'h', 't', 't', 'p', '/', '1', '.', '0' };
  115. const char *request =
  116. "GET / HTTP/1.0\r\nConnection: close\r\nHost: "HOSTNAME"\r\n\r\n";
  117. size_t written, readbytes;
  118. char buf[160];
  119. BIO_ADDR *peer_addr = NULL;
  120. /*
  121. * Create an SSL_CTX which we can use to create SSL objects from. We
  122. * want an SSL_CTX for creating clients so we use
  123. * OSSL_QUIC_client_method() here.
  124. */
  125. ctx = SSL_CTX_new(OSSL_QUIC_client_method());
  126. if (ctx == NULL) {
  127. printf("Failed to create the SSL_CTX\n");
  128. goto end;
  129. }
  130. /*
  131. * Configure the client to abort the handshake if certificate
  132. * verification fails. Virtually all clients should do this unless you
  133. * really know what you are doing.
  134. */
  135. SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
  136. /* Use the default trusted certificate store */
  137. if (!SSL_CTX_set_default_verify_paths(ctx)) {
  138. printf("Failed to set the default trusted certificate store\n");
  139. goto end;
  140. }
  141. /* Create an SSL object to represent the TLS connection */
  142. ssl = SSL_new(ctx);
  143. if (ssl == NULL) {
  144. printf("Failed to create the SSL object\n");
  145. goto end;
  146. }
  147. /*
  148. * Create the underlying transport socket/BIO and associate it with the
  149. * connection.
  150. */
  151. bio = create_socket_bio(HOSTNAME, PORT, &peer_addr);
  152. if (bio == NULL) {
  153. printf("Failed to crete the BIO\n");
  154. goto end;
  155. }
  156. SSL_set_bio(ssl, bio, bio);
  157. /*
  158. * Tell the server during the handshake which hostname we are attempting
  159. * to connect to in case the server supports multiple hosts.
  160. */
  161. if (!SSL_set_tlsext_host_name(ssl, HOSTNAME)) {
  162. printf("Failed to set the SNI hostname\n");
  163. goto end;
  164. }
  165. /*
  166. * Ensure we check during certificate verification that the server has
  167. * supplied a certificate for the hostname that we were expecting.
  168. * Virtually all clients should do this unless you really know what you
  169. * are doing.
  170. */
  171. if (!SSL_set1_host(ssl, HOSTNAME)) {
  172. printf("Failed to set the certificate verification hostname");
  173. goto end;
  174. }
  175. /* SSL_set_alpn_protos returns 0 for success! */
  176. if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn)) != 0) {
  177. printf("Failed to set the ALPN for the connection\n");
  178. goto end;
  179. }
  180. /* Set the IP address of the remote peer */
  181. if (!SSL_set1_initial_peer_addr(ssl, peer_addr)) {
  182. printf("Failed to set the initial peer address\n");
  183. goto end;
  184. }
  185. /* Do the handshake with the server */
  186. if (SSL_connect(ssl) < 1) {
  187. printf("Failed to connect to the server\n");
  188. /*
  189. * If the failure is due to a verification error we can get more
  190. * information about it from SSL_get_verify_result().
  191. */
  192. if (SSL_get_verify_result(ssl) != X509_V_OK)
  193. printf("Verify error: %s\n",
  194. X509_verify_cert_error_string(SSL_get_verify_result(ssl)));
  195. goto end;
  196. }
  197. /* Write an HTTP GET request to the peer */
  198. if (!SSL_write_ex(ssl, request, strlen(request), &written)) {
  199. printf("Failed to write HTTP request\n");
  200. goto end;
  201. }
  202. /*
  203. * Get up to sizeof(buf) bytes of the response. We keep reading until the
  204. * server closes the connection.
  205. */
  206. while (SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) {
  207. /*
  208. * OpenSSL does not guarantee that the returned data is a string or
  209. * that it is NUL terminated so we use fwrite() to write the exact
  210. * number of bytes that we read. The data could be non-printable or
  211. * have NUL characters in the middle of it. For this simple example
  212. * we're going to print it to stdout anyway.
  213. */
  214. fwrite(buf, 1, readbytes, stdout);
  215. }
  216. /* In case the response didn't finish with a newline we add one now */
  217. printf("\n");
  218. /*
  219. * Check whether we finished the while loop above normally or as the
  220. * result of an error. The 0 argument to SSL_get_error() is the return
  221. * code we received from the SSL_read_ex() call. It must be 0 in order
  222. * to get here. Normal completion is indicated by SSL_ERROR_ZERO_RETURN. In
  223. * QUIC terms this means that the peer has sent FIN on the stream to
  224. * indicate that no further data will be sent.
  225. */
  226. switch (SSL_get_error(ssl, 0)) {
  227. case SSL_ERROR_ZERO_RETURN:
  228. /* Normal completion of the stream */
  229. break;
  230. case SSL_ERROR_SSL:
  231. /*
  232. * Some stream fatal error occurred. This could be because of a stream
  233. * reset - or some failure occurred on the underlying connection.
  234. */
  235. switch (SSL_get_stream_read_state(ssl)) {
  236. case SSL_STREAM_STATE_RESET_REMOTE:
  237. printf("Stream reset occurred\n");
  238. /* The stream has been reset but the connection is still healthy. */
  239. break;
  240. case SSL_STREAM_STATE_CONN_CLOSED:
  241. printf("Connection closed\n");
  242. /* Connection is already closed. Skip SSL_shutdown() */
  243. goto end;
  244. default:
  245. printf("Unknown stream failure\n");
  246. break;
  247. }
  248. break;
  249. default:
  250. /* Some other unexpected error occurred */
  251. printf ("Failed reading remaining data\n");
  252. break;
  253. }
  254. /*
  255. * Repeatedly call SSL_shutdown() until the connection is fully
  256. * closed.
  257. */
  258. do {
  259. ret = SSL_shutdown(ssl);
  260. if (ret < 0) {
  261. printf("Error shutting down: %d\n", ret);
  262. goto end;
  263. }
  264. } while (ret != 1);
  265. /* Success! */
  266. res = EXIT_SUCCESS;
  267. end:
  268. /*
  269. * If something bad happened then we will dump the contents of the
  270. * OpenSSL error stack to stderr. There might be some useful diagnostic
  271. * information there.
  272. */
  273. if (res == EXIT_FAILURE)
  274. ERR_print_errors_fp(stderr);
  275. /*
  276. * Free the resources we allocated. We do not free the BIO object here
  277. * because ownership of it was immediately transferred to the SSL object
  278. * via SSL_set_bio(). The BIO will be freed when we free the SSL object.
  279. */
  280. SSL_free(ssl);
  281. SSL_CTX_free(ctx);
  282. BIO_ADDR_free(peer_addr);
  283. return res;
  284. }