win32 more build fixes
[platform/upstream/libwebsockets.git] / lib / ssl.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 #if defined(LWS_USE_POLARSSL)
25 static const int ciphers[] =
26 {
27         TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
28         TLS_RSA_WITH_AES_256_CBC_SHA,
29         TLS_RSA_WITH_AES_128_CBC_SHA,
30         0
31 };
32
33 static int urandom_bytes(void *ctx, unsigned char *dest, size_t len)
34 {
35         int cur;
36         int fd = open("/dev/urandom", O_RDONLY);
37
38         while (len) {
39                 cur = read(fd, dest, len);
40                 if (cur < 0)
41                         continue;
42                 len -= cur;
43         }
44         close(fd);
45
46         return 0;
47 }
48
49 static void pssl_debug(void *ctx, int level, const char *str)
50 {
51     lwsl_err("PolarSSL [level %d]: %s", level, str);
52 }
53
54 #endif
55
56 int openssl_websocket_private_data_index,
57     openssl_SSL_CTX_private_data_index;
58
59 int lws_ssl_get_error(struct lws *wsi, int n)
60 {
61 #if defined(LWS_USE_POLARSSL)
62 #define ERR_error_string(a, b) ""
63         return n;
64 #else
65 #if defined(LWS_USE_MBEDTLS)
66         return n;
67 #else
68         return SSL_get_error(wsi->ssl, n);
69 #endif
70 #endif
71 }
72
73 void
74 lws_ssl_elaborate_error(void)
75 {
76 #if defined(LWS_USE_POLARSSL)
77 #else
78 #if defined(LWS_USE_MBEDTLS)
79 #else
80
81         char buf[256];
82         u_long err;
83
84         while ((err = ERR_get_error()) != 0) {
85                 ERR_error_string_n(err, buf, sizeof(buf));
86                 lwsl_err("*** %s\n", buf);
87         }
88 #endif
89 #endif
90 }
91
92
93 #if defined(LWS_USE_POLARSSL)
94 #else
95 #if defined(LWS_USE_MBEDTLS)
96 #else
97 static int
98 lws_context_init_ssl_pem_passwd_cb(char * buf, int size, int rwflag, void *userdata)
99 {
100         struct lws_context_creation_info * info =
101                         (struct lws_context_creation_info *)userdata;
102
103         strncpy(buf, info->ssl_private_key_password, size);
104         buf[size - 1] = '\0';
105
106         return strlen(buf);
107 }
108 #endif
109 #endif
110
111 void
112 lws_ssl_bind_passphrase(SSL_CTX *ssl_ctx, struct lws_context_creation_info *info)
113 {
114         if (!info->ssl_private_key_password)
115                 return;
116 #if defined(LWS_USE_POLARSSL)
117 #else
118 #if defined(LWS_USE_MBEDTLS)
119 #else
120         /*
121          * password provided, set ssl callback and user data
122          * for checking password which will be trigered during
123          * SSL_CTX_use_PrivateKey_file function
124          */
125         SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, (void *)info);
126         SSL_CTX_set_default_passwd_cb(ssl_ctx, lws_context_init_ssl_pem_passwd_cb);
127 #endif
128 #endif
129 }
130
131 int
132 lws_context_init_ssl_library(struct lws_context_creation_info *info)
133 {
134 #ifdef USE_WOLFSSL
135 #ifdef USE_OLD_CYASSL
136         lwsl_notice(" Compiled with CyaSSL support\n");
137 #else
138         lwsl_notice(" Compiled with wolfSSL support\n");
139 #endif
140 #else
141 #if defined(LWS_USE_POLARSSL)
142         lwsl_notice(" Compiled with PolarSSL support\n");
143 #else
144 #if defined(LWS_USE_MBEDTLS)
145         lwsl_notice(" Compiled with mbedTLS support\n");
146 #else
147         lwsl_notice(" Compiled with OpenSSL support\n");
148 #endif
149 #endif
150 #endif
151
152         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT)) {
153                 lwsl_notice(" SSL disabled: no LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT\n");
154                 return 0;
155         }
156
157         /* basic openssl init */
158
159 #if defined(LWS_USE_POLARSSL)
160 #else
161 #if defined(LWS_USE_MBEDTLS)
162 #else
163         SSL_library_init();
164
165         OpenSSL_add_all_algorithms();
166         SSL_load_error_strings();
167
168         openssl_websocket_private_data_index =
169                 SSL_get_ex_new_index(0, "lws", NULL, NULL, NULL);
170
171         openssl_SSL_CTX_private_data_index = SSL_CTX_get_ex_new_index(0,
172                         NULL, NULL, NULL, NULL);
173 #endif
174 #endif
175
176         return 0;
177 }
178
179
180 LWS_VISIBLE void
181 lws_ssl_destroy(struct lws_vhost *vhost)
182 {
183         if (!lws_check_opt(vhost->context->options,
184                            LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT))
185                 return;
186
187 #if defined(LWS_USE_POLARSSL)
188 #else
189 #if defined(LWS_USE_MBEDTLS)
190 #else
191
192         if (vhost->ssl_ctx)
193                 SSL_CTX_free(vhost->ssl_ctx);
194         if (!vhost->user_supplied_ssl_ctx && vhost->ssl_client_ctx)
195                 SSL_CTX_free(vhost->ssl_client_ctx);
196
197 #if (OPENSSL_VERSION_NUMBER < 0x01000000) || defined(USE_WOLFSSL)
198         ERR_remove_state(0);
199 #else
200 #if (OPENSSL_VERSION_NUMBER >= 0x10100005L) && \
201         !defined(LIBRESSL_VERSION_NUMBER) && \
202         !defined(OPENSSL_IS_BORINGSSL)
203         ERR_remove_thread_state();
204 #else
205         ERR_remove_thread_state(NULL);
206 #endif
207 #endif
208         ERR_free_strings();
209         EVP_cleanup();
210         CRYPTO_cleanup_all_ex_data();
211 #endif
212 #endif
213 }
214
215 LWS_VISIBLE void
216 lws_decode_ssl_error(void)
217 {
218 #if defined(LWS_USE_POLARSSL)
219 #else
220 #if defined(LWS_USE_MBEDTLS)
221 #else
222         char buf[256];
223         u_long err;
224         while ((err = ERR_get_error()) != 0) {
225                 ERR_error_string_n(err, buf, sizeof(buf));
226                 lwsl_err("*** %lu %s\n", err, buf);
227         }
228 #endif
229 #endif
230 }
231
232 LWS_VISIBLE void
233 lws_ssl_remove_wsi_from_buffered_list(struct lws *wsi)
234 {
235         struct lws_context *context = wsi->context;
236         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
237
238         if (!wsi->pending_read_list_prev &&
239             !wsi->pending_read_list_next &&
240             pt->pending_read_list != wsi)
241                 /* we are not on the list */
242                 return;
243
244         /* point previous guy's next to our next */
245         if (!wsi->pending_read_list_prev)
246                 pt->pending_read_list = wsi->pending_read_list_next;
247         else
248                 wsi->pending_read_list_prev->pending_read_list_next =
249                         wsi->pending_read_list_next;
250
251         /* point next guy's previous to our previous */
252         if (wsi->pending_read_list_next)
253                 wsi->pending_read_list_next->pending_read_list_prev =
254                         wsi->pending_read_list_prev;
255
256         wsi->pending_read_list_prev = NULL;
257         wsi->pending_read_list_next = NULL;
258 }
259
260 LWS_VISIBLE int
261 lws_ssl_capable_read(struct lws *wsi, unsigned char *buf, int len)
262 {
263         struct lws_context *context = wsi->context;
264         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
265         int n = 0;
266
267         if (!wsi->ssl)
268                 return lws_ssl_capable_read_no_ssl(wsi, buf, len);
269
270 #if defined(LWS_USE_POLARSSL)
271 #else
272 #if defined(LWS_USE_MBEDTLS)
273 #else
274         n = SSL_read(wsi->ssl, buf, len);
275 #endif
276 #endif
277
278         /* manpage: returning 0 means connection shut down */
279         if (!n)
280                 return LWS_SSL_CAPABLE_ERROR;
281
282         if (n < 0) {
283                 n = lws_ssl_get_error(wsi, n);
284                 if (n ==  SSL_ERROR_WANT_READ || n ==  SSL_ERROR_WANT_WRITE)
285                         return LWS_SSL_CAPABLE_MORE_SERVICE;
286
287                 return LWS_SSL_CAPABLE_ERROR;
288         }
289
290         if (wsi->vhost)
291                 wsi->vhost->rx += n;
292
293         /*
294          * if it was our buffer that limited what we read,
295          * check if SSL has additional data pending inside SSL buffers.
296          *
297          * Because these won't signal at the network layer with POLLIN
298          * and if we don't realize, this data will sit there forever
299          */
300         if (n != len)
301                 goto bail;
302         if (!wsi->ssl)
303                 goto bail;
304 #if defined(LWS_USE_POLARSSL)
305         if (ssl_get_bytes_avail(wsi->ssl) <= 0)
306                 goto bail;
307 #else
308 #if defined(LWS_USE_MBEDTLS)
309 #else
310         if (!SSL_pending(wsi->ssl))
311                 goto bail;
312 #endif
313 #endif
314         if (wsi->pending_read_list_next)
315                 return n;
316         if (wsi->pending_read_list_prev)
317                 return n;
318         if (pt->pending_read_list == wsi)
319                 return n;
320
321         /* add us to the linked list of guys with pending ssl */
322         if (pt->pending_read_list)
323                 pt->pending_read_list->pending_read_list_prev = wsi;
324
325         wsi->pending_read_list_next = pt->pending_read_list;
326         wsi->pending_read_list_prev = NULL;
327         pt->pending_read_list = wsi;
328
329         return n;
330 bail:
331         lws_ssl_remove_wsi_from_buffered_list(wsi);
332
333         return n;
334 }
335
336 LWS_VISIBLE int
337 lws_ssl_pending(struct lws *wsi)
338 {
339         if (!wsi->ssl)
340                 return 0;
341 #if defined(LWS_USE_POLARSSL)
342         return ssl_get_bytes_avail(wsi->ssl) > 0;
343 #else
344 #if defined(LWS_USE_MBEDTLS)
345         return ssl_get_bytes_avail(wsi->ssl) > 0;;
346 #else
347         return SSL_pending(wsi->ssl);
348 #endif
349 #endif
350 }
351
352 LWS_VISIBLE int
353 lws_ssl_capable_write(struct lws *wsi, unsigned char *buf, int len)
354 {
355         int n;
356
357         if (!wsi->ssl)
358                 return lws_ssl_capable_write_no_ssl(wsi, buf, len);
359
360 #if defined(LWS_USE_POLARSSL)
361         n = ssl_write(wsi->ssl, buf, len);
362 #else
363 #if defined(LWS_USE_MBEDTLS)
364 #else
365         n = SSL_write(wsi->ssl, buf, len);
366 #endif
367 #endif
368         if (n > 0)
369                 return n;
370
371         n = lws_ssl_get_error(wsi, n);
372         if (n == SSL_ERROR_WANT_READ || n == SSL_ERROR_WANT_WRITE) {
373                 if (n == SSL_ERROR_WANT_WRITE)
374                         lws_set_blocking_send(wsi);
375                 return LWS_SSL_CAPABLE_MORE_SERVICE;
376         }
377
378         return LWS_SSL_CAPABLE_ERROR;
379 }
380
381 LWS_VISIBLE int
382 lws_ssl_close(struct lws *wsi)
383 {
384         int n;
385
386         if (!wsi->ssl)
387                 return 0; /* not handled */
388
389 #if defined(LWS_USE_POLARSSL)
390         ssl_close_notify(wsi->ssl);
391         (void)n; /* we need to close the fd? */
392         ssl_free(wsi->ssl);
393 #else
394 #if defined(LWS_USE_MBEDTLS)
395 #else
396         n = SSL_get_fd(wsi->ssl);
397         SSL_shutdown(wsi->ssl);
398         compatible_close(n);
399         SSL_free(wsi->ssl);
400 #endif
401 #endif
402         wsi->ssl = NULL;
403
404         return 1; /* handled */
405 }
406
407 /* leave all wsi close processing to the caller */
408
409 LWS_VISIBLE int
410 lws_server_socket_service_ssl(struct lws *wsi, lws_sockfd_type accept_fd)
411 {
412         struct lws_context *context = wsi->context;
413         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
414         int n, m;
415 #if !defined(USE_WOLFSSL) && !defined(LWS_USE_POLARSSL) && !defined(LWS_USE_MBEDTLS)
416         BIO *bio;
417 #endif
418
419         if (!LWS_SSL_ENABLED(wsi->vhost))
420                 return 0;
421
422         switch (wsi->mode) {
423         case LWSCM_SSL_INIT:
424
425                 if (wsi->ssl)
426                         lwsl_err("%s: leaking ssl\n", __func__);
427                 if (accept_fd == LWS_SOCK_INVALID)
428                         assert(0);
429
430 #if defined(LWS_USE_POLARSSL)
431         {
432                 ssl_session *ssn;
433                 int rc;
434
435                 wsi->ssl = lws_zalloc(sizeof(ssl_context));
436                 ssn = lws_zalloc(sizeof(ssl_session));
437
438                 rc = ssl_init(wsi->ssl);
439                 if (rc) {
440                         lwsl_err("ssl_init failed\n");
441                         goto fail;
442                 }
443
444                 ssl_set_endpoint(wsi->ssl, SSL_IS_SERVER);
445                 ssl_set_authmode(wsi->ssl, SSL_VERIFY_OPTIONAL);
446                 ssl_set_rng(wsi->ssl, urandom_bytes, NULL);
447                 ssl_set_dbg(wsi->ssl, pssl_debug, NULL);
448                 ssl_set_bio(wsi->ssl, net_recv, &wsi->sock, net_send, &wsi->sock);
449
450                 ssl_set_ciphersuites(wsi->ssl, ciphers);
451
452                 ssl_set_session(wsi->ssl, ssn);
453
454                 ssl_set_ca_chain(wsi->ssl, &wsi->vhost->ssl_ctx->ca,
455                                  NULL, NULL);
456
457                 ssl_set_own_cert_rsa(wsi->ssl,
458                                 &wsi->vhost->ssl_ctx->certificate,
459                                 &wsi->vhost->ssl_ctx->key);
460
461 //              ssl_set_dh_param(wsi->ssl, my_dhm_P, my_dhm_G);
462
463                 lwsl_err("%s: polarssl init done\n", __func__);
464         }
465 #else
466 #if defined(LWS_USE_MBEDTLS)
467 #else
468                 wsi->ssl = SSL_new(wsi->vhost->ssl_ctx);
469                 if (wsi->ssl == NULL) {
470                         lwsl_err("SSL_new failed: %s\n",
471                                  ERR_error_string(lws_ssl_get_error(wsi, 0), NULL));
472                         lws_decode_ssl_error();
473                         if (accept_fd != LWS_SOCK_INVALID)
474                                 compatible_close(accept_fd);
475                         goto fail;
476                 }
477
478                 SSL_set_ex_data(wsi->ssl,
479                         openssl_websocket_private_data_index, wsi->vhost);
480
481                 SSL_set_fd(wsi->ssl, accept_fd);
482 #endif
483 #endif
484
485 #ifdef USE_WOLFSSL
486 #ifdef USE_OLD_CYASSL
487                 CyaSSL_set_using_nonblock(wsi->ssl, 1);
488 #else
489                 wolfSSL_set_using_nonblock(wsi->ssl, 1);
490 #endif
491 #else
492 #if defined(LWS_USE_POLARSSL)
493
494 #else
495 #if defined(LWS_USE_MBEDTLS)
496 #else
497                 SSL_set_mode(wsi->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
498                 bio = SSL_get_rbio(wsi->ssl);
499                 if (bio)
500                         BIO_set_nbio(bio, 1); /* nonblocking */
501                 else
502                         lwsl_notice("NULL rbio\n");
503                 bio = SSL_get_wbio(wsi->ssl);
504                 if (bio)
505                         BIO_set_nbio(bio, 1); /* nonblocking */
506                 else
507                         lwsl_notice("NULL rbio\n");
508 #endif
509 #endif
510 #endif
511
512                 /*
513                  * we are not accepted yet, but we need to enter ourselves
514                  * as a live connection.  That way we can retry when more
515                  * pieces come if we're not sorted yet
516                  */
517
518                 wsi->mode = LWSCM_SSL_ACK_PENDING;
519                 if (insert_wsi_socket_into_fds(context, wsi)) {
520                         lwsl_err("%s: failed to insert into fds\n", __func__);
521                         goto fail;
522                 }
523
524                 lws_set_timeout(wsi, PENDING_TIMEOUT_SSL_ACCEPT,
525                                 context->timeout_secs);
526
527                 lwsl_info("inserted SSL accept into fds, trying SSL_accept\n");
528
529                 /* fallthru */
530
531         case LWSCM_SSL_ACK_PENDING:
532
533                 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
534                         lwsl_err("%s: lws_change_pollfd failed\n", __func__);
535                         goto fail;
536                 }
537
538                 lws_latency_pre(context, wsi);
539
540                 n = recv(wsi->sock, (char *)pt->serv_buf, LWS_MAX_SOCKET_IO_BUF,
541                          MSG_PEEK);
542
543                 /*
544                  * optionally allow non-SSL connect on SSL listening socket
545                  * This is disabled by default, if enabled it goes around any
546                  * SSL-level access control (eg, client-side certs) so leave
547                  * it disabled unless you know it's not a problem for you
548                  */
549
550                 if (wsi->vhost->allow_non_ssl_on_ssl_port) {
551                         if (n >= 1 && pt->serv_buf[0] >= ' ') {
552                                 /*
553                                 * TLS content-type for Handshake is 0x16, and
554                                 * for ChangeCipherSpec Record, it's 0x14
555                                 *
556                                 * A non-ssl session will start with the HTTP
557                                 * method in ASCII.  If we see it's not a legit
558                                 * SSL handshake kill the SSL for this
559                                 * connection and try to handle as a HTTP
560                                 * connection upgrade directly.
561                                 */
562                                 wsi->use_ssl = 0;
563 #if defined(LWS_USE_POLARSSL)
564                                 ssl_close_notify(wsi->ssl);
565                                 ssl_free(wsi->ssl);
566 #else
567 #if defined(LWS_USE_MBEDTLS)
568 #else
569                                 SSL_shutdown(wsi->ssl);
570                                 SSL_free(wsi->ssl);
571 #endif
572 #endif
573                                 wsi->ssl = NULL;
574                                 if (lws_check_opt(context->options,
575                                     LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS))
576                                         wsi->redirect_to_https = 1;
577                                 goto accepted;
578                         }
579                         if (!n) /*
580                                  * connection is gone, or nothing to read
581                                  * if it's gone, we will timeout on
582                                  * PENDING_TIMEOUT_SSL_ACCEPT
583                                  */
584                                 break;
585                         if (n < 0 && (LWS_ERRNO == LWS_EAGAIN ||
586                                       LWS_ERRNO == LWS_EWOULDBLOCK)) {
587                                 /*
588                                  * well, we get no way to know ssl or not
589                                  * so go around again waiting for something
590                                  * to come and give us a hint, or timeout the
591                                  * connection.
592                                  */
593                                 m = SSL_ERROR_WANT_READ;
594                                 goto go_again;
595                         }
596                 }
597
598                 /* normal SSL connection processing path */
599 #if defined(LWS_USE_POLARSSL)
600                 n = ssl_handshake(wsi->ssl);
601 #else
602 #if defined(LWS_USE_MBEDTLS)
603 #else
604                 n = SSL_accept(wsi->ssl);
605 #endif
606 #endif
607                 lws_latency(context, wsi,
608                         "SSL_accept LWSCM_SSL_ACK_PENDING\n", n, n == 1);
609
610                 if (n == 1)
611                         goto accepted;
612
613                 m = lws_ssl_get_error(wsi, n);
614                 lwsl_debug("SSL_accept failed %d / %s\n",
615                            m, ERR_error_string(m, NULL));
616 go_again:
617                 if (m == SSL_ERROR_WANT_READ) {
618                         if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
619                                 lwsl_err("%s: WANT_READ change_pollfd failed\n", __func__);
620                                 goto fail;
621                         }
622
623                         lwsl_info("SSL_ERROR_WANT_READ\n");
624                         break;
625                 }
626                 if (m == SSL_ERROR_WANT_WRITE) {
627                         if (lws_change_pollfd(wsi, 0, LWS_POLLOUT)) {
628                                 lwsl_err("%s: WANT_WRITE change_pollfd failed\n", __func__);
629                                 goto fail;
630                         }
631
632                         break;
633                 }
634                 lwsl_err("SSL_accept failed skt %u: %s\n",
635                            wsi->sock, ERR_error_string(m, NULL));
636
637                 lws_ssl_elaborate_error();
638                 goto fail;
639
640 accepted:
641                 /* OK, we are accepted... give him some time to negotiate */
642                 lws_set_timeout(wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
643                                 context->timeout_secs);
644
645                 wsi->mode = LWSCM_HTTP_SERVING;
646
647                 lws_http2_configure_if_upgraded(wsi);
648
649                 lwsl_debug("accepted new SSL conn\n");
650                 break;
651         }
652
653         return 0;
654
655 fail:
656         return 1;
657 }
658
659 void
660 lws_ssl_SSL_CTX_destroy(struct lws_vhost *vhost)
661 {
662         if (vhost->ssl_ctx) {
663 #if defined(LWS_USE_POLARSSL)
664                 lws_free(vhost->ssl_ctx);
665 #else
666 #if defined(LWS_USE_MBEDTLS)
667 #else
668                 SSL_CTX_free(vhost->ssl_ctx);
669 #endif
670 #endif
671         }
672         if (!vhost->user_supplied_ssl_ctx && vhost->ssl_client_ctx) {
673 #if defined(LWS_USE_POLARSSL)
674                 lws_free(vhost->ssl_client_ctx);
675 #else
676 #if defined(LWS_USE_MBEDTLS)
677 #else
678                 SSL_CTX_free(vhost->ssl_client_ctx);
679 #endif
680 #endif
681         }
682 }
683
684 void
685 lws_ssl_context_destroy(struct lws_context *context)
686 {
687 #if defined(LWS_USE_POLARSSL)
688 #else
689 #if defined(LWS_USE_MBEDTLS)
690 #else
691 #if (OPENSSL_VERSION_NUMBER < 0x01000000) || defined(USE_WOLFSSL)
692         ERR_remove_state(0);
693 #else
694 #if (OPENSSL_VERSION_NUMBER >= 0x10100005L) && \
695         !defined(LIBRESSL_VERSION_NUMBER) && \
696         !defined(OPENSSL_IS_BORINGSSL)
697         ERR_remove_thread_state();
698 #else
699         ERR_remove_thread_state(NULL);
700 #endif
701 #endif
702         ERR_free_strings();
703         EVP_cleanup();
704         CRYPTO_cleanup_all_ex_data();
705 #endif
706 #endif
707 }