Coverage Report

Created: 2023-03-26 07:20

/src/libwebsockets/lib/tls/openssl/openssl-client.c
Line
Count
Source (jump to first uncovered line)
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
96
  /* keep old behaviour accepting self-signed server certs */
97
0
  if (!preverify_ok) {
98
0
    err = X509_STORE_CTX_get_error(x509_ctx);
99
100
0
    if (err != X509_V_OK) {
101
0
      ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
102
0
          SSL_get_ex_data_X509_STORE_CTX_idx());
103
0
      wsi = SSL_get_ex_data(ssl,
104
0
          openssl_websocket_private_data_index);
105
0
      if (!wsi) {
106
0
        lwsl_err("%s: can't get wsi from ssl privdata\n",
107
0
           __func__);
108
109
0
        return 0;
110
0
      }
111
112
0
      if ((err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
113
0
           err == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) &&
114
0
           wsi->tls.use_ssl & LCCSCF_ALLOW_SELFSIGNED) {
115
0
        lwsl_notice("accepting self-signed "
116
0
              "certificate (verify_callback)\n");
117
0
        X509_STORE_CTX_set_error(x509_ctx, X509_V_OK);
118
0
        return 1; // ok
119
0
    } else if ((err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY ||
120
0
          err == X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE) &&
121
0
          wsi->tls.use_ssl & LCCSCF_ALLOW_INSECURE) {
122
0
        lwsl_notice("accepting non-trusted certificate\n");
123
0
        X509_STORE_CTX_set_error(x509_ctx, X509_V_OK);
124
0
        return 1;  /* ok */
125
0
      } else if ((err == X509_V_ERR_CERT_NOT_YET_VALID ||
126
0
            err == X509_V_ERR_CERT_HAS_EXPIRED) &&
127
0
            wsi->tls.use_ssl & LCCSCF_ALLOW_EXPIRED) {
128
0
        if (err == X509_V_ERR_CERT_NOT_YET_VALID)
129
0
          lwsl_notice("accepting not yet valid "
130
0
                "certificate (verify_"
131
0
                "callback)\n");
132
0
        else if (err == X509_V_ERR_CERT_HAS_EXPIRED)
133
0
          lwsl_notice("accepting expired "
134
0
                "certificate (verify_"
135
0
                "callback)\n");
136
0
        X509_STORE_CTX_set_error(x509_ctx, X509_V_OK);
137
0
        return 1; // ok
138
0
      }
139
0
    }
140
0
  }
141
142
0
  ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
143
0
           SSL_get_ex_data_X509_STORE_CTX_idx());
144
0
  wsi = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
145
0
  if (!wsi) {
146
0
    lwsl_err("%s: can't get wsi from ssl privdata\n",  __func__);
147
148
0
    return 0;
149
0
  }
150
151
#if defined(LWS_WITH_TLS_JIT_TRUST)
152
  if (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY) {
153
    union lws_tls_cert_info_results ci;
154
    STACK_OF(X509) *x509_stack;
155
156
    x509_stack = X509_STORE_CTX_get1_chain(x509_ctx);
157
    if (x509_stack) {
158
159
      for (n = 0; n < OPENSSL_sk_num((const OPENSSL_STACK *)x509_stack) &&
160
            wsi->tls.kid_chain.count !=
161
             LWS_ARRAY_SIZE(wsi->tls.kid_chain.akid); n++) {
162
        X509 *x509 = OPENSSL_sk_value((const OPENSSL_STACK *)x509_stack, n);
163
164
        if (!lws_tls_openssl_cert_info(x509,
165
              LWS_TLS_CERT_INFO_SUBJECT_KEY_ID,
166
              &ci, 0))
167
          lws_tls_kid_copy(&ci,
168
            &wsi->tls.kid_chain.skid[
169
                 wsi->tls.kid_chain.count]);
170
171
        if (!lws_tls_openssl_cert_info(x509,
172
               LWS_TLS_CERT_INFO_AUTHORITY_KEY_ID,
173
               &ci, 0))
174
          lws_tls_kid_copy(&ci,
175
             &wsi->tls.kid_chain.akid[
176
                 wsi->tls.kid_chain.count]);
177
178
        wsi->tls.kid_chain.count++;
179
      }
180
181
      sk_X509_pop_free(x509_stack, X509_free);
182
    }
183
184
    lws_tls_jit_trust_sort_kids(wsi, &wsi->tls.kid_chain);
185
  }
186
#endif
187
188
0
  n = lws_get_context_protocol(wsi->a.context, 0).callback(wsi,
189
0
      LWS_CALLBACK_OPENSSL_PERFORM_SERVER_CERT_VERIFICATION,
190
0
      x509_ctx, ssl, (unsigned int)preverify_ok);
191
192
  /* keep old behaviour if something wrong with server certs */
193
  /* if ssl error is overruled in callback and cert is ok,
194
   * X509_STORE_CTX_set_error(x509_ctx, X509_V_OK); must be set and
195
   * return value is 0 from callback */
196
0
  if (!preverify_ok) {
197
0
    int err = X509_STORE_CTX_get_error(x509_ctx);
198
199
0
    if (err != X509_V_OK) {
200
      /* cert validation error was not handled in callback */
201
0
      int depth = X509_STORE_CTX_get_error_depth(x509_ctx);
202
0
      const char *msg = X509_verify_cert_error_string(err);
203
204
0
      lws_strncpy(wsi->tls.err_helper, msg,
205
0
            sizeof(wsi->tls.err_helper));
206
207
0
      lwsl_err("SSL error: %s (preverify_ok=%d;err=%d;"
208
0
         "depth=%d)\n", msg, preverify_ok, err, depth);
209
210
#if defined(LWS_WITH_SYS_METRICS)
211
      {
212
        char buckname[64];
213
214
        lws_snprintf(buckname, sizeof(buckname),
215
               "tls=\"%s\"", msg);
216
        lws_metrics_hist_bump_describe_wsi(wsi,
217
          lws_metrics_priv_to_pub(wsi->a.context->mth_conn_failures),
218
          buckname);
219
      }
220
#endif
221
222
0
      return preverify_ok;  // not ok
223
0
    }
224
0
  }
