2 * libwebsockets - openSSL-specific client tls code
4 * Copyright (C) 2010-2017 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 "core/private.h"
24 #include "tls/openssl/private.h"
27 * Care: many openssl apis return 1 for success. These are translated to the
28 * lws convention of 0 for success.
31 int lws_openssl_describe_cipher(struct lws *wsi);
33 extern int openssl_websocket_private_data_index,
34 openssl_SSL_CTX_private_data_index;
36 #if !defined(USE_WOLFSSL)
39 OpenSSL_client_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
45 /* keep old behaviour accepting self-signed server certs */
47 int err = X509_STORE_CTX_get_error(x509_ctx);
49 if (err != X509_V_OK) {
50 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
51 SSL_get_ex_data_X509_STORE_CTX_idx());
52 wsi = SSL_get_ex_data(ssl,
53 openssl_websocket_private_data_index);
55 lwsl_err("%s: can't get wsi from ssl privdata\n",
61 if ((err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
62 err == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) &&
63 wsi->tls.use_ssl & LCCSCF_ALLOW_SELFSIGNED) {
64 lwsl_notice("accepting self-signed "
65 "certificate (verify_callback)\n");
66 X509_STORE_CTX_set_error(x509_ctx, X509_V_OK);
68 } else if ((err == X509_V_ERR_CERT_NOT_YET_VALID ||
69 err == X509_V_ERR_CERT_HAS_EXPIRED) &&
70 wsi->tls.use_ssl & LCCSCF_ALLOW_EXPIRED) {
71 if (err == X509_V_ERR_CERT_NOT_YET_VALID)
72 lwsl_notice("accepting not yet valid "
73 "certificate (verify_"
75 else if (err == X509_V_ERR_CERT_HAS_EXPIRED)
76 lwsl_notice("accepting expired "
77 "certificate (verify_"
79 X509_STORE_CTX_set_error(x509_ctx, X509_V_OK);
85 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
86 SSL_get_ex_data_X509_STORE_CTX_idx());
87 wsi = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
89 lwsl_err("%s: can't get wsi from ssl privdata\n", __func__);
94 n = lws_get_context_protocol(wsi->context, 0).callback(wsi,
95 LWS_CALLBACK_OPENSSL_PERFORM_SERVER_CERT_VERIFICATION,
96 x509_ctx, ssl, preverify_ok);
98 /* keep old behaviour if something wrong with server certs */
99 /* if ssl error is overruled in callback and cert is ok,
100 * X509_STORE_CTX_set_error(x509_ctx, X509_V_OK); must be set and
101 * return value is 0 from callback */
103 int err = X509_STORE_CTX_get_error(x509_ctx);
105 if (err != X509_V_OK) {
106 /* cert validation error was not handled in callback */
107 int depth = X509_STORE_CTX_get_error_depth(x509_ctx);
108 const char *msg = X509_verify_cert_error_string(err);
110 lwsl_err("SSL error: %s (preverify_ok=%d;err=%d;"
111 "depth=%d)\n", msg, preverify_ok, err, depth);
113 return preverify_ok; // not ok
117 * convert callback return code from 0 = OK to verify callback
118 * return value 1 = OK
126 lws_ssl_client_bio_create(struct lws *wsi)
128 char hostname[128], *p;
129 #if defined(LWS_HAVE_SSL_set_alpn_protos) && \
130 defined(LWS_HAVE_SSL_get0_alpn_selected)
131 uint8_t openssl_alpn[40];
132 const char *alpn_comma = wsi->context->tls.alpn_default;
136 #if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)
137 if (lws_hdr_copy(wsi, hostname, sizeof(hostname),
138 _WSI_TOKEN_CLIENT_HOST) <= 0)
141 lwsl_err("%s: Unable to get hostname\n", __func__);
147 * remove any :port part on the hostname... necessary for network
148 * connection but typical certificates do not contain it
159 wsi->tls.ssl = SSL_new(wsi->vhost->tls.ssl_client_ctx);
161 lwsl_err("SSL_new failed: %s\n",
162 ERR_error_string(lws_ssl_get_error(wsi, 0), NULL));
163 lws_tls_err_describe_clear();
167 #if defined (LWS_HAVE_SSL_SET_INFO_CALLBACK)
168 if (wsi->vhost->tls.ssl_info_event_mask)
169 SSL_set_info_callback(wsi->tls.ssl, lws_ssl_info_callback);
172 #if defined LWS_HAVE_X509_VERIFY_PARAM_set1_host
173 if (!(wsi->tls.use_ssl & LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK)) {
174 X509_VERIFY_PARAM *param = SSL_get0_param(wsi->tls.ssl);
176 /* Enable automatic hostname checks */
177 X509_VERIFY_PARAM_set_hostflags(param,
178 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
179 // Handle the case where the hostname is an IP address.
180 if (!X509_VERIFY_PARAM_set1_ip_asc(param, hostname))
181 X509_VERIFY_PARAM_set1_host(param, hostname, 0);
185 #if !defined(USE_WOLFSSL)
186 #ifndef USE_OLD_CYASSL
187 /* OpenSSL_client_verify_callback will be called @ SSL_connect() */
188 SSL_set_verify(wsi->tls.ssl, SSL_VERIFY_PEER,
189 OpenSSL_client_verify_callback);
193 #if !defined(USE_WOLFSSL)
194 SSL_set_mode(wsi->tls.ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
197 * use server name indication (SNI), if supported,
198 * when establishing connection
201 #ifdef USE_OLD_CYASSL
202 #ifdef CYASSL_SNI_HOST_NAME
203 CyaSSL_UseSNI(wsi->tls.ssl, CYASSL_SNI_HOST_NAME, hostname,
207 #ifdef WOLFSSL_SNI_HOST_NAME
208 wolfSSL_UseSNI(wsi->tls.ssl, WOLFSSL_SNI_HOST_NAME, hostname,
213 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
214 SSL_set_tlsext_host_name(wsi->tls.ssl, hostname);
220 * wolfSSL/CyaSSL does certificate verification differently
222 * If we should ignore the certificate, we need to set
223 * this before SSL_new and SSL_connect is called.
224 * Otherwise the connect will simply fail with error code -155
226 #ifdef USE_OLD_CYASSL
227 if (wsi->tls.use_ssl == 2)
228 CyaSSL_set_verify(wsi->tls.ssl, SSL_VERIFY_NONE, NULL);
230 if (wsi->tls.use_ssl == 2)
231 wolfSSL_set_verify(wsi->tls.ssl, SSL_VERIFY_NONE, NULL);
233 #endif /* USE_WOLFSSL */
235 wsi->tls.client_bio = BIO_new_socket((int)(long long)wsi->desc.sockfd,
237 SSL_set_bio(wsi->tls.ssl, wsi->tls.client_bio, wsi->tls.client_bio);
240 #ifdef USE_OLD_CYASSL
241 CyaSSL_set_using_nonblock(wsi->tls.ssl, 1);
243 wolfSSL_set_using_nonblock(wsi->tls.ssl, 1);
246 BIO_set_nbio(wsi->tls.client_bio, 1); /* nonblocking */
249 #if defined(LWS_HAVE_SSL_set_alpn_protos) && \
250 defined(LWS_HAVE_SSL_get0_alpn_selected)
251 if (wsi->vhost->tls.alpn)
252 alpn_comma = wsi->vhost->tls.alpn;
253 #if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)
254 if (lws_hdr_copy(wsi, hostname, sizeof(hostname),
255 _WSI_TOKEN_CLIENT_ALPN) > 0)
256 alpn_comma = hostname;
259 lwsl_info("client conn using alpn list '%s'\n", alpn_comma);
261 n = lws_alpn_comma_to_openssl(alpn_comma, openssl_alpn,
262 sizeof(openssl_alpn) - 1);
264 SSL_set_alpn_protos(wsi->tls.ssl, openssl_alpn, n);
267 SSL_set_ex_data(wsi->tls.ssl, openssl_websocket_private_data_index,
273 enum lws_ssl_capable_status
274 lws_tls_client_connect(struct lws *wsi)
276 #if defined(LWS_HAVE_SSL_set_alpn_protos) && \
277 defined(LWS_HAVE_SSL_get0_alpn_selected)
278 const unsigned char *prot;
286 n = SSL_connect(wsi->tls.ssl);
288 #if defined(LWS_HAVE_SSL_set_alpn_protos) && \
289 defined(LWS_HAVE_SSL_get0_alpn_selected)
290 SSL_get0_alpn_selected(wsi->tls.ssl, &prot, &len);
292 if (len >= sizeof(a))
294 memcpy(a, (const char *)prot, len);
297 lws_role_call_alpn_negotiated(wsi, (const char *)a);
299 lwsl_info("client connect OK\n");
300 lws_openssl_describe_cipher(wsi);
301 return LWS_SSL_CAPABLE_DONE;
304 m = lws_ssl_get_error(wsi, n);
306 if (m == SSL_ERROR_SYSCALL)
307 return LWS_SSL_CAPABLE_ERROR;
309 if (m == SSL_ERROR_WANT_READ || SSL_want_read(wsi->tls.ssl))
310 return LWS_SSL_CAPABLE_MORE_SERVICE_READ;
312 if (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->tls.ssl))
313 return LWS_SSL_CAPABLE_MORE_SERVICE_WRITE;
315 if (!n) /* we don't know what he wants, but he says to retry */
316 return LWS_SSL_CAPABLE_MORE_SERVICE;
318 return LWS_SSL_CAPABLE_ERROR;
322 lws_tls_client_confirm_peer_cert(struct lws *wsi, char *ebuf, int ebuf_len)
324 #if !defined(USE_WOLFSSL)
325 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
326 char *p = (char *)&pt->serv_buf[0];
330 lws_latency_pre(wsi->context, wsi);
333 n = SSL_get_verify_result(wsi->tls.ssl);
334 lws_latency(wsi->context, wsi,
335 "SSL_get_verify_result LWS_CONNMODE..HANDSHAKE", n, n > 0);
337 lwsl_debug("get_verify says %d\n", n);
342 if ((n == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
343 n == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) &&
344 (wsi->tls.use_ssl & LCCSCF_ALLOW_SELFSIGNED)) {
345 lwsl_info("accepting self-signed certificate\n");
349 if ((n == X509_V_ERR_CERT_NOT_YET_VALID ||
350 n == X509_V_ERR_CERT_HAS_EXPIRED) &&
351 (wsi->tls.use_ssl & LCCSCF_ALLOW_EXPIRED)) {
352 lwsl_info("accepting expired certificate\n");
355 if (n == X509_V_ERR_CERT_NOT_YET_VALID) {
356 lwsl_info("Cert is from the future... "
357 "probably our clock... accepting...\n");
360 lws_snprintf(ebuf, ebuf_len,
361 "server's cert didn't look good, X509_V_ERR = %d: %s\n",
362 n, ERR_error_string(n, sb));
363 lwsl_info("%s\n", ebuf);
364 lws_tls_err_describe_clear();
368 #else /* USE_WOLFSSL */
374 lws_tls_client_create_vhost_context(struct lws_vhost *vh,
375 const struct lws_context_creation_info *info,
376 const char *cipher_list,
377 const char *ca_filepath,
379 unsigned int ca_mem_len,
380 const char *cert_filepath,
381 const void *cert_mem,
382 unsigned int cert_mem_len,
383 const char *private_key_filepath)
385 struct lws_tls_client_reuse *tcr;
386 const unsigned char *ca_mem_ptr;
387 X509_STORE *x509_store;
397 /* basic openssl init already happened in context init */
399 /* choose the most recent spin of the api */
400 #if defined(LWS_HAVE_TLS_CLIENT_METHOD)
401 method = (SSL_METHOD *)TLS_client_method();
402 #elif defined(LWS_HAVE_TLSV1_2_CLIENT_METHOD)
403 method = (SSL_METHOD *)TLSv1_2_client_method();
405 method = (SSL_METHOD *)SSLv23_client_method();
409 error = ERR_get_error();
410 lwsl_err("problem creating ssl method %lu: %s\n",
411 error, ERR_error_string(error,
412 (char *)vh->context->pt[0].serv_buf));
417 * OpenSSL client contexts are quite expensive, because they bring in
418 * the system certificate bundle for each one. So if you have multiple
419 * vhosts, each with a client context, it can add up to several
420 * megabytes of heap. In the case the client contexts are configured
421 * identically, they could perfectly well have shared just the one.
423 * For that reason, use a hash to fingerprint the context configuration
424 * and prefer to reuse an existing one with the same fingerprint if
428 mdctx = EVP_MD_CTX_create();
432 if (EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL) != 1) {
433 EVP_MD_CTX_destroy(mdctx);
438 if (info->ssl_client_options_set)
439 EVP_DigestUpdate(mdctx, &info->ssl_client_options_set,
440 sizeof(info->ssl_client_options_set));
442 #if (OPENSSL_VERSION_NUMBER >= 0x009080df) && !defined(USE_WOLFSSL)
443 if (info->ssl_client_options_clear)
444 EVP_DigestUpdate(mdctx, &info->ssl_client_options_clear,
445 sizeof(info->ssl_client_options_clear));
449 EVP_DigestUpdate(mdctx, cipher_list, strlen(cipher_list));
451 #if defined(LWS_HAVE_SSL_CTX_set_ciphersuites)
452 if (info->client_tls_1_3_plus_cipher_list)
453 EVP_DigestUpdate(mdctx, info->client_tls_1_3_plus_cipher_list,
454 strlen(info->client_tls_1_3_plus_cipher_list));
457 if (!lws_check_opt(vh->options, LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS)) {
459 EVP_DigestUpdate(mdctx, &c, 1);
463 EVP_DigestUpdate(mdctx, ca_filepath, strlen(ca_filepath));
466 EVP_DigestUpdate(mdctx, cert_filepath, strlen(cert_filepath));
468 if (private_key_filepath)
469 EVP_DigestUpdate(mdctx, private_key_filepath,
470 strlen(private_key_filepath));
471 if (ca_mem && ca_mem_len)
472 EVP_DigestUpdate(mdctx, ca_mem, ca_mem_len);
474 if (cert_mem && cert_mem_len)
475 EVP_DigestUpdate(mdctx, cert_mem, cert_mem_len);
478 EVP_DigestFinal_ex(mdctx, hash, &len);
479 EVP_MD_CTX_destroy(mdctx);
481 /* look for existing client context with same config already */
483 lws_start_foreach_dll_safe(struct lws_dll2 *, p, tp,
484 lws_dll2_get_head(&vh->context->tls.cc_owner)) {
485 tcr = lws_container_of(p, struct lws_tls_client_reuse, cc_list);
487 if (!memcmp(hash, tcr->hash, len)) {
492 vh->tls.ssl_client_ctx = tcr->ssl_client_ctx;
494 lwsl_info("%s: vh %s: reusing client ctx %d: use %d\n",
495 __func__, vh->name, tcr->index,
500 } lws_end_foreach_dll_safe(p, tp);
502 /* no existing one the same... create new client SSL_CTX */
506 vh->tls.ssl_client_ctx = SSL_CTX_new(method);
507 if (!vh->tls.ssl_client_ctx) {
508 error = ERR_get_error();
509 lwsl_err("problem creating ssl context %lu: %s\n",
510 error, ERR_error_string(error,
511 (char *)vh->context->pt[0].serv_buf));
515 tcr = lws_zalloc(sizeof(*tcr), "client ctx tcr");
517 SSL_CTX_free(vh->tls.ssl_client_ctx);
521 tcr->ssl_client_ctx = vh->tls.ssl_client_ctx;
523 memcpy(tcr->hash, hash, len);
524 tcr->index = vh->context->tls.count_client_contexts++;
525 lws_dll2_add_head(&tcr->cc_list, &vh->context->tls.cc_owner);
527 lwsl_info("%s: vh %s: created new client ctx %d\n", __func__,
528 vh->name, tcr->index);
530 /* bind the tcr to the client context */
532 SSL_CTX_set_ex_data(vh->tls.ssl_client_ctx,
533 openssl_SSL_CTX_private_data_index,
536 #ifdef SSL_OP_NO_COMPRESSION
537 SSL_CTX_set_options(vh->tls.ssl_client_ctx, SSL_OP_NO_COMPRESSION);
540 SSL_CTX_set_options(vh->tls.ssl_client_ctx,
541 SSL_OP_CIPHER_SERVER_PREFERENCE);
543 SSL_CTX_set_mode(vh->tls.ssl_client_ctx,
544 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
545 SSL_MODE_RELEASE_BUFFERS);
547 if (info->ssl_client_options_set)
548 SSL_CTX_set_options(vh->tls.ssl_client_ctx,
549 info->ssl_client_options_set);
551 /* SSL_clear_options introduced in 0.9.8m */
552 #if (OPENSSL_VERSION_NUMBER >= 0x009080df) && !defined(USE_WOLFSSL)
553 if (info->ssl_client_options_clear)
554 SSL_CTX_clear_options(vh->tls.ssl_client_ctx,
555 info->ssl_client_options_clear);
559 SSL_CTX_set_cipher_list(vh->tls.ssl_client_ctx, cipher_list);
561 #if defined(LWS_HAVE_SSL_CTX_set_ciphersuites)
562 if (info->client_tls_1_3_plus_cipher_list)
563 SSL_CTX_set_ciphersuites(vh->tls.ssl_client_ctx,
564 info->client_tls_1_3_plus_cipher_list);
567 #ifdef LWS_SSL_CLIENT_USE_OS_CA_CERTS
568 if (!lws_check_opt(vh->options, LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS))
569 /* loads OS default CA certs */
570 SSL_CTX_set_default_verify_paths(vh->tls.ssl_client_ctx);
573 /* openssl init for cert verification (for client sockets) */
574 if (!ca_filepath && (!ca_mem || !ca_mem_len)) {
575 if (!SSL_CTX_load_verify_locations(
576 vh->tls.ssl_client_ctx, NULL, LWS_OPENSSL_CLIENT_CERTS))
577 lwsl_err("Unable to load SSL Client certs from %s "
578 "(set by LWS_OPENSSL_CLIENT_CERTS) -- "
579 "client ssl isn't going to work\n",
580 LWS_OPENSSL_CLIENT_CERTS);
581 } else if (ca_filepath) {
582 if (!SSL_CTX_load_verify_locations(
583 vh->tls.ssl_client_ctx, ca_filepath, NULL)) {
585 "Unable to load SSL Client certs "
586 "file from %s -- client ssl isn't "
587 "going to work\n", ca_filepath);
588 lws_tls_err_describe_clear();
591 lwsl_info("loaded ssl_ca_filepath\n");
593 ca_mem_ptr = (const unsigned char*)ca_mem;
594 client_CA = d2i_X509(NULL, &ca_mem_ptr, ca_mem_len);
595 x509_store = X509_STORE_new();
596 if (!client_CA || !X509_STORE_add_cert(x509_store, client_CA)) {
597 X509_STORE_free(x509_store);
598 lwsl_err("Unable to load SSL Client certs from "
599 "ssl_ca_mem -- client ssl isn't going to "
601 lws_tls_err_describe_clear();
603 /* it doesn't increment x509_store ref counter */
604 SSL_CTX_set_cert_store(vh->tls.ssl_client_ctx,
606 lwsl_info("loaded ssl_ca_mem\n");
609 X509_free(client_CA);
613 * callback allowing user code to load extra verification certs
614 * helping the client to verify server identity
617 /* support for client-side certificate authentication */
619 if (lws_tls_use_any_upgrade_check_extant(cert_filepath) !=
620 LWS_TLS_EXTANT_YES &&
621 (info->options & LWS_SERVER_OPTION_IGNORE_MISSING_CERT))
624 lwsl_notice("%s: doing cert filepath %s\n", __func__,
626 n = SSL_CTX_use_certificate_chain_file(vh->tls.ssl_client_ctx,
629 lwsl_err("problem %d getting cert '%s'\n", n,
631 lws_tls_err_describe_clear();
634 lwsl_notice("Loaded client cert %s\n", cert_filepath);
635 } else if (cert_mem && cert_mem_len) {
636 n = SSL_CTX_use_certificate_ASN1(vh->tls.ssl_client_ctx,
637 cert_mem_len, cert_mem);
639 lwsl_err("%s: problem interpreting client cert\n",
641 lws_tls_err_describe_clear();
645 if (private_key_filepath) {
646 lwsl_notice("%s: doing private key filepath\n", __func__);
647 lws_ssl_bind_passphrase(vh->tls.ssl_client_ctx, 1, info);
648 /* set the private key from KeyFile */
649 if (SSL_CTX_use_PrivateKey_file(vh->tls.ssl_client_ctx,
650 private_key_filepath, SSL_FILETYPE_PEM) != 1) {
651 lwsl_err("use_PrivateKey_file '%s'\n",
652 private_key_filepath);
653 lws_tls_err_describe_clear();
656 lwsl_notice("Loaded client cert private key %s\n",
657 private_key_filepath);
659 /* verify private key */
660 if (!SSL_CTX_check_private_key(vh->tls.ssl_client_ctx)) {
661 lwsl_err("Private SSL key doesn't match cert\n");