Coverage Report

Created: 2026-09-04 06:34

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libwebsockets/lib/tls/openssl/openssl-client.c
Line
Count
Source
1
/*
2
 * libwebsockets - small server side websockets and web server implementation
3
 *
4
 * Copyright (C) 2010 - 2019 Andy Green <andy@warmcat.com>
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to
8
 * deal in the Software without restriction, including without limitation the
9
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10
 * sell copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22
 * IN THE SOFTWARE.
23
 */
24
25
#include "lws_config.h"
26
#ifdef LWS_HAVE_X509_VERIFY_PARAM_set1_host
27
/* Before glibc 2.10, strnlen required _GNU_SOURCE */
28
#if !defined(_GNU_SOURCE)
29
#define _GNU_SOURCE
30
#endif
31
#endif
32
#include <string.h>
33
34
#include "private-lib-core.h"
35
#include "private-lib-tls-openssl.h"
36
37
/*
38
 * Care: many openssl apis return 1 for success.  These are translated to the
39
 * lws convention of 0 for success.
40
 */
41
42
int lws_openssl_describe_cipher(struct lws *wsi);
43
44
extern int openssl_websocket_private_data_index,
45
    openssl_SSL_CTX_private_data_index;
46
47
#if !defined(USE_WOLFSSL)
48
49
#if 0
50
#if defined(LWS_WITH_TLS_JIT_TRUST)
51
52
/*
53
 * Completion of sync or async JIT trust lookup
54
 */
55
56
int
57
lws_tls_jit_trust_got_cert_cb(void *got_opaque, const uint8_t *der,
58
            size_t der_len)
59
{
60
  X509 *x = d2i_X509(NULL, &der, (long)der_len);
61
  /** !!! this is not safe for async atm */
62
  struct lws *wsi = (struct lws *)got_opaque;
63
  X509_STORE *xs;
64
  int ret = 0;
65
66
  if (!x) {
67
    lwsl_err("%s: failed\n", __func__);
68
    return 1;
69
  }
70
71
  xs = SSL_CTX_get_cert_store(SSL_get_SSL_CTX(wsi->tls.ssl));
72
  if (xs) {
73
    if (X509_STORE_add_cert(xs, x) != 1) {
74
      lwsl_warn("%s: unable to set trusted CA\n", __func__);
75
      ret = 1;
76
    } else
77
      lwsl_notice("%s: added trusted CA to CTX for next time\n",
78
          __func__);
79
  } else
80
    lwsl_warn("%s: couldn't get cert store\n", __func__);
81
82
  X509_free(x);
83
84
  return ret;
85
}
86
#endif
87
#endif
88
89
static int
90
OpenSSL_client_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
91
0
{
92
0
  SSL *ssl;
93
0
  int n, err = 0;
94
0
  struct lws *wsi;
95
0
  const struct lws_protocols *lp;
96
97
  /* keep old behaviour accepting self-signed server certs */
98
0
  if (!preverify_ok) {
99
0
    err = X509_STORE_CTX_get_error(x509_ctx);
100
101
0
    if (err != X509_V_OK) {
102
0
      ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
103
0
          SSL_get_ex_data_X509_STORE_CTX_idx());
104
0
      wsi = SSL_get_ex_data(ssl,
105
0
          openssl_websocket_private_data_index);
106
0
      if (!wsi) {
107
0
        lwsl_err("%s: can't get wsi from ssl privdata\n",
108
0
           __func__);
109
110
0
        return 0;
111
0
      }
112
113
0
      if ((err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
114
0
           err == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) &&
115
0
           wsi->tls.use_ssl & LCCSCF_ALLOW_SELFSIGNED) {
116
0
        lwsl_notice("accepting self-signed "
117
0
              "certificate (verify_callback)\n");
118
0
        X509_STORE_CTX_set_error(x509_ctx, X509_V_OK);
119
0
        return 1; // ok
120
0
    } else if ((err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY ||
121
0
          err == X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE) &&
122
0
          wsi->tls.use_ssl & LCCSCF_ALLOW_INSECURE) {
123
0
        lwsl_notice("accepting non-trusted certificate\n");
124
0
        X509_STORE_CTX_set_error(x509_ctx, X509_V_OK);
125
0
        return 1;  /* ok */
126
0
      } else if ((err == X509_V_ERR_CERT_NOT_YET_VALID ||
127
0
            err == X509_V_ERR_CERT_HAS_EXPIRED) &&
128
0
            wsi->tls.use_ssl & LCCSCF_ALLOW_EXPIRED) {
129
0
        if (err == X509_V_ERR_CERT_NOT_YET_VALID)
130
0
          lwsl_notice("accepting not yet valid "
131
0
                "certificate (verify_"
132
0
                "callback)\n");
133
0
        else if (err == X509_V_ERR_CERT_HAS_EXPIRED)
134
0
          lwsl_notice("accepting expired "
135
0
                "certificate (verify_"
136
0
                "callback)\n");
137
0
        X509_STORE_CTX_set_error(x509_ctx, X509_V_OK);
138
0
        return 1; // ok
139
0
      }
140
0
    }
141
0
  }
142
143
0
  ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
144
0
           SSL_get_ex_data_X509_STORE_CTX_idx());
145
0
  wsi = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
146
0
  if (!wsi) {
147
0
    lwsl_err("%s: can't get wsi from ssl privdata\n",  __func__);
148
149
0
    return 0;
150
0
  }
151
152
#if defined(LWS_WITH_TLS_JIT_TRUST)
153
  if (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY) {
154
    union lws_tls_cert_info_results ci;
155
    STACK_OF(X509) *x509_stack;
156
157
    x509_stack = X509_STORE_CTX_get1_chain(x509_ctx);
158
    if (x509_stack) {
159
160
      for (n = 0; n < OPENSSL_sk_num((const OPENSSL_STACK *)x509_stack) &&
161
            wsi->tls.kid_chain.count !=
162
             LWS_ARRAY_SIZE(wsi->tls.kid_chain.akid); n++) {
163
        X509 *x509 = OPENSSL_sk_value((const OPENSSL_STACK *)x509_stack, n);
164
165
        if (!lws_tls_openssl_cert_info(x509,
166
              LWS_TLS_CERT_INFO_SUBJECT_KEY_ID,
167
              &ci, 0))
168
          lws_tls_kid_copy(&ci,
169
            &wsi->tls.kid_chain.skid[
170
                 wsi->tls.kid_chain.count]);
171
172
        if (!lws_tls_openssl_cert_info(x509,
173
               LWS_TLS_CERT_INFO_AUTHORITY_KEY_ID,
174
               &ci, 0))
175
          lws_tls_kid_copy(&ci,
176
             &wsi->tls.kid_chain.akid[
177
                 wsi->tls.kid_chain.count]);
178
179
        wsi->tls.kid_chain.count++;
180
      }
181
182
      sk_X509_pop_free(x509_stack, X509_free);
183
    }
184
185
    lws_tls_jit_trust_sort_kids(wsi, &wsi->tls.kid_chain);
186
  }