225
  /*
226
   * convert callback return code from 0 = OK to verify callback
227
   * return value 1 = OK
228
   */
229
0
  return !n;
230
0
}
231
#endif
232
233
int
234
lws_ssl_client_bio_create(struct lws *wsi)
235
0
{
236
0
  char hostname[128], *p;
237
0
#if defined(LWS_HAVE_SSL_set_alpn_protos) && \
238
0
    defined(LWS_HAVE_SSL_get0_alpn_selected)
239
0
  uint8_t openssl_alpn[40];
240
0
  const char *alpn_comma = wsi->a.context->tls.alpn_default;
241
0
  int n;
242
0
#endif
243
244
0
  if (wsi->stash) {
245
0
    lws_strncpy(hostname, wsi->stash->cis[CIS_HOST], sizeof(hostname));
246
0
#if defined(LWS_HAVE_SSL_set_alpn_protos) && \
247
0
    defined(LWS_HAVE_SSL_get0_alpn_selected)
248
0
    alpn_comma = wsi->stash->cis[CIS_ALPN];
249
0
#endif
250
0
  } else {
251
0
#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)
252
0
    if (lws_hdr_copy(wsi, hostname, sizeof(hostname),
253
0
         _WSI_TOKEN_CLIENT_HOST) <= 0)
254
0
#endif
255
0
    {
256
0
      lwsl_err("%s: Unable to get hostname\n", __func__);
257
258
0
      return -1;
259
0
    }
260
0
  }
261
262
  /*
263
   * remove any :port part on the hostname... necessary for network
264
   * connection but typical certificates do not contain it
265
   */
266
0
  p = hostname;
267
0
  while (*p) {
268
0
    if (*p == ':') {
269
0
      *p = '\0';
270
0
      break;
271
0
    }
272
0
    p++;
273
0
  }
274
275
0
  wsi->tls.ssl = SSL_new(wsi->a.vhost->tls.ssl_client_ctx);
276
0
  if (!wsi->tls.ssl) {
277
0
    const char *es = ERR_error_string(
278
#if defined(LWS_WITH_BORINGSSL)
279
  (uint32_t)
280
#else
281
0
  (unsigned long)
282
0
#endif
283
0
  lws_ssl_get_error(wsi, 0), NULL);
284
0
    lwsl_err("SSL_new failed: %s\n", es);
285
0
    lws_tls_err_describe_clear();
286
0
    return -1;
287
0
  }
288
289
0
#if defined(LWS_WITH_TLS_SESSIONS)
290
0
  if (!(wsi->a.vhost->options & LWS_SERVER_OPTION_DISABLE_TLS_SESSION_CACHE))
291
0
    lws_tls_reuse_session(wsi);
292
0
#endif
293
294
0
#if defined (LWS_HAVE_SSL_SET_INFO_CALLBACK)
295
0
  if (wsi->a.vhost->tls.ssl_info_event_mask)
296
0
    SSL_set_info_callback(wsi->tls.ssl, lws_ssl_info_callback);
297
0
#endif
298
299
0
#if defined(LWS_HAVE_X509_VERIFY_PARAM_set1_host)
300
0
  if (!(wsi->tls.use_ssl & LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK)) {
301
0
#if !defined(USE_WOLFSSL)
302
303
0
    X509_VERIFY_PARAM *param = SSL_get0_param(wsi->tls.ssl);
304
305
    /* Enable automatic hostname checks */
306
0
    X509_VERIFY_PARAM_set_hostflags(param,
307
0
          X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
308
    /* Handle the case where the hostname is an IP address */
309
0
    if (!X509_VERIFY_PARAM_set1_ip_asc(param, hostname))
310
0
      X509_VERIFY_PARAM_set1_host(param, hostname,
311
0
          strnlen(hostname, sizeof(hostname)));
312
0
#endif
313
314
0
  }
315
#else
316
  if (!(wsi->tls.use_ssl & LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK)) {
317
    lwsl_err("%s: your tls lib is too old to have "
318
       "X509_VERIFY_PARAM_set1_host, failing all client tls\n",
319
       __func__);
320
    return -1;
321
  }
322
#endif
323
324
0
#if !defined(USE_WOLFSSL)
325
0
#ifndef USE_OLD_CYASSL
326
  /* OpenSSL_client_verify_callback will be called @ SSL_connect() */
327
0
  SSL_set_verify(wsi->tls.ssl, SSL_VERIFY_PEER,
328
0
           OpenSSL_client_verify_callback);
329
0
#endif
330
0
#endif
331
332
0
#if !defined(USE_WOLFSSL)
333
0
  SSL_set_mode(wsi->tls.ssl,  SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
334
0
#endif
335
  /*
336
   * use server name indication (SNI), if supported,
337
   * when establishing connection
338
   */
339
#ifdef USE_WOLFSSL
340
#ifdef USE_OLD_CYASSL
341
#ifdef CYASSL_SNI_HOST_NAME
342
  CyaSSL_UseSNI(wsi->tls.ssl, CYASSL_SNI_HOST_NAME, hostname,
343
          strlen(hostname));
344
#endif
345
#else
346
#if defined(WOLFSSL_SNI_HOST_NAME) || defined(HAVE_SNI)
347
  wolfSSL_UseSNI(wsi->tls.ssl, WOLFSSL_SNI_HOST_NAME, hostname,
348
           (unsigned short)strlen(hostname));
349
#endif
350
#endif
351
#else
352
0
#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
353
0
  SSL_set_tlsext_host_name(wsi->tls.ssl, hostname);
354
0
#endif
355
0
#endif
356
357
#ifdef USE_WOLFSSL
358
  /*
359
   * wolfSSL/CyaSSL does certificate verification differently
360
   * from OpenSSL.
361
   * If we should ignore the certificate, we need to set
362
   * this before SSL_new and SSL_connect is called.
363
   * Otherwise the connect will simply fail with error code -155
364
   */
365
#ifdef USE_OLD_CYASSL
366
  if (wsi->tls.use_ssl & LCCSCF_ALLOW_SELFSIGNED)
367
    CyaSSL_set_verify(wsi->tls.ssl, SSL_VERIFY_NONE, NULL);
368
#else
369
  if (wsi->tls.use_ssl & LCCSCF_ALLOW_SELFSIGNED)
370
    wolfSSL_set_verify(wsi->tls.ssl, SSL_VERIFY_NONE, NULL);
371
#endif
372
#endif /* USE_WOLFSSL */
373
374
0
  wsi->tls.client_bio = BIO_new_socket((int)(lws_intptr_t)wsi->desc.sockfd,
375
0
               BIO_NOCLOSE);
376
0
  SSL_set_bio(wsi->tls.ssl, wsi->tls.client_bio, wsi->tls.client_bio);
377
378
#ifdef USE_WOLFSSL
379
#ifdef USE_OLD_CYASSL
380
  CyaSSL_set_using_nonblock(wsi->tls.ssl, 1);
381
#else
382
  wolfSSL_set_using_nonblock(wsi->tls.ssl, 1);
383
#endif
384
#else
385
0
  BIO_set_nbio(wsi->tls.client_bio, 1); /* nonblocking */
386
0
#endif
387
388
0
#if defined(LWS_HAVE_SSL_set_alpn_protos) && \
389
0
    defined(LWS_HAVE_SSL_get0_alpn_selected)
390
0
  if (wsi->a.vhost->tls.alpn)
391
0
    alpn_comma = wsi->a.vhost->tls.alpn;
392
0
  if (wsi->stash) {
393
0
    alpn_comma = wsi->stash->cis[CIS_ALPN];
394
0
#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)
395
0
  } else {
396
0
    if (lws_hdr_copy(wsi, hostname, sizeof(hostname),
397
0
         _WSI_TOKEN_CLIENT_ALPN) > 0)
398
0
      alpn_comma = hostname;
399
0
#endif
400
0
  }
401
402
0
  lwsl_info("%s client conn using alpn list '%s'\n", wsi->role_ops->name, alpn_comma);
403
404
0
  n = lws_alpn_comma_to_openssl(alpn_comma, openssl_alpn,
405
0
              sizeof(openssl_alpn) - 1);
406
407
0
  SSL_set_alpn_protos(wsi->tls.ssl, openssl_alpn, (unsigned int)n);
408
0
#endif
409
410
0
  SSL_set_ex_data(wsi->tls.ssl, openssl_websocket_private_data_index,
411
0
      wsi);
412
413
0
  if (wsi->sys_tls_client_cert) {
414
0
    lws_system_blob_t *b = lws_system_get_blob(wsi->a.context,
415
0
          LWS_SYSBLOB_TYPE_CLIENT_CERT_DER,
416
0
          wsi->sys_tls_client_cert - 1);
417
0
    const uint8_t *data;
418
0
    size_t size;
419
420
0
    if (!b)
421
0
      goto no_client_cert;
422
423
    /*
424
     * Set up the per-connection client cert
425
     */
426
427
0
    size = lws_system_blob_get_size(b);
428
0
    if (!size)
429
0
      goto no_client_cert;
430
431
0
    if (lws_system_blob_get_single_ptr(b, &data))
432
0
      goto no_client_cert;
433
434
0
    if (SSL_use_certificate_ASN1(wsi->tls.ssl,
435
#if defined(USE_WOLFSSL)
436
      (unsigned char *)
437
#endif
438
0
          data,
439
#if defined(LWS_WITH_BORINGSSL)
440
          (size_t)
441
#else
442
0
          (int)
443
0
#endif
444
0
          size) != 1) {
445
0
      lwsl_err("%s: use_certificate failed\n", __func__);
446
0
      lws_tls_err_describe_clear();
447
0
      goto no_client_cert;
448
0
    }
449
450
0
    b = lws_system_get_blob(wsi->a.context,
451
0
          LWS_SYSBLOB_TYPE_CLIENT_KEY_DER,
452
0
          wsi->sys_tls_client_cert - 1);
453
0
    if (!b)
454
0
      goto no_client_cert;
455
456
0
    size = lws_system_blob_get_size(b);
457
0
    if (!size)
458
0
      goto no_client_cert;
459
460
0
    if (lws_system_blob_get_single_ptr(b, &data))
461
0
      goto no_client_cert;
462
463
0
    if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, wsi->tls.ssl,
464
#if defined(USE_WOLFSSL)
465
      (unsigned char *)
466
#endif
467
468
0
              data,
469
#if defined(LWS_WITH_BORINGSSL)
470
          (size_t)
471
#else
472
0
          (int)
473
0
#endif
474
0
              size) != 1 &&
475
0
        SSL_use_PrivateKey_ASN1(EVP_PKEY_EC, wsi->tls.ssl,
476
#if defined(USE_WOLFSSL)
477
      (unsigned char *)
478
#endif
479
0
              data,
480
#if defined(LWS_WITH_BORINGSSL)
481
          (size_t)
482
#else
483
0
          (int)
484
0
#endif
485
0
              size) != 1) {
486
0
      lwsl_err("%s: use_privkey failed\n", __func__);
487
0
      lws_tls_err_describe_clear();
488
0
      goto no_client_cert;
489
0
    }
490
491
0
    if (SSL_check_private_key(wsi->tls.ssl) != 1) {
492
0
      lwsl_err("Private SSL key doesn't match cert\n");
493
0
      lws_tls_err_describe_clear();
494
0
      return 1;
495
0
    }
496
497
0
    lwsl_notice("%s: set system client cert %u\n", __func__,
498
0
        wsi->sys_tls_client_cert - 1);
499
0
  }
500
501
0
  return 0;
502
503
0
no_client_cert:
504
0
  lwsl_err("%s: unable to set up system client cert %d\n", __func__,
505
0
      wsi->sys_tls_client_cert - 1);
506
507
0
  return 1;
508
0
}
509
510
enum lws_ssl_capable_status
511
lws_tls_client_connect(struct lws *wsi, char *errbuf, size_t elen)
512
0
{
513
0
#if defined(LWS_HAVE_SSL_set_alpn_protos) && \
514
0
    defined(LWS_HAVE_SSL_get0_alpn_selected)
515
0
  const unsigned char *prot;
516
0
  char a[32];
517
0
  unsigned int len;
518
0
#endif
519
0
  int m, n, en;
520
0
#if defined(LWS_WITH_TLS_SESSIONS) && defined(LWS_HAVE_SSL_SESSION_set_time)
521
0
  SSL_SESSION *sess;
522
0
#endif
523
0
  errno = 0;
524
0
  ERR_clear_error();
525
0
  wsi->tls.err_helper[0] = '\0';
526
0
  n = SSL_connect(wsi->tls.ssl);
527
0
  en = errno;
528
529
0
  m = lws_ssl_get_error(wsi, n);
530
531
0
  if (m == SSL_ERROR_SYSCALL
532
#if defined(WIN32)
533
      && en
534
#endif
535
0
  ) {
536
0
#if defined(WIN32) || (_LWS_ENABLED_LOGS & LLL_INFO)
537
0
    lwsl_info("%s: n %d, m %d, errno %d\n", __func__, n, m, en);
538
0
#endif
539
0
    lws_snprintf(errbuf, elen, "connect SYSCALL %d", en);
540
0
    return LWS_SSL_CAPABLE_ERROR;
541
0
  }
542
543
0
  if (m == SSL_ERROR_SSL) {
544
0
    n = lws_snprintf(errbuf, elen, "tls: %s", wsi->tls.err_helper);
545
0
    if (!wsi->tls.err_helper[0])
546
0
      ERR_error_string_n((unsigned int)m, errbuf + n, (elen - (unsigned int)n));
547
0
    return LWS_SSL_CAPABLE_ERROR;
548
0
  }
549
550
0
#if defined(LWS_WITH_TLS_SESSIONS)
551
0
  if (SSL_session_reused(wsi->tls.ssl)) {
552
0
#if defined(LWS_HAVE_SSL_SESSION_set_time)
553
0
    sess = SSL_get_session(wsi->tls.ssl);
554
0
    if (sess) /* should always be true */
555
#if defined(OPENSSL_IS_BORINGSSL)
556
      SSL_SESSION_set_time(sess, (uint64_t)time(NULL)); /* extend session lifetime */
557
#else
558
0
      SSL_SESSION_set_time(sess, (long)time(NULL)); /* extend session lifetime */
559
0
#endif
560
0
#endif
561
0
  }
562
0
#endif
563
564
0
  if (m == SSL_ERROR_WANT_READ || SSL_want_read(wsi->tls.ssl))
565
0
    return LWS_SSL_CAPABLE_MORE_SERVICE_READ;
566
567
0
  if (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->tls.ssl))
