1/*
2 * libwebsockets - small server side websockets and web server implementation
3 *
4 * Copyright (C) 2010 - 2019 Andy Green <andy@warmcat.com>
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to
8 * deal in the Software without restriction, including without limitation the
9 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 * sell copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22 * IN THE SOFTWARE.
23 */
24
25#include "private-lib-core.h"
26#include "private-lib-tls-mbedtls.h"
27
28void
29lws_ssl_destroy(struct lws_vhost *vhost)
30{
31	if (!lws_check_opt(vhost->context->options,
32			   LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT))
33		return;
34
35	if (vhost->tls.ssl_ctx)
36		SSL_CTX_free(vhost->tls.ssl_ctx);
37	if (!vhost->tls.user_supplied_ssl_ctx && vhost->tls.ssl_client_ctx)
38		SSL_CTX_free(vhost->tls.ssl_client_ctx);
39
40	if (vhost->tls.x509_client_CA)
41		X509_free(vhost->tls.x509_client_CA);
42}
43
44int
45lws_ssl_capable_read(struct lws *wsi, unsigned char *buf, size_t len)
46{
47	struct lws_context *context = wsi->a.context;
48	struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
49	int n = 0, m;
50
51	if (!wsi->tls.ssl)
52		return lws_ssl_capable_read_no_ssl(wsi, buf, len);
53
54	errno = 0;
55	n = SSL_read(wsi->tls.ssl, buf, (int)len);
56#if defined(LWS_PLAT_FREERTOS)
57	if (!n && errno == LWS_ENOTCONN) {
58		lwsl_debug("%s: SSL_read ENOTCONN\n", lws_wsi_tag(wsi));
59		return LWS_SSL_CAPABLE_ERROR;
60	}
61#endif
62
63	lwsl_debug("%s: %s: SSL_read says %d\n", __func__, lws_wsi_tag(wsi), n);
64	/* manpage: returning 0 means connection shut down */
65	if (!n) {
66		wsi->socket_is_permanently_unusable = 1;
67
68		return LWS_SSL_CAPABLE_ERROR;
69	}
70
71	if (n < 0) {
72		m = SSL_get_error(wsi->tls.ssl, n);
73		lwsl_debug("%s: %s: ssl err %d errno %d\n", __func__, lws_wsi_tag(wsi), m, errno);
74		if (errno == LWS_ENOTCONN)
75			/* If the socket isn't connected anymore, bail out. */
76			goto do_err1;
77
78#if defined(LWS_PLAT_FREERTOS)
79		if (errno == LWS_ECONNABORTED)
80			goto do_err1;
81#endif
82
83		if (m == SSL_ERROR_ZERO_RETURN ||
84		    m == SSL_ERROR_SYSCALL)
85			goto do_err;
86
87		if (m == SSL_ERROR_WANT_READ || SSL_want_read(wsi->tls.ssl)) {
88			lwsl_debug("%s: WANT_READ\n", __func__);
89			lwsl_debug("%s: LWS_SSL_CAPABLE_MORE_SERVICE\n", lws_wsi_tag(wsi));
90			return LWS_SSL_CAPABLE_MORE_SERVICE;
91		}
92		if (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->tls.ssl)) {
93			lwsl_info("%s: WANT_WRITE\n", __func__);
94			lwsl_debug("%s: LWS_SSL_CAPABLE_MORE_SERVICE\n", lws_wsi_tag(wsi));
95			wsi->tls_read_wanted_write = 1;
96			lws_callback_on_writable(wsi);
97			return LWS_SSL_CAPABLE_MORE_SERVICE;
98		}
99
100do_err1:
101		wsi->socket_is_permanently_unusable = 1;
102
103do_err:
104#if defined(LWS_WITH_SYS_METRICS)
105	if (wsi->a.vhost)
106		lws_metric_event(wsi->a.vhost->mt_traffic_rx, METRES_NOGO, 0);
107#endif
108
109		return LWS_SSL_CAPABLE_ERROR;
110	}
111
112#if defined(LWS_TLS_LOG_PLAINTEXT_RX)
113	/*
114	 * If using mbedtls type tls library, this is the earliest point for all
115	 * paths to dump what was received as decrypted data from the tls tunnel
116	 */
117	lwsl_notice("%s: len %d\n", __func__, n);
118	lwsl_hexdump_notice(buf, (size_t)n);
119#endif
120
121#if defined(LWS_WITH_SYS_METRICS)
122	if (wsi->a.vhost)
123		lws_metric_event(wsi->a.vhost->mt_traffic_rx,
124				 METRES_GO /* rx */, (u_mt_t)n);
125#endif
126
127	/*
128	 * if it was our buffer that limited what we read,
129	 * check if SSL has additional data pending inside SSL buffers.
130	 *
131	 * Because these won't signal at the network layer with POLLIN
132	 * and if we don't realize, this data will sit there forever
133	 */
134	if (n != (int)len)
135		goto bail;
136	if (!wsi->tls.ssl)
137		goto bail;
138
139	if (SSL_pending(wsi->tls.ssl)) {
140		if (lws_dll2_is_detached(&wsi->tls.dll_pending_tls))
141			lws_dll2_add_head(&wsi->tls.dll_pending_tls,
142					  &pt->tls.dll_pending_tls_owner);
143	} else
144		__lws_ssl_remove_wsi_from_buffered_list(wsi);
145
146	return n;
147bail:
148	lws_ssl_remove_wsi_from_buffered_list(wsi);
149
150	return n;
151}
152
153int
154lws_ssl_pending(struct lws *wsi)
155{
156	if (!wsi->tls.ssl)
157		return 0;
158
159	return SSL_pending(wsi->tls.ssl);
160}
161
162int
163lws_ssl_capable_write(struct lws *wsi, unsigned char *buf, size_t len)
164{
165	int n, m;
166
167#if defined(LWS_TLS_LOG_PLAINTEXT_TX)
168	/*
169	 * If using mbedtls type tls library, this is the last point for all
170	 * paths before sending data into the tls tunnel, where you can dump it
171	 * and see what is being sent.
172	 */
173	lwsl_notice("%s: len %d\n", __func__, (int)len);
174	lwsl_hexdump_notice(buf, len);
175#endif
176
177	if (!wsi->tls.ssl)
178		return lws_ssl_capable_write_no_ssl(wsi, buf, len);
179
180	n = SSL_write(wsi->tls.ssl, buf, (int)len);
181	if (n > 0) {
182#if defined(LWS_WITH_SYS_METRICS)
183		if (wsi->a.vhost)
184			lws_metric_event(wsi->a.vhost->mt_traffic_tx,
185					 METRES_GO, (u_mt_t)n);
186#endif
187		return n;
188	}
189
190	m = SSL_get_error(wsi->tls.ssl, n);
191	if (m != SSL_ERROR_SYSCALL) {
192		if (m == SSL_ERROR_WANT_READ || SSL_want_read(wsi->tls.ssl)) {
193			lwsl_notice("%s: want read\n", __func__);
194
195			return LWS_SSL_CAPABLE_MORE_SERVICE;
196		}
197
198		if (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->tls.ssl)) {
199			lws_set_blocking_send(wsi);
200			lwsl_debug("%s: want write\n", __func__);
201
202			return LWS_SSL_CAPABLE_MORE_SERVICE;
203		}
204	}
205
206	lwsl_debug("%s failed: %d\n",__func__, m);
207	wsi->socket_is_permanently_unusable = 1;
208
209#if defined(LWS_WITH_SYS_METRICS)
210		if (wsi->a.vhost)
211			lws_metric_event(wsi->a.vhost->mt_traffic_tx,
212					 METRES_NOGO, (u_mt_t)n);
213#endif
214
215	return LWS_SSL_CAPABLE_ERROR;
216}
217
218int openssl_SSL_CTX_private_data_index;
219
220void
221lws_ssl_info_callback(const SSL *ssl, int where, int ret)
222{
223	struct lws *wsi;
224	struct lws_context *context;
225	struct lws_ssl_info si;
226
227	context = (struct lws_context *)SSL_CTX_get_ex_data(
228					SSL_get_SSL_CTX(ssl),
229					openssl_SSL_CTX_private_data_index);
230	if (!context)
231		return;
232	wsi = wsi_from_fd(context, SSL_get_fd(ssl));
233	if (!wsi)
234		return;
235
236	if (!(where & wsi->a.vhost->tls.ssl_info_event_mask))
237		return;
238
239	si.where = where;
240	si.ret = ret;
241
242	if (user_callback_handle_rxflow(wsi->a.protocol->callback,
243					wsi, LWS_CALLBACK_SSL_INFO,
244					wsi->user_space, &si, 0))
245		lws_set_timeout(wsi, PENDING_TIMEOUT_KILLED_BY_SSL_INFO, -1);
246}
247
248
249int
250lws_ssl_close(struct lws *wsi)
251{
252	lws_sockfd_type n;
253
254	if (!wsi->tls.ssl)
255		return 0; /* not handled */
256
257#if defined (LWS_HAVE_SSL_SET_INFO_CALLBACK)
258	/* kill ssl callbacks, becausse we will remove the fd from the
259	 * table linking it to the wsi
260	 */
261	if (wsi->a.vhost->tls.ssl_info_event_mask)
262		SSL_set_info_callback(wsi->tls.ssl, NULL);
263#endif
264
265#if defined(LWS_TLS_SYNTHESIZE_CB)
266	lws_sul_cancel(&wsi->tls.sul_cb_synth);
267	/*
268	 * ... check the session in case it did not live long enough to get
269	 * the scheduled callback to sample it
270	 */
271	lws_sess_cache_synth_cb(&wsi->tls.sul_cb_synth);
272#endif
273
274	n = SSL_get_fd(wsi->tls.ssl);
275	if (!wsi->socket_is_permanently_unusable)
276		SSL_shutdown(wsi->tls.ssl);
277	compatible_close(n);
278	SSL_free(wsi->tls.ssl);
279	wsi->tls.ssl = NULL;
280
281	lws_tls_restrict_return(wsi);
282
283	return 1; /* handled */
284}
285
286void
287lws_ssl_SSL_CTX_destroy(struct lws_vhost *vhost)
288{
289	if (vhost->tls.ssl_ctx)
290		SSL_CTX_free(vhost->tls.ssl_ctx);
291
292	if (!vhost->tls.user_supplied_ssl_ctx && vhost->tls.ssl_client_ctx)
293		SSL_CTX_free(vhost->tls.ssl_client_ctx);
294#if defined(LWS_WITH_ACME)
295	lws_tls_acme_sni_cert_destroy(vhost);
296#endif
297}
298
299void
300lws_ssl_context_destroy(struct lws_context *context)
301{
302}
303
304lws_tls_ctx *
305lws_tls_ctx_from_wsi(struct lws *wsi)
306{
307	if (!wsi->tls.ssl)
308		return NULL;
309
310	return SSL_get_SSL_CTX(wsi->tls.ssl);
311}
312
313enum lws_ssl_capable_status
314__lws_tls_shutdown(struct lws *wsi)
315{
316	int n = SSL_shutdown(wsi->tls.ssl);
317
318	lwsl_debug("SSL_shutdown=%d for fd %d\n", n, wsi->desc.sockfd);
319
320	switch (n) {
321	case 1: /* successful completion */
322		(void)shutdown(wsi->desc.sockfd, SHUT_WR);
323		return LWS_SSL_CAPABLE_DONE;
324
325	case 0: /* needs a retry */
326		__lws_change_pollfd(wsi, 0, LWS_POLLIN);
327		return LWS_SSL_CAPABLE_MORE_SERVICE;
328
329	default: /* fatal error, or WANT */
330		n = SSL_get_error(wsi->tls.ssl, n);
331		if (n != SSL_ERROR_SYSCALL && n != SSL_ERROR_SSL) {
332			if (SSL_want_read(wsi->tls.ssl)) {
333				lwsl_debug("(wants read)\n");
334				__lws_change_pollfd(wsi, 0, LWS_POLLIN);
335				return LWS_SSL_CAPABLE_MORE_SERVICE_READ;
336			}
337			if (SSL_want_write(wsi->tls.ssl)) {
338				lwsl_debug("(wants write)\n");
339				__lws_change_pollfd(wsi, 0, LWS_POLLOUT);
340				return LWS_SSL_CAPABLE_MORE_SERVICE_WRITE;
341			}
342		}
343		return LWS_SSL_CAPABLE_ERROR;
344	}
345}
346
347
348static int
349tops_fake_POLLIN_for_buffered_mbedtls(struct lws_context_per_thread *pt)
350{
351	return lws_tls_fake_POLLIN_for_buffered(pt);
352}
353
354const struct lws_tls_ops tls_ops_mbedtls = {
355	/* fake_POLLIN_for_buffered */	tops_fake_POLLIN_for_buffered_mbedtls,
356};
357