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"
23 #include <openssl/err.h>
25 int openssl_websocket_private_data_index;
27 static int lws_context_init_ssl_pem_passwd_cb(char * buf, int size, int rwflag, void *userdata)
29 struct lws_context_creation_info * info = (struct lws_context_creation_info *)userdata;
31 strncpy(buf, info->ssl_private_key_password, size);
37 static void lws_ssl_bind_passphrase(SSL_CTX *ssl_ctx,
38 struct lws_context_creation_info *info)
40 if (!info->ssl_private_key_password)
43 * password provided, set ssl callback and user data
44 * for checking password which will be trigered during
45 * SSL_CTX_use_PrivateKey_file function
47 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, (void *)info);
48 SSL_CTX_set_default_passwd_cb(ssl_ctx,
49 lws_context_init_ssl_pem_passwd_cb);
54 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
58 struct libwebsocket_context *context;
60 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
61 SSL_get_ex_data_X509_STORE_CTX_idx());
64 * !!! nasty openssl requires the index to come as a library-scope
67 context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
69 n = context->protocols[0].callback(NULL, NULL,
70 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
71 x509_ctx, ssl, preverify_ok);
73 /* convert return code from 0 = OK to 1 = OK */
78 lws_context_init_server_ssl(struct lws_context_creation_info *info,
79 struct libwebsocket_context *context)
85 if (info->port != CONTEXT_PORT_NO_LISTEN) {
87 context->use_ssl = info->ssl_cert_filepath != NULL;
90 lwsl_notice(" Compiled with CYASSL support\n");
92 lwsl_notice(" Compiled with OpenSSL support\n");
95 if (info->ssl_cipher_list)
96 lwsl_notice(" SSL ciphers: '%s'\n", info->ssl_cipher_list);
99 lwsl_notice(" Using SSL mode\n");
101 lwsl_notice(" Using non-SSL mode\n");
104 /* basic openssl init */
108 OpenSSL_add_all_algorithms();
109 SSL_load_error_strings();
111 openssl_websocket_private_data_index =
112 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
115 * Firefox insists on SSLv23 not SSLv3
116 * Konq disables SSLv2 by default now, SSLv23 works
118 * SSLv23_server_method() is the openssl method for "allow all TLS
119 * versions", compared to e.g. TLSv1_2_server_method() which only allows
120 * tlsv1.2. Unwanted versions must be disabled using SSL_CTX_set_options()
123 method = (SSL_METHOD *)SSLv23_server_method();
125 error = ERR_get_error();
126 lwsl_err("problem creating ssl method %lu: %s\n",
127 error, ERR_error_string(error,
128 (char *)context->service_buffer));
131 context->ssl_ctx = SSL_CTX_new(method); /* create context */
132 if (!context->ssl_ctx) {
133 error = ERR_get_error();
134 lwsl_err("problem creating ssl context %lu: %s\n",
135 error, ERR_error_string(error,
136 (char *)context->service_buffer));
140 /* Disable SSLv2 and SSLv3 */
141 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
142 #ifdef SSL_OP_NO_COMPRESSION
143 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_NO_COMPRESSION);
145 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
146 if (info->ssl_cipher_list)
147 SSL_CTX_set_cipher_list(context->ssl_ctx,
148 info->ssl_cipher_list);
150 /* as a server, are we requiring clients to identify themselves? */
153 LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
155 /* absolutely require the client cert */
157 SSL_CTX_set_verify(context->ssl_ctx,
158 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
159 OpenSSL_verify_callback);
162 * give user code a chance to load certs into the server
163 * allowing it to verify incoming client certs
166 context->protocols[0].callback(context, NULL,
167 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
168 context->ssl_ctx, NULL, 0);
171 if (info->options & LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT) {
172 /* Normally SSL listener rejects non-ssl, optionally allow */
173 context->allow_non_ssl_on_ssl_port = 1;
176 if (context->use_ssl) {
178 /* openssl init for server sockets */
180 /* set the local certificate from CertFile */
181 n = SSL_CTX_use_certificate_chain_file(context->ssl_ctx,
182 info->ssl_cert_filepath);
184 error = ERR_get_error();
185 lwsl_err("problem getting cert '%s' %lu: %s\n",
186 info->ssl_cert_filepath,
188 ERR_error_string(error,
189 (char *)context->service_buffer));
192 lws_ssl_bind_passphrase(context->ssl_ctx, info);
194 if (info->ssl_private_key_filepath != NULL) {
195 /* set the private key from KeyFile */
196 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
197 info->ssl_private_key_filepath,
198 SSL_FILETYPE_PEM) != 1) {
199 error = ERR_get_error();
200 lwsl_err("ssl problem getting key '%s' %lu: %s\n",
201 info->ssl_private_key_filepath,
203 ERR_error_string(error,
204 (char *)context->service_buffer));
209 if (context->protocols[0].callback(context, NULL,
210 LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY,
211 context->ssl_ctx, NULL, 0))
212 lwsl_err("ssl private key not set\n");
216 /* verify private key */
217 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
218 lwsl_err("Private SSL key doesn't match cert\n");
223 * SSL is happy and has a cert it's content with
224 * If we're supporting HTTP2, initialize that
227 lws_context_init_http2_ssl(context);
235 lws_ssl_destroy(struct libwebsocket_context *context)
237 if (context->ssl_ctx)
238 SSL_CTX_free(context->ssl_ctx);
239 if (!context->user_supplied_ssl_ctx && context->ssl_client_ctx)
240 SSL_CTX_free(context->ssl_client_ctx);
242 #if (OPENSSL_VERSION_NUMBER < 0x01000000) || defined(USE_CYASSL)
245 ERR_remove_thread_state(NULL);
249 CRYPTO_cleanup_all_ex_data();
253 libwebsockets_decode_ssl_error(void)
258 while ((err = ERR_get_error()) != 0) {
259 ERR_error_string_n(err, buf, sizeof(buf));
260 lwsl_err("*** %lu %s\n", err, buf);
264 #ifndef LWS_NO_CLIENT
266 int lws_context_init_client_ssl(struct lws_context_creation_info *info,
267 struct libwebsocket_context *context)
273 if (info->provided_client_ssl_ctx) {
274 /* use the provided OpenSSL context if given one */
275 context->ssl_client_ctx = info->provided_client_ssl_ctx;
276 /* nothing for lib to delete */
277 context->user_supplied_ssl_ctx = 1;
281 if (info->port != CONTEXT_PORT_NO_LISTEN)
284 /* basic openssl init */
288 OpenSSL_add_all_algorithms();
289 SSL_load_error_strings();
291 method = (SSL_METHOD *)SSLv23_client_method();
293 error = ERR_get_error();
294 lwsl_err("problem creating ssl method %lu: %s\n",
295 error, ERR_error_string(error,
296 (char *)context->service_buffer));
300 context->ssl_client_ctx = SSL_CTX_new(method);
301 if (!context->ssl_client_ctx) {
302 error = ERR_get_error();
303 lwsl_err("problem creating ssl context %lu: %s\n",
304 error, ERR_error_string(error,
305 (char *)context->service_buffer));
309 #ifdef SSL_OP_NO_COMPRESSION
310 SSL_CTX_set_options(context->ssl_client_ctx,
311 SSL_OP_NO_COMPRESSION);
313 SSL_CTX_set_options(context->ssl_client_ctx,
314 SSL_OP_CIPHER_SERVER_PREFERENCE);
315 if (info->ssl_cipher_list)
316 SSL_CTX_set_cipher_list(context->ssl_client_ctx,
317 info->ssl_cipher_list);
319 #ifdef LWS_SSL_CLIENT_USE_OS_CA_CERTS
320 if (!(info->options & LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS))
321 /* loads OS default CA certs */
322 SSL_CTX_set_default_verify_paths(context->ssl_client_ctx);
325 /* openssl init for cert verification (for client sockets) */
326 if (!info->ssl_ca_filepath) {
327 if (!SSL_CTX_load_verify_locations(
328 context->ssl_client_ctx, NULL,
329 LWS_OPENSSL_CLIENT_CERTS))
331 "Unable to load SSL Client certs from %s "
332 "(set by --with-client-cert-dir= "
333 "in configure) -- client ssl isn't "
334 "going to work", LWS_OPENSSL_CLIENT_CERTS);
336 if (!SSL_CTX_load_verify_locations(
337 context->ssl_client_ctx, info->ssl_ca_filepath,
340 "Unable to load SSL Client certs "
341 "file from %s -- client ssl isn't "
342 "going to work", info->ssl_ca_filepath);
344 lwsl_info("loaded ssl_ca_filepath\n");
347 * callback allowing user code to load extra verification certs
348 * helping the client to verify server identity
351 /* support for client-side certificate authentication */
352 if (info->ssl_cert_filepath) {
353 n = SSL_CTX_use_certificate_chain_file(
354 context->ssl_client_ctx,
355 info->ssl_cert_filepath);
357 lwsl_err("problem getting cert '%s' %lu: %s\n",
358 info->ssl_cert_filepath,
360 ERR_error_string(ERR_get_error(),
361 (char *)context->service_buffer));
365 if (info->ssl_private_key_filepath) {
366 lws_ssl_bind_passphrase(context->ssl_client_ctx, info);
367 /* set the private key from KeyFile */
368 if (SSL_CTX_use_PrivateKey_file(context->ssl_client_ctx,
369 info->ssl_private_key_filepath, SSL_FILETYPE_PEM) != 1) {
370 lwsl_err("use_PrivateKey_file '%s' %lu: %s\n",
371 info->ssl_private_key_filepath,
373 ERR_error_string(ERR_get_error(),
374 (char *)context->service_buffer));
378 /* verify private key */
379 if (!SSL_CTX_check_private_key(
380 context->ssl_client_ctx)) {
381 lwsl_err("Private SSL key doesn't match cert\n");
386 context->protocols[0].callback(context, NULL,
387 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
388 context->ssl_client_ctx, NULL, 0);
395 lws_ssl_capable_read(struct libwebsocket_context *context,
396 struct libwebsocket *wsi, unsigned char *buf, int len)
401 return lws_ssl_capable_read_no_ssl(context, wsi, buf, len);
403 wsi->buffered_reads_pending = 0;
405 n = SSL_read(wsi->ssl, buf, len);
408 * if it was our buffer that limited what we read,
409 * check if SSL has additional data pending inside SSL buffers.
411 * Because these won't signal at the network layer with POLLIN
412 * and if we don't realize, this data will sit there forever
414 if (n == len && wsi->ssl && SSL_pending(wsi->ssl)) {
415 context->ssl_flag_buffered_reads = 1;
416 wsi->buffered_reads_pending = 1;
421 n = SSL_get_error(wsi->ssl, n);
422 if (n == SSL_ERROR_WANT_READ || n == SSL_ERROR_WANT_WRITE)
423 return LWS_SSL_CAPABLE_MORE_SERVICE;
425 return LWS_SSL_CAPABLE_ERROR;
429 lws_ssl_capable_write(struct libwebsocket *wsi, unsigned char *buf, int len)
434 return lws_ssl_capable_write_no_ssl(wsi, buf, len);
436 n = SSL_write(wsi->ssl, buf, len);
440 n = SSL_get_error(wsi->ssl, n);
441 if (n == SSL_ERROR_WANT_READ || n == SSL_ERROR_WANT_WRITE) {
442 if (n == SSL_ERROR_WANT_WRITE)
443 lws_set_blocking_send(wsi);
444 return LWS_SSL_CAPABLE_MORE_SERVICE;
447 return LWS_SSL_CAPABLE_ERROR;
451 lws_ssl_close(struct libwebsocket *wsi)
456 return 0; /* not handled */
458 n = SSL_get_fd(wsi->ssl);
459 SSL_shutdown(wsi->ssl);
463 return 1; /* handled */
467 lws_server_socket_service_ssl(struct libwebsocket_context *context,
468 struct libwebsocket **pwsi, struct libwebsocket *new_wsi,
469 int accept_fd, struct libwebsocket_pollfd *pollfd)
472 struct libwebsocket *wsi = *pwsi;
477 if (!LWS_SSL_ENABLED(context))
481 case LWS_CONNMODE_SERVER_LISTENER:
484 lwsl_err("no new_wsi\n");
488 new_wsi->ssl = SSL_new(context->ssl_ctx);
489 if (new_wsi->ssl == NULL) {
490 lwsl_err("SSL_new failed: %s\n",
491 ERR_error_string(SSL_get_error(
492 new_wsi->ssl, 0), NULL));
493 libwebsockets_decode_ssl_error();
495 compatible_close(accept_fd);
499 SSL_set_ex_data(new_wsi->ssl,
500 openssl_websocket_private_data_index, context);
502 SSL_set_fd(new_wsi->ssl, accept_fd);
505 CyaSSL_set_using_nonblock(new_wsi->ssl, 1);
507 SSL_set_mode(new_wsi->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
508 bio = SSL_get_rbio(new_wsi->ssl);
510 BIO_set_nbio(bio, 1); /* nonblocking */
512 lwsl_notice("NULL rbio\n");
513 bio = SSL_get_wbio(new_wsi->ssl);
515 BIO_set_nbio(bio, 1); /* nonblocking */
517 lwsl_notice("NULL rbio\n");
521 * we are not accepted yet, but we need to enter ourselves
522 * as a live connection. That way we can retry when more
523 * pieces come if we're not sorted yet
528 wsi->mode = LWS_CONNMODE_SSL_ACK_PENDING;
529 insert_wsi_socket_into_fds(context, wsi);
531 libwebsocket_set_timeout(wsi, PENDING_TIMEOUT_SSL_ACCEPT,
534 lwsl_info("inserted SSL accept into fds, trying SSL_accept\n");
538 case LWS_CONNMODE_SSL_ACK_PENDING:
540 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0))
543 lws_libev_io(context, wsi, LWS_EV_STOP | LWS_EV_WRITE);
545 lws_latency_pre(context, wsi);
547 n = recv(wsi->sock, context->service_buffer,
548 sizeof(context->service_buffer), MSG_PEEK);
551 * optionally allow non-SSL connect on SSL listening socket
552 * This is disabled by default, if enabled it goes around any
553 * SSL-level access control (eg, client-side certs) so leave
554 * it disabled unless you know it's not a problem for you
557 if (context->allow_non_ssl_on_ssl_port && n >= 1 &&
558 context->service_buffer[0] >= ' ') {
560 * TLS content-type for Handshake is 0x16
561 * TLS content-type for ChangeCipherSpec Record is 0x14
563 * A non-ssl session will start with the HTTP method in
564 * ASCII. If we see it's not a legit SSL handshake
565 * kill the SSL for this connection and try to handle
566 * as a HTTP connection upgrade directly.
569 SSL_shutdown(wsi->ssl);
575 /* normal SSL connection processing path */
577 n = SSL_accept(wsi->ssl);
578 lws_latency(context, wsi,
579 "SSL_accept LWS_CONNMODE_SSL_ACK_PENDING\n", n, n == 1);
584 m = SSL_get_error(wsi->ssl, n);
585 lwsl_debug("SSL_accept failed %d / %s\n",
586 m, ERR_error_string(m, NULL));
588 if (m == SSL_ERROR_WANT_READ) {
589 if (lws_change_pollfd(wsi, 0, LWS_POLLIN))
592 lws_libev_io(context, wsi, LWS_EV_START | LWS_EV_READ);
594 lwsl_info("SSL_ERROR_WANT_READ\n");
597 if (m == SSL_ERROR_WANT_WRITE) {
598 if (lws_change_pollfd(wsi, 0, LWS_POLLOUT))
601 lws_libev_io(context, wsi, LWS_EV_START | LWS_EV_WRITE);
604 lwsl_debug("SSL_accept failed skt %u: %s\n",
605 pollfd->fd, ERR_error_string(m, NULL));
609 /* OK, we are accepted... give him some time to negotiate */
610 libwebsocket_set_timeout(wsi,
611 PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
614 wsi->mode = LWS_CONNMODE_HTTP_SERVING;
616 lws_http2_configure_if_upgraded(wsi);
618 lwsl_debug("accepted new SSL conn\n");
629 lws_ssl_context_destroy(struct libwebsocket_context *context)
631 if (context->ssl_ctx)
632 SSL_CTX_free(context->ssl_ctx);
633 if (!context->user_supplied_ssl_ctx && context->ssl_client_ctx)
634 SSL_CTX_free(context->ssl_client_ctx);
636 #if (OPENSSL_VERSION_NUMBER < 0x01000000) || defined(USE_CYASSL)
639 ERR_remove_thread_state(NULL);
643 CRYPTO_cleanup_all_ex_data();