1
0

tls-server-block.c 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. /*
  2. * Copyright 2024 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-server-block.pod
  12. */
  13. #include <string.h>
  14. /* Include the appropriate header file for SOCK_STREAM */
  15. #ifdef _WIN32 /* Windows */
  16. # include <stdarg.h>
  17. # include <winsock2.h>
  18. #else /* Linux/Unix */
  19. # include <err.h>
  20. # include <sys/socket.h>
  21. # include <sys/select.h>
  22. #endif
  23. #include <openssl/bio.h>
  24. #include <openssl/ssl.h>
  25. #include <openssl/err.h>
  26. static const char cache_id[] = "OpenSSL Demo Server";
  27. #ifdef _WIN32
  28. static const char *progname;
  29. static void vwarnx(const char *fmt, va_list ap)
  30. {
  31. if (progname != NULL)
  32. fprintf(stderr, "%s: ", progname);
  33. vfprintf(stderr, fmt, ap);
  34. putc('\n', stderr);
  35. }
  36. static void errx(int status, const char *fmt, ...)
  37. {
  38. va_list ap;
  39. va_start(ap, fmt);
  40. vwarnx(fmt, ap);
  41. va_end(ap);
  42. exit(status);
  43. }
  44. static void warnx(const char *fmt, ...)
  45. {
  46. va_list ap;
  47. va_start(ap, fmt);
  48. vwarnx(fmt, ap);
  49. va_end(ap);
  50. }
  51. #endif
  52. /* Minimal TLS echo server. */
  53. int main(int argc, char *argv[])
  54. {
  55. int res = EXIT_FAILURE;
  56. long opts;
  57. const char *hostport;
  58. SSL_CTX *ctx = NULL;
  59. BIO *acceptor_bio;
  60. #ifdef _WIN32
  61. progname = argv[0];
  62. #endif
  63. if (argc != 2)
  64. errx(res, "Usage: %s [host:]port", argv[0]);
  65. hostport = argv[1];
  66. /*
  67. * An SSL_CTX holds shared configuration information for multiple
  68. * subsequent per-client SSL connections.
  69. */
  70. ctx = SSL_CTX_new(TLS_server_method());
  71. if (ctx == NULL) {
  72. ERR_print_errors_fp(stderr);
  73. errx(res, "Failed to create server SSL_CTX");
  74. }
  75. /*
  76. * TLS versions older than TLS 1.2 are deprecated by IETF and SHOULD
  77. * be avoided if possible.
  78. */
  79. if (!SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION)) {
  80. SSL_CTX_free(ctx);
  81. ERR_print_errors_fp(stderr);
  82. errx(res, "Failed to set the minimum TLS protocol version");
  83. }
  84. #if 0
  85. /*
  86. * In applications (e.g. SMTP) where most clients are performing
  87. * unauthenticated opportunistic TLS it may make sense to set the security
  88. * level to 0, allowing weaker encryption parameters, which are still
  89. * stronger than a potential cleartext fallback.
  90. *
  91. * The default security level is 2 (as of OpenSSL 3.2), which is roughly
  92. * equivalent to that of 112 bit symmetric keys, or 2048-bit RSA or
  93. * finite-field Diffie-Hellman keys. Notably, non-zero security levels no
  94. * longer allow the use of SHA-1 in certificate signatures, key exchange
  95. * or in the TLS 1.[01] PRF (so TLS 1.0 and 1.1 require security level 0).
  96. */
  97. SSL_CTX_set_security_level(ctx, 0);
  98. #endif
  99. /*
  100. * Tolerate clients hanging up without a TLS "shutdown". Appropriate in all
  101. * application protocols which perform their own message "framing", and
  102. * don't rely on TLS to defend against "truncation" attacks.
  103. */
  104. opts = SSL_OP_IGNORE_UNEXPECTED_EOF;
  105. /*
  106. * Block potential CPU-exhaustion attacks by clients that request frequent
  107. * renegotiation. This is of course only effective if there are existing
  108. * limits on initial full TLS handshake or connection rates.
  109. */
  110. opts |= SSL_OP_NO_RENEGOTIATION;
  111. /*
  112. * Most servers elect to use their own cipher preference rather than that of
  113. * the client.
  114. */
  115. opts |= SSL_OP_CIPHER_SERVER_PREFERENCE;
  116. /* Apply the selection options */
  117. SSL_CTX_set_options(ctx, opts);
  118. /*
  119. * Load the server's certificate *chain* file (PEM format), which includes
  120. * not only the leaf (end-entity) server certificate, but also any
  121. * intermediate issuer-CA certificates. The leaf certificate must be the
  122. * first certificate in the file.
  123. *
  124. * In advanced use-cases this can be called multiple times, once per public
  125. * key algorithm for which the server has a corresponding certificate.
  126. * However, the corresponding private key (see below) must be loaded first,
  127. * *before* moving on to the next chain file.
  128. *
  129. * The requisite files "chain.pem" and "pkey.pem" can be generated by running
  130. * "make chain" in this directory. If the server will be executed from some
  131. * other directory, move or copy the files there.
  132. */
  133. if (SSL_CTX_use_certificate_chain_file(ctx, "chain.pem") <= 0) {
  134. SSL_CTX_free(ctx);
  135. ERR_print_errors_fp(stderr);
  136. errx(res, "Failed to load the server certificate chain file");
  137. }
  138. /*
  139. * Load the corresponding private key, this also checks that the private
  140. * key matches the just loaded end-entity certificate. It does not check
  141. * whether the certificate chain is valid, the certificates could be
  142. * expired, or may otherwise fail to form a chain that a client can validate.
  143. */
  144. if (SSL_CTX_use_PrivateKey_file(ctx, "pkey.pem", SSL_FILETYPE_PEM) <= 0) {
  145. SSL_CTX_free(ctx);
  146. ERR_print_errors_fp(stderr);
  147. errx(res, "Error loading the server private key file, "
  148. "possible key/cert mismatch???");
  149. }
  150. /*
  151. * Servers that want to enable session resumption must specify a cache id
  152. * byte array, that identifies the server application, and reduces the
  153. * chance of inappropriate cache sharing.
  154. */
  155. SSL_CTX_set_session_id_context(ctx, (void *)cache_id, sizeof(cache_id));
  156. SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER);
  157. /*
  158. * How many client TLS sessions to cache. The default is
  159. * SSL_SESSION_CACHE_MAX_SIZE_DEFAULT (20k in recent OpenSSL versions),
  160. * which may be too small or too large.
  161. */
  162. SSL_CTX_sess_set_cache_size(ctx, 1024);
  163. /*
  164. * Sessions older than this are considered a cache miss even if still in
  165. * the cache. The default is two hours. Busy servers whose clients make
  166. * many connections in a short burst may want a shorter timeout, on lightly
  167. * loaded servers with sporadic connections from any given client, a longer
  168. * time may be appropriate.
  169. */
  170. SSL_CTX_set_timeout(ctx, 3600);
  171. /*
  172. * Clients rarely employ certificate-based authentication, and so we don't
  173. * require "mutual" TLS authentication (indeed there's no way to know
  174. * whether or how the client authenticated the server, so the term "mutual"
  175. * is potentially misleading).
  176. *
  177. * Since we're not soliciting or processing client certificates, we don't
  178. * need to configure a trusted-certificate store, so no call to
  179. * SSL_CTX_set_default_verify_paths() is needed. The server's own
  180. * certificate chain is assumed valid.
  181. */
  182. SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
  183. /*
  184. * Create a listener socket wrapped in a BIO.
  185. * The first call to BIO_do_accept() initialises the socket
  186. */
  187. acceptor_bio = BIO_new_accept(hostport);
  188. if (acceptor_bio == NULL) {
  189. SSL_CTX_free(ctx);
  190. ERR_print_errors_fp(stderr);
  191. errx(res, "Error creating acceptor bio");
  192. }
  193. BIO_set_bind_mode(acceptor_bio, BIO_BIND_REUSEADDR);
  194. if (BIO_do_accept(acceptor_bio) <= 0) {
  195. SSL_CTX_free(ctx);
  196. ERR_print_errors_fp(stderr);
  197. errx(res, "Error setting up acceptor socket");
  198. }
  199. /* Wait for incoming connection */
  200. for (;;) {
  201. BIO *client_bio;
  202. SSL *ssl;
  203. unsigned char buf[8192];
  204. size_t nread;
  205. size_t nwritten;
  206. size_t total = 0;
  207. /* Pristine error stack for each new connection */
  208. ERR_clear_error();
  209. /* Wait for the next client to connect */
  210. if (BIO_do_accept(acceptor_bio) <= 0) {
  211. /* Client went away before we accepted the connection */
  212. continue;
  213. }
  214. /* Pop the client connection from the BIO chain */
  215. client_bio = BIO_pop(acceptor_bio);
  216. fprintf(stderr, "New client connection accepted\n");
  217. /* Associate a new SSL handle with the new connection */
  218. if ((ssl = SSL_new(ctx)) == NULL) {
  219. ERR_print_errors_fp(stderr);
  220. warnx("Error creating SSL handle for new connection");
  221. BIO_free(client_bio);
  222. continue;
  223. }
  224. SSL_set_bio(ssl, client_bio, client_bio);
  225. /* Attempt an SSL handshake with the client */
  226. if (SSL_accept(ssl) <= 0) {
  227. ERR_print_errors_fp(stderr);
  228. warnx("Error performing SSL handshake with client");
  229. SSL_free(ssl);
  230. continue;
  231. }
  232. while (SSL_read_ex(ssl, buf, sizeof(buf), &nread) > 0) {
  233. if (SSL_write_ex(ssl, buf, nread, &nwritten) > 0 &&
  234. nwritten == nread) {
  235. total += nwritten;
  236. continue;
  237. }
  238. warnx("Error echoing client input");
  239. break;
  240. }
  241. fprintf(stderr, "Client connection closed, %zu bytes sent\n", total);
  242. SSL_free(ssl);
  243. }
  244. /*
  245. * Unreachable placeholder cleanup code, the above loop runs forever.
  246. */
  247. SSL_CTX_free(ctx);
  248. return EXIT_SUCCESS;
  249. }