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