187
#endif
188
0
  lp = &(lws_get_context_protocol(wsi->a.context, 0));
189
0
  if (wsi->a.protocol)
190
0
    lp = wsi->a.protocol;
191
192
0
  n = lp->callback(wsi,
193
0
      LWS_CALLBACK_OPENSSL_PERFORM_SERVER_CERT_VERIFICATION,
194
0
      x509_ctx, ssl, (unsigned int)preverify_ok);
195
196
  /* keep old behaviour if something wrong with server certs */
197
  /* if ssl error is overruled in callback and cert is ok,
198
   * X509_STORE_CTX_set_error(x509_ctx, X509_V_OK); must be set and
199
   * return value is 0 from callback */
200
0
  if (!preverify_ok) {
201
0
    int err = X509_STORE_CTX_get_error(x509_ctx);
202
203
0
    if (err != X509_V_OK) {
204
      /* cert validation error was not handled in callback */
205
0
      int depth = X509_STORE_CTX_get_error_depth(x509_ctx);
206
0
      const char *msg = X509_verify_cert_error_string(err);
207
208
0
      lws_strncpy(wsi->tls.err_helper, msg,
209
0
            sizeof(wsi->tls.err_helper));
210
211
0
      lwsl_err("SSL error: %s (preverify_ok=%d;err=%d;"
212
0
         "depth=%d)\n", msg, preverify_ok, err, depth);
213
214
0
      if (err == X509_V_ERR_HOSTNAME_MISMATCH) {
215
0
        const char *expected = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
216
0
        char cert_cn[256] = "unknown";
217
0
        X509 *cert = X509_STORE_CTX_get_current_cert(x509_ctx);
218
0
        if (cert) {
219
0
          const X509_NAME *subject = X509_get_subject_name(cert);
220
0
          if (subject)
221
0
            X509_NAME_get_text_by_NID(subject, NID_commonName, cert_cn, sizeof(cert_cn));
222
0
        }
223
0
        lwsl_err("Hostname mismatch details: Expected='%s', Cert CN='%s'\n",
224
0
          expected ? expected : "unknown", cert_cn);
225
0
      }
226
227
#if defined(LWS_WITH_SYS_METRICS)
228
      {
229
        char buckname[64];
230
231
        lws_snprintf(buckname, sizeof(buckname),
232
               "tls=\"%s\"", msg);
233
        lws_metrics_hist_bump_describe_wsi(wsi,
234
          lws_metrics_priv_to_pub(wsi->a.context->mth_conn_failures),
235
          buckname);
236
      }
237
#endif
238
239
0
      return preverify_ok;  // not ok
240
0
    }
241
0
  }
242
  /*
243
   * convert callback return code from 0 = OK to verify callback
244
   * return value 1 = OK
245
   */
246
0
  return !n;
