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