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 "private-lib-core.h"
23 #include "private-lib-tls-openssl.h"
26 * Care: many openssl apis return 1 for success. These are translated to the
27 * lws convention of 0 for success.
30 int lws_openssl_describe_cipher(struct lws *wsi);
32 extern int openssl_websocket_private_data_index,
33 openssl_SSL_CTX_private_data_index;
35 #if !defined(USE_WOLFSSL)
38 OpenSSL_client_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
44 /* keep old behaviour accepting self-signed server certs */
46 int err = X509_STORE_CTX_get_error(x509_ctx);
48 if (err != X509_V_OK) {
49 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
50 SSL_get_ex_data_X509_STORE_CTX_idx());
51 wsi = SSL_get_ex_data(ssl,
52 openssl_websocket_private_data_index);
54 lwsl_err("%s: can't get wsi from ssl privdata\n",
60 if ((err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
61 err == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) &&
62 wsi->tls.use_ssl & LCCSCF_ALLOW_SELFSIGNED) {
63 lwsl_notice("accepting self-signed "
64 "certificate (verify_callback)\n");
65 X509_STORE_CTX_set_error(x509_ctx, X509_V_OK);
67 } else if ((err == X509_V_ERR_CERT_NOT_YET_VALID ||
68 err == X509_V_ERR_CERT_HAS_EXPIRED) &&
69 wsi->tls.use_ssl & LCCSCF_ALLOW_EXPIRED) {
70 if (err == X509_V_ERR_CERT_NOT_YET_VALID)
71 lwsl_notice("accepting not yet valid "
72 "certificate (verify_"
74 else if (err == X509_V_ERR_CERT_HAS_EXPIRED)
75 lwsl_notice("accepting expired "
76 "certificate (verify_"
78 X509_STORE_CTX_set_error(x509_ctx, X509_V_OK);
84 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
85 SSL_get_ex_data_X509_STORE_CTX_idx());
86 wsi = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
88 lwsl_err("%s: can't get wsi from ssl privdata\n", __func__);
93 n = lws_get_context_protocol(wsi->context, 0).callback(wsi,
94 LWS_CALLBACK_OPENSSL_PERFORM_SERVER_CERT_VERIFICATION,
95 x509_ctx, ssl, preverify_ok);
97 /* keep old behaviour if something wrong with server certs */
98 /* if ssl error is overruled in callback and cert is ok,
99 * X509_STORE_CTX_set_error(x509_ctx, X509_V_OK); must be set and
100 * return value is 0 from callback */
102 int err = X509_STORE_CTX_get_error(x509_ctx);
104 if (err != X509_V_OK) {
105 /* cert validation error was not handled in callback */
106 int depth = X509_STORE_CTX_get_error_depth(x509_ctx);
107 const char *msg = X509_verify_cert_error_string(err);
109 lwsl_err("SSL error: %s (preverify_ok=%d;err=%d;"
110 "depth=%d)\n", msg, preverify_ok, err, depth);
112 return preverify_ok; // not ok
116 * convert callback return code from 0 = OK to verify callback
117 * return value 1 = OK
125 lws_ssl_client_bio_create(struct lws *wsi)
127 char hostname[128], *p;
128 #if defined(LWS_HAVE_SSL_set_alpn_protos) && \
129 defined(LWS_HAVE_SSL_get0_alpn_selected)
130 uint8_t openssl_alpn[40];
131 const char *alpn_comma = wsi->context->tls.alpn_default;
135 #if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)
136 if (lws_hdr_copy(wsi, hostname, sizeof(hostname),
137 _WSI_TOKEN_CLIENT_HOST) <= 0)
140 lwsl_err("%s: Unable to get hostname\n", __func__);
146 * remove any :port part on the hostname... necessary for network
147 * connection but typical certificates do not contain it
158 wsi->tls.ssl = SSL_new(wsi->vhost->tls.ssl_client_ctx);
160 lwsl_err("SSL_new failed: %s\n",
161 ERR_error_string(lws_ssl_get_error(wsi, 0), NULL));
162 lws_tls_err_describe_clear();
166 #if defined (LWS_HAVE_SSL_SET_INFO_CALLBACK)
167 if (wsi->vhost->tls.ssl_info_event_mask)
168 SSL_set_info_callback(wsi->tls.ssl, lws_ssl_info_callback);
171 #if defined LWS_HAVE_X509_VERIFY_PARAM_set1_host
172 if (!(wsi->tls.use_ssl & LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK)) {
173 X509_VERIFY_PARAM *param = SSL_get0_param(wsi->tls.ssl);
175 /* Enable automatic hostname checks */
176 X509_VERIFY_PARAM_set_hostflags(param,
177 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
178 // Handle the case where the hostname is an IP address.
179 if (!X509_VERIFY_PARAM_set1_ip_asc(param, hostname))
180 X509_VERIFY_PARAM_set1_host(param, hostname, 0);
184 #if !defined(USE_WOLFSSL)
185 #ifndef USE_OLD_CYASSL
186 /* OpenSSL_client_verify_callback will be called @ SSL_connect() */
187 SSL_set_verify(wsi->tls.ssl, SSL_VERIFY_PEER,
188 OpenSSL_client_verify_callback);
192 #if !defined(USE_WOLFSSL)
193 SSL_set_mode(wsi->tls.ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
196 * use server name indication (SNI), if supported,
197 * when establishing connection
200 #ifdef USE_OLD_CYASSL
201 #ifdef CYASSL_SNI_HOST_NAME
202 CyaSSL_UseSNI(wsi->tls.ssl, CYASSL_SNI_HOST_NAME, hostname,
206 #ifdef WOLFSSL_SNI_HOST_NAME
207 wolfSSL_UseSNI(wsi->tls.ssl, WOLFSSL_SNI_HOST_NAME, hostname,
212 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
213 SSL_set_tlsext_host_name(wsi->tls.ssl, hostname);
219 * wolfSSL/CyaSSL does certificate verification differently
221 * If we should ignore the certificate, we need to set
222 * this before SSL_new and SSL_connect is called.
223 * Otherwise the connect will simply fail with error code -155
225 #ifdef USE_OLD_CYASSL
226 if (wsi->tls.use_ssl == 2)
227 CyaSSL_set_verify(wsi->tls.ssl, SSL_VERIFY_NONE, NULL);
229 if (wsi->tls.use_ssl == 2)
230 wolfSSL_set_verify(wsi->tls.ssl, SSL_VERIFY_NONE, NULL);
232 #endif /* USE_WOLFSSL */
234 wsi->tls.client_bio = BIO_new_socket((int)(long long)wsi->desc.sockfd,
236 SSL_set_bio(wsi->tls.ssl, wsi->tls.client_bio, wsi->tls.client_bio);
239 #ifdef USE_OLD_CYASSL
240 CyaSSL_set_using_nonblock(wsi->tls.ssl, 1);
242 wolfSSL_set_using_nonblock(wsi->tls.ssl, 1);
245 BIO_set_nbio(wsi->tls.client_bio, 1); /* nonblocking */
248 #if defined(LWS_HAVE_SSL_set_alpn_protos) && \
249 defined(LWS_HAVE_SSL_get0_alpn_selected)
250 if (wsi->vhost->tls.alpn)
251 alpn_comma = wsi->vhost->tls.alpn;
252 #if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)
253 if (lws_hdr_copy(wsi, hostname, sizeof(hostname),
254 _WSI_TOKEN_CLIENT_ALPN) > 0)
255 alpn_comma = hostname;
258 lwsl_info("client conn using alpn list '%s'\n", alpn_comma);
260 n = lws_alpn_comma_to_openssl(alpn_comma, openssl_alpn,
261 sizeof(openssl_alpn) - 1);
263 SSL_set_alpn_protos(wsi->tls.ssl, openssl_alpn, n);
266 SSL_set_ex_data(wsi->tls.ssl, openssl_websocket_private_data_index,
272 enum lws_ssl_capable_status
273 lws_tls_client_connect(struct lws *wsi)
275 #if defined(LWS_HAVE_SSL_set_alpn_protos) && \
276 defined(LWS_HAVE_SSL_get0_alpn_selected)
277 const unsigned char *prot;
285 n = SSL_connect(wsi->tls.ssl);
287 #if defined(LWS_HAVE_SSL_set_alpn_protos) && \
288 defined(LWS_HAVE_SSL_get0_alpn_selected)
289 SSL_get0_alpn_selected(wsi->tls.ssl, &prot, &len);
291 if (len >= sizeof(a))
293 memcpy(a, (const char *)prot, len);
296 lws_role_call_alpn_negotiated(wsi, (const char *)a);
298 lwsl_info("client connect OK\n");
299 lws_openssl_describe_cipher(wsi);
300 return LWS_SSL_CAPABLE_DONE;
303 m = lws_ssl_get_error(wsi, n);
305 if (m == SSL_ERROR_SYSCALL)
306 return LWS_SSL_CAPABLE_ERROR;
308 if (m == SSL_ERROR_WANT_READ || SSL_want_read(wsi->tls.ssl))
309 return LWS_SSL_CAPABLE_MORE_SERVICE_READ;
311 if (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->tls.ssl))
312 return LWS_SSL_CAPABLE_MORE_SERVICE_WRITE;
314 if (!n) /* we don't know what he wants, but he says to retry */
315 return LWS_SSL_CAPABLE_MORE_SERVICE;
317 return LWS_SSL_CAPABLE_ERROR;
321 lws_tls_client_confirm_peer_cert(struct lws *wsi, char *ebuf, int ebuf_len)
323 #if !defined(USE_WOLFSSL)
324 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
325 char *p = (char *)&pt->serv_buf[0];
329 lws_latency_pre(wsi->context, wsi);
332 n = SSL_get_verify_result(wsi->tls.ssl);
333 lws_latency(wsi->context, wsi,
334 "SSL_get_verify_result LWS_CONNMODE..HANDSHAKE", n, n > 0);
336 lwsl_debug("get_verify says %d\n", n);
341 if ((n == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
342 n == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) &&
343 (wsi->tls.use_ssl & LCCSCF_ALLOW_SELFSIGNED)) {
344 lwsl_info("accepting self-signed certificate\n");
348 if ((n == X509_V_ERR_CERT_NOT_YET_VALID ||
349 n == X509_V_ERR_CERT_HAS_EXPIRED) &&
350 (wsi->tls.use_ssl & LCCSCF_ALLOW_EXPIRED)) {
351 lwsl_info("accepting expired certificate\n");
354 if (n == X509_V_ERR_CERT_NOT_YET_VALID) {
355 lwsl_info("Cert is from the future... "
356 "probably our clock... accepting...\n");
359 lws_snprintf(ebuf, ebuf_len,
360 "server's cert didn't look good, X509_V_ERR = %d: %s\n",
361 n, ERR_error_string(n, sb));
362 lwsl_info("%s\n", ebuf);
363 lws_tls_err_describe_clear();
367 #else /* USE_WOLFSSL */
373 lws_tls_client_create_vhost_context(struct lws_vhost *vh,
374 const struct lws_context_creation_info *info,
375 const char *cipher_list,
376 const char *ca_filepath,
378 unsigned int ca_mem_len,
379 const char *cert_filepath,
380 const void *cert_mem,
381 unsigned int cert_mem_len,
382 const char *private_key_filepath)
384 struct lws_tls_client_reuse *tcr;
385 const unsigned char *ca_mem_ptr;
386 X509_STORE *x509_store;
396 /* basic openssl init already happened in context init */
398 /* choose the most recent spin of the api */
399 #if defined(LWS_HAVE_TLS_CLIENT_METHOD)
400 method = (SSL_METHOD *)TLS_client_method();
401 #elif defined(LWS_HAVE_TLSV1_2_CLIENT_METHOD)
402 method = (SSL_METHOD *)TLSv1_2_client_method();
404 method = (SSL_METHOD *)SSLv23_client_method();
408 error = ERR_get_error();
409 lwsl_err("problem creating ssl method %lu: %s\n",
410 error, ERR_error_string(error,
411 (char *)vh->context->pt[0].serv_buf));
416 * OpenSSL client contexts are quite expensive, because they bring in
417 * the system certificate bundle for each one. So if you have multiple
418 * vhosts, each with a client context, it can add up to several
419 * megabytes of heap. In the case the client contexts are configured
420 * identically, they could perfectly well have shared just the one.
422 * For that reason, use a hash to fingerprint the context configuration
423 * and prefer to reuse an existing one with the same fingerprint if
427 mdctx = EVP_MD_CTX_create();
431 if (EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL) != 1) {
432 EVP_MD_CTX_destroy(mdctx);
437 if (info->ssl_client_options_set)
438 EVP_DigestUpdate(mdctx, &info->ssl_client_options_set,
439 sizeof(info->ssl_client_options_set));
441 #if (OPENSSL_VERSION_NUMBER >= 0x009080df) && !defined(USE_WOLFSSL)
442 if (info->ssl_client_options_clear)
443 EVP_DigestUpdate(mdctx, &info->ssl_client_options_clear,
444 sizeof(info->ssl_client_options_clear));
448 EVP_DigestUpdate(mdctx, cipher_list, strlen(cipher_list));
450 #if defined(LWS_HAVE_SSL_CTX_set_ciphersuites)
451 if (info->client_tls_1_3_plus_cipher_list)
452 EVP_DigestUpdate(mdctx, info->client_tls_1_3_plus_cipher_list,
453 strlen(info->client_tls_1_3_plus_cipher_list));
456 if (!lws_check_opt(vh->options, LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS)) {
458 EVP_DigestUpdate(mdctx, &c, 1);
462 EVP_DigestUpdate(mdctx, ca_filepath, strlen(ca_filepath));
465 EVP_DigestUpdate(mdctx, cert_filepath, strlen(cert_filepath));
467 if (private_key_filepath)
468 EVP_DigestUpdate(mdctx, private_key_filepath,
469 strlen(private_key_filepath));
470 if (ca_mem && ca_mem_len)
471 EVP_DigestUpdate(mdctx, ca_mem, ca_mem_len);
473 if (cert_mem && cert_mem_len)
474 EVP_DigestUpdate(mdctx, cert_mem, cert_mem_len);
477 EVP_DigestFinal_ex(mdctx, hash, &len);
478 EVP_MD_CTX_destroy(mdctx);
480 /* look for existing client context with same config already */
482 lws_start_foreach_dll_safe(struct lws_dll2 *, p, tp,
483 lws_dll2_get_head(&vh->context->tls.cc_owner)) {
484 tcr = lws_container_of(p, struct lws_tls_client_reuse, cc_list);
486 if (!memcmp(hash, tcr->hash, len)) {
491 vh->tls.ssl_client_ctx = tcr->ssl_client_ctx;
493 lwsl_info("%s: vh %s: reusing client ctx %d: use %d\n",
494 __func__, vh->name, tcr->index,
499 } lws_end_foreach_dll_safe(p, tp);
501 /* no existing one the same... create new client SSL_CTX */
505 vh->tls.ssl_client_ctx = SSL_CTX_new(method);
506 if (!vh->tls.ssl_client_ctx) {
507 error = ERR_get_error();
508 lwsl_err("problem creating ssl context %lu: %s\n",
509 error, ERR_error_string(error,
510 (char *)vh->context->pt[0].serv_buf));
514 tcr = lws_zalloc(sizeof(*tcr), "client ctx tcr");
516 SSL_CTX_free(vh->tls.ssl_client_ctx);
520 tcr->ssl_client_ctx = vh->tls.ssl_client_ctx;
522 memcpy(tcr->hash, hash, len);
523 tcr->index = vh->context->tls.count_client_contexts++;
524 lws_dll2_add_head(&tcr->cc_list, &vh->context->tls.cc_owner);
526 lwsl_info("%s: vh %s: created new client ctx %d\n", __func__,
527 vh->name, tcr->index);
529 /* bind the tcr to the client context */
531 SSL_CTX_set_ex_data(vh->tls.ssl_client_ctx,
532 openssl_SSL_CTX_private_data_index,
535 #ifdef SSL_OP_NO_COMPRESSION
536 SSL_CTX_set_options(vh->tls.ssl_client_ctx, SSL_OP_NO_COMPRESSION);
539 SSL_CTX_set_options(vh->tls.ssl_client_ctx,
540 SSL_OP_CIPHER_SERVER_PREFERENCE);
542 SSL_CTX_set_mode(vh->tls.ssl_client_ctx,
543 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
544 SSL_MODE_RELEASE_BUFFERS);
546 if (info->ssl_client_options_set)
547 SSL_CTX_set_options(vh->tls.ssl_client_ctx,
548 info->ssl_client_options_set);
550 /* SSL_clear_options introduced in 0.9.8m */
551 #if (OPENSSL_VERSION_NUMBER >= 0x009080df) && !defined(USE_WOLFSSL)
552 if (info->ssl_client_options_clear)
553 SSL_CTX_clear_options(vh->tls.ssl_client_ctx,
554 info->ssl_client_options_clear);
558 SSL_CTX_set_cipher_list(vh->tls.ssl_client_ctx, cipher_list);
560 #if defined(LWS_HAVE_SSL_CTX_set_ciphersuites)
561 if (info->client_tls_1_3_plus_cipher_list)
562 SSL_CTX_set_ciphersuites(vh->tls.ssl_client_ctx,
563 info->client_tls_1_3_plus_cipher_list);
566 #ifdef LWS_SSL_CLIENT_USE_OS_CA_CERTS
567 if (!lws_check_opt(vh->options, LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS))
568 /* loads OS default CA certs */
569 SSL_CTX_set_default_verify_paths(vh->tls.ssl_client_ctx);
572 /* openssl init for cert verification (for client sockets) */
573 if (!ca_filepath && (!ca_mem || !ca_mem_len)) {
574 if (!SSL_CTX_load_verify_locations(
575 vh->tls.ssl_client_ctx, NULL, LWS_OPENSSL_CLIENT_CERTS))
576 lwsl_err("Unable to load SSL Client certs from %s "
577 "(set by LWS_OPENSSL_CLIENT_CERTS) -- "
578 "client ssl isn't going to work\n",
579 LWS_OPENSSL_CLIENT_CERTS);
580 } else if (ca_filepath) {
581 if (!SSL_CTX_load_verify_locations(
582 vh->tls.ssl_client_ctx, ca_filepath, NULL)) {
584 "Unable to load SSL Client certs "
585 "file from %s -- client ssl isn't "
586 "going to work\n", ca_filepath);
587 lws_tls_err_describe_clear();
590 lwsl_info("loaded ssl_ca_filepath\n");
592 ca_mem_ptr = (const unsigned char*)ca_mem;
593 client_CA = d2i_X509(NULL, &ca_mem_ptr, ca_mem_len);
594 x509_store = X509_STORE_new();
595 if (!client_CA || !X509_STORE_add_cert(x509_store, client_CA)) {
596 X509_STORE_free(x509_store);
597 lwsl_err("Unable to load SSL Client certs from "
598 "ssl_ca_mem -- client ssl isn't going to "
600 lws_tls_err_describe_clear();
602 /* it doesn't increment x509_store ref counter */
603 SSL_CTX_set_cert_store(vh->tls.ssl_client_ctx,
605 lwsl_info("loaded ssl_ca_mem\n");
608 X509_free(client_CA);
612 * callback allowing user code to load extra verification certs
613 * helping the client to verify server identity
616 /* support for client-side certificate authentication */
618 if (lws_tls_use_any_upgrade_check_extant(cert_filepath) !=
619 LWS_TLS_EXTANT_YES &&
620 (info->options & LWS_SERVER_OPTION_IGNORE_MISSING_CERT))
623 lwsl_notice("%s: doing cert filepath %s\n", __func__,
625 n = SSL_CTX_use_certificate_chain_file(vh->tls.ssl_client_ctx,
628 lwsl_err("problem %d getting cert '%s'\n", n,
630 lws_tls_err_describe_clear();
633 lwsl_notice("Loaded client cert %s\n", cert_filepath);
634 } else if (cert_mem && cert_mem_len) {
635 n = SSL_CTX_use_certificate_ASN1(vh->tls.ssl_client_ctx,
636 cert_mem_len, cert_mem);
638 lwsl_err("%s: problem interpreting client cert\n",
640 lws_tls_err_describe_clear();
644 if (private_key_filepath) {
645 lwsl_notice("%s: doing private key filepath\n", __func__);
646 lws_ssl_bind_passphrase(vh->tls.ssl_client_ctx, 1, info);
647 /* set the private key from KeyFile */
648 if (SSL_CTX_use_PrivateKey_file(vh->tls.ssl_client_ctx,
649 private_key_filepath, SSL_FILETYPE_PEM) != 1) {
650 lwsl_err("use_PrivateKey_file '%s'\n",
651 private_key_filepath);
652 lws_tls_err_describe_clear();
655 lwsl_notice("Loaded client cert private key %s\n",
656 private_key_filepath);
658 /* verify private key */
659 if (!SSL_CTX_check_private_key(vh->tls.ssl_client_ctx)) {
660 lwsl_err("Private SSL key doesn't match cert\n");