247
0
}
248
#endif
249
250
int
251
lws_ssl_client_bio_create(struct lws *wsi)
252
0
{
253
0
  char hostname[128], *p;
254
0
#if (defined(LWS_HAVE_SSL_set_alpn_protos) || defined(OPENSSL_IS_AWSLC)) && \
255
0
    (defined(LWS_HAVE_SSL_get0_alpn_selected) || defined(OPENSSL_IS_AWSLC))
256
0
  uint8_t openssl_alpn[40];
257
0
  const char *alpn_comma = wsi->a.context->tls.alpn_default;
258
0
  int n;
259
0
#endif
260
261
0
  if (wsi->stash) {
262
0
    lws_strncpy(hostname, wsi->stash->cis[CIS_HOST], sizeof(hostname));
263
0
#if (defined(LWS_HAVE_SSL_set_alpn_protos) || defined(OPENSSL_IS_AWSLC)) && \
264
0
    (defined(LWS_HAVE_SSL_get0_alpn_selected) || defined(OPENSSL_IS_AWSLC))
265
0
    alpn_comma = wsi->stash->cis[CIS_ALPN];
266
0
#endif
267
0
  } else {
268
0
#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)
269
0
    if (lws_hdr_copy(wsi, hostname, sizeof(hostname),
270
0
         _WSI_TOKEN_CLIENT_HOST) <= 0)
271
0
#endif
272
0
    {
273
0
      lwsl_err("%s: Unable to get hostname\n", __func__);
274
275
0
      return -1;
276
0
    }
277
0
  }
278
279
  /*
280
   * remove any :port part on the hostname... necessary for network
281
   * connection but typical certificates do not contain it
282
   */
283
0
  p = hostname;
284
0
  while (*p) {
285
0
    if (*p == ':') {
286
0
      *p = '\0';
287
0
      break;
288
0
    }
289
0
    p++;
290
0
  }
291
292
0
  wsi->tls.ssl = SSL_new(wsi->a.vhost->tls.ssl_client_ctx);
293
0
  if (!wsi->tls.ssl) {
294
0
    unsigned long err = ERR_get_error();
295
0
    const char *es = ERR_error_string(LWS_TLS_ERR_CAST(err), NULL);
296
0
    lwsl_err("SSL_new failed: %s (real error %lu)\n", es, err);
297
0
    lws_tls_err_describe_clear();
298
0
    return -1;
299
0
  }
300
301
0
#if defined(LWS_WITH_TLS_SESSIONS)
302
0
  if (!(wsi->a.vhost->options & LWS_SERVER_OPTION_DISABLE_TLS_SESSION_CACHE))
303
0
    lws_tls_reuse_session(wsi);
304
0
#endif
305
306
0
#if defined (LWS_HAVE_SSL_SET_INFO_CALLBACK)
307
0
  if (wsi->a.vhost->tls.ssl_info_event_mask)
308
0
    SSL_set_info_callback(wsi->tls.ssl, lws_ssl_info_callback);
309
0
#endif
310
311
0
#if defined(LWS_HAVE_X509_VERIFY_PARAM_set1_host)
312
0
  if (!(wsi->tls.use_ssl & LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK)) {
313
0
#if !defined(USE_WOLFSSL)
314
315
0
    X509_VERIFY_PARAM *param = SSL_get0_param(wsi->tls.ssl);
316
317
    /* Enable automatic hostname checks */
318
0
    X509_VERIFY_PARAM_set_hostflags(param,
319
0
          X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
320
    /* Handle the case where the hostname is an IP address */
321
0
    if (!X509_VERIFY_PARAM_set1_ip_asc(param, hostname))
322
0
      X509_VERIFY_PARAM_set1_host(param, hostname,
323
0
          strnlen(hostname, sizeof(hostname)));
324
0
#endif
325
326
0
  }
327
#else
328
  if (!(wsi->tls.use_ssl & LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK)) {
329
    lwsl_err("%s: your tls lib is too old to have "
330
       "X509_VERIFY_PARAM_set1_host, failing all client tls\n",
331
       __func__);
332
    return -1;
333
  }
334
#endif
335
336
0
#if !defined(USE_WOLFSSL)
337
0
#ifndef USE_OLD_CYASSL
338
  /* OpenSSL_client_verify_callback will be called @ SSL_connect() */
339
0
  SSL_set_verify(wsi->tls.ssl, SSL_VERIFY_PEER,
340
0
           OpenSSL_client_verify_callback);
341
0
#endif
342
0
#endif
343
344
0
#if !defined(USE_WOLFSSL)
345
0
  SSL_set_mode(wsi->tls.ssl,  SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
346
0
#endif
347
  /*
348
   * use server name indication (SNI), if supported,
349
   * when establishing connection
350
   */
351
#ifdef USE_WOLFSSL
352
#ifdef USE_OLD_CYASSL
353
#ifdef CYASSL_SNI_HOST_NAME
354
  CyaSSL_UseSNI(wsi->tls.ssl, CYASSL_SNI_HOST_NAME, hostname,
355
          strlen(hostname));
356
#endif
357
#else
358
#if defined(WOLFSSL_SNI_HOST_NAME) || defined(HAVE_SNI)
359
  wolfSSL_UseSNI(wsi->tls.ssl, WOLFSSL_SNI_HOST_NAME, hostname,
360
           (unsigned short)strlen(hostname));
361
#endif
362
#endif
363
#else
364
0
#if defined(SSL_CTRL_SET_TLSEXT_HOSTNAME) || defined(LWS_HAVE_SSL_set_tlsext_host_name)
365
0
  SSL_set_tlsext_host_name(wsi->tls.ssl, hostname);
366
0
#endif
367
0
#endif
368
369
#ifdef USE_WOLFSSL
370
  /*
371
   * wolfSSL/CyaSSL does certificate verification differently
372
   * from OpenSSL.
373
   * If we should ignore the certificate, we need to set
374
   * this before SSL_new and SSL_connect is called.
375
   * Otherwise the connect will simply fail with error code -155
376
   */
377
#ifdef USE_OLD_CYASSL
378
  if (wsi->tls.use_ssl & LCCSCF_ALLOW_SELFSIGNED)
379
    CyaSSL_set_verify(wsi->tls.ssl, SSL_VERIFY_NONE, NULL);
380
#else
381
  if (wsi->tls.use_ssl & LCCSCF_ALLOW_SELFSIGNED)
382
    wolfSSL_set_verify(wsi->tls.ssl, SSL_VERIFY_NONE, NULL);
383
#endif
384
#endif /* USE_WOLFSSL */
385
386
0
  wsi->tls.client_bio = BIO_new_socket((int)(lws_intptr_t)wsi->desc.sockfd,
387
0
               BIO_NOCLOSE);
388
0
  SSL_set_bio(wsi->tls.ssl, wsi->tls.client_bio, wsi->tls.client_bio);
389
390
#ifdef USE_WOLFSSL
391
#ifdef USE_OLD_CYASSL
392
  CyaSSL_set_using_nonblock(wsi->tls.ssl, 1);
393
#else
394
  wolfSSL_set_using_nonblock(wsi->tls.ssl, 1);
395
#endif
396
#else
397
0
  BIO_set_nbio(wsi->tls.client_bio, 1); /* nonblocking */
398
0
#endif
399
400
0
#if (defined(LWS_HAVE_SSL_set_alpn_protos) || defined(OPENSSL_IS_AWSLC)) && \
401
0
    (defined(LWS_HAVE_SSL_get0_alpn_selected) || defined(OPENSSL_IS_AWSLC))
402
0
  if (wsi->a.vhost->tls.alpn)
403
0
    alpn_comma = wsi->a.vhost->tls.alpn;
404
0
  if (wsi->role_ops && !strcmp(wsi->role_ops->name, "quic")) {
405
    /*
406
     * QUIC only carries QUIC-mapped ALPNs (h3 family).  The
407
     * stash / vhost lists are the TCP ALPNs (eg, "h2,http/1.1"):
408
     * offering those on QUIC can get "h2" negotiated on top of
409
     * the UDP transport, where the h2 role can never make
410
     * progress.  For the alt-svc QUIC race, connect2 puts the
411
     * h3-only list in wsi->alpn (the TCP fallback restores the
412
     * original from there); native h3 streams also carry their
413
     * ALPN in wsi->alpn.
414
     */
415
0
    alpn_comma = wsi->alpn[0] ? wsi->alpn : "h3";
416
0
  } else
417
0
  if (wsi->stash) {
418
0
    alpn_comma = wsi->stash->cis[CIS_ALPN];
419
0
#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)
420
0
  } else {
421
0
    if (lws_hdr_copy(wsi, hostname, sizeof(hostname),
422
0
         _WSI_TOKEN_CLIENT_ALPN) > 0)
423
0
      alpn_comma = hostname;
424
0
#endif
425
0
  }
426
427
0
  lwsl_info("%s client conn using alpn list '%s'\n", wsi->role_ops->name, alpn_comma);
428
429
0
  n = lws_alpn_comma_to_openssl(alpn_comma, openssl_alpn,
430
0
              sizeof(openssl_alpn) - 1);
431
432
0
  SSL_set_alpn_protos(wsi->tls.ssl, openssl_alpn, (unsigned int)n);
433
0
#endif
434
435
0
  SSL_set_ex_data(wsi->tls.ssl, openssl_websocket_private_data_index,
436
0
      wsi);
437
438
0
  if (wsi->sys_tls_client_cert) {
439
0
    lws_system_blob_t *b = lws_system_get_blob(wsi->a.context,
440
0
          LWS_SYSBLOB_TYPE_CLIENT_CERT_DER,
441
0
          wsi->sys_tls_client_cert - 1);
442
0
    const uint8_t *data;
443
0
    size_t size;
444
445
0
    if (!b)
446
0
      goto no_client_cert;
447
448
    /*
449
     * Set up the per-connection client cert
450
     */
451
452
0
    size = lws_system_blob_get_size(b);
453
0
    if (!size)
454
0
      goto no_client_cert;
455
456
0
    if (lws_system_blob_get_single_ptr(b, &data))
457
0
      goto no_client_cert;
458
459
0
    if (SSL_use_certificate_ASN1(wsi->tls.ssl, SSL_DATA_CAST(data),
460
0
      SSL_SIZE_T_CAST(size)) != 1) {
461
0
      lwsl_err("%s: use_certificate failed\n", __func__);
462
0
      lws_tls_err_describe_clear();
463
0
      goto no_client_cert;
464
0
    }
465
466
0
    b = lws_system_get_blob(wsi->a.context,
467
0
          LWS_SYSBLOB_TYPE_CLIENT_KEY_DER,
468
0
          wsi->sys_tls_client_cert - 1);
469
0
    if (!b)
470
0
      goto no_client_cert;
471
472
0
    size = lws_system_blob_get_size(b);
473
0
    if (!size)
474
0
      goto no_client_cert;
475
476
0
    if (lws_system_blob_get_single_ptr(b, &data))
477
0
      goto no_client_cert;
478
479
0
    if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, wsi->tls.ssl, SSL_DATA_CAST(data),
480
0
      SSL_SIZE_T_CAST(size)) != 1 &&
481
0
        SSL_use_PrivateKey_ASN1(EVP_PKEY_EC, wsi->tls.ssl, SSL_DATA_CAST(data),
482
0
      SSL_SIZE_T_CAST(size)) != 1) {
483
484
0
      lwsl_err("%s: use_privkey failed\n", __func__);
485
0
      lws_tls_err_describe_clear();
486
0
      goto no_client_cert;
487
0
    }
488
489
0
    if (SSL_check_private_key(wsi->tls.ssl) != 1) {
490
0
      lwsl_err("Private SSL key doesn't match cert\n");
491
0
      lws_tls_err_describe_clear();
492
0
      return 1;
493
0
    }
494
495
0
    lwsl_notice("%s: set system client cert %u\n", __func__,
496
0
        wsi->sys_tls_client_cert - 1);
497
0
  }
498
499
0
  return 0;
500
501
0
no_client_cert:
502
0
  lwsl_err("%s: unable to set up system client cert %d\n", __func__,
503
0
      wsi->sys_tls_client_cert - 1);
504
505
0
  return 1;
506
0
}
507
508
#if defined(LWS_WITH_TCP_TLS)
509
enum lws_ssl_capable_status
510
lws_tls_client_connect(struct lws *wsi, char *errbuf, size_t elen)
511
0
{
512
0
  int m, n, en;
513
0
  unsigned long l;
514
0
#if defined(LWS_WITH_TLS_SESSIONS) && defined(LWS_HAVE_SSL_SESSION_set_time)
515
0
  SSL_SESSION *sess;
516
0
#endif
517
0
  errno = 0;
518
0
  ERR_clear_error();
519
0
  wsi->tls.err_helper[0] = '\0';
520
0
  n = SSL_connect(wsi->tls.ssl);
521
0
  en = errno;
522
523
0
  m = lws_ssl_get_error(wsi, n);
524
525
0
  if (m == SSL_ERROR_SYSCALL
526
#if defined(WIN32)
527
      && en
528
#endif
529
0
  ) {
530
0
#if defined(WIN32) || (_LWS_ENABLED_LOGS & LLL_INFO)
531
0
    lwsl_info("%s: n %d, m %d, errno %d\n", __func__, n, m, en);
532
0
#endif
533
0
    lws_snprintf(errbuf, elen, "connect SYSCALL %d", en);
534
0
    return LWS_SSL_CAPABLE_ERROR;
535
0
  }
536
537
0
  if (m == SSL_ERROR_SSL) {
538
0
    l = ERR_get_error();
539
0
    n = lws_snprintf(errbuf, elen, "tls: %s", wsi->tls.err_helper);
540
0
    if (!wsi->tls.err_helper[0])
541
0
      ERR_error_string_n(LWS_TLS_ERR_CAST(l), errbuf + n, (elen - (unsigned int)n));
542
0
    return LWS_SSL_CAPABLE_ERROR;
543
0
  }
544
545
0
#if defined(LWS_WITH_TLS_SESSIONS)
546
0
  if (SSL_session_reused(wsi->tls.ssl)) {
547
0
#if defined(LWS_HAVE_SSL_SESSION_set_time)
548
0
    sess = SSL_get_session(wsi->tls.ssl);
549
0
    if (sess) /* should always be true */
550
#if defined(OPENSSL_IS_BORINGSSL) || defined(LWS_WITH_AWSLC)
551
      SSL_SESSION_set_time(sess, (uint64_t)time(NULL)); /* extend session lifetime */
552
#else
553
0
      SSL_SESSION_set_time(sess, (long)time(NULL)); /* extend session lifetime */
554
0
#endif
555
0
#endif
556
0
  }
557
0
#endif
558
559
0
  if (m == SSL_ERROR_WANT_READ || SSL_want_read(wsi->tls.ssl))
560
0
    return LWS_SSL_CAPABLE_MORE_SERVICE_READ;
561
562
0
  if (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->tls.ssl))
