v1.7.9
[platform/upstream/libwebsockets.git] / lib / ssl.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2014 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 #ifndef USE_WOLFSSL
24  #include <openssl/err.h>
25 #endif
26
27 #ifdef LWS_HAVE_OPENSSL_ECDH_H
28 #include <openssl/ecdh.h>
29 #endif
30
31 int openssl_websocket_private_data_index;
32
33 static int
34 lws_context_init_ssl_pem_passwd_cb(char * buf, int size, int rwflag, void *userdata)
35 {
36         struct lws_context_creation_info * info =
37                         (struct lws_context_creation_info *)userdata;
38
39         strncpy(buf, info->ssl_private_key_password, size);
40         buf[size - 1] = '\0';
41
42         return strlen(buf);
43 }
44
45 static void lws_ssl_bind_passphrase(SSL_CTX *ssl_ctx, struct lws_context_creation_info *info)
46 {
47         if (!info->ssl_private_key_password)
48                 return;
49         /*
50          * password provided, set ssl callback and user data
51          * for checking password which will be trigered during
52          * SSL_CTX_use_PrivateKey_file function
53          */
54         SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, (void *)info);
55         SSL_CTX_set_default_passwd_cb(ssl_ctx, lws_context_init_ssl_pem_passwd_cb);
56 }
57
58 #ifndef LWS_NO_SERVER
59 static int
60 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
61 {
62         SSL *ssl;
63         int n;
64         struct lws_context *context;
65         struct lws wsi;
66
67         ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
68                 SSL_get_ex_data_X509_STORE_CTX_idx());
69
70         /*
71          * !!! nasty openssl requires the index to come as a library-scope
72          * static
73          */
74         context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
75
76         /*
77          * give him a fake wsi with context set, so he can use lws_get_context()
78          * in the callback
79          */
80         memset(&wsi, 0, sizeof(wsi));
81         wsi.context = context;
82
83         n = context->protocols[0].callback(&wsi,
84                         LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
85                                            x509_ctx, ssl, preverify_ok);
86
87         /* convert return code from 0 = OK to 1 = OK */
88         return !n;
89 }
90
91 static int
92 lws_context_ssl_init_ecdh(struct lws_context *context)
93 {
94 #ifdef LWS_SSL_SERVER_WITH_ECDH_CERT
95         int KeyType;
96         EC_KEY *EC_key = NULL;
97         X509 *x;
98         EVP_PKEY *pkey;
99
100         if (!(context->options & LWS_SERVER_OPTION_SSL_ECDH))
101                 return 0;
102
103         lwsl_notice(" Using ECDH certificate support\n");
104
105         /* Get X509 certificate from ssl context */
106         x = sk_X509_value(context->ssl_ctx->extra_certs, 0);
107         if (!x) {
108                 lwsl_err("%s: x is NULL\n", __func__);
109                 return 1;
110         }
111         /* Get the public key from certificate */
112         pkey = X509_get_pubkey(x);
113         if (!pkey) {
114                 lwsl_err("%s: pkey is NULL\n", __func__);
115
116                 return 1;
117         }
118         /* Get the key type */
119         KeyType = EVP_PKEY_type(pkey->type);
120
121         if (EVP_PKEY_EC != KeyType) {
122                 lwsl_notice("Key type is not EC\n");
123                 return 0;
124         }
125         /* Get the key */
126         EC_key = EVP_PKEY_get1_EC_KEY(pkey);
127         /* Set ECDH parameter */
128         if (!EC_key) {
129                 lwsl_err("%s: ECDH key is NULL \n", __func__);
130                 return 1;
131         }
132         SSL_CTX_set_tmp_ecdh(context->ssl_ctx, EC_key);
133         EC_KEY_free(EC_key);
134 #endif
135         return 0;
136 }
137
138 static int
139 lws_context_ssl_init_ecdh_curve(struct lws_context_creation_info *info,
140                                 struct lws_context *context)
141 {
142 #ifdef LWS_HAVE_OPENSSL_ECDH_H
143         EC_KEY *ecdh;
144         int ecdh_nid;
145         const char *ecdh_curve = "prime256v1";
146
147         ecdh_nid = OBJ_sn2nid(ecdh_curve);
148         if (NID_undef == ecdh_nid) {
149                 lwsl_err("SSL: Unknown curve name '%s'", ecdh_curve);
150                 return 1;
151         }
152
153         ecdh = EC_KEY_new_by_curve_name(ecdh_nid);
154         if (NULL == ecdh) {
155                 lwsl_err("SSL: Unable to create curve '%s'", ecdh_curve);
156                 return 1;
157         }
158         SSL_CTX_set_tmp_ecdh(context->ssl_ctx, ecdh);
159         EC_KEY_free(ecdh);
160
161         SSL_CTX_set_options(context->ssl_ctx, SSL_OP_SINGLE_ECDH_USE);
162
163         lwsl_notice(" SSL ECDH curve '%s'\n", ecdh_curve);
164 #else
165         lwsl_notice(" OpenSSL doesn't support ECDH\n");
166 #endif
167         return 0;
168 }
169
170 LWS_VISIBLE int
171 lws_context_init_server_ssl(struct lws_context_creation_info *info,
172                             struct lws_context *context)
173 {
174         SSL_METHOD *method;
175         struct lws wsi;
176         int error;
177         int n;
178
179         if (info->port != CONTEXT_PORT_NO_LISTEN) {
180
181                 context->use_ssl = info->ssl_cert_filepath != NULL;
182
183 #ifdef USE_WOLFSSL
184 #ifdef USE_OLD_CYASSL
185                 lwsl_notice(" Compiled with CyaSSL support\n");
186 #else
187                 lwsl_notice(" Compiled with wolfSSL support\n");
188 #endif
189 #else
190                 lwsl_notice(" Compiled with OpenSSL support\n");
191 #endif
192
193                 if (info->ssl_cipher_list)
194                         lwsl_notice(" SSL ciphers: '%s'\n", info->ssl_cipher_list);
195
196                 if (context->use_ssl)
197                         lwsl_notice(" Using SSL mode\n");
198                 else
199                         lwsl_notice(" Using non-SSL mode\n");
200         }
201
202         /*
203          * give him a fake wsi with context set, so he can use
204          * lws_get_context() in the callback
205          */
206         memset(&wsi, 0, sizeof(wsi));
207         wsi.context = context;
208
209         /* basic openssl init */
210
211         SSL_library_init();
212
213         OpenSSL_add_all_algorithms();
214         SSL_load_error_strings();
215
216         openssl_websocket_private_data_index =
217                 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
218
219         /*
220          * Firefox insists on SSLv23 not SSLv3
221          * Konq disables SSLv2 by default now, SSLv23 works
222          *
223          * SSLv23_server_method() is the openssl method for "allow all TLS
224          * versions", compared to e.g. TLSv1_2_server_method() which only allows
225          * tlsv1.2. Unwanted versions must be disabled using SSL_CTX_set_options()
226          */
227
228         method = (SSL_METHOD *)SSLv23_server_method();
229         if (!method) {
230                 error = ERR_get_error();
231                 lwsl_err("problem creating ssl method %lu: %s\n",
232                         error, ERR_error_string(error,
233                                               (char *)context->pt[0].serv_buf));
234                 return 1;
235         }
236         context->ssl_ctx = SSL_CTX_new(method); /* create context */
237         if (!context->ssl_ctx) {
238                 error = ERR_get_error();
239                 lwsl_err("problem creating ssl context %lu: %s\n",
240                         error, ERR_error_string(error,
241                                               (char *)context->pt[0].serv_buf));
242                 return 1;
243         }
244
245         /* Disable SSLv2 and SSLv3 */
246         SSL_CTX_set_options(context->ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
247 #ifdef SSL_OP_NO_COMPRESSION
248         SSL_CTX_set_options(context->ssl_ctx, SSL_OP_NO_COMPRESSION);
249 #endif
250         SSL_CTX_set_options(context->ssl_ctx, SSL_OP_SINGLE_DH_USE);
251         SSL_CTX_set_options(context->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
252         if (info->ssl_cipher_list)
253                 SSL_CTX_set_cipher_list(context->ssl_ctx,
254                                                 info->ssl_cipher_list);
255
256         /* as a server, are we requiring clients to identify themselves? */
257
258         if (info->options & LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
259                 int verify_options = SSL_VERIFY_PEER;
260
261                 if (!(info->options & LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED))
262                         verify_options |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
263
264                 SSL_CTX_set_session_id_context(context->ssl_ctx,
265                                 (unsigned char *)context, sizeof(void *));
266
267                 /* absolutely require the client cert */
268
269                 SSL_CTX_set_verify(context->ssl_ctx,
270                        verify_options, OpenSSL_verify_callback);
271         }
272
273         /*
274          * give user code a chance to load certs into the server
275          * allowing it to verify incoming client certs
276          */
277
278         if (info->ssl_ca_filepath &&
279             !SSL_CTX_load_verify_locations(context->ssl_ctx,
280                                            info->ssl_ca_filepath, NULL)) {
281                 lwsl_err("%s: SSL_CTX_load_verify_locations unhappy\n");
282         }
283
284         if (lws_context_ssl_init_ecdh_curve(info, context))
285                 return -1;
286
287         context->protocols[0].callback(&wsi,
288                         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
289                                                context->ssl_ctx, NULL, 0);
290
291         if (info->options & LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT)
292                 /* Normally SSL listener rejects non-ssl, optionally allow */
293                 context->allow_non_ssl_on_ssl_port = 1;
294
295         if (context->use_ssl) {
296                 /* openssl init for server sockets */
297
298                 /* set the local certificate from CertFile */
299                 n = SSL_CTX_use_certificate_chain_file(context->ssl_ctx,
300                                         info->ssl_cert_filepath);
301                 if (n != 1) {
302                         error = ERR_get_error();
303                         lwsl_err("problem getting cert '%s' %lu: %s\n",
304                                 info->ssl_cert_filepath,
305                                 error,
306                                 ERR_error_string(error,
307                                               (char *)context->pt[0].serv_buf));
308                         return 1;
309                 }
310                 lws_ssl_bind_passphrase(context->ssl_ctx, info);
311
312                 if (info->ssl_private_key_filepath != NULL) {
313                         /* set the private key from KeyFile */
314                         if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
315                                      info->ssl_private_key_filepath,
316                                                        SSL_FILETYPE_PEM) != 1) {
317                                 error = ERR_get_error();
318                                 lwsl_err("ssl problem getting key '%s' %lu: %s\n",
319                                          info->ssl_private_key_filepath, error,
320                                          ERR_error_string(error,
321                                               (char *)context->pt[0].serv_buf));
322                                 return 1;
323                         }
324                 } else
325                         if (context->protocols[0].callback(&wsi,
326                                 LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY,
327                                                 context->ssl_ctx, NULL, 0)) {
328                                 lwsl_err("ssl private key not set\n");
329
330                                 return 1;
331                         }
332
333                 /* verify private key */
334                 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
335                         lwsl_err("Private SSL key doesn't match cert\n");
336                         return 1;
337                 }
338
339                 if (lws_context_ssl_init_ecdh(context))
340                         return 1;
341
342                 /*
343                  * SSL is happy and has a cert it's content with
344                  * If we're supporting HTTP2, initialize that
345                  */
346
347                 lws_context_init_http2_ssl(context);
348         }
349
350         return 0;
351 }
352 #endif
353
354 LWS_VISIBLE void
355 lws_ssl_destroy(struct lws_context *context)
356 {
357         if (context->ssl_ctx)
358                 SSL_CTX_free(context->ssl_ctx);
359         if (!context->user_supplied_ssl_ctx && context->ssl_client_ctx)
360                 SSL_CTX_free(context->ssl_client_ctx);
361
362 #if (OPENSSL_VERSION_NUMBER < 0x01000000) || defined(USE_WOLFSSL)
363         ERR_remove_state(0);
364 #else
365         ERR_remove_thread_state(NULL);
366 #endif
367         ERR_free_strings();
368         EVP_cleanup();
369         CRYPTO_cleanup_all_ex_data();
370 }
371
372 LWS_VISIBLE void
373 lws_decode_ssl_error(void)
374 {
375         char buf[256];
376         u_long err;
377
378         while ((err = ERR_get_error()) != 0) {
379                 ERR_error_string_n(err, buf, sizeof(buf));
380                 lwsl_err("*** %lu %s\n", err, buf);
381         }
382 }
383
384 #ifndef LWS_NO_CLIENT
385
386 int lws_context_init_client_ssl(struct lws_context_creation_info *info,
387                                 struct lws_context *context)
388 {
389         int error;
390         int n;
391         SSL_METHOD *method;
392         struct lws wsi;
393
394         if (info->provided_client_ssl_ctx) {
395                 /* use the provided OpenSSL context if given one */
396                 context->ssl_client_ctx = info->provided_client_ssl_ctx;
397                 /* nothing for lib to delete */
398                 context->user_supplied_ssl_ctx = 1;
399                 return 0;
400         }
401
402         if (info->port != CONTEXT_PORT_NO_LISTEN)
403                 return 0;
404
405         /* basic openssl init */
406
407         SSL_library_init();
408
409         OpenSSL_add_all_algorithms();
410         SSL_load_error_strings();
411
412         method = (SSL_METHOD *)SSLv23_client_method();
413         if (!method) {
414                 error = ERR_get_error();
415                 lwsl_err("problem creating ssl method %lu: %s\n",
416                         error, ERR_error_string(error,
417                                       (char *)context->pt[0].serv_buf));
418                 return 1;
419         }
420         /* create context */
421         context->ssl_client_ctx = SSL_CTX_new(method);
422         if (!context->ssl_client_ctx) {
423                 error = ERR_get_error();
424                 lwsl_err("problem creating ssl context %lu: %s\n",
425                         error, ERR_error_string(error,
426                                       (char *)context->pt[0].serv_buf));
427                 return 1;
428         }
429
430 #ifdef SSL_OP_NO_COMPRESSION
431         SSL_CTX_set_options(context->ssl_client_ctx,
432                                                  SSL_OP_NO_COMPRESSION);
433 #endif
434         SSL_CTX_set_options(context->ssl_client_ctx,
435                                        SSL_OP_CIPHER_SERVER_PREFERENCE);
436         if (info->ssl_cipher_list)
437                 SSL_CTX_set_cipher_list(context->ssl_client_ctx,
438                                                 info->ssl_cipher_list);
439
440 #ifdef LWS_SSL_CLIENT_USE_OS_CA_CERTS
441         if (!(info->options & LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS))
442                 /* loads OS default CA certs */
443                 SSL_CTX_set_default_verify_paths(context->ssl_client_ctx);
444 #endif
445
446         /* openssl init for cert verification (for client sockets) */
447         if (!info->ssl_ca_filepath) {
448                 if (!SSL_CTX_load_verify_locations(
449                         context->ssl_client_ctx, NULL,
450                                              LWS_OPENSSL_CLIENT_CERTS))
451                         lwsl_err(
452                             "Unable to load SSL Client certs from %s "
453                             "(set by --with-client-cert-dir= "
454                             "in configure) --  client ssl isn't "
455                             "going to work", LWS_OPENSSL_CLIENT_CERTS);
456         } else
457                 if (!SSL_CTX_load_verify_locations(
458                         context->ssl_client_ctx, info->ssl_ca_filepath,
459                                                           NULL))
460                         lwsl_err(
461                                 "Unable to load SSL Client certs "
462                                 "file from %s -- client ssl isn't "
463                                 "going to work", info->ssl_ca_filepath);
464                 else
465                         lwsl_info("loaded ssl_ca_filepath\n");
466
467         /*
468          * callback allowing user code to load extra verification certs
469          * helping the client to verify server identity
470          */
471
472         /* support for client-side certificate authentication */
473         if (info->ssl_cert_filepath) {
474                 n = SSL_CTX_use_certificate_chain_file(context->ssl_client_ctx,
475                                                        info->ssl_cert_filepath);
476                 if (n != 1) {
477                         lwsl_err("problem getting cert '%s' %lu: %s\n",
478                                 info->ssl_cert_filepath,
479                                 ERR_get_error(),
480                                 ERR_error_string(ERR_get_error(),
481                                 (char *)context->pt[0].serv_buf));
482                         return 1;
483                 }
484         }
485         if (info->ssl_private_key_filepath) {
486                 lws_ssl_bind_passphrase(context->ssl_client_ctx, info);
487                 /* set the private key from KeyFile */
488                 if (SSL_CTX_use_PrivateKey_file(context->ssl_client_ctx,
489                     info->ssl_private_key_filepath, SSL_FILETYPE_PEM) != 1) {
490                         lwsl_err("use_PrivateKey_file '%s' %lu: %s\n",
491                                 info->ssl_private_key_filepath,
492                                 ERR_get_error(),
493                                 ERR_error_string(ERR_get_error(),
494                                       (char *)context->pt[0].serv_buf));
495                         return 1;
496                 }
497
498                 /* verify private key */
499                 if (!SSL_CTX_check_private_key(context->ssl_client_ctx)) {
500                         lwsl_err("Private SSL key doesn't match cert\n");
501                         return 1;
502                 }
503         }
504
505         /*
506          * give him a fake wsi with context set, so he can use
507          * lws_get_context() in the callback
508          */
509         memset(&wsi, 0, sizeof(wsi));
510         wsi.context = context;
511
512         context->protocols[0].callback(&wsi,
513                         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
514                                        context->ssl_client_ctx, NULL, 0);
515
516         return 0;
517 }
518 #endif
519
520 LWS_VISIBLE void
521 lws_ssl_remove_wsi_from_buffered_list(struct lws *wsi)
522 {
523         struct lws_context *context = wsi->context;
524         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
525
526         if (!wsi->pending_read_list_prev &&
527             !wsi->pending_read_list_next &&
528             pt->pending_read_list != wsi)
529                 /* we are not on the list */
530                 return;
531
532         /* point previous guy's next to our next */
533         if (!wsi->pending_read_list_prev)
534                 pt->pending_read_list = wsi->pending_read_list_next;
535         else
536                 wsi->pending_read_list_prev->pending_read_list_next =
537                         wsi->pending_read_list_next;
538
539         /* point next guy's previous to our previous */
540         if (wsi->pending_read_list_next)
541                 wsi->pending_read_list_next->pending_read_list_prev =
542                         wsi->pending_read_list_prev;
543
544         wsi->pending_read_list_prev = NULL;
545         wsi->pending_read_list_next = NULL;
546 }
547
548 LWS_VISIBLE int
549 lws_ssl_capable_read(struct lws *wsi, unsigned char *buf, int len)
550 {
551         struct lws_context *context = wsi->context;
552         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
553         int n;
554
555         if (!wsi->ssl)
556                 return lws_ssl_capable_read_no_ssl(wsi, buf, len);
557
558         n = SSL_read(wsi->ssl, buf, len);
559         /* manpage: returning 0 means connection shut down */
560         if (!n)
561                 return LWS_SSL_CAPABLE_ERROR;
562
563         if (n < 0) {
564                 n = SSL_get_error(wsi->ssl, n);
565                 if (n ==  SSL_ERROR_WANT_READ || n ==  SSL_ERROR_WANT_WRITE)
566                         return LWS_SSL_CAPABLE_MORE_SERVICE;
567
568                 return LWS_SSL_CAPABLE_ERROR;
569         }
570
571         /*
572          * if it was our buffer that limited what we read,
573          * check if SSL has additional data pending inside SSL buffers.
574          *
575          * Because these won't signal at the network layer with POLLIN
576          * and if we don't realize, this data will sit there forever
577          */
578         if (n != len)
579                 goto bail;
580         if (!wsi->ssl)
581                 goto bail;
582         if (!SSL_pending(wsi->ssl))
583                 goto bail;
584         if (wsi->pending_read_list_next)
585                 return n;
586         if (wsi->pending_read_list_prev)
587                 return n;
588         if (pt->pending_read_list == wsi)
589                 return n;
590
591         /* add us to the linked list of guys with pending ssl */
592         if (pt->pending_read_list)
593                 pt->pending_read_list->pending_read_list_prev = wsi;
594
595         wsi->pending_read_list_next = pt->pending_read_list;
596         wsi->pending_read_list_prev = NULL;
597         pt->pending_read_list = wsi;
598
599         return n;
600 bail:
601         lws_ssl_remove_wsi_from_buffered_list(wsi);
602
603         return n;
604 }
605
606 LWS_VISIBLE int
607 lws_ssl_pending(struct lws *wsi)
608 {
609         if (!wsi->ssl)
610                 return 0;
611
612         return SSL_pending(wsi->ssl);
613 }
614
615 LWS_VISIBLE int
616 lws_ssl_capable_write(struct lws *wsi, unsigned char *buf, int len)
617 {
618         int n;
619
620         if (!wsi->ssl)
621                 return lws_ssl_capable_write_no_ssl(wsi, buf, len);
622
623         n = SSL_write(wsi->ssl, buf, len);
624         if (n > 0)
625                 return n;
626
627         n = SSL_get_error(wsi->ssl, n);
628         if (n == SSL_ERROR_WANT_READ || n == SSL_ERROR_WANT_WRITE) {
629                 if (n == SSL_ERROR_WANT_WRITE)
630                         lws_set_blocking_send(wsi);
631                 return LWS_SSL_CAPABLE_MORE_SERVICE;
632         }
633
634         return LWS_SSL_CAPABLE_ERROR;
635 }
636
637 LWS_VISIBLE int
638 lws_ssl_close(struct lws *wsi)
639 {
640         int n;
641
642         if (!wsi->ssl)
643                 return 0; /* not handled */
644
645         n = SSL_get_fd(wsi->ssl);
646         SSL_shutdown(wsi->ssl);
647         compatible_close(n);
648         SSL_free(wsi->ssl);
649         wsi->ssl = NULL;
650
651         return 1; /* handled */
652 }
653
654 /* leave all wsi close processing to the caller */
655
656 LWS_VISIBLE int
657 lws_server_socket_service_ssl(struct lws *wsi, lws_sockfd_type accept_fd)
658 {
659         struct lws_context *context = wsi->context;
660         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
661         int n, m;
662 #ifndef USE_WOLFSSL
663         BIO *bio;
664 #endif
665
666         if (!LWS_SSL_ENABLED(context))
667                 return 0;
668
669         switch (wsi->mode) {
670         case LWSCM_SSL_INIT:
671
672                 wsi->ssl = SSL_new(context->ssl_ctx);
673                 if (wsi->ssl == NULL) {
674                         lwsl_err("SSL_new failed: %s\n",
675                                  ERR_error_string(SSL_get_error(wsi->ssl, 0), NULL));
676                         lws_decode_ssl_error();
677                         if (accept_fd != LWS_SOCK_INVALID)
678                                 compatible_close(accept_fd);
679                         goto fail;
680                 }
681
682                 SSL_set_ex_data(wsi->ssl,
683                         openssl_websocket_private_data_index, context);
684
685                 SSL_set_fd(wsi->ssl, accept_fd);
686
687 #ifdef USE_WOLFSSL
688 #ifdef USE_OLD_CYASSL
689                 CyaSSL_set_using_nonblock(wsi->ssl, 1);
690 #else
691                 wolfSSL_set_using_nonblock(wsi->ssl, 1);
692 #endif
693 #else
694                 SSL_set_mode(wsi->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
695                 bio = SSL_get_rbio(wsi->ssl);
696                 if (bio)
697                         BIO_set_nbio(bio, 1); /* nonblocking */
698                 else
699                         lwsl_notice("NULL rbio\n");
700                 bio = SSL_get_wbio(wsi->ssl);
701                 if (bio)
702                         BIO_set_nbio(bio, 1); /* nonblocking */
703                 else
704                         lwsl_notice("NULL rbio\n");
705 #endif
706
707                 /*
708                  * we are not accepted yet, but we need to enter ourselves
709                  * as a live connection.  That way we can retry when more
710                  * pieces come if we're not sorted yet
711                  */
712
713                 wsi->mode = LWSCM_SSL_ACK_PENDING;
714                 if (insert_wsi_socket_into_fds(context, wsi))
715                         goto fail;
716
717                 lws_set_timeout(wsi, PENDING_TIMEOUT_SSL_ACCEPT,
718                                 context->timeout_secs);
719
720                 lwsl_info("inserted SSL accept into fds, trying SSL_accept\n");
721
722                 /* fallthru */
723
724         case LWSCM_SSL_ACK_PENDING:
725
726                 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0))
727                         goto fail;
728
729                 lws_latency_pre(context, wsi);
730
731                 n = recv(wsi->sock, (char *)pt->serv_buf, LWS_MAX_SOCKET_IO_BUF,
732                          MSG_PEEK);
733
734                 /*
735                  * optionally allow non-SSL connect on SSL listening socket
736                  * This is disabled by default, if enabled it goes around any
737                  * SSL-level access control (eg, client-side certs) so leave
738                  * it disabled unless you know it's not a problem for you
739                  */
740
741                 if (context->allow_non_ssl_on_ssl_port) {
742                         if (n >= 1 && pt->serv_buf[0] >= ' ') {
743                                 /*
744                                 * TLS content-type for Handshake is 0x16, and
745                                 * for ChangeCipherSpec Record, it's 0x14
746                                 *
747                                 * A non-ssl session will start with the HTTP
748                                 * method in ASCII.  If we see it's not a legit
749                                 * SSL handshake kill the SSL for this
750                                 * connection and try to handle as a HTTP
751                                 * connection upgrade directly.
752                                 */
753                                 wsi->use_ssl = 0;
754                                 SSL_shutdown(wsi->ssl);
755                                 SSL_free(wsi->ssl);
756                                 wsi->ssl = NULL;
757                                 goto accepted;
758                         }
759                         if (!n) /*
760                                  * connection is gone, or nothing to read
761                                  * if it's gone, we will timeout on
762                                  * PENDING_TIMEOUT_SSL_ACCEPT
763                                  */
764                                 break;
765                         if (n < 0 && (LWS_ERRNO == LWS_EAGAIN ||
766                                       LWS_ERRNO == LWS_EWOULDBLOCK)) {
767                                 /*
768                                  * well, we get no way to know ssl or not
769                                  * so go around again waiting for something
770                                  * to come and give us a hint, or timeout the
771                                  * connection.
772                                  */
773                                 m = SSL_ERROR_WANT_READ;
774                                 goto go_again;
775                         }
776                 }
777
778                 /* normal SSL connection processing path */
779
780                 n = SSL_accept(wsi->ssl);
781                 lws_latency(context, wsi,
782                         "SSL_accept LWSCM_SSL_ACK_PENDING\n", n, n == 1);
783
784                 if (n == 1)
785                         goto accepted;
786
787                 m = SSL_get_error(wsi->ssl, n);
788                 lwsl_debug("SSL_accept failed %d / %s\n",
789                            m, ERR_error_string(m, NULL));
790 go_again:
791                 if (m == SSL_ERROR_WANT_READ) {
792                         if (lws_change_pollfd(wsi, 0, LWS_POLLIN))
793                                 goto fail;
794
795                         lwsl_info("SSL_ERROR_WANT_READ\n");
796                         break;
797                 }
798                 if (m == SSL_ERROR_WANT_WRITE) {
799                         if (lws_change_pollfd(wsi, 0, LWS_POLLOUT))
800                                 goto fail;
801
802                         break;
803                 }
804                 lwsl_debug("SSL_accept failed skt %u: %s\n",
805                            wsi->sock, ERR_error_string(m, NULL));
806                 goto fail;
807
808 accepted:
809                 /* OK, we are accepted... give him some time to negotiate */
810                 lws_set_timeout(wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
811                                 context->timeout_secs);
812
813                 wsi->mode = LWSCM_HTTP_SERVING;
814
815                 lws_http2_configure_if_upgraded(wsi);
816
817                 lwsl_debug("accepted new SSL conn\n");
818                 break;
819         }
820
821         return 0;
822
823 fail:
824         return 1;
825 }
826
827 LWS_VISIBLE void
828 lws_ssl_context_destroy(struct lws_context *context)
829 {
830         if (context->ssl_ctx)
831                 SSL_CTX_free(context->ssl_ctx);
832         if (!context->user_supplied_ssl_ctx && context->ssl_client_ctx)
833                 SSL_CTX_free(context->ssl_client_ctx);
834
835 #if (OPENSSL_VERSION_NUMBER < 0x01000000) || defined(USE_WOLFSSL)
836         ERR_remove_state(0);
837 #else
838         ERR_remove_thread_state(NULL);
839 #endif
840         ERR_free_strings();
841         EVP_cleanup();
842         CRYPTO_cleanup_all_ex_data();
843 }