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