568
0
    return LWS_SSL_CAPABLE_MORE_SERVICE_WRITE;
569
570
0
  if (n == 1 || m == SSL_ERROR_SYSCALL) {
571
0
#if defined(LWS_HAVE_SSL_set_alpn_protos) && \
572
0
    defined(LWS_HAVE_SSL_get0_alpn_selected)
573
0
    SSL_get0_alpn_selected(wsi->tls.ssl, &prot, &len);
574
575
0
    if (len >= sizeof(a))
576
0
      len = sizeof(a) - 1;
577
0
    memcpy(a, (const char *)prot, len);
578
0
    a[len] = '\0';
579
580
0
    lws_role_call_alpn_negotiated(wsi, (const char *)a);
581
0
#endif
582
#if defined(LWS_TLS_SYNTHESIZE_CB)
583
    lws_sul_schedule(wsi->a.context, wsi->tsi,
584
         &wsi->tls.sul_cb_synth,
585
         lws_sess_cache_synth_cb, 500 * LWS_US_PER_MS);
586
#endif
587
588
0
    lwsl_info("client connect OK\n");
589
0
    lws_openssl_describe_cipher(wsi);
590
0
    return LWS_SSL_CAPABLE_DONE;
591
0
  }
592
593
0
  if (!n) /* we don't know what he wants, but he says to retry */
