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 int openssl_websocket_private_data_index;
30 lws_context_init_ssl_pem_passwd_cb(char * buf, int size, int rwflag, void *userdata)
32 struct lws_context_creation_info * info =
33 (struct lws_context_creation_info *)userdata;
35 strncpy(buf, info->ssl_private_key_password, size);
41 static void lws_ssl_bind_passphrase(SSL_CTX *ssl_ctx, struct lws_context_creation_info *info)
43 if (!info->ssl_private_key_password)
46 * password provided, set ssl callback and user data
47 * for checking password which will be trigered during
48 * SSL_CTX_use_PrivateKey_file function
50 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, (void *)info);
51 SSL_CTX_set_default_passwd_cb(ssl_ctx, lws_context_init_ssl_pem_passwd_cb);
56 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
60 struct lws_context *context;
63 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
64 SSL_get_ex_data_X509_STORE_CTX_idx());
67 * !!! nasty openssl requires the index to come as a library-scope
70 context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
73 * give him a fake wsi with context set, so he can use lws_get_context()
76 memset(&wsi, 0, sizeof(wsi));
77 wsi.context = context;
79 n = context->protocols[0].callback(&wsi,
80 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
81 x509_ctx, ssl, preverify_ok);
83 /* convert return code from 0 = OK to 1 = OK */
88 lws_context_init_server_ssl(struct lws_context_creation_info *info,
89 struct lws_context *context)
95 #ifdef LWS_SSL_SERVER_WITH_ECDH_CERT
97 EC_KEY *EC_key = NULL;
102 if (info->port != CONTEXT_PORT_NO_LISTEN) {
104 context->use_ssl = info->ssl_cert_filepath != NULL;
107 #ifdef USE_OLD_CYASSL
108 lwsl_notice(" Compiled with CyaSSL support\n");
110 lwsl_notice(" Compiled with wolfSSL support\n");
113 lwsl_notice(" Compiled with OpenSSL support\n");
116 if (info->ssl_cipher_list)
117 lwsl_notice(" SSL ciphers: '%s'\n", info->ssl_cipher_list);
119 if (context->use_ssl)
120 lwsl_notice(" Using SSL mode\n");
122 lwsl_notice(" Using non-SSL mode\n");
126 * give him a fake wsi with context set, so he can use
127 * lws_get_context() in the callback
129 memset(&wsi, 0, sizeof(wsi));
130 wsi.context = context;
132 /* basic openssl init */
136 OpenSSL_add_all_algorithms();
137 SSL_load_error_strings();
139 openssl_websocket_private_data_index =
140 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
143 * Firefox insists on SSLv23 not SSLv3
144 * Konq disables SSLv2 by default now, SSLv23 works
146 * SSLv23_server_method() is the openssl method for "allow all TLS
147 * versions", compared to e.g. TLSv1_2_server_method() which only allows
148 * tlsv1.2. Unwanted versions must be disabled using SSL_CTX_set_options()
151 method = (SSL_METHOD *)SSLv23_server_method();
153 error = ERR_get_error();
154 lwsl_err("problem creating ssl method %lu: %s\n",
155 error, ERR_error_string(error,
156 (char *)context->pt[0].serv_buf));
159 context->ssl_ctx = SSL_CTX_new(method); /* create context */
160 if (!context->ssl_ctx) {
161 error = ERR_get_error();
162 lwsl_err("problem creating ssl context %lu: %s\n",
163 error, ERR_error_string(error,
164 (char *)context->pt[0].serv_buf));
168 /* Disable SSLv2 and SSLv3 */
169 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
170 #ifdef SSL_OP_NO_COMPRESSION
171 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_NO_COMPRESSION);
173 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
174 if (info->ssl_cipher_list)
175 SSL_CTX_set_cipher_list(context->ssl_ctx,
176 info->ssl_cipher_list);
178 /* as a server, are we requiring clients to identify themselves? */
180 if (info->options & LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
181 int verify_options = SSL_VERIFY_PEER;
183 if (!(info->options & LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED))
184 verify_options |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
186 SSL_CTX_set_session_id_context(context->ssl_ctx,
187 (unsigned char *)context, sizeof(void *));
189 /* absolutely require the client cert */
191 SSL_CTX_set_verify(context->ssl_ctx,
192 verify_options, OpenSSL_verify_callback);
195 * give user code a chance to load certs into the server
196 * allowing it to verify incoming client certs
199 context->protocols[0].callback(&wsi,
200 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
201 context->ssl_ctx, NULL, 0);
204 if (info->options & LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT)
205 /* Normally SSL listener rejects non-ssl, optionally allow */
206 context->allow_non_ssl_on_ssl_port = 1;
208 if (context->use_ssl) {
209 /* openssl init for server sockets */
211 /* set the local certificate from CertFile */
212 n = SSL_CTX_use_certificate_chain_file(context->ssl_ctx,
213 info->ssl_cert_filepath);
215 error = ERR_get_error();
216 lwsl_err("problem getting cert '%s' %lu: %s\n",
217 info->ssl_cert_filepath,
219 ERR_error_string(error,
220 (char *)context->pt[0].serv_buf));
223 lws_ssl_bind_passphrase(context->ssl_ctx, info);
225 if (info->ssl_private_key_filepath != NULL) {
226 /* set the private key from KeyFile */
227 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
228 info->ssl_private_key_filepath,
229 SSL_FILETYPE_PEM) != 1) {
230 error = ERR_get_error();
231 lwsl_err("ssl problem getting key '%s' %lu: %s\n",
232 info->ssl_private_key_filepath, error,
233 ERR_error_string(error,
234 (char *)context->pt[0].serv_buf));
238 if (context->protocols[0].callback(&wsi,
239 LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY,
240 context->ssl_ctx, NULL, 0)) {
241 lwsl_err("ssl private key not set\n");
246 /* verify private key */
247 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
248 lwsl_err("Private SSL key doesn't match cert\n");
252 #ifdef LWS_SSL_SERVER_WITH_ECDH_CERT
253 if (context->options & LWS_SERVER_OPTION_SSL_ECDH) {
254 lwsl_notice(" Using ECDH certificate support\n");
256 /* Get X509 certificate from ssl context */
257 x = sk_X509_value(context->ssl_ctx->extra_certs, 0);
258 /* Get the public key from certificate */
259 pkey = X509_get_pubkey(x);
260 /* Get the key type */
261 KeyType = EVP_PKEY_type(pkey->type);
263 if (EVP_PKEY_EC != KeyType) {
264 lwsl_err("Key type is not EC\n");
268 EC_key = EVP_PKEY_get1_EC_KEY(pkey);
269 /* Set ECDH parameter */
271 error = ERR_get_error();
272 lwsl_err("ECDH key is NULL \n");
275 SSL_CTX_set_tmp_ecdh(context->ssl_ctx, EC_key);
281 * SSL is happy and has a cert it's content with
282 * If we're supporting HTTP2, initialize that
285 lws_context_init_http2_ssl(context);
293 lws_ssl_destroy(struct lws_context *context)
295 if (context->ssl_ctx)
296 SSL_CTX_free(context->ssl_ctx);
297 if (!context->user_supplied_ssl_ctx && context->ssl_client_ctx)
298 SSL_CTX_free(context->ssl_client_ctx);
300 #if (OPENSSL_VERSION_NUMBER < 0x01000000) || defined(USE_WOLFSSL)
303 ERR_remove_thread_state(NULL);
307 CRYPTO_cleanup_all_ex_data();
311 lws_decode_ssl_error(void)
316 while ((err = ERR_get_error()) != 0) {
317 ERR_error_string_n(err, buf, sizeof(buf));
318 lwsl_err("*** %lu %s\n", err, buf);
322 #ifndef LWS_NO_CLIENT
324 int lws_context_init_client_ssl(struct lws_context_creation_info *info,
325 struct lws_context *context)
332 if (info->provided_client_ssl_ctx) {
333 /* use the provided OpenSSL context if given one */
334 context->ssl_client_ctx = info->provided_client_ssl_ctx;
335 /* nothing for lib to delete */
336 context->user_supplied_ssl_ctx = 1;
340 if (info->port != CONTEXT_PORT_NO_LISTEN)
343 /* basic openssl init */
347 OpenSSL_add_all_algorithms();
348 SSL_load_error_strings();
350 method = (SSL_METHOD *)SSLv23_client_method();
352 error = ERR_get_error();
353 lwsl_err("problem creating ssl method %lu: %s\n",
354 error, ERR_error_string(error,
355 (char *)context->pt[0].serv_buf));
359 context->ssl_client_ctx = SSL_CTX_new(method);
360 if (!context->ssl_client_ctx) {
361 error = ERR_get_error();
362 lwsl_err("problem creating ssl context %lu: %s\n",
363 error, ERR_error_string(error,
364 (char *)context->pt[0].serv_buf));
368 #ifdef SSL_OP_NO_COMPRESSION
369 SSL_CTX_set_options(context->ssl_client_ctx,
370 SSL_OP_NO_COMPRESSION);
372 SSL_CTX_set_options(context->ssl_client_ctx,
373 SSL_OP_CIPHER_SERVER_PREFERENCE);
374 if (info->ssl_cipher_list)
375 SSL_CTX_set_cipher_list(context->ssl_client_ctx,
376 info->ssl_cipher_list);
378 #ifdef LWS_SSL_CLIENT_USE_OS_CA_CERTS
379 if (!(info->options & LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS))
380 /* loads OS default CA certs */
381 SSL_CTX_set_default_verify_paths(context->ssl_client_ctx);
384 /* openssl init for cert verification (for client sockets) */
385 if (!info->ssl_ca_filepath) {
386 if (!SSL_CTX_load_verify_locations(
387 context->ssl_client_ctx, NULL,
388 LWS_OPENSSL_CLIENT_CERTS))
390 "Unable to load SSL Client certs from %s "
391 "(set by --with-client-cert-dir= "
392 "in configure) -- client ssl isn't "
393 "going to work", LWS_OPENSSL_CLIENT_CERTS);
395 if (!SSL_CTX_load_verify_locations(
396 context->ssl_client_ctx, info->ssl_ca_filepath,
399 "Unable to load SSL Client certs "
400 "file from %s -- client ssl isn't "
401 "going to work", info->ssl_ca_filepath);
403 lwsl_info("loaded ssl_ca_filepath\n");
406 * callback allowing user code to load extra verification certs
407 * helping the client to verify server identity
410 /* support for client-side certificate authentication */
411 if (info->ssl_cert_filepath) {
412 n = SSL_CTX_use_certificate_chain_file(context->ssl_client_ctx,
413 info->ssl_cert_filepath);
415 lwsl_err("problem getting cert '%s' %lu: %s\n",
416 info->ssl_cert_filepath,
418 ERR_error_string(ERR_get_error(),
419 (char *)context->pt[0].serv_buf));
423 if (info->ssl_private_key_filepath) {
424 lws_ssl_bind_passphrase(context->ssl_client_ctx, info);
425 /* set the private key from KeyFile */
426 if (SSL_CTX_use_PrivateKey_file(context->ssl_client_ctx,
427 info->ssl_private_key_filepath, SSL_FILETYPE_PEM) != 1) {
428 lwsl_err("use_PrivateKey_file '%s' %lu: %s\n",
429 info->ssl_private_key_filepath,
431 ERR_error_string(ERR_get_error(),
432 (char *)context->pt[0].serv_buf));
436 /* verify private key */
437 if (!SSL_CTX_check_private_key(context->ssl_client_ctx)) {
438 lwsl_err("Private SSL key doesn't match cert\n");
444 * give him a fake wsi with context set, so he can use
445 * lws_get_context() in the callback
447 memset(&wsi, 0, sizeof(wsi));
448 wsi.context = context;
450 context->protocols[0].callback(&wsi,
451 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
452 context->ssl_client_ctx, NULL, 0);
459 lws_ssl_remove_wsi_from_buffered_list(struct lws *wsi)
461 struct lws_context *context = wsi->context;
462 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
464 if (!wsi->pending_read_list_prev &&
465 !wsi->pending_read_list_next &&
466 pt->pending_read_list != wsi)
467 /* we are not on the list */
470 /* point previous guy's next to our next */
471 if (!wsi->pending_read_list_prev)
472 pt->pending_read_list = wsi->pending_read_list_next;
474 wsi->pending_read_list_prev->pending_read_list_next =
475 wsi->pending_read_list_next;
477 /* point next guy's previous to our previous */
478 if (wsi->pending_read_list_next)
479 wsi->pending_read_list_next->pending_read_list_prev =
480 wsi->pending_read_list_prev;
482 wsi->pending_read_list_prev = NULL;
483 wsi->pending_read_list_next = NULL;
487 lws_ssl_capable_read(struct lws *wsi, unsigned char *buf, int len)
489 struct lws_context *context = wsi->context;
490 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
494 return lws_ssl_capable_read_no_ssl(wsi, buf, len);
496 n = SSL_read(wsi->ssl, buf, len);
497 /* manpage: returning 0 means connection shut down */
499 return LWS_SSL_CAPABLE_ERROR;
502 n = SSL_get_error(wsi->ssl, n);
503 if (n == SSL_ERROR_WANT_READ || n == SSL_ERROR_WANT_WRITE)
504 return LWS_SSL_CAPABLE_MORE_SERVICE;
506 return LWS_SSL_CAPABLE_ERROR;
510 * if it was our buffer that limited what we read,
511 * check if SSL has additional data pending inside SSL buffers.
513 * Because these won't signal at the network layer with POLLIN
514 * and if we don't realize, this data will sit there forever
520 if (!SSL_pending(wsi->ssl))
522 if (wsi->pending_read_list_next)
524 if (wsi->pending_read_list_prev)
526 if (pt->pending_read_list == wsi)
529 /* add us to the linked list of guys with pending ssl */
530 if (pt->pending_read_list)
531 pt->pending_read_list->pending_read_list_prev = wsi;
533 wsi->pending_read_list_next = pt->pending_read_list;
534 wsi->pending_read_list_prev = NULL;
535 pt->pending_read_list = wsi;
539 lws_ssl_remove_wsi_from_buffered_list(wsi);
545 lws_ssl_pending(struct lws *wsi)
550 return SSL_pending(wsi->ssl);
554 lws_ssl_capable_write(struct lws *wsi, unsigned char *buf, int len)
559 return lws_ssl_capable_write_no_ssl(wsi, buf, len);
561 n = SSL_write(wsi->ssl, buf, len);
565 n = SSL_get_error(wsi->ssl, n);
566 if (n == SSL_ERROR_WANT_READ || n == SSL_ERROR_WANT_WRITE) {
567 if (n == SSL_ERROR_WANT_WRITE)
568 lws_set_blocking_send(wsi);
569 return LWS_SSL_CAPABLE_MORE_SERVICE;
572 return LWS_SSL_CAPABLE_ERROR;
576 lws_ssl_close(struct lws *wsi)
581 return 0; /* not handled */
583 n = SSL_get_fd(wsi->ssl);
584 SSL_shutdown(wsi->ssl);
589 return 1; /* handled */
592 /* leave all wsi close processing to the caller */
595 lws_server_socket_service_ssl(struct lws **pwsi, struct lws *new_wsi,
596 lws_sockfd_type accept_fd,
597 struct lws_pollfd *pollfd)
599 struct lws *wsi = *pwsi;
600 struct lws_context *context = wsi->context;
601 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
607 if (!LWS_SSL_ENABLED(context))
611 case LWSCM_SERVER_LISTENER:
614 lwsl_err("no new_wsi\n");
618 new_wsi->ssl = SSL_new(context->ssl_ctx);
619 if (new_wsi->ssl == NULL) {
620 lwsl_err("SSL_new failed: %s\n",
621 ERR_error_string(SSL_get_error(new_wsi->ssl, 0), NULL));
622 lws_decode_ssl_error();
623 compatible_close(accept_fd);
627 SSL_set_ex_data(new_wsi->ssl,
628 openssl_websocket_private_data_index, context);
630 SSL_set_fd(new_wsi->ssl, accept_fd);
633 #ifdef USE_OLD_CYASSL
634 CyaSSL_set_using_nonblock(new_wsi->ssl, 1);
636 wolfSSL_set_using_nonblock(new_wsi->ssl, 1);
639 SSL_set_mode(new_wsi->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
640 bio = SSL_get_rbio(new_wsi->ssl);
642 BIO_set_nbio(bio, 1); /* nonblocking */
644 lwsl_notice("NULL rbio\n");
645 bio = SSL_get_wbio(new_wsi->ssl);
647 BIO_set_nbio(bio, 1); /* nonblocking */
649 lwsl_notice("NULL rbio\n");
653 * we are not accepted yet, but we need to enter ourselves
654 * as a live connection. That way we can retry when more
655 * pieces come if we're not sorted yet
660 wsi->mode = LWSCM_SSL_ACK_PENDING;
661 if (insert_wsi_socket_into_fds(context, wsi))
664 lws_set_timeout(wsi, PENDING_TIMEOUT_SSL_ACCEPT,
667 lwsl_info("inserted SSL accept into fds, trying SSL_accept\n");
671 case LWSCM_SSL_ACK_PENDING:
673 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0))
676 lws_libev_io(wsi, LWS_EV_STOP | LWS_EV_WRITE);
678 lws_latency_pre(context, wsi);
680 n = recv(wsi->sock, (char *)pt->serv_buf, LWS_MAX_SOCKET_IO_BUF,
684 * optionally allow non-SSL connect on SSL listening socket
685 * This is disabled by default, if enabled it goes around any
686 * SSL-level access control (eg, client-side certs) so leave
687 * it disabled unless you know it's not a problem for you
690 if (context->allow_non_ssl_on_ssl_port) {
691 if (n >= 1 && pt->serv_buf[0] >= ' ') {
693 * TLS content-type for Handshake is 0x16, and
694 * for ChangeCipherSpec Record, it's 0x14
696 * A non-ssl session will start with the HTTP
697 * method in ASCII. If we see it's not a legit
698 * SSL handshake kill the SSL for this
699 * connection and try to handle as a HTTP
700 * connection upgrade directly.
703 SSL_shutdown(wsi->ssl);
709 * connection is gone, or nothing to read
710 * if it's gone, we will timeout on
711 * PENDING_TIMEOUT_SSL_ACCEPT
714 if (n < 0 && (LWS_ERRNO == LWS_EAGAIN ||
715 LWS_ERRNO == LWS_EWOULDBLOCK)) {
717 * well, we get no way to know ssl or not
718 * so go around again waiting for something
719 * to come and give us a hint, or timeout the
722 m = SSL_ERROR_WANT_READ;
727 /* normal SSL connection processing path */
729 n = SSL_accept(wsi->ssl);
730 lws_latency(context, wsi,
731 "SSL_accept LWSCM_SSL_ACK_PENDING\n", n, n == 1);
736 m = SSL_get_error(wsi->ssl, n);
737 lwsl_debug("SSL_accept failed %d / %s\n",
738 m, ERR_error_string(m, NULL));
740 if (m == SSL_ERROR_WANT_READ) {
741 if (lws_change_pollfd(wsi, 0, LWS_POLLIN))
744 lws_libev_io(wsi, LWS_EV_START | LWS_EV_READ);
746 lwsl_info("SSL_ERROR_WANT_READ\n");
749 if (m == SSL_ERROR_WANT_WRITE) {
750 if (lws_change_pollfd(wsi, 0, LWS_POLLOUT))
753 lws_libev_io(wsi, LWS_EV_START | LWS_EV_WRITE);
756 lwsl_debug("SSL_accept failed skt %u: %s\n",
757 pollfd->fd, ERR_error_string(m, NULL));
761 /* OK, we are accepted... give him some time to negotiate */
762 lws_set_timeout(wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
765 wsi->mode = LWSCM_HTTP_SERVING;
767 lws_http2_configure_if_upgraded(wsi);
769 lwsl_debug("accepted new SSL conn\n");
780 lws_ssl_context_destroy(struct lws_context *context)
782 if (context->ssl_ctx)
783 SSL_CTX_free(context->ssl_ctx);
784 if (!context->user_supplied_ssl_ctx && context->ssl_client_ctx)
785 SSL_CTX_free(context->ssl_client_ctx);
787 #if (OPENSSL_VERSION_NUMBER < 0x01000000) || defined(USE_WOLFSSL)
790 ERR_remove_thread_state(NULL);
794 CRYPTO_cleanup_all_ex_data();