563
0
    return LWS_SSL_CAPABLE_MORE_SERVICE_WRITE;
564
565
0
  if (n == 1 || m == SSL_ERROR_SYSCALL) {
566
    /*
567
     * Handle the negotiated ALPN the same way at handshake
568
     * completion as the gnutls backend does: this also records
569
     * the negotiated ALPN in the client alpn cache, so later
570
     * connections to the same origin can take the stored
571
     * knowledge into account
572
     */
573
0
    lws_tls_server_conn_alpn(wsi);
574
#if defined(LWS_TLS_SYNTHESIZE_CB)
575
    lws_sul_schedule(wsi->a.context, wsi->tsi,
576
         &wsi->tls.sul_cb_synth,
577
         lws_sess_cache_synth_cb, 500 * LWS_US_PER_MS);
578
#endif
579
580
0
    lwsl_info("client connect OK\n");
581
0
    lws_openssl_describe_cipher(wsi);
582
0
    return LWS_SSL_CAPABLE_DONE;
583
0
  }
584
585
0
  if (!n) /* we don't know what he wants, but he says to retry */
586
0
    return LWS_SSL_CAPABLE_MORE_SERVICE_READ;
587
588
0
  lws_snprintf(errbuf, elen, "connect unk %d", m);
589
590
0
  return LWS_SSL_CAPABLE_ERROR;