594
0
    return LWS_SSL_CAPABLE_MORE_SERVICE;
595
596
0
  lws_snprintf(errbuf, elen, "connect unk %d", m);
597
598
0
  return LWS_SSL_CAPABLE_ERROR;
599
0
}
600
601
int
602
lws_tls_client_confirm_peer_cert(struct lws *wsi, char *ebuf, size_t ebuf_len)
603
0
{
604
0
#if !defined(USE_WOLFSSL)
605
0
  struct lws_context_per_thread *pt = &wsi->a.context->pt[(int)wsi->tsi];
606
0
  char *p = (char *)&pt->serv_buf[0];
607
0
  const char *es, *type = "";
608
0
  unsigned int avoid = 0;
609
0
  char *sb = p;
610
0
  long n;
611
612
0
  errno = 0;
613
0
  ERR_clear_error();
614
0
  n = SSL_get_verify_result(wsi->tls.ssl);
615
616
0
  switch (n) {
617
0
  case X509_V_OK:
618
0
    return 0;
619
620
0
  case X509_V_ERR_HOSTNAME_MISMATCH:
621
0
    type = "tls=hostname";
622
0
    avoid = LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK;
623
0
    break;
624
625
0
  case X509_V_ERR_INVALID_CA:
626
0
  case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
627
0
  case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
628
0
    type = "tls=invalidca";
629
0
    avoid = LCCSCF_ALLOW_SELFSIGNED;
630
0
    break;
631
632
0
  case X509_V_ERR_CERT_NOT_YET_VALID:
633
0
    type = "tls=notyetvalid";
634
0
    avoid = LCCSCF_ALLOW_EXPIRED;
635
0
    break;
636
637
0
  case X509_V_ERR_CERT_HAS_EXPIRED:
638
0
    type = "tls=expired";
639
0
    avoid = LCCSCF_ALLOW_EXPIRED;
640
0
    break;
641
0
  }
642
643
0
  lwsl_info("%s: cert problem: %s\n", __func__, type);
644
645
#if defined(LWS_WITH_SYS_METRICS)
646
  lws_metrics_hist_bump_describe_wsi(wsi,
647
      lws_metrics_priv_to_pub(wsi->a.context->mth_conn_failures), type);
648
#endif
649
650
0
  if (wsi->tls.use_ssl & avoid) {
651
0
    lwsl_info("%s: allowing anyway\n", __func__);
652
653
0
    return 0;
654
0
  }
655
656
0
  es = ERR_error_string(
657
  #if defined(LWS_WITH_BORINGSSL)
658
           (uint32_t)
659
  #else
660
0
           (unsigned long)
661
0
  #endif
662
0
           n, sb);
663
0
  lws_snprintf(ebuf, ebuf_len,
664
0
    "server's cert didn't look good, %s X509_V_ERR = %ld: %s\n",
665
0
     type, n, es);
666
0
  lwsl_info("%s\n", ebuf);
667
0
  lws_tls_err_describe_clear();
668
669
0
  return -1;
670
671
#else /* USE_WOLFSSL */
672
  return 0;
673
#endif
674
0
}
675
676
int
677
lws_tls_client_vhost_extra_cert_mem(struct lws_vhost *vh,
678
                const uint8_t *der, size_t der_len)
