quic-client-block.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. int family, 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, family, 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. /*
  95. * Simple application to send a basic HTTP/1.0 request to a server and
  96. * print the response on the screen. Note that HTTP/1.0 over QUIC is
  97. * non-standard and will not typically be supported by real world servers. This
  98. * is for demonstration purposes only.
  99. */
  100. int main(int argc, char *argv[])
  101. {
  102. SSL_CTX *ctx = NULL;
  103. SSL *ssl = NULL;
  104. BIO *bio = NULL;
  105. int res = EXIT_FAILURE;
  106. int ret;
  107. unsigned char alpn[] = { 8, 'h', 't', 't', 'p', '/', '1', '.', '0' };
  108. const char *request_start = "GET / HTTP/1.0\r\nConnection: close\r\nHost: ";
  109. const char *request_end = "\r\n\r\n";
  110. size_t written, readbytes;
  111. char buf[160];
  112. BIO_ADDR *peer_addr = NULL;
  113. char *hostname, *port;
  114. int argnext = 1;
  115. int ipv6 = 0;
  116. if (argc < 3) {
  117. printf("Usage: quic-client-block [-6] hostname port\n");
  118. goto end;
  119. }
  120. if (!strcmp(argv[argnext], "-6")) {
  121. if (argc < 4) {
  122. printf("Usage: quic-client-block [-6] hostname port\n");
  123. goto end;
  124. }
  125. ipv6 = 1;
  126. argnext++;
  127. }
  128. hostname = argv[argnext++];
  129. port = argv[argnext];
  130. /*
  131. * Create an SSL_CTX which we can use to create SSL objects from. We
  132. * want an SSL_CTX for creating clients so we use
  133. * OSSL_QUIC_client_method() here.
  134. */
  135. ctx = SSL_CTX_new(OSSL_QUIC_client_method());
  136. if (ctx == NULL) {
  137. printf("Failed to create the SSL_CTX\n");
  138. goto end;
  139. }
  140. /*
  141. * Configure the client to abort the handshake if certificate
  142. * verification fails. Virtually all clients should do this unless you
  143. * really know what you are doing.
  144. */
  145. SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
  146. /* Use the default trusted certificate store */
  147. if (!SSL_CTX_set_default_verify_paths(ctx)) {
  148. printf("Failed to set the default trusted certificate store\n");
  149. goto end;
  150. }
  151. /* Create an SSL object to represent the TLS connection */
  152. ssl = SSL_new(ctx);
  153. if (ssl == NULL) {
  154. printf("Failed to create the SSL object\n");
  155. goto end;
  156. }
  157. /*
  158. * Create the underlying transport socket/BIO and associate it with the
  159. * connection.
  160. */
  161. bio = create_socket_bio(hostname, port, ipv6 ? AF_INET6 : AF_INET, &peer_addr);
  162. if (bio == NULL) {
  163. printf("Failed to crete the BIO\n");
  164. goto end;
  165. }
  166. SSL_set_bio(ssl, bio, bio);
  167. /*
  168. * Tell the server during the handshake which hostname we are attempting
  169. * to connect to in case the server supports multiple hosts.
  170. */
  171. if (!SSL_set_tlsext_host_name(ssl, hostname)) {
  172. printf("Failed to set the SNI hostname\n");
  173. goto end;
  174. }
  175. /*
  176. * Ensure we check during certificate verification that the server has
  177. * supplied a certificate for the hostname that we were expecting.
  178. * Virtually all clients should do this unless you really know what you
  179. * are doing.
  180. */
  181. if (!SSL_set1_host(ssl, hostname)) {
  182. printf("Failed to set the certificate verification hostname");
  183. goto end;
  184. }
  185. /* SSL_set_alpn_protos returns 0 for success! */
  186. if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn)) != 0) {
  187. printf("Failed to set the ALPN for the connection\n");
  188. goto end;
  189. }
  190. /* Set the IP address of the remote peer */
  191. if (!SSL_set1_initial_peer_addr(ssl, peer_addr)) {
  192. printf("Failed to set the initial peer address\n");
  193. goto end;
  194. }
  195. /* Do the handshake with the server */
  196. if (SSL_connect(ssl) < 1) {
  197. printf("Failed to connect to the server\n");
  198. /*
  199. * If the failure is due to a verification error we can get more
  200. * information about it from SSL_get_verify_result().
  201. */
  202. if (SSL_get_verify_result(ssl) != X509_V_OK)
  203. printf("Verify error: %s\n",
  204. X509_verify_cert_error_string(SSL_get_verify_result(ssl)));
  205. goto end;
  206. }
  207. /* Write an HTTP GET request to the peer */
  208. if (!SSL_write_ex(ssl, request_start, strlen(request_start), &written)) {
  209. printf("Failed to write start of HTTP request\n");
  210. goto end;
  211. }
  212. if (!SSL_write_ex(ssl, hostname, strlen(hostname), &written)) {
  213. printf("Failed to write hostname in HTTP request\n");
  214. goto end;
  215. }
  216. if (!SSL_write_ex(ssl, request_end, strlen(request_end), &written)) {
  217. printf("Failed to write end of HTTP request\n");
  218. goto end;
  219. }
  220. /*
  221. * Get up to sizeof(buf) bytes of the response. We keep reading until the
  222. * server closes the connection.
  223. */
  224. while (SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) {
  225. /*
  226. * OpenSSL does not guarantee that the returned data is a string or
  227. * that it is NUL terminated so we use fwrite() to write the exact
  228. * number of bytes that we read. The data could be non-printable or
  229. * have NUL characters in the middle of it. For this simple example
  230. * we're going to print it to stdout anyway.
  231. */
  232. fwrite(buf, 1, readbytes, stdout);
  233. }
  234. /* In case the response didn't finish with a newline we add one now */
  235. printf("\n");
  236. /*
  237. * Check whether we finished the while loop above normally or as the
  238. * result of an error. The 0 argument to SSL_get_error() is the return
  239. * code we received from the SSL_read_ex() call. It must be 0 in order
  240. * to get here. Normal completion is indicated by SSL_ERROR_ZERO_RETURN. In
  241. * QUIC terms this means that the peer has sent FIN on the stream to
  242. * indicate that no further data will be sent.
  243. */
  244. switch (SSL_get_error(ssl, 0)) {
  245. case SSL_ERROR_ZERO_RETURN:
  246. /* Normal completion of the stream */
  247. break;
  248. case SSL_ERROR_SSL:
  249. /*
  250. * Some stream fatal error occurred. This could be because of a stream
  251. * reset - or some failure occurred on the underlying connection.
  252. */
  253. switch (SSL_get_stream_read_state(ssl)) {
  254. case SSL_STREAM_STATE_RESET_REMOTE:
  255. printf("Stream reset occurred\n");
  256. /* The stream has been reset but the connection is still healthy. */
  257. break;
  258. case SSL_STREAM_STATE_CONN_CLOSED:
  259. printf("Connection closed\n");
  260. /* Connection is already closed. Skip SSL_shutdown() */
  261. goto end;
  262. default:
  263. printf("Unknown stream failure\n");
  264. break;
  265. }
  266. break;
  267. default:
  268. /* Some other unexpected error occurred */
  269. printf ("Failed reading remaining data\n");
  270. break;
  271. }
  272. /*
  273. * Repeatedly call SSL_shutdown() until the connection is fully
  274. * closed.
  275. */
  276. do {
  277. ret = SSL_shutdown(ssl);
  278. if (ret < 0) {
  279. printf("Error shutting down: %d\n", ret);
  280. goto end;
  281. }
  282. } while (ret != 1);
  283. /* Success! */
  284. res = EXIT_SUCCESS;
  285. end:
  286. /*
  287. * If something bad happened then we will dump the contents of the
  288. * OpenSSL error stack to stderr. There might be some useful diagnostic
  289. * information there.
  290. */
  291. if (res == EXIT_FAILURE)
  292. ERR_print_errors_fp(stderr);
  293. /*
  294. * Free the resources we allocated. We do not free the BIO object here
  295. * because ownership of it was immediately transferred to the SSL object
  296. * via SSL_set_bio(). The BIO will be freed when we free the SSL object.
  297. */
  298. SSL_free(ssl);
  299. SSL_CTX_free(ctx);
  300. BIO_ADDR_free(peer_addr);
  301. return res;
  302. }