591
0
}
592
593
int
594
lws_tls_client_confirm_peer_cert(struct lws *wsi, char *ebuf, size_t ebuf_len)
595
0
{
596
0
#if !defined(USE_WOLFSSL)
597
0
  char buf[256];
598
0
  const char *es, *type = "";
599
0
  unsigned int avoid = 0;
600
0
  long n;
601
602
0
  errno = 0;
603
0
  ERR_clear_error();
604
0
  n = SSL_get_verify_result(wsi->tls.ssl);
605
606
0
  switch (n) {
607
0
  case X509_V_OK:
608
0
    return 0;
609
610
0
  case X509_V_ERR_HOSTNAME_MISMATCH:
611
0
    type = "tls=hostname";
612
0
    avoid = LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK;
613
0
    break;
614
615
0
  case X509_V_ERR_INVALID_CA:
616
0
  case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
617
0
  case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
618
0
    type = "tls=invalidca";
619
0
    avoid = LCCSCF_ALLOW_SELFSIGNED;
620
0
    break;
621
622
0
  case X509_V_ERR_CERT_NOT_YET_VALID:
623
0
    type = "tls=notyetvalid";
624
0
    avoid = LCCSCF_ALLOW_EXPIRED;
625
0
    break;
626
627
0
  case X509_V_ERR_CERT_HAS_EXPIRED:
628
0
    type = "tls=expired";
629
0
    avoid = LCCSCF_ALLOW_EXPIRED;
630
0
    break;
631
0
  }
632
633
0
  lwsl_info("%s: cert problem: %s\n", __func__, type);
634
635
#if defined(LWS_WITH_SYS_METRICS)
636
  lws_metrics_hist_bump_describe_wsi(wsi,
637
      lws_metrics_priv_to_pub(wsi->a.context->mth_conn_failures), type);
638
#endif
639
640
0
  if (wsi->tls.use_ssl & avoid) {
641
0
    lwsl_info("%s: allowing anyway\n", __func__);
642
643
0
    return 0;
644
0
  }
645
646
0
  es = ERR_error_string(LWS_TLS_ERR_CAST(n), buf);
647
0
  lws_snprintf(ebuf, ebuf_len,
648
0
    "server's cert didn't look good, %s X509_V_ERR = %ld: %s\n",
649
0
     type, n, es);
650
0
  lwsl_info("%s\n", ebuf);
651
0
  lws_tls_err_describe_clear();
652
653
0
  return -1;
654
655
#else /* USE_WOLFSSL */
656
  return 0;
657
#endif
658
0
}
659
#endif
660
661
int
662
lws_tls_client_vhost_extra_cert_mem(struct lws_vhost *vh,
663
                const uint8_t *der, size_t der_len)
664
0
{
665
0
  X509_STORE *st;
666
#if defined(USE_WOLFSSL)
667
  X509 *x  = d2i_X509(NULL, &der, (int)der_len);
668
#else
669
0
  X509 *x  = d2i_X509(NULL, &der, (long)der_len);
670
0
#endif
671
0
  int n;
672
673
0
  if (!x) {
674
0
    lwsl_err("%s: Failed to load DER\n", __func__);
675
0
    lws_tls_err_describe_clear();
676
0
    return 1;
677
0
  }
678
679
0
  st = SSL_CTX_get_cert_store(vh->tls.ssl_client_ctx);
680
0
  if (!st) {
681
0
    st = X509_STORE_new();
682
0
    if (!st) {
683
0
      lwsl_err("%s: failed to create cert store\n", __func__);
684
0
      X509_free(x);
685
0
      return 1;
686
0
    }
687
0
    SSL_CTX_set_cert_store(vh->tls.ssl_client_ctx, st);
688
0
  }
689
690
0
  n = X509_STORE_add_cert(st, x);
691
0
  if (n != 1)
692
0
    lwsl_err("%s: failed to add cert\n", __func__);
693
694
0
  X509_free(x);
695
696
0
  return n != 1;
697
0
}
698
699
int
700
lws_tls_client_create_vhost_context(struct lws_vhost *vh,
701
            const struct lws_context_creation_info *info,
702
            const char *cipher_list,
703
            const char *ca_filepath,
704
            const void *ca_mem,
705
            unsigned int ca_mem_len,
706
            const char *cert_filepath,
707
            const void *cert_mem,
708
            unsigned int cert_mem_len,
709
            const char *private_key_filepath,
710
          const void *key_mem,
711
            unsigned int key_mem_len
712
          )
