2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010-2014 Andy Green <andy@warmcat.com>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation:
9 * version 2.1 of the License.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22 #include "private-libwebsockets.h"
24 #include <openssl/err.h>
27 #ifdef LWS_HAVE_OPENSSL_ECDH_H
28 #include <openssl/ecdh.h>
31 int openssl_websocket_private_data_index;
34 lws_context_init_ssl_pem_passwd_cb(char * buf, int size, int rwflag, void *userdata)
36 struct lws_context_creation_info * info =
37 (struct lws_context_creation_info *)userdata;
39 strncpy(buf, info->ssl_private_key_password, size);
45 static void lws_ssl_bind_passphrase(SSL_CTX *ssl_ctx, struct lws_context_creation_info *info)
47 if (!info->ssl_private_key_password)
50 * password provided, set ssl callback and user data
51 * for checking password which will be trigered during
52 * SSL_CTX_use_PrivateKey_file function
54 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, (void *)info);
55 SSL_CTX_set_default_passwd_cb(ssl_ctx, lws_context_init_ssl_pem_passwd_cb);
60 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
64 struct lws_context *context;
67 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
68 SSL_get_ex_data_X509_STORE_CTX_idx());
71 * !!! nasty openssl requires the index to come as a library-scope
74 context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
77 * give him a fake wsi with context set, so he can use lws_get_context()
80 memset(&wsi, 0, sizeof(wsi));
81 wsi.context = context;
83 n = context->protocols[0].callback(&wsi,
84 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
85 x509_ctx, ssl, preverify_ok);
87 /* convert return code from 0 = OK to 1 = OK */
92 lws_context_ssl_init_ecdh(struct lws_context *context)
94 #ifdef LWS_SSL_SERVER_WITH_ECDH_CERT
96 EC_KEY *EC_key = NULL;
100 if (!(context->options & LWS_SERVER_OPTION_SSL_ECDH))
103 lwsl_notice(" Using ECDH certificate support\n");
105 /* Get X509 certificate from ssl context */
106 x = sk_X509_value(context->ssl_ctx->extra_certs, 0);
108 lwsl_err("%s: x is NULL\n", __func__);
111 /* Get the public key from certificate */
112 pkey = X509_get_pubkey(x);
114 lwsl_err("%s: pkey is NULL\n", __func__);
118 /* Get the key type */
119 KeyType = EVP_PKEY_type(pkey->type);
121 if (EVP_PKEY_EC != KeyType) {
122 lwsl_notice("Key type is not EC\n");
126 EC_key = EVP_PKEY_get1_EC_KEY(pkey);
127 /* Set ECDH parameter */
129 lwsl_err("%s: ECDH key is NULL \n", __func__);
132 SSL_CTX_set_tmp_ecdh(context->ssl_ctx, EC_key);
139 lws_context_ssl_init_ecdh_curve(struct lws_context_creation_info *info,
140 struct lws_context *context)
142 #ifdef LWS_HAVE_OPENSSL_ECDH_H
145 const char *ecdh_curve = "prime256v1";
147 ecdh_nid = OBJ_sn2nid(ecdh_curve);
148 if (NID_undef == ecdh_nid) {
149 lwsl_err("SSL: Unknown curve name '%s'", ecdh_curve);
153 ecdh = EC_KEY_new_by_curve_name(ecdh_nid);
155 lwsl_err("SSL: Unable to create curve '%s'", ecdh_curve);
158 SSL_CTX_set_tmp_ecdh(context->ssl_ctx, ecdh);
161 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_SINGLE_ECDH_USE);
163 lwsl_notice(" SSL ECDH curve '%s'\n", ecdh_curve);
165 lwsl_notice(" OpenSSL doesn't support ECDH\n");
171 lws_context_init_server_ssl(struct lws_context_creation_info *info,
172 struct lws_context *context)
179 if (info->port != CONTEXT_PORT_NO_LISTEN) {
181 context->use_ssl = info->ssl_cert_filepath != NULL;
184 #ifdef USE_OLD_CYASSL
185 lwsl_notice(" Compiled with CyaSSL support\n");
187 lwsl_notice(" Compiled with wolfSSL support\n");
190 lwsl_notice(" Compiled with OpenSSL support\n");
193 if (info->ssl_cipher_list)
194 lwsl_notice(" SSL ciphers: '%s'\n", info->ssl_cipher_list);
196 if (context->use_ssl)
197 lwsl_notice(" Using SSL mode\n");
199 lwsl_notice(" Using non-SSL mode\n");
203 * give him a fake wsi with context set, so he can use
204 * lws_get_context() in the callback
206 memset(&wsi, 0, sizeof(wsi));
207 wsi.context = context;
209 /* basic openssl init */
213 OpenSSL_add_all_algorithms();
214 SSL_load_error_strings();
216 openssl_websocket_private_data_index =
217 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
220 * Firefox insists on SSLv23 not SSLv3
221 * Konq disables SSLv2 by default now, SSLv23 works
223 * SSLv23_server_method() is the openssl method for "allow all TLS
224 * versions", compared to e.g. TLSv1_2_server_method() which only allows
225 * tlsv1.2. Unwanted versions must be disabled using SSL_CTX_set_options()
228 method = (SSL_METHOD *)SSLv23_server_method();
230 error = ERR_get_error();
231 lwsl_err("problem creating ssl method %lu: %s\n",
232 error, ERR_error_string(error,
233 (char *)context->pt[0].serv_buf));
236 context->ssl_ctx = SSL_CTX_new(method); /* create context */
237 if (!context->ssl_ctx) {
238 error = ERR_get_error();
239 lwsl_err("problem creating ssl context %lu: %s\n",
240 error, ERR_error_string(error,
241 (char *)context->pt[0].serv_buf));
245 /* Disable SSLv2 and SSLv3 */
246 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
247 #ifdef SSL_OP_NO_COMPRESSION
248 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_NO_COMPRESSION);
250 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_SINGLE_DH_USE);
251 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
252 if (info->ssl_cipher_list)
253 SSL_CTX_set_cipher_list(context->ssl_ctx,
254 info->ssl_cipher_list);
256 /* as a server, are we requiring clients to identify themselves? */
258 if (info->options & LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
259 int verify_options = SSL_VERIFY_PEER;
261 if (!(info->options & LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED))
262 verify_options |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
264 SSL_CTX_set_session_id_context(context->ssl_ctx,
265 (unsigned char *)context, sizeof(void *));
267 /* absolutely require the client cert */
269 SSL_CTX_set_verify(context->ssl_ctx,
270 verify_options, OpenSSL_verify_callback);
274 * give user code a chance to load certs into the server
275 * allowing it to verify incoming client certs
278 if (info->ssl_ca_filepath &&
279 !SSL_CTX_load_verify_locations(context->ssl_ctx,
280 info->ssl_ca_filepath, NULL)) {
281 lwsl_err("%s: SSL_CTX_load_verify_locations unhappy\n");
284 if (lws_context_ssl_init_ecdh_curve(info, context))
287 context->protocols[0].callback(&wsi,
288 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
289 context->ssl_ctx, NULL, 0);
291 if (info->options & LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT)
292 /* Normally SSL listener rejects non-ssl, optionally allow */
293 context->allow_non_ssl_on_ssl_port = 1;
295 if (context->use_ssl) {
296 /* openssl init for server sockets */
298 /* set the local certificate from CertFile */
299 n = SSL_CTX_use_certificate_chain_file(context->ssl_ctx,
300 info->ssl_cert_filepath);
302 error = ERR_get_error();
303 lwsl_err("problem getting cert '%s' %lu: %s\n",
304 info->ssl_cert_filepath,
306 ERR_error_string(error,
307 (char *)context->pt[0].serv_buf));
310 lws_ssl_bind_passphrase(context->ssl_ctx, info);
312 if (info->ssl_private_key_filepath != NULL) {
313 /* set the private key from KeyFile */
314 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
315 info->ssl_private_key_filepath,
316 SSL_FILETYPE_PEM) != 1) {
317 error = ERR_get_error();
318 lwsl_err("ssl problem getting key '%s' %lu: %s\n",
319 info->ssl_private_key_filepath, error,
320 ERR_error_string(error,
321 (char *)context->pt[0].serv_buf));
325 if (context->protocols[0].callback(&wsi,
326 LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY,
327 context->ssl_ctx, NULL, 0)) {
328 lwsl_err("ssl private key not set\n");
333 /* verify private key */
334 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
335 lwsl_err("Private SSL key doesn't match cert\n");
339 if (lws_context_ssl_init_ecdh(context))
343 * SSL is happy and has a cert it's content with
344 * If we're supporting HTTP2, initialize that
347 lws_context_init_http2_ssl(context);
355 lws_ssl_destroy(struct lws_context *context)
357 if (context->ssl_ctx)
358 SSL_CTX_free(context->ssl_ctx);
359 if (!context->user_supplied_ssl_ctx && context->ssl_client_ctx)
360 SSL_CTX_free(context->ssl_client_ctx);
362 #if (OPENSSL_VERSION_NUMBER < 0x01000000) || defined(USE_WOLFSSL)
365 ERR_remove_thread_state(NULL);
369 CRYPTO_cleanup_all_ex_data();
373 lws_decode_ssl_error(void)
378 while ((err = ERR_get_error()) != 0) {
379 ERR_error_string_n(err, buf, sizeof(buf));
380 lwsl_err("*** %lu %s\n", err, buf);
384 #ifndef LWS_NO_CLIENT
386 int lws_context_init_client_ssl(struct lws_context_creation_info *info,
387 struct lws_context *context)
394 if (info->provided_client_ssl_ctx) {
395 /* use the provided OpenSSL context if given one */
396 context->ssl_client_ctx = info->provided_client_ssl_ctx;
397 /* nothing for lib to delete */
398 context->user_supplied_ssl_ctx = 1;
402 if (info->port != CONTEXT_PORT_NO_LISTEN)
405 /* basic openssl init */
409 OpenSSL_add_all_algorithms();
410 SSL_load_error_strings();
412 method = (SSL_METHOD *)SSLv23_client_method();
414 error = ERR_get_error();
415 lwsl_err("problem creating ssl method %lu: %s\n",
416 error, ERR_error_string(error,
417 (char *)context->pt[0].serv_buf));
421 context->ssl_client_ctx = SSL_CTX_new(method);
422 if (!context->ssl_client_ctx) {
423 error = ERR_get_error();
424 lwsl_err("problem creating ssl context %lu: %s\n",
425 error, ERR_error_string(error,
426 (char *)context->pt[0].serv_buf));
430 #ifdef SSL_OP_NO_COMPRESSION
431 SSL_CTX_set_options(context->ssl_client_ctx,
432 SSL_OP_NO_COMPRESSION);
434 SSL_CTX_set_options(context->ssl_client_ctx,
435 SSL_OP_CIPHER_SERVER_PREFERENCE);
436 if (info->ssl_cipher_list)
437 SSL_CTX_set_cipher_list(context->ssl_client_ctx,
438 info->ssl_cipher_list);
440 #ifdef LWS_SSL_CLIENT_USE_OS_CA_CERTS
441 if (!(info->options & LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS))
442 /* loads OS default CA certs */
443 SSL_CTX_set_default_verify_paths(context->ssl_client_ctx);
446 /* openssl init for cert verification (for client sockets) */
447 if (!info->ssl_ca_filepath) {
448 if (!SSL_CTX_load_verify_locations(
449 context->ssl_client_ctx, NULL,
450 LWS_OPENSSL_CLIENT_CERTS))
452 "Unable to load SSL Client certs from %s "
453 "(set by --with-client-cert-dir= "
454 "in configure) -- client ssl isn't "
455 "going to work", LWS_OPENSSL_CLIENT_CERTS);
457 if (!SSL_CTX_load_verify_locations(
458 context->ssl_client_ctx, info->ssl_ca_filepath,
461 "Unable to load SSL Client certs "
462 "file from %s -- client ssl isn't "
463 "going to work", info->ssl_ca_filepath);
465 lwsl_info("loaded ssl_ca_filepath\n");
468 * callback allowing user code to load extra verification certs
469 * helping the client to verify server identity
472 /* support for client-side certificate authentication */
473 if (info->ssl_cert_filepath) {
474 n = SSL_CTX_use_certificate_chain_file(context->ssl_client_ctx,
475 info->ssl_cert_filepath);
477 lwsl_err("problem getting cert '%s' %lu: %s\n",
478 info->ssl_cert_filepath,
480 ERR_error_string(ERR_get_error(),
481 (char *)context->pt[0].serv_buf));
485 if (info->ssl_private_key_filepath) {
486 lws_ssl_bind_passphrase(context->ssl_client_ctx, info);
487 /* set the private key from KeyFile */
488 if (SSL_CTX_use_PrivateKey_file(context->ssl_client_ctx,
489 info->ssl_private_key_filepath, SSL_FILETYPE_PEM) != 1) {
490 lwsl_err("use_PrivateKey_file '%s' %lu: %s\n",
491 info->ssl_private_key_filepath,
493 ERR_error_string(ERR_get_error(),
494 (char *)context->pt[0].serv_buf));
498 /* verify private key */
499 if (!SSL_CTX_check_private_key(context->ssl_client_ctx)) {
500 lwsl_err("Private SSL key doesn't match cert\n");
506 * give him a fake wsi with context set, so he can use
507 * lws_get_context() in the callback
509 memset(&wsi, 0, sizeof(wsi));
510 wsi.context = context;
512 context->protocols[0].callback(&wsi,
513 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
514 context->ssl_client_ctx, NULL, 0);
521 lws_ssl_remove_wsi_from_buffered_list(struct lws *wsi)
523 struct lws_context *context = wsi->context;
524 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
526 if (!wsi->pending_read_list_prev &&
527 !wsi->pending_read_list_next &&
528 pt->pending_read_list != wsi)
529 /* we are not on the list */
532 /* point previous guy's next to our next */
533 if (!wsi->pending_read_list_prev)
534 pt->pending_read_list = wsi->pending_read_list_next;
536 wsi->pending_read_list_prev->pending_read_list_next =
537 wsi->pending_read_list_next;
539 /* point next guy's previous to our previous */
540 if (wsi->pending_read_list_next)
541 wsi->pending_read_list_next->pending_read_list_prev =
542 wsi->pending_read_list_prev;
544 wsi->pending_read_list_prev = NULL;
545 wsi->pending_read_list_next = NULL;
549 lws_ssl_capable_read(struct lws *wsi, unsigned char *buf, int len)
551 struct lws_context *context = wsi->context;
552 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
556 return lws_ssl_capable_read_no_ssl(wsi, buf, len);
558 n = SSL_read(wsi->ssl, buf, len);
559 /* manpage: returning 0 means connection shut down */
561 return LWS_SSL_CAPABLE_ERROR;
564 n = SSL_get_error(wsi->ssl, n);
565 if (n == SSL_ERROR_WANT_READ || n == SSL_ERROR_WANT_WRITE)
566 return LWS_SSL_CAPABLE_MORE_SERVICE;
568 return LWS_SSL_CAPABLE_ERROR;
572 * if it was our buffer that limited what we read,
573 * check if SSL has additional data pending inside SSL buffers.
575 * Because these won't signal at the network layer with POLLIN
576 * and if we don't realize, this data will sit there forever
582 if (!SSL_pending(wsi->ssl))
584 if (wsi->pending_read_list_next)
586 if (wsi->pending_read_list_prev)
588 if (pt->pending_read_list == wsi)
591 /* add us to the linked list of guys with pending ssl */
592 if (pt->pending_read_list)
593 pt->pending_read_list->pending_read_list_prev = wsi;
595 wsi->pending_read_list_next = pt->pending_read_list;
596 wsi->pending_read_list_prev = NULL;
597 pt->pending_read_list = wsi;
601 lws_ssl_remove_wsi_from_buffered_list(wsi);
607 lws_ssl_pending(struct lws *wsi)
612 return SSL_pending(wsi->ssl);
616 lws_ssl_capable_write(struct lws *wsi, unsigned char *buf, int len)
621 return lws_ssl_capable_write_no_ssl(wsi, buf, len);
623 n = SSL_write(wsi->ssl, buf, len);
627 n = SSL_get_error(wsi->ssl, n);
628 if (n == SSL_ERROR_WANT_READ || n == SSL_ERROR_WANT_WRITE) {
629 if (n == SSL_ERROR_WANT_WRITE)
630 lws_set_blocking_send(wsi);
631 return LWS_SSL_CAPABLE_MORE_SERVICE;
634 return LWS_SSL_CAPABLE_ERROR;
638 lws_ssl_close(struct lws *wsi)
643 return 0; /* not handled */
645 n = SSL_get_fd(wsi->ssl);
646 SSL_shutdown(wsi->ssl);
651 return 1; /* handled */
654 /* leave all wsi close processing to the caller */
657 lws_server_socket_service_ssl(struct lws *wsi, lws_sockfd_type accept_fd)
659 struct lws_context *context = wsi->context;
660 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
666 if (!LWS_SSL_ENABLED(context))
672 wsi->ssl = SSL_new(context->ssl_ctx);
673 if (wsi->ssl == NULL) {
674 lwsl_err("SSL_new failed: %s\n",
675 ERR_error_string(SSL_get_error(wsi->ssl, 0), NULL));
676 lws_decode_ssl_error();
677 if (accept_fd != LWS_SOCK_INVALID)
678 compatible_close(accept_fd);
682 SSL_set_ex_data(wsi->ssl,
683 openssl_websocket_private_data_index, context);
685 SSL_set_fd(wsi->ssl, accept_fd);
688 #ifdef USE_OLD_CYASSL
689 CyaSSL_set_using_nonblock(wsi->ssl, 1);
691 wolfSSL_set_using_nonblock(wsi->ssl, 1);
694 SSL_set_mode(wsi->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
695 bio = SSL_get_rbio(wsi->ssl);
697 BIO_set_nbio(bio, 1); /* nonblocking */
699 lwsl_notice("NULL rbio\n");
700 bio = SSL_get_wbio(wsi->ssl);
702 BIO_set_nbio(bio, 1); /* nonblocking */
704 lwsl_notice("NULL rbio\n");
708 * we are not accepted yet, but we need to enter ourselves
709 * as a live connection. That way we can retry when more
710 * pieces come if we're not sorted yet
713 wsi->mode = LWSCM_SSL_ACK_PENDING;
714 if (insert_wsi_socket_into_fds(context, wsi))
717 lws_set_timeout(wsi, PENDING_TIMEOUT_SSL_ACCEPT,
718 context->timeout_secs);
720 lwsl_info("inserted SSL accept into fds, trying SSL_accept\n");
724 case LWSCM_SSL_ACK_PENDING:
726 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0))
729 lws_latency_pre(context, wsi);
731 n = recv(wsi->sock, (char *)pt->serv_buf, LWS_MAX_SOCKET_IO_BUF,
735 * optionally allow non-SSL connect on SSL listening socket
736 * This is disabled by default, if enabled it goes around any
737 * SSL-level access control (eg, client-side certs) so leave
738 * it disabled unless you know it's not a problem for you
741 if (context->allow_non_ssl_on_ssl_port) {
742 if (n >= 1 && pt->serv_buf[0] >= ' ') {
744 * TLS content-type for Handshake is 0x16, and
745 * for ChangeCipherSpec Record, it's 0x14
747 * A non-ssl session will start with the HTTP
748 * method in ASCII. If we see it's not a legit
749 * SSL handshake kill the SSL for this
750 * connection and try to handle as a HTTP
751 * connection upgrade directly.
754 SSL_shutdown(wsi->ssl);
760 * connection is gone, or nothing to read
761 * if it's gone, we will timeout on
762 * PENDING_TIMEOUT_SSL_ACCEPT
765 if (n < 0 && (LWS_ERRNO == LWS_EAGAIN ||
766 LWS_ERRNO == LWS_EWOULDBLOCK)) {
768 * well, we get no way to know ssl or not
769 * so go around again waiting for something
770 * to come and give us a hint, or timeout the
773 m = SSL_ERROR_WANT_READ;
778 /* normal SSL connection processing path */
780 n = SSL_accept(wsi->ssl);
781 lws_latency(context, wsi,
782 "SSL_accept LWSCM_SSL_ACK_PENDING\n", n, n == 1);
787 m = SSL_get_error(wsi->ssl, n);
788 lwsl_debug("SSL_accept failed %d / %s\n",
789 m, ERR_error_string(m, NULL));
791 if (m == SSL_ERROR_WANT_READ) {
792 if (lws_change_pollfd(wsi, 0, LWS_POLLIN))
795 lwsl_info("SSL_ERROR_WANT_READ\n");
798 if (m == SSL_ERROR_WANT_WRITE) {
799 if (lws_change_pollfd(wsi, 0, LWS_POLLOUT))
804 lwsl_debug("SSL_accept failed skt %u: %s\n",
805 wsi->sock, ERR_error_string(m, NULL));
809 /* OK, we are accepted... give him some time to negotiate */
810 lws_set_timeout(wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
811 context->timeout_secs);
813 wsi->mode = LWSCM_HTTP_SERVING;
815 lws_http2_configure_if_upgraded(wsi);
817 lwsl_debug("accepted new SSL conn\n");
828 lws_ssl_context_destroy(struct lws_context *context)
830 if (context->ssl_ctx)
831 SSL_CTX_free(context->ssl_ctx);
832 if (!context->user_supplied_ssl_ctx && context->ssl_client_ctx)
833 SSL_CTX_free(context->ssl_client_ctx);
835 #if (OPENSSL_VERSION_NUMBER < 0x01000000) || defined(USE_WOLFSSL)
838 ERR_remove_thread_state(NULL);
842 CRYPTO_cleanup_all_ex_data();