679
0
{
680
0
  X509_STORE *st;
681
#if defined(USE_WOLFSSL)
682
  X509 *x  = d2i_X509(NULL, &der, (int)der_len);
683
#else
684
0
  X509 *x  = d2i_X509(NULL, &der, (long)der_len);
685
0
#endif
686
0
  int n;
687
688
0
  if (!x) {
689
0
    lwsl_err("%s: Failed to load DER\n", __func__);
690
0
    lws_tls_err_describe_clear();
691
0
    return 1;
692
0
  }
693
694
0
  st = SSL_CTX_get_cert_store(vh->tls.ssl_client_ctx);
695
0
  if (!st) {
696
0
    lwsl_err("%s: failed to get cert store\n", __func__);
697
0
    X509_free(x);
698
0
    return 1;
699
0
  }
700
701
0
  n = X509_STORE_add_cert(st, x);
702
0
  if (n != 1)
703
0
    lwsl_err("%s: failed to add cert\n", __func__);
704
705
0
  X509_free(x);
706
707
0
  return n != 1;
708
0
}
709
710
#if defined(LWS_HAVE_SSL_CTX_set_keylog_callback) && \
711
  defined(LWS_WITH_TLS) && defined(LWS_WITH_CLIENT)
712
static void
713
lws_klog_dump(const SSL *ssl, const char *line)
714
0
{
715
0
  struct lws *wsi = SSL_get_ex_data(ssl,
716
0
            openssl_websocket_private_data_index);
717
0
  char path[128], hdr[128], ts[64];
718
0
  size_t w = 0, wx = 0;
719
0
  int fd, t;
720
721
0
  if (!wsi || !wsi->a.context->keylog_file[0] || !wsi->a.vhost)
722
0
    return;
723
724
0
  lws_snprintf(path, sizeof(path), "%s.%s", wsi->a.context->keylog_file,
725
0
      wsi->a.vhost->name);
726
727
0
  fd = open(path, O_CREAT | O_RDWR | O_APPEND, 0600);
728
0
  if (fd == -1) {
729
0
    lwsl_vhost_warn(wsi->a.vhost, "Failed to append %s", path);
730
0
    return;
731
0
  }
732
733
  /* the first item in the chunk */
734
0
  if (!strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET", 31)) {
735
0
    w += (size_t)write(fd, "\n# ", 3);
736
0
    wx += 3;
737
0
    t = lwsl_timestamp(LLL_WARN, ts, sizeof(ts));
738
0
    wx += (size_t)t;
739
0
    w += (size_t)write(fd, ts, (size_t)t);
740
741
0
    t = lws_snprintf(hdr, sizeof(hdr), "%s\n", wsi->lc.gutag);
742
0
    w += (size_t)write(fd, hdr, (size_t)t);
743
0
    wx += (size_t)t;
744
745
0
    lwsl_vhost_warn(wsi->a.vhost, "appended ssl keylog: %s", path);
746
0
  }
747
748
0
  wx += strlen(line) + 1;
749
0
  w += (size_t)write(fd, line, 
750
#if defined(WIN32)
751
      (unsigned int)
752
#endif
753
0
      strlen(line));
754
0
  w += (size_t)write(fd, "\n", 1);
755
0
  close(fd);
756
757
0
  if (w != wx) {
758
0
    lwsl_vhost_warn(wsi->a.vhost, "Failed to write %s", path);
759
0
    return;
760
0
  }
761
0
}
762
#endif
763
764
int
765
lws_tls_client_create_vhost_context(struct lws_vhost *vh,
766
            const struct lws_context_creation_info *info,
767
            const char *cipher_list,
768
            const char *ca_filepath,
769
            const void *ca_mem,
770
            unsigned int ca_mem_len,
771
            const char *cert_filepath,
772
            const void *cert_mem,
773
            unsigned int cert_mem_len,
774
            const char *private_key_filepath,
775
          const void *key_mem,
776
            unsigned int key_mem_len
777
          )
778
0
{
779
0
  struct lws_tls_client_reuse *tcr;
780
0
  X509_STORE *x509_store;
781
0
  unsigned long error;
782
0
  SSL_METHOD *method;
783
0
  EVP_MD_CTX *mdctx;
784
0
  unsigned int len;
785
0
  uint8_t hash[32];
786
0
  X509 *client_CA;
787
0
  char c;
788
0
  int n;
789
790
  /* basic openssl init already happened in context init */
791
792
  /* choose the most recent spin of the api */
793
0
#if defined(LWS_HAVE_TLS_CLIENT_METHOD)
794
0
  method = (SSL_METHOD *)TLS_client_method();
795
#elif defined(LWS_HAVE_TLSV1_2_CLIENT_METHOD)
796
  method = (SSL_METHOD *)TLSv1_2_client_method();
797
#else
798
  method = (SSL_METHOD *)SSLv23_client_method();
799
#endif
800
801
0
  if (!method) {
802
0
    const char *es;
803
804
0
    error = ERR_get_error();
805
0
    es = ERR_error_string(
806
    #if defined(LWS_WITH_BORINGSSL)
807
      (uint32_t)
808
    #else
809
0
      (unsigned long)
810
0
    #endif
811
0
       error, (char *)vh->context->pt[0].serv_buf);
812
0
    lwsl_err("problem creating ssl method %lu: %s\n",
813
0
      error, es);
814
0
    return 1;
815
0
  }
816
817
  /*
818
   * OpenSSL client contexts are quite expensive, because they bring in
819
   * the system certificate bundle for each one.  So if you have multiple
820
   * vhosts, each with a client context, it can add up to several
821
   * megabytes of heap.  In the case the client contexts are configured
822
   * identically, they could perfectly well have shared just the one.
823
   *
824
   * For that reason, use a hash to fingerprint the context configuration
825
   * and prefer to reuse an existing one with the same fingerprint if
826
   * possible.
827
   */
828
829
0
   mdctx = EVP_MD_CTX_create();
830
0
   if (!mdctx)
831
0
     return 1;
832
833
0
  if (EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL) != 1) {
834
0
    EVP_MD_CTX_destroy(mdctx);
835
836
0
    return 1;
837
0
  }