713
0
{
714
0
#if defined(LWS_HAVE_SSL_CTX_set1_groups_list)
715
  /*
716
   * the client-specific group list if given, else the generic
717
   * .ecdh_curve one
718
   */
719
0
  const char *group_list = vh->tls.cfg_client_ecdh_curve ?
720
0
         vh->tls.cfg_client_ecdh_curve :
721
0
         vh->tls.cfg_ecdh_curve;
722
0
#endif
723
0
  struct lws_tls_client_reuse *tcr;
724
0
  unsigned long error;
725
0
  SSL_METHOD *method;
726
0
  EVP_MD_CTX *mdctx;
727
0
  unsigned int len;
728
0
  uint8_t hash[32];
729
0
  char c;
730
0
  int n;
731
732
  /* basic openssl init already happened in context init */
733
734
  /* choose the most recent spin of the api */
735
0
#if defined(LWS_HAVE_TLS_CLIENT_METHOD)
736
0
  method = (SSL_METHOD *)TLS_client_method();
737
#elif defined(LWS_HAVE_TLSV1_2_CLIENT_METHOD)
738
  method = (SSL_METHOD *)TLSv1_2_client_method();
739
#else
740
  method = (SSL_METHOD *)SSLv23_client_method();
741
#endif
742
743
0
  if (!method) {
744
0
    const char *es;
745
0
    char buf[256];
746
747
0
    error = ERR_peek_error();
748
0
    es = ERR_error_string(LWS_TLS_ERR_CAST(ERR_get_error()), buf);
749
0
    lwsl_err("problem creating ssl method %lu: %s\n",
750
0
      error, es);
751
0
    return 1;
752
0
  }
753
754
  /*
755
   * OpenSSL client contexts are quite expensive, because they bring in
756
   * the system certificate bundle for each one.  So if you have multiple
757
   * vhosts, each with a client context, it can add up to several
758
   * megabytes of heap.  In the case the client contexts are configured
759
   * identically, they could perfectly well have shared just the one.
760
   *
761
   * For that reason, use a hash to fingerprint the context configuration
762
   * and prefer to reuse an existing one with the same fingerprint if
763
   * possible.
764
   */
765
766
0
   mdctx = EVP_MD_CTX_create();
767
0
   if (!mdctx)
768
0
     return 1;
769
770
0
  if (EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL) != 1) {
771
0
    EVP_MD_CTX_destroy(mdctx);
772
773
0
    return 1;
774
0
  }
775
776
0
  if (info->ssl_client_options_set)
777
0
    EVP_DigestUpdate(mdctx, &info->ssl_client_options_set,
778
0
         sizeof(info->ssl_client_options_set));
779
780
0
#if (OPENSSL_VERSION_NUMBER >= 0x009080df) && !defined(USE_WOLFSSL)
781
0
  if (info->ssl_client_options_clear)
782
0
    EVP_DigestUpdate(mdctx, &info->ssl_client_options_clear,
783
0
         sizeof(info->ssl_client_options_clear));
784
0
#endif
785
786
0
  if (info->client_tls_ciphers_iana)
787
0
    EVP_DigestUpdate(mdctx, info->client_tls_ciphers_iana,
788
0
         strlen(info->client_tls_ciphers_iana));
789
0
  else {
790
0
    if (cipher_list)
791
0
      EVP_DigestUpdate(mdctx, cipher_list, strlen(cipher_list));
792
793
0
#if defined(LWS_HAVE_SSL_CTX_set_ciphersuites)
794
0
    if (info->client_tls_1_3_plus_cipher_list)
795
0
      EVP_DigestUpdate(mdctx, info->client_tls_1_3_plus_cipher_list,
796
0
           strlen(info->client_tls_1_3_plus_cipher_list));
797
0
#endif
798
0
  }
799
800
0
#if defined(LWS_HAVE_SSL_CTX_set1_groups_list)
801
  /* the group list also affects the identity of the client context */
802
0
  if (group_list)
803
0
    EVP_DigestUpdate(mdctx, group_list, strlen(group_list));
804
0
#endif
805
806
0
  if (!lws_check_opt(vh->options, LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS)) {
807
0
    c = 1;
808
0
    EVP_DigestUpdate(mdctx, &c, 1);
809
0
  }
810
811
0
  if (ca_filepath)
812
0
    EVP_DigestUpdate(mdctx, ca_filepath, strlen(ca_filepath));
813
814
0
  if (cert_filepath)
815
0
    EVP_DigestUpdate(mdctx, cert_filepath, strlen(cert_filepath));
816
817
0
  if (private_key_filepath)
818
0
    EVP_DigestUpdate(mdctx, private_key_filepath,
819
0
         strlen(private_key_filepath));
820
0
  if (ca_mem && ca_mem_len)
821
0
    EVP_DigestUpdate(mdctx, ca_mem, ca_mem_len);
822
823
0
  if (cert_mem && cert_mem_len)
824
0
    EVP_DigestUpdate(mdctx, cert_mem, cert_mem_len);
825
826
0
  len = sizeof(hash);
827
0
  EVP_DigestFinal_ex(mdctx, hash, &len);
828
0
  EVP_MD_CTX_destroy(mdctx);
829
830
  /* look for existing client context with same config already */
831
832
0
  lws_start_foreach_dll_safe(struct lws_dll2 *, p, tp,
833
0
       lws_dll2_get_head(&vh->context->tls.cc_owner)) {
834
0
    tcr = lws_container_of(p, struct lws_tls_client_reuse, cc_list);
835
836
0
    if (!memcmp(hash, tcr->hash, len)) {
837
838
      /* it's a match */
839
840
0
      tcr->refcount++;
841
0
      vh->tls.ssl_client_ctx = tcr->ssl_client_ctx;
842
0
      vh->tls.tcr = tcr;
843
844
0
      lwsl_info("%s: vh %s: reusing client ctx %d: use %d\n",
845
0
           __func__, vh->name, tcr->index,
846
0
           tcr->refcount);
847
848
0
      return 0;
849
0
    }
850
0
  } lws_end_foreach_dll_safe(p, tp);
851
852
  /* no existing one the same... create new client SSL_CTX */
853
854
0
  errno = 0;
855
0
  ERR_clear_error();
856
0
  vh->tls.ssl_client_ctx = SSL_CTX_new(method);
857
0
  if (!vh->tls.ssl_client_ctx) {
858
0
    const char *es;
859
0
    char buf[256];
860
861
0
    error = ERR_peek_error();
862
0
    es = ERR_error_string(LWS_TLS_ERR_CAST(ERR_get_error()), buf);
863
0
    lwsl_err("problem creating ssl context %lu: %s\n",
864
0
      error, es);
865
0
    return 1;
866
0
  }
867
868
0
  SSL_CTX_set_ex_data(vh->tls.ssl_client_ctx,
869
0
        openssl_SSL_CTX_private_data_index,
870
0
        (char *)vh->context);
