openssl-ssl.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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. #include "private-lib-tls-openssl.h"
  26. #include <errno.h>
  27. int openssl_websocket_private_data_index,
  28. openssl_SSL_CTX_private_data_index;
  29. /*
  30. * Care: many openssl apis return 1 for success. These are translated to the
  31. * lws convention of 0 for success.
  32. */
  33. int lws_openssl_describe_cipher(struct lws *wsi)
  34. {
  35. #if !defined(LWS_WITH_NO_LOGS) && !defined(USE_WOLFSSL)
  36. int np = -1;
  37. SSL *s = wsi->tls.ssl;
  38. SSL_get_cipher_bits(s, &np);
  39. lwsl_info("%s: wsi %p: %s, %s, %d bits, %s\n", __func__, wsi,
  40. SSL_get_cipher_name(s), SSL_get_cipher(s), np,
  41. SSL_get_cipher_version(s));
  42. #endif
  43. return 0;
  44. }
  45. int lws_ssl_get_error(struct lws *wsi, int n)
  46. {
  47. int m;
  48. if (!wsi->tls.ssl)
  49. return 99;
  50. m = SSL_get_error(wsi->tls.ssl, n);
  51. lwsl_debug("%s: %p %d -> %d (errno %d)\n", __func__, wsi->tls.ssl, n, m,
  52. errno);
  53. if (m == SSL_ERROR_SSL)
  54. lws_tls_err_describe_clear();
  55. // assert (errno != 9);
  56. return m;
  57. }
  58. #if defined(LWS_WITH_SERVER)
  59. static int
  60. lws_context_init_ssl_pem_passwd_cb(char *buf, int size, int rwflag,
  61. void *userdata)
  62. {
  63. struct lws_context_creation_info * info =
  64. (struct lws_context_creation_info *)userdata;
  65. strncpy(buf, info->ssl_private_key_password, size);
  66. buf[size - 1] = '\0';
  67. return (int)strlen(buf);
  68. }
  69. #endif
  70. #if defined(LWS_WITH_CLIENT)
  71. static int
  72. lws_context_init_ssl_pem_passwd_client_cb(char *buf, int size, int rwflag,
  73. void *userdata)
  74. {
  75. struct lws_context_creation_info * info =
  76. (struct lws_context_creation_info *)userdata;
  77. const char *p = info->ssl_private_key_password;
  78. if (info->client_ssl_private_key_password)
  79. p = info->client_ssl_private_key_password;
  80. strncpy(buf, p, size);
  81. buf[size - 1] = '\0';
  82. return (int)strlen(buf);
  83. }
  84. #endif
  85. void
  86. lws_ssl_bind_passphrase(SSL_CTX *ssl_ctx, int is_client,
  87. const struct lws_context_creation_info *info)
  88. {
  89. if (
  90. #if defined(LWS_WITH_SERVER)
  91. !info->ssl_private_key_password
  92. #endif
  93. #if defined(LWS_WITH_SERVER) && defined(LWS_WITH_CLIENT)
  94. &&
  95. #endif
  96. #if defined(LWS_WITH_CLIENT)
  97. !info->client_ssl_private_key_password
  98. #endif
  99. )
  100. return;
  101. /*
  102. * password provided, set ssl callback and user data
  103. * for checking password which will be trigered during
  104. * SSL_CTX_use_PrivateKey_file function
  105. */
  106. SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, (void *)info);
  107. SSL_CTX_set_default_passwd_cb(ssl_ctx, is_client ?
  108. #if defined(LWS_WITH_CLIENT)
  109. lws_context_init_ssl_pem_passwd_client_cb:
  110. #else
  111. NULL:
  112. #endif
  113. #if defined(LWS_WITH_SERVER)
  114. lws_context_init_ssl_pem_passwd_cb
  115. #else
  116. NULL
  117. #endif
  118. );
  119. }
  120. #if defined(LWS_WITH_CLIENT)
  121. static void
  122. lws_ssl_destroy_client_ctx(struct lws_vhost *vhost)
  123. {
  124. struct lws_tls_client_reuse *tcr;
  125. if (vhost->tls.user_supplied_ssl_ctx || !vhost->tls.ssl_client_ctx)
  126. return;
  127. tcr = SSL_CTX_get_ex_data(vhost->tls.ssl_client_ctx,
  128. openssl_SSL_CTX_private_data_index);
  129. if (!tcr || --tcr->refcount)
  130. return;
  131. SSL_CTX_free(vhost->tls.ssl_client_ctx);
  132. vhost->tls.ssl_client_ctx = NULL;
  133. vhost->context->tls.count_client_contexts--;
  134. lws_dll2_remove(&tcr->cc_list);
  135. lws_free(tcr);
  136. }
  137. #endif
  138. void
  139. lws_ssl_destroy(struct lws_vhost *vhost)
  140. {
  141. if (!lws_check_opt(vhost->context->options,
  142. LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT))
  143. return;
  144. if (vhost->tls.ssl_ctx)
  145. SSL_CTX_free(vhost->tls.ssl_ctx);
  146. #if defined(LWS_WITH_CLIENT)
  147. lws_ssl_destroy_client_ctx(vhost);
  148. #endif
  149. // after 1.1.0 no need
  150. #if (OPENSSL_VERSION_NUMBER < 0x10100000)
  151. // <= 1.0.1f = old api, 1.0.1g+ = new api
  152. #if (OPENSSL_VERSION_NUMBER <= 0x1000106f) || defined(USE_WOLFSSL)
  153. ERR_remove_state(0);
  154. #else
  155. #if OPENSSL_VERSION_NUMBER >= 0x1010005f && \
  156. !defined(LIBRESSL_VERSION_NUMBER) && \
  157. !defined(OPENSSL_IS_BORINGSSL)
  158. ERR_remove_thread_state();
  159. #else
  160. ERR_remove_thread_state(NULL);
  161. #endif
  162. #endif
  163. /* not needed after 1.1.0 */
  164. #if (OPENSSL_VERSION_NUMBER >= 0x10002000) && \
  165. (OPENSSL_VERSION_NUMBER <= 0x10100000)
  166. SSL_COMP_free_compression_methods();
  167. #endif
  168. ERR_free_strings();
  169. EVP_cleanup();
  170. CRYPTO_cleanup_all_ex_data();
  171. #endif
  172. }
  173. int
  174. lws_ssl_capable_read(struct lws *wsi, unsigned char *buf, int len)
  175. {
  176. struct lws_context *context = wsi->a.context;
  177. struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
  178. int n = 0, m;
  179. if (!wsi->tls.ssl)
  180. return lws_ssl_capable_read_no_ssl(wsi, buf, len);
  181. lws_stats_bump(pt, LWSSTATS_C_API_READ, 1);
  182. errno = 0;
  183. ERR_clear_error();
  184. n = SSL_read(wsi->tls.ssl, buf, len);
  185. #if defined(LWS_PLAT_FREERTOS)
  186. if (!n && errno == LWS_ENOTCONN) {
  187. lwsl_debug("%p: SSL_read ENOTCONN\n", wsi);
  188. return LWS_SSL_CAPABLE_ERROR;
  189. }
  190. #endif
  191. #if defined(LWS_WITH_STATS)
  192. if (!wsi->seen_rx && wsi->accept_start_us) {
  193. lws_stats_bump(pt, LWSSTATS_US_SSL_RX_DELAY_AVG,
  194. lws_now_usecs() -
  195. wsi->accept_start_us);
  196. lws_stats_bump(pt, LWSSTATS_C_SSL_CONNS_HAD_RX, 1);
  197. wsi->seen_rx = 1;
  198. }
  199. #endif
  200. lwsl_debug("%p: SSL_read says %d\n", wsi, n);
  201. /* manpage: returning 0 means connection shut down
  202. *
  203. * 2018-09-10: https://github.com/openssl/openssl/issues/1903
  204. *
  205. * So, in summary, if you get a 0 or -1 return from SSL_read() /
  206. * SSL_write(), you should call SSL_get_error():
  207. *
  208. * - If you get back SSL_ERROR_RETURN_ZERO then you know the connection
  209. * has been cleanly shutdown by the peer. To fully close the
  210. * connection you may choose to call SSL_shutdown() to send a
  211. * close_notify back.
  212. *
  213. * - If you get back SSL_ERROR_SSL then some kind of internal or
  214. * protocol error has occurred. More details will be on the SSL error
  215. * queue. You can also call SSL_get_shutdown(). If this indicates a
  216. * state of SSL_RECEIVED_SHUTDOWN then you know a fatal alert has
  217. * been received from the peer (if it had been a close_notify then
  218. * SSL_get_error() would have returned SSL_ERROR_RETURN_ZERO).
  219. * SSL_ERROR_SSL is considered fatal - you should not call
  220. * SSL_shutdown() in this case.
  221. *
  222. * - If you get back SSL_ERROR_SYSCALL then some kind of fatal (i.e.
  223. * non-retryable) error has occurred in a system call.
  224. */
  225. if (n <= 0) {
  226. m = lws_ssl_get_error(wsi, n);
  227. lwsl_debug("%p: ssl err %d errno %d\n", wsi, m, errno);
  228. if (m == SSL_ERROR_ZERO_RETURN) /* cleanly shut down */
  229. return LWS_SSL_CAPABLE_ERROR;
  230. /* hm not retryable.. could be 0 size pkt or error */
  231. if (m == SSL_ERROR_SSL || m == SSL_ERROR_SYSCALL ||
  232. errno == LWS_ENOTCONN) {
  233. /* unclean, eg closed conn */
  234. wsi->socket_is_permanently_unusable = 1;
  235. return LWS_SSL_CAPABLE_ERROR;
  236. }
  237. /* retryable? */
  238. if (SSL_want_read(wsi->tls.ssl)) {
  239. lwsl_debug("%s: WANT_READ\n", __func__);
  240. lwsl_debug("%p: LWS_SSL_CAPABLE_MORE_SERVICE\n", wsi);
  241. return LWS_SSL_CAPABLE_MORE_SERVICE;
  242. }
  243. if (SSL_want_write(wsi->tls.ssl)) {
  244. lwsl_debug("%s: WANT_WRITE\n", __func__);
  245. lwsl_debug("%p: LWS_SSL_CAPABLE_MORE_SERVICE\n", wsi);
  246. return LWS_SSL_CAPABLE_MORE_SERVICE;
  247. }
  248. /* keep on trucking it seems */
  249. }
  250. #if 0
  251. /*
  252. * If using openssl type tls library, this is the earliest point for all
  253. * paths to dump what was received as decrypted data from the tls tunnel
  254. */
  255. lwsl_notice("%s: len %d\n", __func__, n);
  256. lwsl_hexdump_notice(buf, n);
  257. #endif
  258. lws_stats_bump(pt, LWSSTATS_B_READ, n);
  259. #if defined(LWS_WITH_SERVER_STATUS)
  260. if (wsi->a.vhost)
  261. wsi->a.vhost->conn_stats.rx += n;
  262. #endif
  263. #if defined(LWS_WITH_DETAILED_LATENCY)
  264. if (context->detailed_latency_cb) {
  265. wsi->detlat.req_size = len;
  266. wsi->detlat.acc_size = n;
  267. wsi->detlat.type = LDLT_READ;
  268. wsi->detlat.latencies[LAT_DUR_PROXY_RX_TO_ONWARD_TX] =
  269. lws_now_usecs() - pt->ust_left_poll;
  270. wsi->detlat.latencies[LAT_DUR_USERCB] = 0;
  271. lws_det_lat_cb(wsi->a.context, &wsi->detlat);
  272. }
  273. #endif
  274. /*
  275. * if it was our buffer that limited what we read,
  276. * check if SSL has additional data pending inside SSL buffers.
  277. *
  278. * Because these won't signal at the network layer with POLLIN
  279. * and if we don't realize, this data will sit there forever
  280. */
  281. if (n != len)
  282. goto bail;
  283. if (!wsi->tls.ssl)
  284. goto bail;
  285. if (SSL_pending(wsi->tls.ssl)) {
  286. if (lws_dll2_is_detached(&wsi->tls.dll_pending_tls))
  287. lws_dll2_add_head(&wsi->tls.dll_pending_tls,
  288. &pt->tls.dll_pending_tls_owner);
  289. } else
  290. __lws_ssl_remove_wsi_from_buffered_list(wsi);
  291. return n;
  292. bail:
  293. lws_ssl_remove_wsi_from_buffered_list(wsi);
  294. return n;
  295. }
  296. int
  297. lws_ssl_pending(struct lws *wsi)
  298. {
  299. if (!wsi->tls.ssl)
  300. return 0;
  301. return SSL_pending(wsi->tls.ssl);
  302. }
  303. int
  304. lws_ssl_capable_write(struct lws *wsi, unsigned char *buf, int len)
  305. {
  306. int n, m;
  307. #if 0
  308. /*
  309. * If using OpenSSL type tls library, this is the last point for all
  310. * paths before sending data into the tls tunnel, where you can dump it
  311. * and see what is being sent.
  312. */
  313. lwsl_notice("%s: len %d\n", __func__, len);
  314. lwsl_hexdump_notice(buf, len);
  315. #endif
  316. if (!wsi->tls.ssl)
  317. return lws_ssl_capable_write_no_ssl(wsi, buf, len);
  318. errno = 0;
  319. ERR_clear_error();
  320. n = SSL_write(wsi->tls.ssl, buf, len);
  321. if (n > 0)
  322. return n;
  323. m = lws_ssl_get_error(wsi, n);
  324. if (m != SSL_ERROR_SYSCALL) {
  325. if (m == SSL_ERROR_WANT_READ || SSL_want_read(wsi->tls.ssl)) {
  326. lwsl_notice("%s: want read\n", __func__);
  327. return LWS_SSL_CAPABLE_MORE_SERVICE;
  328. }
  329. if (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->tls.ssl)) {
  330. lws_set_blocking_send(wsi);
  331. lwsl_debug("%s: want write\n", __func__);
  332. return LWS_SSL_CAPABLE_MORE_SERVICE;
  333. }
  334. }
  335. lwsl_debug("%s failed: %s\n",__func__, ERR_error_string(m, NULL));
  336. lws_tls_err_describe_clear();
  337. wsi->socket_is_permanently_unusable = 1;
  338. return LWS_SSL_CAPABLE_ERROR;
  339. }
  340. void
  341. lws_ssl_info_callback(const SSL *ssl, int where, int ret)
  342. {
  343. struct lws *wsi;
  344. struct lws_context *context;
  345. struct lws_ssl_info si;
  346. int fd;
  347. #ifndef USE_WOLFSSL
  348. context = (struct lws_context *)SSL_CTX_get_ex_data(
  349. SSL_get_SSL_CTX(ssl),
  350. openssl_SSL_CTX_private_data_index);
  351. #else
  352. context = (struct lws_context *)SSL_CTX_get_ex_data(
  353. SSL_get_SSL_CTX((SSL*) ssl),
  354. openssl_SSL_CTX_private_data_index);
  355. #endif
  356. if (!context)
  357. return;
  358. fd = SSL_get_fd(ssl);
  359. if (fd < 0 || (fd - lws_plat_socket_offset()) < 0)
  360. return;
  361. wsi = wsi_from_fd(context, fd);
  362. if (!wsi)
  363. return;
  364. if (!(where & wsi->a.vhost->tls.ssl_info_event_mask))
  365. return;
  366. si.where = where;
  367. si.ret = ret;
  368. if (user_callback_handle_rxflow(wsi->a.protocol->callback,
  369. wsi, LWS_CALLBACK_SSL_INFO,
  370. wsi->user_space, &si, 0))
  371. lws_set_timeout(wsi, PENDING_TIMEOUT_KILLED_BY_SSL_INFO, -1);
  372. }
  373. int
  374. lws_ssl_close(struct lws *wsi)
  375. {
  376. lws_sockfd_type n;
  377. if (!wsi->tls.ssl)
  378. return 0; /* not handled */
  379. #if defined (LWS_HAVE_SSL_SET_INFO_CALLBACK)
  380. /* kill ssl callbacks, because we will remove the fd from the
  381. * table linking it to the wsi
  382. */
  383. if (wsi->a.vhost->tls.ssl_info_event_mask)
  384. SSL_set_info_callback(wsi->tls.ssl, NULL);
  385. #endif
  386. n = SSL_get_fd(wsi->tls.ssl);
  387. if (!wsi->socket_is_permanently_unusable)
  388. SSL_shutdown(wsi->tls.ssl);
  389. compatible_close(n);
  390. SSL_free(wsi->tls.ssl);
  391. wsi->tls.ssl = NULL;
  392. lws_tls_restrict_return(wsi->a.context);
  393. // lwsl_notice("%s: ssl restr %d, simul %d\n", __func__,
  394. // wsi->a.context->simultaneous_ssl_restriction,
  395. // wsi->a.context->simultaneous_ssl);
  396. return 1; /* handled */
  397. }
  398. void
  399. lws_ssl_SSL_CTX_destroy(struct lws_vhost *vhost)
  400. {
  401. if (vhost->tls.ssl_ctx)
  402. SSL_CTX_free(vhost->tls.ssl_ctx);
  403. #if defined(LWS_WITH_CLIENT)
  404. lws_ssl_destroy_client_ctx(vhost);
  405. #endif
  406. #if defined(LWS_WITH_ACME)
  407. lws_tls_acme_sni_cert_destroy(vhost);
  408. #endif
  409. }
  410. void
  411. lws_ssl_context_destroy(struct lws_context *context)
  412. {
  413. // after 1.1.0 no need
  414. #if (OPENSSL_VERSION_NUMBER < 0x10100000)
  415. // <= 1.0.1f = old api, 1.0.1g+ = new api
  416. #if (OPENSSL_VERSION_NUMBER <= 0x1000106f) || defined(USE_WOLFSSL)
  417. ERR_remove_state(0);
  418. #else
  419. #if OPENSSL_VERSION_NUMBER >= 0x1010005f && \
  420. !defined(LIBRESSL_VERSION_NUMBER) && \
  421. !defined(OPENSSL_IS_BORINGSSL)
  422. ERR_remove_thread_state();
  423. #else
  424. ERR_remove_thread_state(NULL);
  425. #endif
  426. #endif
  427. // after 1.1.0 no need
  428. #if (OPENSSL_VERSION_NUMBER >= 0x10002000) && (OPENSSL_VERSION_NUMBER <= 0x10100000)
  429. SSL_COMP_free_compression_methods();
  430. #endif
  431. ERR_free_strings();
  432. EVP_cleanup();
  433. CRYPTO_cleanup_all_ex_data();
  434. #endif
  435. }
  436. lws_tls_ctx *
  437. lws_tls_ctx_from_wsi(struct lws *wsi)
  438. {
  439. if (!wsi->tls.ssl)
  440. return NULL;
  441. return SSL_get_SSL_CTX(wsi->tls.ssl);
  442. }
  443. enum lws_ssl_capable_status
  444. __lws_tls_shutdown(struct lws *wsi)
  445. {
  446. int n;
  447. errno = 0;
  448. ERR_clear_error();
  449. n = SSL_shutdown(wsi->tls.ssl);
  450. lwsl_debug("SSL_shutdown=%d for fd %d\n", n, wsi->desc.sockfd);
  451. switch (n) {
  452. case 1: /* successful completion */
  453. n = shutdown(wsi->desc.sockfd, SHUT_WR);
  454. return LWS_SSL_CAPABLE_DONE;
  455. case 0: /* needs a retry */
  456. __lws_change_pollfd(wsi, 0, LWS_POLLIN);
  457. return LWS_SSL_CAPABLE_MORE_SERVICE;
  458. default: /* fatal error, or WANT */
  459. n = SSL_get_error(wsi->tls.ssl, n);
  460. if (n != SSL_ERROR_SYSCALL && n != SSL_ERROR_SSL) {
  461. if (SSL_want_read(wsi->tls.ssl)) {
  462. lwsl_debug("(wants read)\n");
  463. __lws_change_pollfd(wsi, 0, LWS_POLLIN);
  464. return LWS_SSL_CAPABLE_MORE_SERVICE_READ;
  465. }
  466. if (SSL_want_write(wsi->tls.ssl)) {
  467. lwsl_debug("(wants write)\n");
  468. __lws_change_pollfd(wsi, 0, LWS_POLLOUT);
  469. return LWS_SSL_CAPABLE_MORE_SERVICE_WRITE;
  470. }
  471. }
  472. return LWS_SSL_CAPABLE_ERROR;
  473. }
  474. }
  475. static int
  476. tops_fake_POLLIN_for_buffered_openssl(struct lws_context_per_thread *pt)
  477. {
  478. return lws_tls_fake_POLLIN_for_buffered(pt);
  479. }
  480. const struct lws_tls_ops tls_ops_openssl = {
  481. /* fake_POLLIN_for_buffered */ tops_fake_POLLIN_for_buffered_openssl,
  482. };