838
839
0
  if (info->ssl_client_options_set)
840
0
    EVP_DigestUpdate(mdctx, &info->ssl_client_options_set,
841
0
         sizeof(info->ssl_client_options_set));
842
843
0
#if (OPENSSL_VERSION_NUMBER >= 0x009080df) && !defined(USE_WOLFSSL)
844
0
  if (info->ssl_client_options_clear)
845
0
    EVP_DigestUpdate(mdctx, &info->ssl_client_options_clear,
846
0
         sizeof(info->ssl_client_options_clear));
847
0
#endif
848
849
0
  if (cipher_list)
850
0
    EVP_DigestUpdate(mdctx, cipher_list, strlen(cipher_list));
851
852
#if defined(LWS_HAVE_SSL_CTX_set_ciphersuites)
853
  if (info->client_tls_1_3_plus_cipher_list)
854
    EVP_DigestUpdate(mdctx, info->client_tls_1_3_plus_cipher_list,
855
         strlen(info->client_tls_1_3_plus_cipher_list));
856
#endif
857
858
0
  if (!lws_check_opt(vh->options, LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS)) {
859
0
    c = 1;
860
0
    EVP_DigestUpdate(mdctx, &c, 1);
861
0
  }
862
863
0
  if (ca_filepath)
864
0
    EVP_DigestUpdate(mdctx, ca_filepath, strlen(ca_filepath));
865
866
0
  if (cert_filepath)
867
0
    EVP_DigestUpdate(mdctx, cert_filepath, strlen(cert_filepath));
868
869
0
  if (private_key_filepath)
870
0
    EVP_DigestUpdate(mdctx, private_key_filepath,
871
0
         strlen(private_key_filepath));
872
0
  if (ca_mem && ca_mem_len)
873
0
    EVP_DigestUpdate(mdctx, ca_mem, ca_mem_len);
874
875
0
  if (cert_mem && cert_mem_len)
876
0
    EVP_DigestUpdate(mdctx, cert_mem, cert_mem_len);
877
878
0
  len = sizeof(hash);
879
0
  EVP_DigestFinal_ex(mdctx, hash, &len);
880
0
  EVP_MD_CTX_destroy(mdctx);
881
882
  /* look for existing client context with same config already */
883
884
0
  lws_start_foreach_dll_safe(struct lws_dll2 *, p, tp,
885
0
       lws_dll2_get_head(&vh->context->tls.cc_owner)) {
886
0
    tcr = lws_container_of(p, struct lws_tls_client_reuse, cc_list);
887
888
0
    if (!memcmp(hash, tcr->hash, len)) {
889
890
      /* it's a match */
891
892
0
      tcr->refcount++;
893
0
      vh->tls.ssl_client_ctx = tcr->ssl_client_ctx;
894
0
      vh->tls.tcr = tcr;
895
896
0
      lwsl_info("%s: vh %s: reusing client ctx %d: use %d\n",
897
0
           __func__, vh->name, tcr->index,
898
0
           tcr->refcount);
899
900
0
      return 0;
901
0
    }
902
0
  } lws_end_foreach_dll_safe(p, tp);
903
904
  /* no existing one the same... create new client SSL_CTX */
905
906
0
  errno = 0;
907
0
  ERR_clear_error();
908
0
  vh->tls.ssl_client_ctx = SSL_CTX_new(method);
909
0
  if (!vh->tls.ssl_client_ctx) {
910
0
    const char *es;
911
912
0
    error = ERR_get_error();
913
0
    es = ERR_error_string(
914
    #if defined(LWS_WITH_BORINGSSL)
915
      (uint32_t)
916
    #else
917
0
      (unsigned long)
918
0
    #endif
919
0
       error, (char *)vh->context->pt[0].serv_buf);
920
0
    lwsl_err("problem creating ssl context %lu: %s\n",
921
0
      error, es);
922
0
    return 1;
923
0
  }
924
925
0
  lws_plat_vhost_tls_client_ctx_init(vh);
926
927
0
  tcr = lws_zalloc(sizeof(*tcr), "client ctx tcr");
928
0
  if (!tcr) {
929
0
    SSL_CTX_free(vh->tls.ssl_client_ctx);
930
0
    return 1;
931
0
  }
932
933
0
  tcr->ssl_client_ctx = vh->tls.ssl_client_ctx;
934
0
  tcr->refcount = 1;
935
0
  memcpy(tcr->hash, hash, len);
936
0
  tcr->index = vh->context->tls.count_client_contexts++;
937
0
  lws_dll2_add_head(&tcr->cc_list, &vh->context->tls.cc_owner);
938
939
0
  lwsl_info("%s: vh %s: created new client ctx %d\n", __func__,
940
0
      vh->name, tcr->index);
941
942
  /* bind the tcr to the client context */
943
944
0
  vh->tls.tcr = tcr;
945
946
0
#if defined(LWS_HAVE_SSL_CTX_set_keylog_callback) && \
947
0
    defined(LWS_WITH_TLS) && defined(LWS_WITH_CLIENT)
948
0
  if (vh->context->keylog_file[0])
949
0
    SSL_CTX_set_keylog_callback(vh->tls.ssl_client_ctx, lws_klog_dump);
950
0
#endif
951
952
0
#if defined(LWS_WITH_TLS_SESSIONS)
953
0
  vh->tls_session_cache_max = info->tls_session_cache_max ?
954
0
            info->tls_session_cache_max : 10;
955
0
  lws_tls_session_cache(vh, info->tls_session_timeout);
956
0
#endif
957
958
0
#ifdef SSL_OP_NO_COMPRESSION
959
0
  SSL_CTX_set_options(vh->tls.ssl_client_ctx, SSL_OP_NO_COMPRESSION);