871
872
0
  lws_plat_vhost_tls_client_ctx_init(vh);
873
874
0
  tcr = lws_zalloc(sizeof(*tcr), "client ctx tcr");
875
0
  if (!tcr) {
876
0
    SSL_CTX_free(vh->tls.ssl_client_ctx);
877
0
    return 1;
878
0
  }
879
880
0
  tcr->ssl_client_ctx = vh->tls.ssl_client_ctx;
881
0
  tcr->refcount = 1;
882
0
  memcpy(tcr->hash, hash, len);
883
0
  tcr->index = vh->context->tls.count_client_contexts++;
884
0
  lws_dll2_add_head(&tcr->cc_list, &vh->context->tls.cc_owner);
885
886
0
  lwsl_info("%s: vh %s: created new client ctx %d\n", __func__,
887
0
      vh->name, tcr->index);
888
889
  /* bind the tcr to the client context */
890
891
0
  vh->tls.tcr = tcr;
892
893
0
#if defined(LWS_WITH_TLS_KEYLOG) && \
894
0
    defined(LWS_WITH_TLS) && defined(LWS_WITH_CLIENT)
895
0
  if (vh->context->keylog_file[0])
896
0
    SSL_CTX_set_keylog_callback(vh->tls.ssl_client_ctx, lws_klog_dump);
897
0
#endif
898
899
0
#if defined(LWS_WITH_TLS_SESSIONS)
900
0
  vh->tls_session_cache_max = info->tls_session_cache_max ?
901
0
            info->tls_session_cache_max : 10;
902
0
  lws_tls_session_cache(vh, info->tls_session_timeout);
903
0
#endif
904
905
0
#ifdef SSL_OP_NO_COMPRESSION
906
0
  SSL_CTX_set_options(vh->tls.ssl_client_ctx, SSL_OP_NO_COMPRESSION);
907
0
#endif
908
909
0
  SSL_CTX_set_options(vh->tls.ssl_client_ctx,
910
0
          SSL_OP_CIPHER_SERVER_PREFERENCE);
911
912
0
  SSL_CTX_set_mode(vh->tls.ssl_client_ctx,
913
0
       SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
914
0
       SSL_MODE_RELEASE_BUFFERS);
915
916
0
  SSL_OPT_TYPE ssl_client_options_set_value = (SSL_OPT_TYPE) info->ssl_client_options_set;
917
918
0
  if (info->ssl_client_options_set)
919
0
    SSL_CTX_set_options(vh->tls.ssl_client_ctx, ssl_client_options_set_value);
920
921
0
#if (OPENSSL_VERSION_NUMBER >= 0x009080df) && !defined(USE_WOLFSSL)
922
  /* SSL_clear_options introduced in 0.9.8m */
923
0
  SSL_OPT_TYPE ssl_client_options_clear_value = (SSL_OPT_TYPE) info->ssl_client_options_clear;
924
925
0
  if (info->ssl_client_options_clear)
926
0
    SSL_CTX_clear_options(vh->tls.ssl_client_ctx, ssl_client_options_clear_value);
927
0
#endif
928
929
0
  if (info->client_tls_ciphers_iana) {
930
0
    char *p = lws_strdup(info->client_tls_ciphers_iana);
931
0
    if (p) {
932
0
      char *q = p;
933
0
      while (*q) {
934
0
        if (*q == ',')
935
0
          *q = ':';
936
0
        q++;
937
0
      }
938
0
      SSL_CTX_set_cipher_list(vh->tls.ssl_client_ctx, p);
939
0
#if defined(LWS_HAVE_SSL_CTX_set_ciphersuites)
940
0
      SSL_CTX_set_ciphersuites(vh->tls.ssl_client_ctx, p);
941
0
#endif
942
0
      lws_free(p);
943
0
    }
944
0
  } else {
945
0
    if (cipher_list)
946
0
      SSL_CTX_set_cipher_list(vh->tls.ssl_client_ctx, cipher_list);
947
948
0
#if defined(LWS_HAVE_SSL_CTX_set_ciphersuites)
949
0
    if (info->client_tls_1_3_plus_cipher_list)
950
0
      SSL_CTX_set_ciphersuites(vh->tls.ssl_client_ctx,
951
0
             info->client_tls_1_3_plus_cipher_list);
952
0
#endif
953
0
  }
954
955
0
#if defined(LWS_HAVE_SSL_CTX_set1_groups_list)
956
  /* restrict the groups offered to the peer, if asked to */
957
0
  if (group_list) {
958
0
    if (!SSL_CTX_set1_groups_list(vh->tls.ssl_client_ctx,
959
0
                group_list)) {
960
0
      lwsl_err("%s: SSL_CTX_set1_groups_list '%s' failed\n",
961
0
         __func__, group_list);
962
0
      lws_tls_err_describe_clear();
963
964
0
      return 1;
965
0
    }
966
0
    lwsl_notice("%s: vh %s: client groups list '%s'\n", __func__,
967
0
          vh->name, group_list);
968
0
  }
969
0
#endif
970
971
0
#ifdef LWS_SSL_CLIENT_USE_OS_CA_CERTS
972
0
  if (!lws_check_opt(vh->options, LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS))
973
    /* loads OS default CA certs */
974
0
    SSL_CTX_set_default_verify_paths(vh->tls.ssl_client_ctx);
975
0
#endif
976
977
  /* openssl init for cert verification (for client sockets) */
