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