tls-server.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. /*
  2. * libwebsockets - small server side websockets and web server implementation
  3. *
  4. * Copyright (C) 2010 - 2019 Andy Green <[email protected]>
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to
  8. * deal in the Software without restriction, including without limitation the
  9. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  10. * sell copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  21. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  22. * IN THE SOFTWARE.
  23. */
  24. #include "private-lib-core.h"
  25. #if defined(LWS_WITH_SERVER)
  26. static void
  27. lws_sul_tls_cb(lws_sorted_usec_list_t *sul)
  28. {
  29. struct lws_context_per_thread *pt = lws_container_of(sul,
  30. struct lws_context_per_thread, sul_tls);
  31. lws_tls_check_all_cert_lifetimes(pt->context);
  32. __lws_sul_insert_us(&pt->pt_sul_owner[LWSSULLI_MISS_IF_SUSPENDED],
  33. &pt->sul_tls,
  34. (lws_usec_t)24 * 3600 * LWS_US_PER_SEC);
  35. }
  36. int
  37. lws_context_init_server_ssl(const struct lws_context_creation_info *info,
  38. struct lws_vhost *vhost)
  39. {
  40. struct lws_context *context = vhost->context;
  41. lws_fakewsi_def_plwsa(&vhost->context->pt[0]);
  42. lws_fakewsi_prep_plwsa_ctx(vhost->context);
  43. if (!lws_check_opt(info->options,
  44. LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT)) {
  45. vhost->tls.use_ssl = 0;
  46. return 0;
  47. }
  48. /*
  49. * If he is giving a server cert, take it as a sign he wants to use
  50. * it on this vhost. User code can leave the cert filepath NULL and
  51. * set the LWS_SERVER_OPTION_CREATE_VHOST_SSL_CTX option itself, in
  52. * which case he's expected to set up the cert himself at
  53. * LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS, which
  54. * provides the vhost SSL_CTX * in the user parameter.
  55. */
  56. if (info->ssl_cert_filepath || info->server_ssl_cert_mem)
  57. vhost->options |= LWS_SERVER_OPTION_CREATE_VHOST_SSL_CTX;
  58. if (info->port != CONTEXT_PORT_NO_LISTEN) {
  59. vhost->tls.use_ssl = lws_check_opt(vhost->options,
  60. LWS_SERVER_OPTION_CREATE_VHOST_SSL_CTX);
  61. if (vhost->tls.use_ssl && info->ssl_cipher_list)
  62. lwsl_notice(" SSL ciphers: '%s'\n",
  63. info->ssl_cipher_list);
  64. lwsl_notice(" Vhost '%s' using %sTLS mode\n",
  65. vhost->name, vhost->tls.use_ssl ? "" : "non-");
  66. }
  67. /*
  68. * give him a fake wsi with context + vhost set, so he can use
  69. * lws_get_context() in the callback
  70. */
  71. plwsa->vhost = vhost; /* not a real bound wsi */
  72. /*
  73. * as a server, if we are requiring clients to identify themselves
  74. * then set the backend up for it
  75. */
  76. if (lws_check_opt(info->options,
  77. LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT))
  78. /* Normally SSL listener rejects non-ssl, optionally allow */
  79. vhost->tls.allow_non_ssl_on_ssl_port = 1;
  80. /*
  81. * give user code a chance to load certs into the server
  82. * allowing it to verify incoming client certs
  83. */
  84. if (vhost->tls.use_ssl) {
  85. if (lws_tls_server_vhost_backend_init(info, vhost, (struct lws *)plwsa))
  86. return -1;
  87. lws_tls_server_client_cert_verify_config(vhost);
  88. if (vhost->protocols[0].callback((struct lws *)plwsa,
  89. LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
  90. vhost->tls.ssl_ctx, vhost, 0))
  91. return -1;
  92. }
  93. if (vhost->tls.use_ssl)
  94. lws_context_init_alpn(vhost);
  95. /* check certs once a day */
  96. context->pt[0].sul_tls.cb = lws_sul_tls_cb;
  97. __lws_sul_insert_us(&context->pt[0].pt_sul_owner[LWSSULLI_MISS_IF_SUSPENDED],
  98. &context->pt[0].sul_tls,
  99. (lws_usec_t)24 * 3600 * LWS_US_PER_SEC);
  100. return 0;
  101. }
  102. #endif
  103. int
  104. lws_server_socket_service_ssl(struct lws *wsi, lws_sockfd_type accept_fd, char from_pollin)
  105. {
  106. struct lws_context *context = wsi->a.context;
  107. struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
  108. struct lws_vhost *vh;
  109. int n;
  110. if (!LWS_SSL_ENABLED(wsi->a.vhost))
  111. return 0;
  112. switch (lwsi_state(wsi)) {
  113. case LRS_SSL_INIT:
  114. if (wsi->tls.ssl)
  115. lwsl_err("%s: leaking ssl\n", __func__);
  116. if (accept_fd == LWS_SOCK_INVALID)
  117. assert(0);
  118. if (lws_tls_restrict_borrow(context)) {
  119. lwsl_err("%s: failed on ssl restriction\n", __func__);
  120. return 1;
  121. }
  122. if (lws_tls_server_new_nonblocking(wsi, accept_fd)) {
  123. lwsl_err("%s: failed on lws_tls_server_new_nonblocking\n", __func__);
  124. if (accept_fd != LWS_SOCK_INVALID)
  125. compatible_close(accept_fd);
  126. lws_tls_restrict_return(context);
  127. goto fail;
  128. }
  129. #if defined(LWS_WITH_STATS)
  130. context->updated = 1;
  131. #endif
  132. /*
  133. * we are not accepted yet, but we need to enter ourselves
  134. * as a live connection. That way we can retry when more
  135. * pieces come if we're not sorted yet
  136. */
  137. lwsi_set_state(wsi, LRS_SSL_ACK_PENDING);
  138. lws_pt_lock(pt, __func__);
  139. if (__insert_wsi_socket_into_fds(context, wsi)) {
  140. lwsl_err("%s: failed to insert into fds\n", __func__);
  141. goto fail;
  142. }
  143. lws_pt_unlock(pt);
  144. lws_set_timeout(wsi, PENDING_TIMEOUT_SSL_ACCEPT,
  145. context->timeout_secs);
  146. lwsl_debug("inserted SSL accept into fds, trying SSL_accept\n");
  147. /* fallthru */
  148. case LRS_SSL_ACK_PENDING:
  149. if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
  150. lwsl_err("%s: lws_change_pollfd failed\n", __func__);
  151. goto fail;
  152. }
  153. if (wsi->a.vhost->tls.allow_non_ssl_on_ssl_port && !wsi->skip_fallback) {
  154. /*
  155. * We came here by POLLIN, so there is supposed to be
  156. * something to read...
  157. */
  158. n = recv(wsi->desc.sockfd, (char *)pt->serv_buf,
  159. context->pt_serv_buf_size, MSG_PEEK);
  160. /*
  161. * We have LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT..
  162. * this just means don't hang up on him because of no
  163. * tls hello... what happens next is driven by
  164. * additional option flags:
  165. *
  166. * none: fail the connection
  167. *
  168. * LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS:
  169. * Destroy the TLS, issue a redirect using plaintext
  170. * http (this may not be accepted by a client that
  171. * has visited the site before and received an STS
  172. * header).
  173. *
  174. * LWS_SERVER_OPTION_ALLOW_HTTP_ON_HTTPS_LISTENER:
  175. * Destroy the TLS, continue and serve normally
  176. * using http
  177. *
  178. * LWS_SERVER_OPTION_FALLBACK_TO_APPLY_LISTEN_ACCEPT_CONFIG:
  179. * Destroy the TLS, apply whatever role and protocol
  180. * were told in the vhost info struct
  181. * .listen_accept_role / .listen_accept_protocol and
  182. * continue with that
  183. */
  184. if (n >= 1 && pt->serv_buf[0] >= ' ') {
  185. /*
  186. * TLS content-type for Handshake is 0x16, and
  187. * for ChangeCipherSpec Record, it's 0x14
  188. *
  189. * A non-ssl session will start with the HTTP
  190. * method in ASCII. If we see it's not a legit
  191. * SSL handshake kill the SSL for this
  192. * connection and try to handle as a HTTP
  193. * connection upgrade directly.
  194. */
  195. wsi->tls.use_ssl = 0;
  196. lws_tls_server_abort_connection(wsi);
  197. /*
  198. * care... this creates wsi with no ssl when ssl
  199. * is enabled and normally mandatory
  200. */
  201. wsi->tls.ssl = NULL;
  202. if (lws_check_opt(wsi->a.vhost->options,
  203. LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS)) {
  204. lwsl_info("%s: redirecting from http "
  205. "to https\n", __func__);
  206. wsi->tls.redirect_to_https = 1;
  207. goto notls_accepted;
  208. }
  209. if (lws_check_opt(wsi->a.vhost->options,
  210. LWS_SERVER_OPTION_ALLOW_HTTP_ON_HTTPS_LISTENER)) {
  211. lwsl_info("%s: allowing unencrypted "
  212. "http service on tls port\n",
  213. __func__);
  214. goto notls_accepted;
  215. }
  216. if (lws_check_opt(wsi->a.vhost->options,
  217. LWS_SERVER_OPTION_FALLBACK_TO_APPLY_LISTEN_ACCEPT_CONFIG)) {
  218. if (lws_http_to_fallback(wsi, NULL, 0))
  219. goto fail;
  220. lwsl_info("%s: allowing non-tls "
  221. "fallback\n", __func__);
  222. goto notls_accepted;
  223. }
  224. lwsl_notice("%s: client did not send a valid "
  225. "tls hello (default vhost %s)\n",
  226. __func__, wsi->a.vhost->name);
  227. goto fail;
  228. }
  229. if (!n) {
  230. /*
  231. * POLLIN but nothing to read is supposed to
  232. * mean the connection is gone, we should
  233. * fail out...
  234. *
  235. */
  236. lwsl_debug("%s: PEEKed 0 (from_pollin %d)\n",
  237. __func__, from_pollin);
  238. if (!from_pollin)
  239. /*
  240. * If this wasn't actually info from a
  241. * pollin let it go around again until
  242. * either data came or we still get told
  243. * zero length peek AND POLLIN
  244. */
  245. goto punt;
  246. /*
  247. * treat as remote closed
  248. */
  249. goto fail;
  250. }
  251. if (n < 0 && (LWS_ERRNO == LWS_EAGAIN ||
  252. LWS_ERRNO == LWS_EWOULDBLOCK)) {
  253. punt:
  254. /*
  255. * well, we get no way to know ssl or not
  256. * so go around again waiting for something
  257. * to come and give us a hint, or timeout the
  258. * connection.
  259. */
  260. if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
  261. lwsl_err("%s: change_pollfd failed\n",
  262. __func__);
  263. return -1;
  264. }
  265. lwsl_info("SSL_ERROR_WANT_READ\n");
  266. return 0;
  267. }
  268. }
  269. /* normal SSL connection processing path */
  270. #if defined(LWS_WITH_STATS)
  271. /* only set this the first time around */
  272. if (!wsi->accept_start_us)
  273. wsi->accept_start_us = lws_now_usecs();
  274. #endif
  275. errno = 0;
  276. lws_stats_bump(pt, LWSSTATS_C_SSL_ACCEPT_SPIN, 1);
  277. n = lws_tls_server_accept(wsi);
  278. lwsl_info("SSL_accept says %d\n", n);
  279. switch (n) {
  280. case LWS_SSL_CAPABLE_DONE:
  281. break;
  282. case LWS_SSL_CAPABLE_ERROR:
  283. lws_stats_bump(pt, LWSSTATS_C_SSL_CONNECTIONS_FAILED, 1);
  284. lwsl_info("%s: SSL_accept failed socket %u: %d\n",
  285. __func__, wsi->desc.sockfd, n);
  286. wsi->socket_is_permanently_unusable = 1;
  287. goto fail;
  288. default: /* MORE_SERVICE */
  289. return 0;
  290. }
  291. lws_stats_bump(pt, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED, 1);
  292. #if defined(LWS_WITH_STATS)
  293. if (wsi->accept_start_us)
  294. lws_stats_bump(pt,
  295. LWSSTATS_US_SSL_ACCEPT_LATENCY_AVG,
  296. lws_now_usecs() -
  297. wsi->accept_start_us);
  298. wsi->accept_start_us = lws_now_usecs();
  299. #endif
  300. #if defined(LWS_WITH_DETAILED_LATENCY)
  301. if (context->detailed_latency_cb) {
  302. wsi->detlat.type = LDLT_TLS_NEG_SERVER;
  303. wsi->detlat.latencies[LAT_DUR_PROXY_RX_TO_ONWARD_TX] =
  304. lws_now_usecs() -
  305. wsi->detlat.earliest_write_req_pre_write;
  306. wsi->detlat.latencies[LAT_DUR_USERCB] = 0;
  307. lws_det_lat_cb(wsi->a.context, &wsi->detlat);
  308. }
  309. #endif
  310. /* adapt our vhost to match the SNI SSL_CTX that was chosen */
  311. vh = context->vhost_list;
  312. while (vh) {
  313. if (!vh->being_destroyed && wsi->tls.ssl &&
  314. vh->tls.ssl_ctx == lws_tls_ctx_from_wsi(wsi)) {
  315. lwsl_info("setting wsi to vh %s\n", vh->name);
  316. lws_vhost_bind_wsi(vh, wsi);
  317. break;
  318. }
  319. vh = vh->vhost_next;
  320. }
  321. /* OK, we are accepted... give him some time to negotiate */
  322. lws_set_timeout(wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
  323. context->timeout_secs);
  324. lwsi_set_state(wsi, LRS_ESTABLISHED);
  325. if (lws_tls_server_conn_alpn(wsi)) {
  326. lwsl_warn("%s: fail on alpn\n", __func__);
  327. goto fail;
  328. }
  329. lwsl_debug("accepted new SSL conn\n");
  330. break;
  331. default:
  332. break;
  333. }
  334. return 0;
  335. notls_accepted:
  336. lwsi_set_state(wsi, LRS_ESTABLISHED);
  337. return 0;
  338. fail:
  339. return 1;
  340. }