978
0
  if (!ca_filepath && (!ca_mem || !ca_mem_len)) {
979
#if defined(LWS_HAVE_SSL_CTX_load_verify_dir)
980
    if (!SSL_CTX_load_verify_dir(
981
      vh->tls.ssl_client_ctx, LWS_OPENSSL_CLIENT_CERTS))
982
#else
983
0
    if (!SSL_CTX_load_verify_locations(
984
0
      vh->tls.ssl_client_ctx, NULL, LWS_OPENSSL_CLIENT_CERTS))
985
0
#endif
986
0
      lwsl_err("Unable to load SSL Client certs from %s "
987
0
          "(set by LWS_OPENSSL_CLIENT_CERTS) -- "
988
0
          "client ssl isn't going to work\n",
989
0
          LWS_OPENSSL_CLIENT_CERTS);
990
0
  } else if (ca_filepath) {
991
#if defined(LWS_HAVE_SSL_CTX_load_verify_file)
992
    if (!SSL_CTX_load_verify_file(
993
      vh->tls.ssl_client_ctx, ca_filepath)) {
994
#else
995
0
    if (!SSL_CTX_load_verify_locations(
996
0
      vh->tls.ssl_client_ctx, ca_filepath, NULL)) {
997
0
#endif
998
0
      lwsl_err(
999
0
        "Unable to load SSL Client certs "
1000
0
        "file from %s -- client ssl isn't "
1001
0
        "going to work\n", ca_filepath);
1002
0
      lws_tls_err_describe_clear();
1003
0
    }
1004
0
    else
1005
0
      lwsl_info("loaded ssl_ca_filepath\n");
1006
0
  } else {
1007
1008
0
    if (lws_tls_client_vhost_ca_mem_parse(vh, ca_mem, ca_mem_len)) {
1009
0
      lwsl_err("%s: Unable to load x.509 ca_mem\n", __func__);
1010
0
      return 1;
1011
0
    }
1012
0
  }
1013
1014
  /*
1015
   * callback allowing user code to load extra verification certs
1016
   * helping the client to verify server identity
1017
   */
1018
1019
  /* support for client-side certificate authentication */
1020
1021
0
  if (cert_filepath) {
1022
0
    if (lws_tls_use_any_upgrade_check_extant(cert_filepath) !=
1023
0
        LWS_TLS_EXTANT_YES &&
1024
0
        (info->options & LWS_SERVER_OPTION_IGNORE_MISSING_CERT))
1025
0
      return 0;
1026
1027
0
    lwsl_notice("%s: doing cert filepath %s\n", __func__,
1028
0
        cert_filepath);
1029
0
    n = SSL_CTX_use_certificate_chain_file(vh->tls.ssl_client_ctx,
1030
0
                   cert_filepath);
1031
0
    if (n < 1) {
1032
0
      lwsl_err("problem %d getting cert '%s'\n", n,
1033
0
         cert_filepath);
1034
0
      lws_tls_err_describe_clear();
1035
0
      return 1;
1036
0
    }
1037
0
    lwsl_info("Loaded client cert %s\n", cert_filepath);
1038
1039
0
  } else if (cert_mem && cert_mem_len) {
1040
0
    lws_filepos_t flen;
1041
0
    uint8_t *p;
1042
1043
0
    if (lws_tls_alloc_pem_to_der_file(vh->context, NULL, cert_mem,
1044
0
              cert_mem_len, &p, &flen)) {
1045
0
      lwsl_err("%s: couldn't read cert file\n", __func__);
1046
1047
0
      return 1;
1048
0
    }
1049
1050
0
    n = SSL_CTX_use_certificate_ASN1(vh->tls.ssl_client_ctx, SSL_SIZE_T_CAST(flen), p);
1051
1052
0
    if (n < 1) {
1053
0
      lwsl_err("%s: problem interpreting client cert\n",  __func__);
1054
0
      lws_tls_err_describe_clear();
1055
0
    }
1056
1057
0
    lws_free_set_NULL(p);
1058
1059
0
    if (n != 1)
1060
0
      return 1;
1061
1062
0
  }
1063
0
  if (private_key_filepath) {
1064
0
    lwsl_info("%s: using private key filepath\n", __func__);
1065
0
    lws_ssl_bind_passphrase(vh->tls.ssl_client_ctx, 1, info);
1066
    /* set the private key from KeyFile */
1067
0
    if (SSL_CTX_use_PrivateKey_file(vh->tls.ssl_client_ctx,
1068
0
        private_key_filepath, SSL_FILETYPE_PEM) != 1) {
1069
0
      lwsl_err("use_PrivateKey_file '%s'\n",
1070
0
         private_key_filepath);
1071
0
      lws_tls_err_describe_clear();
1072
0
      return 1;
1073
0
    }
1074
0
    lwsl_info("Loaded client cert private key %s\n",
1075
0
          private_key_filepath);
1076
1077
    /* verify private key */
1078
0
    if (!SSL_CTX_check_private_key(vh->tls.ssl_client_ctx)) {
1079
0
      lwsl_err("Private SSL key doesn't match cert\n");
1080
0
      return 1;
1081
0
    }
1082
0
  }
1083
0
  else if (key_mem && key_mem_len) {
1084
1085
0
    lws_filepos_t flen;
1086
0
    uint8_t *p;
1087
1088
0
    if (lws_tls_alloc_pem_to_der_file(vh->context, NULL, key_mem,
1089
0
              key_mem_len, &p, &flen)) {
1090
0
      lwsl_err("%s: couldn't use mem cert\n", __func__);
1091
1092
0
      return 1;
1093
0
    }
1094
1095
0
    n = SSL_CTX_use_PrivateKey_ASN1(EVP_PKEY_RSA, vh->tls.ssl_client_ctx, p,
1096
#if defined(LWS_WITH_BORINGSSL) || defined(LWS_WITH_AWSLC)
1097
        (size_t)
1098
#else
1099
0
        (long)(lws_intptr_t)
1100
0
#endif
1101
0
            flen);
1102
0
    if (n != 1)
1103
0
      n = SSL_CTX_use_PrivateKey_ASN1(EVP_PKEY_EC,
1104
0
              vh->tls.ssl_client_ctx, p,
1105
#if defined(LWS_WITH_BORINGSSL) || defined(LWS_WITH_AWSLC)
1106
        (size_t)
1107
#else
1108
0
        (long)(lws_intptr_t)
1109
0
#endif
1110
0
            flen);
1111
1112
0
    lws_free_set_NULL(p);
1113
1114
0
    if (n != 1)  {
1115
0
      lwsl_err("%s: unable to use key_mem\n", __func__);
1116
1117
0
      return 1;
1118
0
    }
1119
0
  }
1120
1121
#if defined(LWS_ROLE_QUIC) && !defined(LWS_WITH_MBEDTLS) && !defined(LWS_WITH_WOLFSSL) && !defined(LWS_WITH_SCHANNEL) && !defined(LWS_WITH_GNUTLS) && !defined(LWS_WITH_BEARSSL)
1122
  lws_tls_quic_vhost_init(vh->tls.ssl_client_ctx);
1123
#endif
1124
1125
0
  return 0;
1126
0
}
1127
1128