960
0
#endif
961
962
0
  SSL_CTX_set_options(vh->tls.ssl_client_ctx,
963
0
          SSL_OP_CIPHER_SERVER_PREFERENCE);
964
965
0
  SSL_CTX_set_mode(vh->tls.ssl_client_ctx,
966
0
       SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
967
0
       SSL_MODE_RELEASE_BUFFERS);
968
969
0
#if !defined(USE_WOLFSSL)
970
#if defined(LWS_WITH_BORINGSSL)
971
        uint32_t
972
#else
973
0
#if (OPENSSL_VERSION_NUMBER >= 0x10003000l) && \
974
0
  !defined(LIBRESSL_VERSION_NUMBER) /* not documented by openssl */
975
0
    unsigned long
976
#else
977
    long
978
#endif
979
0
#endif
980
#else
981
    long
982
#endif
983
0
      ssl_client_options_set_value =
984
0
#if !defined(USE_WOLFSSL)
985
#if defined(LWS_WITH_BORINGSSL)
986
        (uint32_t)
987
#else
988
0
#if (OPENSSL_VERSION_NUMBER >= 0x10003000l) && \
989
0
  !defined(LIBRESSL_VERSION_NUMBER) /* not documented by openssl */
990
0
        (unsigned long)
991
#else
992
        (long)
993
#endif
994
0
#endif
995
0
#endif
996
0
      info->ssl_client_options_set;
997
998
0
  if (info->ssl_client_options_set)
999
0
    SSL_CTX_set_options(vh->tls.ssl_client_ctx, ssl_client_options_set_value);
1000
1001
0
#if (OPENSSL_VERSION_NUMBER >= 0x009080df) && !defined(USE_WOLFSSL)
1002
1003
  /* SSL_clear_options introduced in 0.9.8m */
1004
#if defined(LWS_WITH_BORINGSSL)
1005
                uint32_t
1006
#else
1007
0
#if (OPENSSL_VERSION_NUMBER >= 0x10003000l) && \
1008
0
  !defined(LIBRESSL_VERSION_NUMBER) /* not documented by openssl */
1009
0
    unsigned long
1010
#else
1011
    long
1012
#endif
1013
0
#endif
1014
1015
0
      ssl_client_options_clear_value =
1016
#if defined(LWS_WITH_BORINGSSL)
1017
        (uint32_t)
1018
#else
1019
0
#if (OPENSSL_VERSION_NUMBER >= 0x10003000l) && \
1020
0
  !defined(LIBRESSL_VERSION_NUMBER) /* not documented by openssl */
1021
0
        (unsigned long)
1022
#else
1023
        (long)
1024
#endif
1025
0
#endif
1026
0
      info->ssl_client_options_clear;
1027
1028
0
  if (info->ssl_client_options_clear)
1029
0
    SSL_CTX_clear_options(vh->tls.ssl_client_ctx, ssl_client_options_clear_value);
1030
0
#endif
1031
1032
0
  if (cipher_list)
1033
0
    SSL_CTX_set_cipher_list(vh->tls.ssl_client_ctx, cipher_list);
1034
1035
#if defined(LWS_HAVE_SSL_CTX_set_ciphersuites)
1036
  if (info->client_tls_1_3_plus_cipher_list)
1037
    SSL_CTX_set_ciphersuites(vh->tls.ssl_client_ctx,
1038
           info->client_tls_1_3_plus_cipher_list);
1039
#endif
1040
1041
0
#ifdef LWS_SSL_CLIENT_USE_OS_CA_CERTS
1042
0
  if (!lws_check_opt(vh->options, LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS))
1043
    /* loads OS default CA certs */
1044
0
    SSL_CTX_set_default_verify_paths(vh->tls.ssl_client_ctx);
1045
0
#endif
1046
1047
  /* openssl init for cert verification (for client sockets) */
