private.h: rename to contain dir
[platform/upstream/libwebsockets.git] / lib / tls / openssl / openssl-client.c
1 /*
2  * libwebsockets - openSSL-specific client tls code
3  *
4  * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com>
5  *
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.
10  *
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.
15  *
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,
19  *  MA  02110-1301  USA
20  */
21
22 #include "private-lib-core.h"
23 #include "private-lib-tls-openssl.h"
24
25 /*
26  * Care: many openssl apis return 1 for success.  These are translated to the
27  * lws convention of 0 for success.
28  */
29
30 int lws_openssl_describe_cipher(struct lws *wsi);
31
32 extern int openssl_websocket_private_data_index,
33     openssl_SSL_CTX_private_data_index;
34
35 #if !defined(USE_WOLFSSL)
36
37 static int
38 OpenSSL_client_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
39 {
40         SSL *ssl;
41         int n;
42         struct lws *wsi;
43
44         /* keep old behaviour accepting self-signed server certs */
45         if (!preverify_ok) {
46                 int err = X509_STORE_CTX_get_error(x509_ctx);
47
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);
53                         if (!wsi) {
54                                 lwsl_err("%s: can't get wsi from ssl privdata\n",
55                                          __func__);
56
57                                 return 0;
58                         }
59
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);
66                                 return 1;       // 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_"
73                                                     "callback)\n");
74                                 else if (err == X509_V_ERR_CERT_HAS_EXPIRED)
75                                         lwsl_notice("accepting expired "
76                                                     "certificate (verify_"
77                                                     "callback)\n");
78                                 X509_STORE_CTX_set_error(x509_ctx, X509_V_OK);
79                                 return 1;       // ok
80                         }
81                 }
82         }
83
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);
87         if (!wsi) {
88                 lwsl_err("%s: can't get wsi from ssl privdata\n",  __func__);
89
90                 return 0;
91         }
92
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);
96
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 */
101         if (!preverify_ok) {
102                 int err = X509_STORE_CTX_get_error(x509_ctx);
103
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);
108
109                         lwsl_err("SSL error: %s (preverify_ok=%d;err=%d;"
110                                  "depth=%d)\n", msg, preverify_ok, err, depth);
111
112                         return preverify_ok;    // not ok
113                 }
114         }
115         /*
116          * convert callback return code from 0 = OK to verify callback
117          * return value 1 = OK
118          */
119         return !n;
120 }
121 #endif
122
123
124 int
125 lws_ssl_client_bio_create(struct lws *wsi)
126 {
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;
132         int n;
133 #endif
134
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)
138 #endif
139         {
140                 lwsl_err("%s: Unable to get hostname\n", __func__);
141
142                 return -1;
143         }
144
145         /*
146          * remove any :port part on the hostname... necessary for network
147          * connection but typical certificates do not contain it
148          */
149         p = hostname;
150         while (*p) {
151                 if (*p == ':') {
152                         *p = '\0';
153                         break;
154                 }
155                 p++;
156         }
157
158         wsi->tls.ssl = SSL_new(wsi->vhost->tls.ssl_client_ctx);
159         if (!wsi->tls.ssl) {
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();
163                 return -1;
164         }
165
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);
169 #endif
170
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);
174
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);
181         }
182 #endif
183
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);
189 #endif
190 #endif
191
192 #if !defined(USE_WOLFSSL)
193         SSL_set_mode(wsi->tls.ssl,  SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
194 #endif
195         /*
196          * use server name indication (SNI), if supported,
197          * when establishing connection
198          */
199 #ifdef USE_WOLFSSL
200 #ifdef USE_OLD_CYASSL
201 #ifdef CYASSL_SNI_HOST_NAME
202         CyaSSL_UseSNI(wsi->tls.ssl, CYASSL_SNI_HOST_NAME, hostname,
203                       strlen(hostname));
204 #endif
205 #else
206 #ifdef WOLFSSL_SNI_HOST_NAME
207         wolfSSL_UseSNI(wsi->tls.ssl, WOLFSSL_SNI_HOST_NAME, hostname,
208                        strlen(hostname));
209 #endif
210 #endif
211 #else
212 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
213         SSL_set_tlsext_host_name(wsi->tls.ssl, hostname);
214 #endif
215 #endif
216
217 #ifdef USE_WOLFSSL
218         /*
219          * wolfSSL/CyaSSL does certificate verification differently
220          * from OpenSSL.
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
224          */
225 #ifdef USE_OLD_CYASSL
226         if (wsi->tls.use_ssl == 2)
227                 CyaSSL_set_verify(wsi->tls.ssl, SSL_VERIFY_NONE, NULL);
228 #else
229         if (wsi->tls.use_ssl == 2)
230                 wolfSSL_set_verify(wsi->tls.ssl, SSL_VERIFY_NONE, NULL);
231 #endif
232 #endif /* USE_WOLFSSL */
233
234         wsi->tls.client_bio = BIO_new_socket((int)(long long)wsi->desc.sockfd,
235                                              BIO_NOCLOSE);
236         SSL_set_bio(wsi->tls.ssl, wsi->tls.client_bio, wsi->tls.client_bio);
237
238 #ifdef USE_WOLFSSL
239 #ifdef USE_OLD_CYASSL
240         CyaSSL_set_using_nonblock(wsi->tls.ssl, 1);
241 #else
242         wolfSSL_set_using_nonblock(wsi->tls.ssl, 1);
243 #endif
244 #else
245         BIO_set_nbio(wsi->tls.client_bio, 1); /* nonblocking */
246 #endif
247
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;
256 #endif
257
258         lwsl_info("client conn using alpn list '%s'\n", alpn_comma);
259
260         n = lws_alpn_comma_to_openssl(alpn_comma, openssl_alpn,
261                                       sizeof(openssl_alpn) - 1);
262
263         SSL_set_alpn_protos(wsi->tls.ssl, openssl_alpn, n);
264 #endif
265
266         SSL_set_ex_data(wsi->tls.ssl, openssl_websocket_private_data_index,
267                         wsi);
268
269         return 0;
270 }
271
272 enum lws_ssl_capable_status
273 lws_tls_client_connect(struct lws *wsi)
274 {
275 #if defined(LWS_HAVE_SSL_set_alpn_protos) && \
276     defined(LWS_HAVE_SSL_get0_alpn_selected)
277         const unsigned char *prot;
278         char a[32];
279         unsigned int len;
280 #endif
281         int m, n;
282
283         errno = 0;
284         ERR_clear_error();
285         n = SSL_connect(wsi->tls.ssl);
286         if (n == 1) {
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);
290
291                 if (len >= sizeof(a))
292                         len = sizeof(a) - 1;
293                 memcpy(a, (const char *)prot, len);
294                 a[len] = '\0';
295
296                 lws_role_call_alpn_negotiated(wsi, (const char *)a);
297 #endif
298                 lwsl_info("client connect OK\n");
299                 lws_openssl_describe_cipher(wsi);
300                 return LWS_SSL_CAPABLE_DONE;
301         }
302
303         m = lws_ssl_get_error(wsi, n);
304
305         if (m == SSL_ERROR_SYSCALL)
306                 return LWS_SSL_CAPABLE_ERROR;
307
308         if (m == SSL_ERROR_WANT_READ || SSL_want_read(wsi->tls.ssl))
309                 return LWS_SSL_CAPABLE_MORE_SERVICE_READ;
310
311         if (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->tls.ssl))
312                 return LWS_SSL_CAPABLE_MORE_SERVICE_WRITE;
313
314         if (!n) /* we don't know what he wants, but he says to retry */
315                 return LWS_SSL_CAPABLE_MORE_SERVICE;
316
317         return LWS_SSL_CAPABLE_ERROR;
318 }
319
320 int
321 lws_tls_client_confirm_peer_cert(struct lws *wsi, char *ebuf, int ebuf_len)
322 {
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];
326         char *sb = p;
327         int n;
328
329         lws_latency_pre(wsi->context, wsi);
330         errno = 0;
331         ERR_clear_error();
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);
335
336         lwsl_debug("get_verify says %d\n", n);
337
338         if (n == X509_V_OK)
339                 return 0;
340
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");
345
346                 return 0;
347         }
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");
352                 return 0;
353         }
354         if (n == X509_V_ERR_CERT_NOT_YET_VALID) {
355                 lwsl_info("Cert is from the future... "
356                             "probably our clock... accepting...\n");
357                 return 0;
358         }
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();
364
365         return -1;
366
367 #else /* USE_WOLFSSL */
368         return 0;
369 #endif
370 }
371
372 int
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,
377                                     const void *ca_mem,
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)
383 {
384         struct lws_tls_client_reuse *tcr;
385         const unsigned char *ca_mem_ptr;
386         X509_STORE *x509_store;
387         unsigned long error;
388         SSL_METHOD *method;
389         EVP_MD_CTX *mdctx;
390         unsigned int len;
391         uint8_t hash[32];
392         X509 *client_CA;
393         char c;
394         int n;
395
396         /* basic openssl init already happened in context init */
397
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();
403 #else
404         method = (SSL_METHOD *)SSLv23_client_method();
405 #endif
406
407         if (!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));
412                 return 1;
413         }
414
415         /*
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.
421          *
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
424          * possible.
425          */
426
427          mdctx = EVP_MD_CTX_create();
428          if (!mdctx)
429                  return 1;
430
431         if (EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL) != 1) {
432                 EVP_MD_CTX_destroy(mdctx);
433
434                 return 1;
435         }
436
437         if (info->ssl_client_options_set)
438                 EVP_DigestUpdate(mdctx, &info->ssl_client_options_set,
439                                  sizeof(info->ssl_client_options_set));
440
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));
445 #endif
446
447         if (cipher_list)
448                 EVP_DigestUpdate(mdctx, cipher_list, strlen(cipher_list));
449
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));
454 #endif
455
456         if (!lws_check_opt(vh->options, LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS)) {
457                 c = 1;
458                 EVP_DigestUpdate(mdctx, &c, 1);
459         }
460
461         if (ca_filepath)
462                 EVP_DigestUpdate(mdctx, ca_filepath, strlen(ca_filepath));
463
464         if (cert_filepath)
465                 EVP_DigestUpdate(mdctx, cert_filepath, strlen(cert_filepath));
466
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);
472
473         if (cert_mem && cert_mem_len)
474                 EVP_DigestUpdate(mdctx, cert_mem, cert_mem_len);
475
476         len = sizeof(hash);
477         EVP_DigestFinal_ex(mdctx, hash, &len);
478         EVP_MD_CTX_destroy(mdctx);
479
480         /* look for existing client context with same config already */
481
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);
485
486                 if (!memcmp(hash, tcr->hash, len)) {
487
488                         /* it's a match */
489
490                         tcr->refcount++;
491                         vh->tls.ssl_client_ctx = tcr->ssl_client_ctx;
492
493                         lwsl_info("%s: vh %s: reusing client ctx %d: use %d\n",
494                                    __func__, vh->name, tcr->index,
495                                    tcr->refcount);
496
497                         return 0;
498                 }
499         } lws_end_foreach_dll_safe(p, tp);
500
501         /* no existing one the same... create new client SSL_CTX */
502
503         errno = 0;
504         ERR_clear_error();
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));
511                 return 1;
512         }
513
514         tcr = lws_zalloc(sizeof(*tcr), "client ctx tcr");
515         if (!tcr) {
516                 SSL_CTX_free(vh->tls.ssl_client_ctx);
517                 return 1;
518         }
519
520         tcr->ssl_client_ctx = vh->tls.ssl_client_ctx;
521         tcr->refcount = 1;
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);
525
526         lwsl_info("%s: vh %s: created new client ctx %d\n", __func__,
527                         vh->name, tcr->index);
528
529         /* bind the tcr to the client context */
530
531         SSL_CTX_set_ex_data(vh->tls.ssl_client_ctx,
532                             openssl_SSL_CTX_private_data_index,
533                             (char *)tcr);
534
535 #ifdef SSL_OP_NO_COMPRESSION
536         SSL_CTX_set_options(vh->tls.ssl_client_ctx, SSL_OP_NO_COMPRESSION);
537 #endif
538
539         SSL_CTX_set_options(vh->tls.ssl_client_ctx,
540                             SSL_OP_CIPHER_SERVER_PREFERENCE);
541
542         SSL_CTX_set_mode(vh->tls.ssl_client_ctx,
543                          SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
544                          SSL_MODE_RELEASE_BUFFERS);
545
546         if (info->ssl_client_options_set)
547                 SSL_CTX_set_options(vh->tls.ssl_client_ctx,
548                                     info->ssl_client_options_set);
549
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);
555 #endif
556
557         if (cipher_list)
558                 SSL_CTX_set_cipher_list(vh->tls.ssl_client_ctx, cipher_list);
559
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);
564 #endif
565
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);
570 #endif
571
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)) {
583                         lwsl_err(
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();
588                 }
589                 else
590                         lwsl_info("loaded ssl_ca_filepath\n");
591         } else {
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 "
599                                  "work\n");
600                         lws_tls_err_describe_clear();
601                 } else {
602                         /* it doesn't increment x509_store ref counter */
603                         SSL_CTX_set_cert_store(vh->tls.ssl_client_ctx,
604                                                x509_store);
605                         lwsl_info("loaded ssl_ca_mem\n");
606                 }
607                 if (client_CA)
608                         X509_free(client_CA);
609         }
610
611         /*
612          * callback allowing user code to load extra verification certs
613          * helping the client to verify server identity
614          */
615
616         /* support for client-side certificate authentication */
617         if (cert_filepath) {
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))
621                         return 0;
622
623                 lwsl_notice("%s: doing cert filepath %s\n", __func__,
624                                 cert_filepath);
625                 n = SSL_CTX_use_certificate_chain_file(vh->tls.ssl_client_ctx,
626                                                        cert_filepath);
627                 if (n < 1) {
628                         lwsl_err("problem %d getting cert '%s'\n", n,
629                                  cert_filepath);
630                         lws_tls_err_describe_clear();
631                         return 1;
632                 }
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);
637                 if (n < 1) {
638                         lwsl_err("%s: problem interpreting client cert\n",
639                                  __func__);
640                         lws_tls_err_describe_clear();
641                         return 1;
642                 }
643         }
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();
653                         return 1;
654                 }
655                 lwsl_notice("Loaded client cert private key %s\n",
656                             private_key_filepath);
657
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");
661                         return 1;
662                 }
663         }
664
665         return 0;
666 }