2
0

tls-client-non-block.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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-tls-client-non-block.pod
  12. */
  13. #include <string.h>
  14. /* Include the appropriate header file for SOCK_STREAM */
  15. #ifdef _WIN32 /* Windows */
  16. # include <winsock2.h>
  17. #else /* Linux/Unix */
  18. # include <sys/socket.h>
  19. # include <sys/select.h>
  20. #endif
  21. #include <openssl/bio.h>
  22. #include <openssl/ssl.h>
  23. #include <openssl/err.h>
  24. /* Helper function to create a BIO connected to the server */
  25. static BIO *create_socket_bio(const char *hostname, const char *port, int family)
  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_STREAM, 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 TCP 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_STREAM, 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), BIO_SOCK_NODELAY)) {
  54. BIO_closesocket(sock);
  55. sock = -1;
  56. continue;
  57. }
  58. /* Set to nonblocking mode */
  59. if (!BIO_socket_nbio(sock, 1)) {
  60. sock = -1;
  61. continue;
  62. }
  63. /* We have a connected socket so break out of the loop */
  64. break;
  65. }
  66. /* Free the address information resources we allocated earlier */
  67. BIO_ADDRINFO_free(res);
  68. /* If sock is -1 then we've been unable to connect to the server */
  69. if (sock == -1)
  70. return NULL;
  71. /* Create a BIO to wrap the socket */
  72. bio = BIO_new(BIO_s_socket());
  73. if (bio == NULL) {
  74. BIO_closesocket(sock);
  75. return NULL;
  76. }
  77. /*
  78. * Associate the newly created BIO with the underlying socket. By
  79. * passing BIO_CLOSE here the socket will be automatically closed when
  80. * the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which
  81. * case you must close the socket explicitly when it is no longer
  82. * needed.
  83. */
  84. BIO_set_fd(bio, sock, BIO_CLOSE);
  85. return bio;
  86. }
  87. static void wait_for_activity(SSL *ssl, int write)
  88. {
  89. fd_set fds;
  90. int width, sock;
  91. /* Get hold of the underlying file descriptor for the socket */
  92. sock = SSL_get_fd(ssl);
  93. FD_ZERO(&fds);
  94. FD_SET(sock, &fds);
  95. width = sock + 1;
  96. /*
  97. * Wait until the socket is writeable or readable. We use select here
  98. * for the sake of simplicity and portability, but you could equally use
  99. * poll/epoll or similar functions
  100. *
  101. * NOTE: For the purposes of this demonstration code this effectively
  102. * makes this demo block until it has something more useful to do. In a
  103. * real application you probably want to go and do other work here (e.g.
  104. * update a GUI, or service other connections).
  105. *
  106. * Let's say for example that you want to update the progress counter on
  107. * a GUI every 100ms. One way to do that would be to add a 100ms timeout
  108. * in the last parameter to "select" below. Then, when select returns,
  109. * you check if it did so because of activity on the file descriptors or
  110. * because of the timeout. If it is due to the timeout then update the
  111. * GUI and then restart the "select".
  112. */
  113. if (write)
  114. select(width, NULL, &fds, NULL, NULL);
  115. else
  116. select(width, &fds, NULL, NULL, NULL);
  117. }
  118. static int handle_io_failure(SSL *ssl, int res)
  119. {
  120. switch (SSL_get_error(ssl, res)) {
  121. case SSL_ERROR_WANT_READ:
  122. /* Temporary failure. Wait until we can read and try again */
  123. wait_for_activity(ssl, 0);
  124. return 1;
  125. case SSL_ERROR_WANT_WRITE:
  126. /* Temporary failure. Wait until we can write and try again */
  127. wait_for_activity(ssl, 1);
  128. return 1;
  129. case SSL_ERROR_ZERO_RETURN:
  130. /* EOF */
  131. return 0;
  132. case SSL_ERROR_SYSCALL:
  133. return -1;
  134. case SSL_ERROR_SSL:
  135. /*
  136. * If the failure is due to a verification error we can get more
  137. * information about it from SSL_get_verify_result().
  138. */
  139. if (SSL_get_verify_result(ssl) != X509_V_OK)
  140. printf("Verify error: %s\n",
  141. X509_verify_cert_error_string(SSL_get_verify_result(ssl)));
  142. return -1;
  143. default:
  144. return -1;
  145. }
  146. }
  147. /*
  148. * Simple application to send a basic HTTP/1.0 request to a server and
  149. * print the response on the screen.
  150. */
  151. int main(int argc, char *argv[])
  152. {
  153. SSL_CTX *ctx = NULL;
  154. SSL *ssl = NULL;
  155. BIO *bio = NULL;
  156. int res = EXIT_FAILURE;
  157. int ret;
  158. const char *request_start = "GET / HTTP/1.0\r\nConnection: close\r\nHost: ";
  159. const char *request_end = "\r\n\r\n";
  160. size_t written, readbytes = 0;
  161. char buf[160];
  162. int eof = 0;
  163. char *hostname, *port;
  164. int argnext = 1;
  165. int ipv6 = 0;
  166. if (argc < 3) {
  167. printf("Usage: tls-client-non-block [-6] hostname port\n");
  168. goto end;
  169. }
  170. if (!strcmp(argv[argnext], "-6")) {
  171. if (argc < 4) {
  172. printf("Usage: tls-client-non-block [-6] hostname port\n");
  173. goto end;
  174. }
  175. ipv6 = 1;
  176. argnext++;
  177. }
  178. hostname = argv[argnext++];
  179. port = argv[argnext];
  180. /*
  181. * Create an SSL_CTX which we can use to create SSL objects from. We
  182. * want an SSL_CTX for creating clients so we use TLS_client_method()
  183. * here.
  184. */
  185. ctx = SSL_CTX_new(TLS_client_method());
  186. if (ctx == NULL) {
  187. printf("Failed to create the SSL_CTX\n");
  188. goto end;
  189. }
  190. /*
  191. * Configure the client to abort the handshake if certificate
  192. * verification fails. Virtually all clients should do this unless you
  193. * really know what you are doing.
  194. */
  195. SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
  196. /* Use the default trusted certificate store */
  197. if (!SSL_CTX_set_default_verify_paths(ctx)) {
  198. printf("Failed to set the default trusted certificate store\n");
  199. goto end;
  200. }
  201. /*
  202. * TLSv1.1 or earlier are deprecated by IETF and are generally to be
  203. * avoided if possible. We require a minimum TLS version of TLSv1.2.
  204. */
  205. if (!SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION)) {
  206. printf("Failed to set the minimum TLS protocol version\n");
  207. goto end;
  208. }
  209. /* Create an SSL object to represent the TLS connection */
  210. ssl = SSL_new(ctx);
  211. if (ssl == NULL) {
  212. printf("Failed to create the SSL object\n");
  213. goto end;
  214. }
  215. /*
  216. * Create the underlying transport socket/BIO and associate it with the
  217. * connection.
  218. */
  219. bio = create_socket_bio(hostname, port, ipv6 ? AF_INET6 : AF_INET);
  220. if (bio == NULL) {
  221. printf("Failed to crete the BIO\n");
  222. goto end;
  223. }
  224. SSL_set_bio(ssl, bio, bio);
  225. /*
  226. * Tell the server during the handshake which hostname we are attempting
  227. * to connect to in case the server supports multiple hosts.
  228. */
  229. if (!SSL_set_tlsext_host_name(ssl, hostname)) {
  230. printf("Failed to set the SNI hostname\n");
  231. goto end;
  232. }
  233. /*
  234. * Ensure we check during certificate verification that the server has
  235. * supplied a certificate for the hostname that we were expecting.
  236. * Virtually all clients should do this unless you really know what you
  237. * are doing.
  238. */
  239. if (!SSL_set1_host(ssl, hostname)) {
  240. printf("Failed to set the certificate verification hostname");
  241. goto end;
  242. }
  243. /* Do the handshake with the server */
  244. while ((ret = SSL_connect(ssl)) != 1) {
  245. if (handle_io_failure(ssl, ret) == 1)
  246. continue; /* Retry */
  247. printf("Failed to connect to server\n");
  248. goto end; /* Cannot retry: error */
  249. }
  250. /* Write an HTTP GET request to the peer */
  251. while (!SSL_write_ex(ssl, request_start, strlen(request_start), &written)) {
  252. if (handle_io_failure(ssl, 0) == 1)
  253. continue; /* Retry */
  254. printf("Failed to write start of HTTP request\n");
  255. goto end; /* Cannot retry: error */
  256. }
  257. while (!SSL_write_ex(ssl, hostname, strlen(hostname), &written)) {
  258. if (handle_io_failure(ssl, 0) == 1)
  259. continue; /* Retry */
  260. printf("Failed to write hostname in HTTP request\n");
  261. goto end; /* Cannot retry: error */
  262. }
  263. while (!SSL_write_ex(ssl, request_end, strlen(request_end), &written)) {
  264. if (handle_io_failure(ssl, 0) == 1)
  265. continue; /* Retry */
  266. printf("Failed to write end of HTTP request\n");
  267. goto end; /* Cannot retry: error */
  268. }
  269. do {
  270. /*
  271. * Get up to sizeof(buf) bytes of the response. We keep reading until
  272. * the server closes the connection.
  273. */
  274. while (!eof && !SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) {
  275. switch (handle_io_failure(ssl, 0)) {
  276. case 1:
  277. continue; /* Retry */
  278. case 0:
  279. eof = 1;
  280. continue;
  281. case -1:
  282. default:
  283. printf("Failed reading remaining data\n");
  284. goto end; /* Cannot retry: error */
  285. }
  286. }
  287. /*
  288. * OpenSSL does not guarantee that the returned data is a string or
  289. * that it is NUL terminated so we use fwrite() to write the exact
  290. * number of bytes that we read. The data could be non-printable or
  291. * have NUL characters in the middle of it. For this simple example
  292. * we're going to print it to stdout anyway.
  293. */
  294. if (!eof)
  295. fwrite(buf, 1, readbytes, stdout);
  296. } while (!eof);
  297. /* In case the response didn't finish with a newline we add one now */
  298. printf("\n");
  299. /*
  300. * The peer already shutdown gracefully (we know this because of the
  301. * SSL_ERROR_ZERO_RETURN (i.e. EOF) above). We should do the same back.
  302. */
  303. while ((ret = SSL_shutdown(ssl)) != 1) {
  304. if (ret < 0 && handle_io_failure(ssl, ret) == 1)
  305. continue; /* Retry */
  306. /*
  307. * ret == 0 is unexpected here because that means "we've sent a
  308. * close_notify and we're waiting for one back". But we already know
  309. * we got one from the peer because of the SSL_ERROR_ZERO_RETURN
  310. * (i.e. EOF) above.
  311. */
  312. printf("Error shutting down\n");
  313. goto end; /* Cannot retry: error */
  314. }
  315. /* Success! */
  316. res = EXIT_SUCCESS;
  317. end:
  318. /*
  319. * If something bad happened then we will dump the contents of the
  320. * OpenSSL error stack to stderr. There might be some useful diagnostic
  321. * information there.
  322. */
  323. if (res == EXIT_FAILURE)
  324. ERR_print_errors_fp(stderr);
  325. /*
  326. * Free the resources we allocated. We do not free the BIO object here
  327. * because ownership of it was immediately transferred to the SSL object
  328. * via SSL_set_bio(). The BIO will be freed when we free the SSL object.
  329. */
  330. SSL_free(ssl);
  331. SSL_CTX_free(ctx);
  332. return res;
  333. }