1048
0
  if (!ca_filepath && (!ca_mem || !ca_mem_len)) {
1049
#if defined(LWS_HAVE_SSL_CTX_load_verify_dir)
1050
    if (!SSL_CTX_load_verify_dir(
1051
      vh->tls.ssl_client_ctx, LWS_OPENSSL_CLIENT_CERTS))
1052
#else
1053
0
    if (!SSL_CTX_load_verify_locations(
1054
0
      vh->tls.ssl_client_ctx, NULL, LWS_OPENSSL_CLIENT_CERTS))
1055
0
#endif
1056
0
      lwsl_err("Unable to load SSL Client certs from %s "
1057
0
          "(set by LWS_OPENSSL_CLIENT_CERTS) -- "
1058
0
          "client ssl isn't going to work\n",
1059
0
          LWS_OPENSSL_CLIENT_CERTS);
1060
0
  } else if (ca_filepath) {
1061
#if defined(LWS_HAVE_SSL_CTX_load_verify_file)
1062
    if (!SSL_CTX_load_verify_file(
1063
      vh->tls.ssl_client_ctx, ca_filepath)) {
1064
#else
1065
0
    if (!SSL_CTX_load_verify_locations(
1066
0
      vh->tls.ssl_client_ctx, ca_filepath, NULL)) {
1067
0
#endif
1068
0
      lwsl_err(
1069
0
        "Unable to load SSL Client certs "
1070
0
        "file from %s -- client ssl isn't "
1071
0
        "going to work\n", ca_filepath);
1072
0
      lws_tls_err_describe_clear();
1073
0
    }
1074
0
    else
1075
0
      lwsl_info("loaded ssl_ca_filepath\n");
1076
0
  } else {
1077
1078
0
    lws_filepos_t amount = 0;
1079
0
    const uint8_t *up;
1080
0
    uint8_t *up1;
1081
1082
0
    if (lws_tls_alloc_pem_to_der_file(vh->context, NULL, ca_mem,
1083
0
              ca_mem_len, &up1, &amount)) {
1084
0
      lwsl_err("%s: Unable to decode x.509 mem\n", __func__);
1085
0
      lwsl_hexdump_notice(ca_mem, ca_mem_len);
1086
0
      return 1;
1087
0
    }
1088
1089
0
    up = up1;
1090
#if defined(USE_WOLFSSL)
1091
    client_CA = d2i_X509(NULL, &up, (int)amount);
1092
#else
1093
0
    client_CA = d2i_X509(NULL, &up, (long)amount);
1094
0
#endif
1095
0
    if (!client_CA) {
1096
0
      lwsl_err("%s: d2i_X509 failed\n", __func__);
1097
0
      lwsl_hexdump_notice(up1, (size_t)amount);
1098
0
      lws_tls_err_describe_clear();
1099
0
    } else {
1100
0
      x509_store = X509_STORE_new();
1101
0
      if (!X509_STORE_add_cert(x509_store, client_CA)) {
1102
0
        X509_STORE_free(x509_store);
1103
0
        lwsl_err("Unable to load SSL Client certs from "
1104
0
           "ssl_ca_mem -- client ssl isn't going to "
1105
0
           "work\n");
1106
0
        lws_tls_err_describe_clear();
1107
0
      } else {
1108
        /* it doesn't increment x509_store ref counter */
1109
0
        SSL_CTX_set_cert_store(vh->tls.ssl_client_ctx,
1110
0
                   x509_store);
1111
0
        lwsl_info("loaded ssl_ca_mem\n");
1112
0
      }
1113
0
    }
1114
0
    if (client_CA)
1115
0
      X509_free(client_CA);
1116
0
    lws_free(up1);
1117
  //  lws_tls_client_vhost_extra_cert_mem(vh, ca_mem, ca_mem_len);
1118
0
  }
1119
1120
  /*
1121
   * callback allowing user code to load extra verification certs
1122
   * helping the client to verify server identity
1123
   */
1124
1125
  /* support for client-side certificate authentication */
1126
1127
0
  if (cert_filepath) {
1128
0
    if (lws_tls_use_any_upgrade_check_extant(cert_filepath) !=
1129
0
        LWS_TLS_EXTANT_YES &&
1130
0
        (info->options & LWS_SERVER_OPTION_IGNORE_MISSING_CERT))
1131
0
      return 0;
1132
1133
0
    lwsl_notice("%s: doing cert filepath %s\n", __func__,
1134
0
        cert_filepath);
1135
0
    n = SSL_CTX_use_certificate_chain_file(vh->tls.ssl_client_ctx,
1136
0
                   cert_filepath);
1137
0
    if (n < 1) {
1138
0
      lwsl_err("problem %d getting cert '%s'\n", n,
1139
0
         cert_filepath);
1140
0
      lws_tls_err_describe_clear();
1141
0
      return 1;
1142
0
    }
1143
0
    lwsl_info("Loaded client cert %s\n", cert_filepath);
1144
1145
0
  } else if (cert_mem && cert_mem_len) {
1146
0
    lws_filepos_t flen;
1147
0
    uint8_t *p;
1148
1149
0
    if (lws_tls_alloc_pem_to_der_file(vh->context, NULL, cert_mem,
1150
0
              cert_mem_len, &p, &flen)) {
1151
0
      lwsl_err("%s: couldn't read cert file\n", __func__);
1152
1153
0
      return 1;
1154
0
    }
1155
1156
0
    n = SSL_CTX_use_certificate_ASN1(vh->tls.ssl_client_ctx,
1157
#if defined(LWS_WITH_BORINGSSL)
1158
        (size_t)
1159
#else
1160
0
        (int)
1161
0
#endif
1162
0
        flen, p);
1163
1164
0
    if (n < 1) {
1165
0
      lwsl_err("%s: problem interpreting client cert\n",  __func__);
1166
0
      lws_tls_err_describe_clear();
1167
0
    }
1168
1169
0
    lws_free_set_NULL(p);
1170
1171
0
    if (n != 1)
1172
0
      return 1;
1173
1174
0
  }
1175
0
  if (private_key_filepath) {
1176
0
    lwsl_info("%s: using private key filepath\n", __func__);
1177
0
    lws_ssl_bind_passphrase(vh->tls.ssl_client_ctx, 1, info);
1178
    /* set the private key from KeyFile */
1179
0
    if (SSL_CTX_use_PrivateKey_file(vh->tls.ssl_client_ctx,
1180
0
        private_key_filepath, SSL_FILETYPE_PEM) != 1) {
1181
0
      lwsl_err("use_PrivateKey_file '%s'\n",
1182
0
         private_key_filepath);
1183
0
      lws_tls_err_describe_clear();
1184
0
      return 1;
1185
0
    }
1186
0
    lwsl_info("Loaded client cert private key %s\n",
1187
0
          private_key_filepath);
1188
1189
    /* verify private key */
1190
0
    if (!SSL_CTX_check_private_key(vh->tls.ssl_client_ctx)) {
1191
0
      lwsl_err("Private SSL key doesn't match cert\n");
1192
0
      return 1;
1193
0
    }
1194
0
  }
1195
0
  else if (key_mem && key_mem_len) {
1196
1197
0
    lws_filepos_t flen;
1198
0
    uint8_t *p;
1199
1200
0
    if (lws_tls_alloc_pem_to_der_file(vh->context, NULL, key_mem,
1201
0
              key_mem_len, &p, &flen)) {
1202
0
      lwsl_err("%s: couldn't use mem cert\n", __func__);
1203
1204
0
      return 1;
1205
0
    }
1206
1207
0
    n = SSL_CTX_use_PrivateKey_ASN1(EVP_PKEY_RSA, vh->tls.ssl_client_ctx, p,
1208
#if defined(LWS_WITH_BORINGSSL)
1209
        (size_t)
1210
#else
1211
0
        (long)(lws_intptr_t)
1212
0
#endif
1213
0
            flen);
1214
0
    if (n != 1)
1215
0
      n = SSL_CTX_use_PrivateKey_ASN1(EVP_PKEY_EC,
1216
0
              vh->tls.ssl_client_ctx, p,
1217
#if defined(LWS_WITH_BORINGSSL)
1218
        (size_t)
1219
#else
1220
0
        (long)(lws_intptr_t)
1221
0
#endif
1222
0
            flen);
1223
1224
0
    lws_free_set_NULL(p);
1225
1226
0
    if (n != 1)  {
1227
0
      lwsl_err("%s: unable to use key_mem\n", __func__);
1228
1229
0
      return 1;
1230
0
    }
1231
0
  }
1232
1233
0
  return 0;
1234
0
}
1235
1236