e60f10aa14d6a60b676e4cafaed28882d954c6b6
[platform/upstream/libwebsockets.git] / lib / ssl-client.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2016 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-libwebsockets.h"
23
24 extern int openssl_websocket_private_data_index,
25     openssl_SSL_CTX_private_data_index;
26
27 extern void
28 lws_ssl_bind_passphrase(SSL_CTX *ssl_ctx, struct lws_context_creation_info *info);
29
30 extern int lws_ssl_get_error(struct lws *wsi, int n);
31
32 #if defined(USE_WOLFSSL)
33 #else
34
35 static int
36 OpenSSL_client_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
37 {
38 #if defined(LWS_WITH_ESP32)
39 //      long gvr = ssl_pm_get_verify_result(
40         lwsl_notice("%s\n", __func__);
41
42         return 0;
43 #else
44         SSL *ssl;
45         int n;
46         struct lws *wsi;
47
48         /* keep old behaviour accepting self-signed server certs */
49         if (!preverify_ok) {
50                 int err = X509_STORE_CTX_get_error(x509_ctx);
51
52                 if (err != X509_V_OK) {
53                         ssl = X509_STORE_CTX_get_ex_data(x509_ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
54                         wsi = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
55
56                         if ((err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
57                                         err == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) &&
58                                         wsi->use_ssl & LCCSCF_ALLOW_SELFSIGNED) {
59                                 lwsl_notice("accepting self-signed certificate (verify_callback)\n");
60                                 X509_STORE_CTX_set_error(x509_ctx, X509_V_OK);
61                                 return 1;       // ok
62                         } else if ((err == X509_V_ERR_CERT_NOT_YET_VALID ||
63                                         err == X509_V_ERR_CERT_HAS_EXPIRED) &&
64                                         wsi->use_ssl & LCCSCF_ALLOW_EXPIRED) {
65                                 if (err == X509_V_ERR_CERT_NOT_YET_VALID)
66                                         lwsl_notice("accepting not yet valid certificate (verify_callback)\n");
67                                 else if (err == X509_V_ERR_CERT_HAS_EXPIRED)
68                                         lwsl_notice("accepting expired certificate (verify_callback)\n");
69                                 X509_STORE_CTX_set_error(x509_ctx, X509_V_OK);
70                                 return 1;       // ok
71                         }
72                 }
73         }
74
75         ssl = X509_STORE_CTX_get_ex_data(x509_ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
76         wsi = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
77
78         n = lws_get_context_protocol(wsi->context, 0).callback(wsi, LWS_CALLBACK_OPENSSL_PERFORM_SERVER_CERT_VERIFICATION, x509_ctx, ssl, preverify_ok);
79
80         /* keep old behaviour if something wrong with server certs */
81         /* if ssl error is overruled in callback and cert is ok,
82          * X509_STORE_CTX_set_error(x509_ctx, X509_V_OK); must be set and
83          * return value is 0 from callback */
84         if (!preverify_ok) {
85                 int err = X509_STORE_CTX_get_error(x509_ctx);
86
87                 if (err != X509_V_OK) { /* cert validation error was not handled in callback */
88                         int depth = X509_STORE_CTX_get_error_depth(x509_ctx);
89                         const char* msg = X509_verify_cert_error_string(err);
90                         lwsl_err("SSL error: %s (preverify_ok=%d;err=%d;depth=%d)\n", msg, preverify_ok, err, depth);
91                         return preverify_ok;    // not ok
92                 }
93         }
94         /* convert callback return code from 0 = OK to verify callback return value 1 = OK */
95         return !n;
96 #endif
97 }
98 #endif
99
100 int
101 lws_ssl_client_bio_create(struct lws *wsi)
102 {
103         char hostname[128], *p;
104
105         if (lws_hdr_copy(wsi, hostname, sizeof(hostname),
106                          _WSI_TOKEN_CLIENT_HOST) <= 0) {
107                 lwsl_err("%s: Unable to get hostname\n", __func__);
108
109                 return -1;
110         }
111
112         /*
113          * remove any :port part on the hostname... necessary for network
114          * connection but typical certificates do not contain it
115          */
116         p = hostname;
117         while (*p) {
118                 if (*p == ':') {
119                         *p = '\0';
120                         break;
121                 }
122                 p++;
123         }
124
125         wsi->ssl = SSL_new(wsi->vhost->ssl_client_ctx);
126         if (!wsi->ssl) {
127                 lwsl_err("SSL_new failed: %s\n",
128                          ERR_error_string(lws_ssl_get_error(wsi, 0), NULL));
129                 lws_ssl_elaborate_error();
130                 return -1;
131         }
132
133 #if defined (LWS_HAVE_SSL_SET_INFO_CALLBACK)
134         if (wsi->vhost->ssl_info_event_mask)
135                 SSL_set_info_callback(wsi->ssl, lws_ssl_info_callback);
136 #endif
137
138 #if defined LWS_HAVE_X509_VERIFY_PARAM_set1_host
139         X509_VERIFY_PARAM *param;
140         (void)param;
141
142         if (!(wsi->use_ssl & LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK)) {
143                 param = SSL_get0_param(wsi->ssl);
144                 /* Enable automatic hostname checks */
145                 X509_VERIFY_PARAM_set_hostflags(param,
146                                                 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
147                 X509_VERIFY_PARAM_set1_host(param, hostname, 0);
148         }
149
150 #endif
151
152 #if !defined(USE_WOLFSSL) && !defined(LWS_WITH_ESP32)
153 #ifndef USE_OLD_CYASSL
154         /* OpenSSL_client_verify_callback will be called @ SSL_connect() */
155         SSL_set_verify(wsi->ssl, SSL_VERIFY_PEER, OpenSSL_client_verify_callback);
156 #endif
157 #endif
158
159 #if !defined(USE_WOLFSSL) && !defined(LWS_WITH_ESP32)
160         SSL_set_mode(wsi->ssl,  SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
161 #endif
162         /*
163          * use server name indication (SNI), if supported,
164          * when establishing connection
165          */
166 #ifdef USE_WOLFSSL
167 #ifdef USE_OLD_CYASSL
168 #ifdef CYASSL_SNI_HOST_NAME
169         CyaSSL_UseSNI(wsi->ssl, CYASSL_SNI_HOST_NAME, hostname, strlen(hostname));
170 #endif
171 #else
172 #ifdef WOLFSSL_SNI_HOST_NAME
173         wolfSSL_UseSNI(wsi->ssl, WOLFSSL_SNI_HOST_NAME, hostname, strlen(hostname));
174 #endif
175 #endif
176 #else
177 #if defined(LWS_WITH_ESP32)
178 // esp-idf openssl shim does not seem ready for this
179 //      SSL_set_verify(wsi->ssl, SSL_VERIFY_PEER, OpenSSL_client_verify_callback);
180         SSL_set_verify(wsi->ssl, SSL_VERIFY_NONE, OpenSSL_client_verify_callback);
181
182 #else
183 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
184         SSL_set_tlsext_host_name(wsi->ssl, hostname);
185 #endif
186 #endif
187 #endif
188
189 #ifdef USE_WOLFSSL
190         /*
191          * wolfSSL/CyaSSL does certificate verification differently
192          * from OpenSSL.
193          * If we should ignore the certificate, we need to set
194          * this before SSL_new and SSL_connect is called.
195          * Otherwise the connect will simply fail with error code -155
196          */
197 #ifdef USE_OLD_CYASSL
198         if (wsi->use_ssl == 2)
199                 CyaSSL_set_verify(wsi->ssl, SSL_VERIFY_NONE, NULL);
200 #else
201         if (wsi->use_ssl == 2)
202                 wolfSSL_set_verify(wsi->ssl, SSL_VERIFY_NONE, NULL);
203 #endif
204 #endif /* USE_WOLFSSL */
205
206 #if !defined(LWS_WITH_ESP32)
207         wsi->client_bio = BIO_new_socket(wsi->desc.sockfd, BIO_NOCLOSE);
208         SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
209 #else
210         SSL_set_fd(wsi->ssl, wsi->desc.sockfd);
211 #endif
212
213 #ifdef USE_WOLFSSL
214 #ifdef USE_OLD_CYASSL
215         CyaSSL_set_using_nonblock(wsi->ssl, 1);
216 #else
217         wolfSSL_set_using_nonblock(wsi->ssl, 1);
218 #endif
219 #else
220 #if !defined(LWS_WITH_ESP32)
221         BIO_set_nbio(wsi->client_bio, 1); /* nonblocking */
222 #endif
223 #endif
224
225 #if !defined(LWS_WITH_ESP32)
226         SSL_set_ex_data(wsi->ssl, openssl_websocket_private_data_index,
227                         wsi);
228 #endif
229
230         return 0;
231 }
232
233 #if defined(LWS_WITH_ESP32)
234 int ERR_get_error(void)
235 {
236         return 0;
237 }
238 #endif
239
240 int
241 lws_ssl_client_connect1(struct lws *wsi)
242 {
243         struct lws_context *context = wsi->context;
244         int n = 0;
245
246         lws_latency_pre(context, wsi);
247
248         n = SSL_connect(wsi->ssl);
249
250         lws_latency(context, wsi,
251           "SSL_connect LWSCM_WSCL_ISSUE_HANDSHAKE", n, n > 0);
252
253         if (n < 0) {
254                 n = lws_ssl_get_error(wsi, n);
255
256                 if (n == SSL_ERROR_WANT_READ)
257                         goto some_wait;
258
259                 if (n == SSL_ERROR_WANT_WRITE) {
260                         /*
261                          * wants us to retry connect due to
262                          * state of the underlying ssl layer...
263                          * but since it may be stalled on
264                          * blocked write, no incoming data may
265                          * arrive to trigger the retry.
266                          * Force (possibly many times if the SSL
267                          * state persists in returning the
268                          * condition code, but other sockets
269                          * are getting serviced inbetweentimes)
270                          * us to get called back when writable.
271                          */
272                         lwsl_info("%s: WANT_WRITE... retrying\n", __func__);
273                         lws_callback_on_writable(wsi);
274 some_wait:
275                         wsi->mode = LWSCM_WSCL_WAITING_SSL;
276
277                         return 0; /* no error */
278                 }
279
280                 {
281                         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
282                         char *p = (char *)&pt->serv_buf[0];
283                         char *sb = p;
284
285                         lwsl_err("ssl hs1 error, X509_V_ERR = %d: %s\n",
286                                  n, ERR_error_string(n, sb));
287                         lws_ssl_elaborate_error();
288                 }
289
290                 n = -1;
291         }
292
293         if (n <= 0) {
294                 /*
295                  * retry if new data comes until we
296                  * run into the connection timeout or win
297                  */
298
299                 unsigned long error = ERR_get_error();
300
301                 if (error != SSL_ERROR_NONE) {
302                         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
303                         char *p = (char *)&pt->serv_buf[0];
304                         char *sb = p;
305                         lwsl_err("SSL connect error %lu: %s\n",
306                                 error, ERR_error_string(error, sb));
307                         return -1;
308                 }
309         }
310
311         return 1;
312 }
313
314 int
315 lws_ssl_client_connect2(struct lws *wsi)
316 {
317         struct lws_context *context = wsi->context;
318         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
319         char *p = (char *)&pt->serv_buf[0];
320         char *sb = p;
321         int n = 0;
322
323         if (wsi->mode == LWSCM_WSCL_WAITING_SSL) {
324                 lws_latency_pre(context, wsi);
325                 n = SSL_connect(wsi->ssl);
326                 lwsl_debug("%s: SSL_connect says %d\n", __func__, n);
327
328                 lws_latency(context, wsi,
329                             "SSL_connect LWSCM_WSCL_WAITING_SSL", n, n > 0);
330
331                 if (n < 0) {
332                         n = lws_ssl_get_error(wsi, n);
333
334                         if (n == SSL_ERROR_WANT_READ) {
335                                 lwsl_info("SSL_connect WANT_READ... retrying\n");
336
337                                 wsi->mode = LWSCM_WSCL_WAITING_SSL;
338
339                                 return 0; /* no error */
340                         }
341
342                         if (n == SSL_ERROR_WANT_WRITE) {
343                                 /*
344                                  * wants us to retry connect due to
345                                  * state of the underlying ssl layer...
346                                  * but since it may be stalled on
347                                  * blocked write, no incoming data may
348                                  * arrive to trigger the retry.
349                                  * Force (possibly many times if the SSL
350                                  * state persists in returning the
351                                  * condition code, but other sockets
352                                  * are getting serviced inbetweentimes)
353                                  * us to get called back when writable.
354                                  */
355                                 lwsl_info("SSL_connect WANT_WRITE... retrying\n");
356                                 lws_callback_on_writable(wsi);
357
358                                 wsi->mode = LWSCM_WSCL_WAITING_SSL;
359
360                                 return 0; /* no error */
361                         }
362
363                         n = -1;
364                 }
365
366                 if (n <= 0) {
367                         /*
368                          * retry if new data comes until we
369                          * run into the connection timeout or win
370                          */
371                         unsigned long error = ERR_get_error();
372                         if (error != SSL_ERROR_NONE) {
373                                 lwsl_err("SSL connect error %lu: %s\n",
374                                          error, ERR_error_string(error, sb));
375                                 return -1;
376                         }
377                 }
378         }
379
380 #if defined(LWS_WITH_ESP32)
381         {
382                 X509 *peer = SSL_get_peer_certificate(wsi->ssl);
383
384                 if (!peer) {
385                         lwsl_notice("peer did not provide cert\n");
386
387                         return -1;
388                 }
389                 lwsl_notice("peer provided cert\n");
390         }
391 #endif
392
393 #ifndef USE_WOLFSSL
394         /*
395          * See comment above about wolfSSL certificate
396          * verification
397          */
398         lws_latency_pre(context, wsi);
399         n = SSL_get_verify_result(wsi->ssl);
400         lws_latency(context, wsi,
401                 "SSL_get_verify_result LWS_CONNMODE..HANDSHAKE", n, n > 0);
402
403         lwsl_debug("get_verify says %d\n", n);
404
405         if (n != X509_V_OK) {
406                 if ((n == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
407                      n == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) &&
408                      (wsi->use_ssl & LCCSCF_ALLOW_SELFSIGNED)) {
409                         lwsl_notice("accepting self-signed certificate\n");
410                 } else if ((n == X509_V_ERR_CERT_NOT_YET_VALID ||
411                             n == X509_V_ERR_CERT_HAS_EXPIRED) &&
412                      (wsi->use_ssl & LCCSCF_ALLOW_EXPIRED)) {
413                         lwsl_notice("accepting expired certificate\n");
414                 } else if (n == X509_V_ERR_CERT_NOT_YET_VALID) {
415                         lwsl_notice("Cert is from the future... "
416                                     "probably our clock... accepting...\n");
417                 } else {
418                         lwsl_err("server's cert didn't look good, X509_V_ERR = %d: %s\n",
419                                  n, ERR_error_string(n, sb));
420                         lws_ssl_elaborate_error();
421                         return -1;
422                 }
423         }
424
425 #endif /* USE_WOLFSSL */
426
427         return 1;
428 }
429
430
431 int lws_context_init_client_ssl(struct lws_context_creation_info *info,
432                                 struct lws_vhost *vhost)
433 {
434         SSL_METHOD *method = NULL;
435         struct lws wsi;
436         unsigned long error;
437 #if !defined(LWS_WITH_ESP32)
438         const char *cipher_list = info->ssl_cipher_list;
439         const char *ca_filepath = info->ssl_ca_filepath;
440         const char *private_key_filepath = info->ssl_private_key_filepath;
441         const char *cert_filepath = info->ssl_cert_filepath;
442
443         int n;
444
445         /*
446          *  for backwards-compatibility default to using ssl_... members, but
447          * if the newer client-specific ones are given, use those
448          */
449         if (info->client_ssl_cipher_list)
450                 cipher_list = info->client_ssl_cipher_list;
451         if (info->client_ssl_ca_filepath)
452                 ca_filepath = info->client_ssl_ca_filepath;
453         if (info->client_ssl_cert_filepath)
454                 cert_filepath = info->client_ssl_cert_filepath;
455         if (info->client_ssl_private_key_filepath)
456                 private_key_filepath = info->client_ssl_private_key_filepath;
457 #endif
458
459         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT))
460                 return 0;
461
462         if (info->provided_client_ssl_ctx) {
463                 /* use the provided OpenSSL context if given one */
464                 vhost->ssl_client_ctx = info->provided_client_ssl_ctx;
465                 /* nothing for lib to delete */
466                 vhost->user_supplied_ssl_ctx = 1;
467
468                 return 0;
469         }
470
471         /* basic openssl init already happened in context init */
472
473         /* choose the most recent spin of the api */
474 #if defined(LWS_HAVE_TLS_CLIENT_METHOD)
475         method = (SSL_METHOD *)TLS_client_method();
476 #elif defined(LWS_HAVE_TLSV1_2_CLIENT_METHOD)
477         method = (SSL_METHOD *)TLSv1_2_client_method();
478 #else
479         method = (SSL_METHOD *)SSLv23_client_method();
480 #endif
481         if (!method) {
482                 error = ERR_get_error();
483                 lwsl_err("problem creating ssl method %lu: %s\n",
484                         error, ERR_error_string(error,
485                                       (char *)vhost->context->pt[0].serv_buf));
486                 return 1;
487         }
488         /* create context */
489         vhost->ssl_client_ctx = SSL_CTX_new(method);
490         if (!vhost->ssl_client_ctx) {
491                 error = ERR_get_error();
492                 lwsl_err("problem creating ssl context %lu: %s\n",
493                         error, ERR_error_string(error,
494                                       (char *)vhost->context->pt[0].serv_buf));
495                 return 1;
496         }
497
498 #ifdef SSL_OP_NO_COMPRESSION
499         SSL_CTX_set_options(vhost->ssl_client_ctx, SSL_OP_NO_COMPRESSION);
500 #endif
501
502 #if !defined(LWS_WITH_ESP32)
503         SSL_CTX_set_options(vhost->ssl_client_ctx,
504                             SSL_OP_CIPHER_SERVER_PREFERENCE);
505
506         if (cipher_list)
507                 SSL_CTX_set_cipher_list(vhost->ssl_client_ctx, cipher_list);
508
509 #ifdef LWS_SSL_CLIENT_USE_OS_CA_CERTS
510         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS))
511                 /* loads OS default CA certs */
512                 SSL_CTX_set_default_verify_paths(vhost->ssl_client_ctx);
513 #endif
514
515         /* openssl init for cert verification (for client sockets) */
516         if (!ca_filepath) {
517                 if (!SSL_CTX_load_verify_locations(
518                         vhost->ssl_client_ctx, NULL,
519                                              LWS_OPENSSL_CLIENT_CERTS))
520                         lwsl_err(
521                             "Unable to load SSL Client certs from %s "
522                             "(set by --with-client-cert-dir= "
523                             "in configure) --  client ssl isn't "
524                             "going to work\n", LWS_OPENSSL_CLIENT_CERTS);
525         } else
526                 if (!SSL_CTX_load_verify_locations(
527                         vhost->ssl_client_ctx, ca_filepath, NULL)) {
528                         lwsl_err(
529                                 "Unable to load SSL Client certs "
530                                 "file from %s -- client ssl isn't "
531                                 "going to work\n", info->client_ssl_ca_filepath);
532                         lws_ssl_elaborate_error();
533                 }
534                 else
535                         lwsl_info("loaded ssl_ca_filepath\n");
536 #endif
537         /*
538          * callback allowing user code to load extra verification certs
539          * helping the client to verify server identity
540          */
541 #if !defined(LWS_WITH_ESP32)
542
543         /* support for client-side certificate authentication */
544         if (cert_filepath) {
545                 lwsl_notice("%s: doing cert filepath\n", __func__);
546                 n = SSL_CTX_use_certificate_chain_file(vhost->ssl_client_ctx,
547                                                        cert_filepath);
548                 if (n < 1) {
549                         lwsl_err("problem %d getting cert '%s'\n", n,
550                                  cert_filepath);
551                         lws_ssl_elaborate_error();
552                         return 1;
553                 }
554                 lwsl_notice("Loaded client cert %s\n", cert_filepath);
555         }
556         if (private_key_filepath) {
557                 lwsl_notice("%s: doing private key filepath\n", __func__);
558                 lws_ssl_bind_passphrase(vhost->ssl_client_ctx, info);
559                 /* set the private key from KeyFile */
560                 if (SSL_CTX_use_PrivateKey_file(vhost->ssl_client_ctx,
561                     private_key_filepath, SSL_FILETYPE_PEM) != 1) {
562                         lwsl_err("use_PrivateKey_file '%s'\n",
563                                  private_key_filepath);
564                         lws_ssl_elaborate_error();
565                         return 1;
566                 }
567                 lwsl_notice("Loaded client cert private key %s\n",
568                             private_key_filepath);
569
570                 /* verify private key */
571                 if (!SSL_CTX_check_private_key(vhost->ssl_client_ctx)) {
572                         lwsl_err("Private SSL key doesn't match cert\n");
573                         return 1;
574                 }
575         }
576 #endif
577         /*
578          * give him a fake wsi with context set, so he can use
579          * lws_get_context() in the callback
580          */
581         memset(&wsi, 0, sizeof(wsi));
582         wsi.vhost = vhost;
583         wsi.context = vhost->context;
584
585         vhost->protocols[0].callback(&wsi,
586                         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
587                                        vhost->ssl_client_ctx, NULL, 0);
588
589         return 0;
590 }