tls-client-block.c 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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-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. #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. {
  26. int sock = -1;
  27. BIO_ADDRINFO *res;
  28. const BIO_ADDRINFO *ai = NULL;
  29. BIO *bio;
  30. /*
  31. * Lookup IP address info for the server.
  32. */
  33. if (!BIO_lookup_ex(hostname, port, BIO_LOOKUP_CLIENT, 0, SOCK_STREAM, 0,
  34. &res))
  35. return NULL;
  36. /*
  37. * Loop through all the possible addresses for the server and find one
  38. * we can connect to.
  39. */
  40. for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {
  41. /*
  42. * Create a TCP socket. We could equally use non-OpenSSL calls such
  43. * as "socket" here for this and the subsequent connect and close
  44. * functions. But for portability reasons and also so that we get
  45. * errors on the OpenSSL stack in the event of a failure we use
  46. * OpenSSL's versions of these functions.
  47. */
  48. sock = BIO_socket(BIO_ADDRINFO_family(ai), SOCK_STREAM, 0, 0);
  49. if (sock == -1)
  50. continue;
  51. /* Connect the socket to the server's address */
  52. if (!BIO_connect(sock, BIO_ADDRINFO_address(ai), BIO_SOCK_NODELAY)) {
  53. BIO_closesocket(sock);
  54. sock = -1;
  55. continue;
  56. }
  57. /* We have a connected socket so break out of the loop */
  58. break;
  59. }
  60. /* Free the address information resources we allocated earlier */
  61. BIO_ADDRINFO_free(res);
  62. /* If sock is -1 then we've been unable to connect to the server */
  63. if (sock == -1)
  64. return NULL;
  65. /* Create a BIO to wrap the socket */
  66. bio = BIO_new(BIO_s_socket());
  67. if (bio == NULL) {
  68. BIO_closesocket(sock);
  69. return NULL;
  70. }
  71. /*
  72. * Associate the newly created BIO with the underlying socket. By
  73. * passing BIO_CLOSE here the socket will be automatically closed when
  74. * the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which
  75. * case you must close the socket explicitly when it is no longer
  76. * needed.
  77. */
  78. BIO_set_fd(bio, sock, BIO_CLOSE);
  79. return bio;
  80. }
  81. /* Server hostname and port details. Must be in quotes */
  82. #ifndef HOSTNAME
  83. # define HOSTNAME "www.example.com"
  84. #endif
  85. #ifndef PORT
  86. # define PORT "443"
  87. #endif
  88. /*
  89. * Simple application to send a basic HTTP/1.0 request to a server and
  90. * print the response on the screen.
  91. */
  92. int main(void)
  93. {
  94. SSL_CTX *ctx = NULL;
  95. SSL *ssl = NULL;
  96. BIO *bio = NULL;
  97. int res = EXIT_FAILURE;
  98. int ret;
  99. const char *request =
  100. "GET / HTTP/1.0\r\nConnection: close\r\nHost: "HOSTNAME"\r\n\r\n";
  101. size_t written, readbytes;
  102. char buf[160];
  103. /*
  104. * Create an SSL_CTX which we can use to create SSL objects from. We
  105. * want an SSL_CTX for creating clients so we use TLS_client_method()
  106. * here.
  107. */
  108. ctx = SSL_CTX_new(TLS_client_method());
  109. if (ctx == NULL) {
  110. printf("Failed to create the SSL_CTX\n");
  111. goto end;
  112. }
  113. /*
  114. * Configure the client to abort the handshake if certificate
  115. * verification fails. Virtually all clients should do this unless you
  116. * really know what you are doing.
  117. */
  118. SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
  119. /* Use the default trusted certificate store */
  120. if (!SSL_CTX_set_default_verify_paths(ctx)) {
  121. printf("Failed to set the default trusted certificate store\n");
  122. goto end;
  123. }
  124. /*
  125. * TLSv1.1 or earlier are deprecated by IETF and are generally to be
  126. * avoided if possible. We require a minimum TLS version of TLSv1.2.
  127. */
  128. if (!SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION)) {
  129. printf("Failed to set the minimum TLS protocol version\n");
  130. goto end;
  131. }
  132. /* Create an SSL object to represent the TLS connection */
  133. ssl = SSL_new(ctx);
  134. if (ssl == NULL) {
  135. printf("Failed to create the SSL object\n");
  136. goto end;
  137. }
  138. /*
  139. * Create the underlying transport socket/BIO and associate it with the
  140. * connection.
  141. */
  142. bio = create_socket_bio(HOSTNAME, PORT);
  143. if (bio == NULL) {
  144. printf("Failed to crete the BIO\n");
  145. goto end;
  146. }
  147. SSL_set_bio(ssl, bio, bio);
  148. /*
  149. * Tell the server during the handshake which hostname we are attempting
  150. * to connect to in case the server supports multiple hosts.
  151. */
  152. if (!SSL_set_tlsext_host_name(ssl, HOSTNAME)) {
  153. printf("Failed to set the SNI hostname\n");
  154. goto end;
  155. }
  156. /*
  157. * Ensure we check during certificate verification that the server has
  158. * supplied a certificate for the hostname that we were expecting.
  159. * Virtually all clients should do this unless you really know what you
  160. * are doing.
  161. */
  162. if (!SSL_set1_host(ssl, HOSTNAME)) {
  163. printf("Failed to set the certificate verification hostname");
  164. goto end;
  165. }
  166. /* Do the handshake with the server */
  167. if (SSL_connect(ssl) < 1) {
  168. printf("Failed to connect to the server\n");
  169. /*
  170. * If the failure is due to a verification error we can get more
  171. * information about it from SSL_get_verify_result().
  172. */
  173. if (SSL_get_verify_result(ssl) != X509_V_OK)
  174. printf("Verify error: %s\n",
  175. X509_verify_cert_error_string(SSL_get_verify_result(ssl)));
  176. goto end;
  177. }
  178. /* Write an HTTP GET request to the peer */
  179. if (!SSL_write_ex(ssl, request, strlen(request), &written)) {
  180. printf("Failed to write HTTP request\n");
  181. goto end;
  182. }
  183. /*
  184. * Get up to sizeof(buf) bytes of the response. We keep reading until the
  185. * server closes the connection.
  186. */
  187. while (SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) {
  188. /*
  189. * OpenSSL does not guarantee that the returned data is a string or
  190. * that it is NUL terminated so we use fwrite() to write the exact
  191. * number of bytes that we read. The data could be non-printable or
  192. * have NUL characters in the middle of it. For this simple example
  193. * we're going to print it to stdout anyway.
  194. */
  195. fwrite(buf, 1, readbytes, stdout);
  196. }
  197. /* In case the response didn't finish with a newline we add one now */
  198. printf("\n");
  199. /*
  200. * Check whether we finished the while loop above normally or as the
  201. * result of an error. The 0 argument to SSL_get_error() is the return
  202. * code we received from the SSL_read_ex() call. It must be 0 in order
  203. * to get here. Normal completion is indicated by SSL_ERROR_ZERO_RETURN.
  204. */
  205. if (SSL_get_error(ssl, 0) != SSL_ERROR_ZERO_RETURN) {
  206. /*
  207. * Some error occurred other than a graceful close down by the
  208. * peer.
  209. */
  210. printf ("Failed reading remaining data\n");
  211. goto end;
  212. }
  213. /*
  214. * The peer already shutdown gracefully (we know this because of the
  215. * SSL_ERROR_ZERO_RETURN above). We should do the same back.
  216. */
  217. ret = SSL_shutdown(ssl);
  218. if (ret < 1) {
  219. /*
  220. * ret < 0 indicates an error. ret == 0 would be unexpected here
  221. * because that means "we've sent a close_notify and we're waiting
  222. * for one back". But we already know we got one from the peer
  223. * because of the SSL_ERROR_ZERO_RETURN above.
  224. */
  225. printf("Error shutting down\n");
  226. goto end;
  227. }
  228. /* Success! */
  229. res = EXIT_SUCCESS;
  230. end:
  231. /*
  232. * If something bad happened then we will dump the contents of the
  233. * OpenSSL error stack to stderr. There might be some useful diagnostic
  234. * information there.
  235. */
  236. if (res == EXIT_FAILURE)
  237. ERR_print_errors_fp(stderr);
  238. /*
  239. * Free the resources we allocated. We do not free the BIO object here
  240. * because ownership of it was immediately transferred to the SSL object
  241. * via SSL_set_bio(). The BIO will be freed when we free the SSL object.
  242. */
  243. SSL_free(ssl);
  244. SSL_CTX_free(ctx);
  245. return res;
  246. }