private.h: rename to contain dir
[platform/upstream/libwebsockets.git] / lib / tls / openssl / openssl-ssl.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com>
5  *
6  *  This library is free software; you can redistribute it and/or
7  *  modify it under the terms of the GNU Lesser General Public
8  *  License as published by the Free Software Foundation:
9  *  version 2.1 of the License.
10  *
11  *  This library is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  *  Lesser General Public License for more details.
15  *
16  *  You should have received a copy of the GNU Lesser General Public
17  *  License along with this library; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19  *  MA  02110-1301  USA
20  */
21
22 #include "private-lib-core.h"
23 #include "private-lib-tls-openssl.h"
24 #include <errno.h>
25
26 int openssl_websocket_private_data_index,
27            openssl_SSL_CTX_private_data_index;
28
29 /*
30  * Care: many openssl apis return 1 for success.  These are translated to the
31  * lws convention of 0 for success.
32  */
33
34 int lws_openssl_describe_cipher(struct lws *wsi)
35 {
36 #if !defined(LWS_WITH_NO_LOGS)
37         int np = -1;
38         SSL *s = wsi->tls.ssl;
39
40         SSL_get_cipher_bits(s, &np);
41         lwsl_info("%s: wsi %p: %s, %s, %d bits, %s\n", __func__, wsi,
42                         SSL_get_cipher_name(s), SSL_get_cipher(s), np,
43                         SSL_get_cipher_version(s));
44 #endif
45
46         return 0;
47 }
48
49 int lws_ssl_get_error(struct lws *wsi, int n)
50 {
51         int m;
52
53         if (!wsi->tls.ssl)
54                 return 99;
55
56         m = SSL_get_error(wsi->tls.ssl, n);
57         lwsl_debug("%s: %p %d -> %d (errno %d)\n", __func__, wsi->tls.ssl, n, m,
58                    errno);
59
60         return m;
61 }
62
63 static int
64 lws_context_init_ssl_pem_passwd_cb(char *buf, int size, int rwflag,
65                                    void *userdata)
66 {
67         struct lws_context_creation_info * info =
68                         (struct lws_context_creation_info *)userdata;
69
70         strncpy(buf, info->ssl_private_key_password, size);
71         buf[size - 1] = '\0';
72
73         return (int)strlen(buf);
74 }
75
76 static int
77 lws_context_init_ssl_pem_passwd_client_cb(char *buf, int size, int rwflag,
78                                           void *userdata)
79 {
80         struct lws_context_creation_info * info =
81                         (struct lws_context_creation_info *)userdata;
82         const char *p = info->ssl_private_key_password;
83
84         if (info->client_ssl_private_key_password)
85                 p = info->client_ssl_private_key_password;
86
87         strncpy(buf, p, size);
88         buf[size - 1] = '\0';
89
90         return (int)strlen(buf);
91 }
92
93 void
94 lws_ssl_bind_passphrase(SSL_CTX *ssl_ctx, int is_client,
95                         const struct lws_context_creation_info *info)
96 {
97         if (!info->ssl_private_key_password &&
98             !info->client_ssl_private_key_password)
99                 return;
100         /*
101          * password provided, set ssl callback and user data
102          * for checking password which will be trigered during
103          * SSL_CTX_use_PrivateKey_file function
104          */
105         SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, (void *)info);
106         SSL_CTX_set_default_passwd_cb(ssl_ctx, is_client ?
107                                       lws_context_init_ssl_pem_passwd_client_cb:
108                                       lws_context_init_ssl_pem_passwd_cb);
109 }
110
111 static void
112 lws_ssl_destroy_client_ctx(struct lws_vhost *vhost)
113 {
114         struct lws_tls_client_reuse *tcr;
115
116         if (vhost->tls.user_supplied_ssl_ctx || !vhost->tls.ssl_client_ctx)
117                 return;
118
119         tcr = SSL_CTX_get_ex_data(vhost->tls.ssl_client_ctx,
120                                   openssl_SSL_CTX_private_data_index);
121
122         if (!tcr || --tcr->refcount)
123                 return;
124
125         SSL_CTX_free(vhost->tls.ssl_client_ctx);
126         vhost->tls.ssl_client_ctx = NULL;
127
128         vhost->context->tls.count_client_contexts--;
129
130         lws_dll2_remove(&tcr->cc_list);
131         lws_free(tcr);
132 }
133
134 LWS_VISIBLE void
135 lws_ssl_destroy(struct lws_vhost *vhost)
136 {
137         if (!lws_check_opt(vhost->context->options,
138                            LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT))
139                 return;
140
141         if (vhost->tls.ssl_ctx)
142                 SSL_CTX_free(vhost->tls.ssl_ctx);
143
144         lws_ssl_destroy_client_ctx(vhost);
145
146 // after 1.1.0 no need
147 #if (OPENSSL_VERSION_NUMBER <  0x10100000)
148 // <= 1.0.1f = old api, 1.0.1g+ = new api
149 #if (OPENSSL_VERSION_NUMBER <= 0x1000106f) || defined(USE_WOLFSSL)
150         ERR_remove_state(0);
151 #else
152 #if OPENSSL_VERSION_NUMBER >= 0x1010005f && \
153     !defined(LIBRESSL_VERSION_NUMBER) && \
154     !defined(OPENSSL_IS_BORINGSSL)
155         ERR_remove_thread_state();
156 #else
157         ERR_remove_thread_state(NULL);
158 #endif
159 #endif
160         /* not needed after 1.1.0 */
161 #if  (OPENSSL_VERSION_NUMBER >= 0x10002000) && \
162      (OPENSSL_VERSION_NUMBER <= 0x10100000)
163         SSL_COMP_free_compression_methods();
164 #endif
165         ERR_free_strings();
166         EVP_cleanup();
167         CRYPTO_cleanup_all_ex_data();
168 #endif
169 }
170
171 LWS_VISIBLE int
172 lws_ssl_capable_read(struct lws *wsi, unsigned char *buf, int len)
173 {
174         struct lws_context *context = wsi->context;
175         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
176         int n = 0, m;
177
178         if (!wsi->tls.ssl)
179                 return lws_ssl_capable_read_no_ssl(wsi, buf, len);
180
181         lws_stats_bump(pt, LWSSTATS_C_API_READ, 1);
182
183         errno = 0;
184         ERR_clear_error();
185         n = SSL_read(wsi->tls.ssl, buf, len);
186 #if defined(LWS_WITH_ESP32)
187         if (!n && errno == LWS_ENOTCONN) {
188                 lwsl_debug("%p: SSL_read ENOTCONN\n", wsi);
189                 return LWS_SSL_CAPABLE_ERROR;
190         }
191 #endif
192 #if defined(LWS_WITH_STATS)
193         if (!wsi->seen_rx && wsi->accept_start_us) {
194                 lws_stats_bump(pt, LWSSTATS_US_SSL_RX_DELAY_AVG,
195                                       lws_now_usecs() -
196                                               wsi->accept_start_us);
197                 lws_stats_bump(pt, LWSSTATS_C_SSL_CONNS_HAD_RX, 1);
198                 wsi->seen_rx = 1;
199         }
200 #endif
201
202
203         lwsl_debug("%p: SSL_read says %d\n", wsi, n);
204         /* manpage: returning 0 means connection shut down
205          *
206          * 2018-09-10: https://github.com/openssl/openssl/issues/1903
207          *
208          * So, in summary, if you get a 0 or -1 return from SSL_read() /
209          * SSL_write(), you should call SSL_get_error():
210          *
211          *  - If you get back SSL_ERROR_RETURN_ZERO then you know the connection
212          *    has been cleanly shutdown by the peer. To fully close the
213          *    connection you may choose to call SSL_shutdown() to send a
214          *    close_notify back.
215          *
216          *  - If you get back SSL_ERROR_SSL then some kind of internal or
217          *    protocol error has occurred. More details will be on the SSL error
218          *    queue. You can also call SSL_get_shutdown(). If this indicates a
219          *    state of SSL_RECEIVED_SHUTDOWN then you know a fatal alert has
220          *    been received from the peer (if it had been a close_notify then
221          *    SSL_get_error() would have returned SSL_ERROR_RETURN_ZERO).
222          *    SSL_ERROR_SSL is considered fatal - you should not call
223          *    SSL_shutdown() in this case.
224          *
225          *  - If you get back SSL_ERROR_SYSCALL then some kind of fatal (i.e.
226          *    non-retryable) error has occurred in a system call.
227          */
228         if (n <= 0) {
229                 m = lws_ssl_get_error(wsi, n);
230                 lwsl_debug("%p: ssl err %d errno %d\n", wsi, m, errno);
231                 if (m == SSL_ERROR_ZERO_RETURN) /* cleanly shut down */
232                         return LWS_SSL_CAPABLE_ERROR;
233
234                 /* hm not retryable.. could be 0 size pkt or error  */
235
236                 if (m == SSL_ERROR_SSL || m == SSL_ERROR_SYSCALL ||
237                     errno == LWS_ENOTCONN) {
238
239                         /* unclean, eg closed conn */
240
241                         wsi->socket_is_permanently_unusable = 1;
242
243                         return LWS_SSL_CAPABLE_ERROR;
244                 }
245
246                 /* retryable? */
247
248                 if (SSL_want_read(wsi->tls.ssl)) {
249                         lwsl_debug("%s: WANT_READ\n", __func__);
250                         lwsl_debug("%p: LWS_SSL_CAPABLE_MORE_SERVICE\n", wsi);
251                         return LWS_SSL_CAPABLE_MORE_SERVICE;
252                 }
253                 if (SSL_want_write(wsi->tls.ssl)) {
254                         lwsl_debug("%s: WANT_WRITE\n", __func__);
255                         lwsl_debug("%p: LWS_SSL_CAPABLE_MORE_SERVICE\n", wsi);
256                         return LWS_SSL_CAPABLE_MORE_SERVICE;
257                 }
258
259                 /* keep on trucking it seems */
260         }
261
262         lws_stats_bump(pt, LWSSTATS_B_READ, n);
263
264         if (wsi->vhost)
265                 wsi->vhost->conn_stats.rx += n;
266
267         // lwsl_hexdump_err(buf, n);
268
269         /*
270          * if it was our buffer that limited what we read,
271          * check if SSL has additional data pending inside SSL buffers.
272          *
273          * Because these won't signal at the network layer with POLLIN
274          * and if we don't realize, this data will sit there forever
275          */
276         if (n != len)
277                 goto bail;
278         if (!wsi->tls.ssl)
279                 goto bail;
280
281         if (SSL_pending(wsi->tls.ssl) &&
282             lws_dll2_is_detached(&wsi->tls.dll_pending_tls))
283                 lws_dll2_add_head(&wsi->tls.dll_pending_tls,
284                                   &pt->tls.dll_pending_tls_owner);
285
286         return n;
287 bail:
288         lws_ssl_remove_wsi_from_buffered_list(wsi);
289
290         return n;
291 }
292
293 LWS_VISIBLE int
294 lws_ssl_pending(struct lws *wsi)
295 {
296         if (!wsi->tls.ssl)
297                 return 0;
298
299         return SSL_pending(wsi->tls.ssl);
300 }
301
302 LWS_VISIBLE int
303 lws_ssl_capable_write(struct lws *wsi, unsigned char *buf, int len)
304 {
305         int n, m;
306
307         if (!wsi->tls.ssl)
308                 return lws_ssl_capable_write_no_ssl(wsi, buf, len);
309
310         errno = 0;
311         ERR_clear_error();
312         n = SSL_write(wsi->tls.ssl, buf, len);
313         if (n > 0)
314                 return n;
315
316         m = lws_ssl_get_error(wsi, n);
317         if (m != SSL_ERROR_SYSCALL) {
318                 if (m == SSL_ERROR_WANT_READ || SSL_want_read(wsi->tls.ssl)) {
319                         lwsl_notice("%s: want read\n", __func__);
320
321                         return LWS_SSL_CAPABLE_MORE_SERVICE;
322                 }
323
324                 if (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->tls.ssl)) {
325                         lws_set_blocking_send(wsi);
326
327                         lwsl_debug("%s: want write\n", __func__);
328
329                         return LWS_SSL_CAPABLE_MORE_SERVICE;
330                 }
331         }
332
333         lwsl_debug("%s failed: %s\n",__func__, ERR_error_string(m, NULL));
334         lws_tls_err_describe_clear();
335
336         wsi->socket_is_permanently_unusable = 1;
337
338         return LWS_SSL_CAPABLE_ERROR;
339 }
340
341 void
342 lws_ssl_info_callback(const SSL *ssl, int where, int ret)
343 {
344         struct lws *wsi;
345         struct lws_context *context;
346         struct lws_ssl_info si;
347
348 #ifndef USE_WOLFSSL
349         context = (struct lws_context *)SSL_CTX_get_ex_data(
350                                         SSL_get_SSL_CTX(ssl),
351                                         openssl_SSL_CTX_private_data_index);
352 #else
353         context = (struct lws_context *)SSL_CTX_get_ex_data(
354                                         SSL_get_SSL_CTX((SSL*) ssl),
355                                         openssl_SSL_CTX_private_data_index);
356 #endif
357         if (!context)
358                 return;
359         wsi = wsi_from_fd(context, SSL_get_fd(ssl));
360         if (!wsi)
361                 return;
362
363         if (!(where & wsi->vhost->tls.ssl_info_event_mask))
364                 return;
365
366         si.where = where;
367         si.ret = ret;
368
369         if (user_callback_handle_rxflow(wsi->protocol->callback,
370                                         wsi, LWS_CALLBACK_SSL_INFO,
371                                         wsi->user_space, &si, 0))
372                 lws_set_timeout(wsi, PENDING_TIMEOUT_KILLED_BY_SSL_INFO, -1);
373 }
374
375
376 LWS_VISIBLE int
377 lws_ssl_close(struct lws *wsi)
378 {
379         lws_sockfd_type n;
380
381         if (!wsi->tls.ssl)
382                 return 0; /* not handled */
383
384 #if defined (LWS_HAVE_SSL_SET_INFO_CALLBACK)
385         /* kill ssl callbacks, because we will remove the fd from the
386          * table linking it to the wsi
387          */
388         if (wsi->vhost->tls.ssl_info_event_mask)
389                 SSL_set_info_callback(wsi->tls.ssl, NULL);
390 #endif
391
392         n = SSL_get_fd(wsi->tls.ssl);
393         if (!wsi->socket_is_permanently_unusable)
394                 SSL_shutdown(wsi->tls.ssl);
395         compatible_close(n);
396         SSL_free(wsi->tls.ssl);
397         wsi->tls.ssl = NULL;
398
399         if (wsi->context->simultaneous_ssl_restriction &&
400             wsi->context->simultaneous_ssl-- ==
401                             wsi->context->simultaneous_ssl_restriction)
402                 /* we made space and can do an accept */
403                 lws_gate_accepts(wsi->context, 1);
404
405         // lwsl_notice("%s: ssl restr %d, simul %d\n", __func__,
406         //              wsi->context->simultaneous_ssl_restriction,
407         //              wsi->context->simultaneous_ssl);
408
409 #if defined(LWS_WITH_STATS)
410         wsi->context->updated = 1;
411 #endif
412
413         return 1; /* handled */
414 }
415
416 void
417 lws_ssl_SSL_CTX_destroy(struct lws_vhost *vhost)
418 {
419         if (vhost->tls.ssl_ctx)
420                 SSL_CTX_free(vhost->tls.ssl_ctx);
421
422         lws_ssl_destroy_client_ctx(vhost);
423
424 #if defined(LWS_WITH_ACME)
425         lws_tls_acme_sni_cert_destroy(vhost);
426 #endif
427 }
428
429 void
430 lws_ssl_context_destroy(struct lws_context *context)
431 {
432 // after 1.1.0 no need
433 #if (OPENSSL_VERSION_NUMBER <  0x10100000)
434 // <= 1.0.1f = old api, 1.0.1g+ = new api
435 #if (OPENSSL_VERSION_NUMBER <= 0x1000106f) || defined(USE_WOLFSSL)
436         ERR_remove_state(0);
437 #else
438 #if OPENSSL_VERSION_NUMBER >= 0x1010005f && \
439     !defined(LIBRESSL_VERSION_NUMBER) && \
440     !defined(OPENSSL_IS_BORINGSSL)
441         ERR_remove_thread_state();
442 #else
443         ERR_remove_thread_state(NULL);
444 #endif
445 #endif
446         // after 1.1.0 no need
447 #if  (OPENSSL_VERSION_NUMBER >= 0x10002000) && (OPENSSL_VERSION_NUMBER <= 0x10100000)
448         SSL_COMP_free_compression_methods();
449 #endif
450         ERR_free_strings();
451         EVP_cleanup();
452         CRYPTO_cleanup_all_ex_data();
453 #endif
454 }
455
456 lws_tls_ctx *
457 lws_tls_ctx_from_wsi(struct lws *wsi)
458 {
459         if (!wsi->tls.ssl)
460                 return NULL;
461
462         return SSL_get_SSL_CTX(wsi->tls.ssl);
463 }
464
465 enum lws_ssl_capable_status
466 __lws_tls_shutdown(struct lws *wsi)
467 {
468         int n;
469
470         errno = 0;
471         ERR_clear_error();
472         n = SSL_shutdown(wsi->tls.ssl);
473         lwsl_debug("SSL_shutdown=%d for fd %d\n", n, wsi->desc.sockfd);
474         switch (n) {
475         case 1: /* successful completion */
476                 n = shutdown(wsi->desc.sockfd, SHUT_WR);
477                 return LWS_SSL_CAPABLE_DONE;
478
479         case 0: /* needs a retry */
480                 __lws_change_pollfd(wsi, 0, LWS_POLLIN);
481                 return LWS_SSL_CAPABLE_MORE_SERVICE;
482
483         default: /* fatal error, or WANT */
484                 n = SSL_get_error(wsi->tls.ssl, n);
485                 if (n != SSL_ERROR_SYSCALL && n != SSL_ERROR_SSL) {
486                         if (SSL_want_read(wsi->tls.ssl)) {
487                                 lwsl_debug("(wants read)\n");
488                                 __lws_change_pollfd(wsi, 0, LWS_POLLIN);
489                                 return LWS_SSL_CAPABLE_MORE_SERVICE_READ;
490                         }
491                         if (SSL_want_write(wsi->tls.ssl)) {
492                                 lwsl_debug("(wants write)\n");
493                                 __lws_change_pollfd(wsi, 0, LWS_POLLOUT);
494                                 return LWS_SSL_CAPABLE_MORE_SERVICE_WRITE;
495                         }
496                 }
497                 return LWS_SSL_CAPABLE_ERROR;
498         }
499 }
500
501
502 static int
503 tops_fake_POLLIN_for_buffered_openssl(struct lws_context_per_thread *pt)
504 {
505         return lws_tls_fake_POLLIN_for_buffered(pt);
506 }
507
508 const struct lws_tls_ops tls_ops_openssl = {
509         /* fake_POLLIN_for_buffered */  tops_fake_POLLIN_for_buffered_openssl,
510 };