• 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 
27 /*
28  * Care: many openssl apis return 1 for success.  These are translated to the
29  * lws convention of 0 for success.
30  */
31 
32 extern int openssl_websocket_private_data_index,
33 	   openssl_SSL_CTX_private_data_index;
34 
35 int lws_openssl_describe_cipher(struct lws *wsi);
36 
37 static int
OpenSSL_verify_callback(int preverify_ok,X509_STORE_CTX * x509_ctx)38 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
39 {
40 	SSL *ssl;
41 	int n;
42 	struct lws *wsi;
43 	union lws_tls_cert_info_results ir;
44 	X509 *topcert = X509_STORE_CTX_get_current_cert(x509_ctx);
45 
46 	ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
47 		SSL_get_ex_data_X509_STORE_CTX_idx());
48 
49 	/*
50 	 * !!! nasty openssl requires the index to come as a library-scope
51 	 * static
52 	 */
53 	wsi = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
54 
55 	n = lws_tls_openssl_cert_info(topcert, LWS_TLS_CERT_INFO_COMMON_NAME,
56 				      &ir, sizeof(ir.ns.name));
57 	if (!n)
58 		lwsl_info("%s: client cert CN '%s'\n", __func__, ir.ns.name);
59 	else
60 		lwsl_info("%s: couldn't get client cert CN\n", __func__);
61 
62 	n = wsi->a.vhost->protocols[0].callback(wsi,
63 			LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
64 					   x509_ctx, ssl, (unsigned int)preverify_ok);
65 
66 	/* convert return code from 0 = OK to 1 = OK */
67 	return !n;
68 }
69 
70 int
lws_tls_server_client_cert_verify_config(struct lws_vhost * vh)71 lws_tls_server_client_cert_verify_config(struct lws_vhost *vh)
72 {
73 	int verify_options = SSL_VERIFY_PEER;
74 
75 	/* as a server, are we requiring clients to identify themselves? */
76 
77 	if (!lws_check_opt(vh->options,
78 			  LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT))
79 		return 0;
80 
81 	if (!lws_check_opt(vh->options,
82 			   LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED))
83 		verify_options |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
84 
85 	SSL_CTX_set_session_id_context(vh->tls.ssl_ctx, (uint8_t *)vh->context,
86 				       sizeof(void *));
87 
88 	/* absolutely require the client cert */
89 	SSL_CTX_set_verify(vh->tls.ssl_ctx, verify_options,
90 			   OpenSSL_verify_callback);
91 
92 	return 0;
93 }
94 
95 #if defined(SSL_TLSEXT_ERR_NOACK) && !defined(OPENSSL_NO_TLSEXT)
96 static int
lws_ssl_server_name_cb(SSL * ssl,int * ad,void * arg)97 lws_ssl_server_name_cb(SSL *ssl, int *ad, void *arg)
98 {
99 	struct lws_context *context = (struct lws_context *)arg;
100 	struct lws_vhost *vhost, *vh;
101 	const char *servername;
102 
103 	if (!ssl)
104 		return SSL_TLSEXT_ERR_NOACK;
105 
106 	/*
107 	 * We can only get ssl accepted connections by using a vhost's ssl_ctx
108 	 * find out which listening one took us and only match vhosts on the
109 	 * same port.
110 	 */
111 	vh = context->vhost_list;
112 	while (vh) {
113 		if (!vh->being_destroyed &&
114 		    vh->tls.ssl_ctx == SSL_get_SSL_CTX(ssl))
115 			break;
116 		vh = vh->vhost_next;
117 	}
118 
119 	if (!vh) {
120 		assert(vh); /* can't match the incoming vh? */
121 		return SSL_TLSEXT_ERR_OK;
122 	}
123 
124 	servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
125 	if (!servername) {
126 		/* the client doesn't know what hostname it wants */
127 		lwsl_info("SNI: Unknown ServerName\n");
128 
129 		return SSL_TLSEXT_ERR_OK;
130 	}
131 
132 	vhost = lws_select_vhost(context, vh->listen_port, servername);
133 	if (!vhost) {
134 		lwsl_info("SNI: none: %s:%d\n", servername, vh->listen_port);
135 
136 		return SSL_TLSEXT_ERR_OK;
137 	}
138 
139 	lwsl_info("SNI: Found: %s:%d\n", servername, vh->listen_port);
140 
141 	/* select the ssl ctx from the selected vhost for this conn */
142 	SSL_set_SSL_CTX(ssl, vhost->tls.ssl_ctx);
143 
144 	return SSL_TLSEXT_ERR_OK;
145 }
146 #endif
147 
148 /*
149  * this may now get called after the vhost creation, when certs become
150  * available.
151  */
152 int
lws_tls_server_certs_load(struct lws_vhost * vhost,struct lws * wsi,const char * cert,const char * private_key,const char * mem_cert,size_t mem_cert_len,const char * mem_privkey,size_t mem_privkey_len)153 lws_tls_server_certs_load(struct lws_vhost *vhost, struct lws *wsi,
154 			  const char *cert, const char *private_key,
155 			  const char *mem_cert, size_t mem_cert_len,
156 			  const char *mem_privkey, size_t mem_privkey_len)
157 {
158 #if !defined(OPENSSL_NO_EC) && defined(LWS_HAVE_EC_KEY_new_by_curve_name) && \
159     ((OPENSSL_VERSION_NUMBER < 0x30000000l) || \
160      defined(LWS_SUPPRESS_DEPRECATED_API_WARNINGS))
161 	const char *ecdh_curve = "prime256v1";
162 #if !defined(LWS_WITH_BORINGSSL) && defined(LWS_HAVE_SSL_EXTRA_CHAIN_CERTS)
163 	STACK_OF(X509) *extra_certs = NULL;
164 #endif
165 	EC_KEY *ecdh, *EC_key = NULL;
166 	EVP_PKEY *pkey;
167 	X509 *x = NULL;
168 	int ecdh_nid;
169 	int KeyType;
170 #endif
171 	unsigned long error;
172 	lws_filepos_t flen;
173 	uint8_t *p;
174 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
175 	int ret;
176 #endif
177 	int n = (int)lws_tls_generic_cert_checks(vhost, cert, private_key), m;
178 
179 	if (!cert && !private_key)
180 		n = LWS_TLS_EXTANT_ALTERNATIVE;
181 
182 	if (n == LWS_TLS_EXTANT_NO && (!mem_cert || !mem_privkey))
183 		return 0;
184 	if (n == LWS_TLS_EXTANT_NO)
185 		n = LWS_TLS_EXTANT_ALTERNATIVE;
186 
187 	if (n == LWS_TLS_EXTANT_ALTERNATIVE && (!mem_cert || !mem_privkey))
188 		return 1; /* no alternative */
189 
190 	if (n == LWS_TLS_EXTANT_ALTERNATIVE) {
191 
192 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
193 
194 		/*
195 		 * Although we have prepared update certs, we no longer have
196 		 * the rights to read our own cert + key we saved.
197 		 *
198 		 * If we were passed copies in memory buffers, use those
199 		 * in favour of the filepaths we normally want.
200 		 */
201 		cert = NULL;
202 		private_key = NULL;
203 	}
204 
205 	/*
206 	 * use the multi-cert interface for backwards compatibility in the
207 	 * both simple files case
208 	 */
209 
210 	if (n != LWS_TLS_EXTANT_ALTERNATIVE && cert) {
211 
212 		/* set the local certificate from CertFile */
213 		m = SSL_CTX_use_certificate_chain_file(vhost->tls.ssl_ctx, cert);
214 		if (m != 1) {
215 			const char *s;
216 			error = ERR_get_error();
217 
218 			s = ERR_error_string(
219 #if defined(LWS_WITH_BORINGSSL)
220 				(uint32_t)
221 #endif
222 					error,
223 				       (char *)vhost->context->pt[0].serv_buf);
224 
225 			lwsl_err("problem getting cert '%s' %lu: %s\n",
226 				 cert, error, s);
227 
228 			return 1;
229 		}
230 
231 		if (private_key) {
232 			/* set the private key from KeyFile */
233 			if (SSL_CTX_use_PrivateKey_file(vhost->tls.ssl_ctx, private_key,
234 							SSL_FILETYPE_PEM) != 1) {
235 				const char *s;
236 				error = ERR_get_error();
237 				s = ERR_error_string(
238 	#if defined(LWS_WITH_BORINGSSL)
239 					(uint32_t)
240 	#endif
241 						error,
242 					       (char *)vhost->context->pt[0].serv_buf);
243 				lwsl_err("ssl problem getting key '%s' %lu: %s\n",
244 					 private_key, error, s);
245 				return 1;
246 			}
247 		} else {
248 			if (vhost->protocols[0].callback(wsi,
249 				      LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY,
250 							 vhost->tls.ssl_ctx, NULL, 0)) {
251 				lwsl_err("ssl private key not set\n");
252 
253 				return 1;
254 			}
255 		}
256 
257 		return 0;
258 	}
259 
260 	/* otherwise allow for DER or PEM, file or memory image */
261 
262 	if (lws_tls_alloc_pem_to_der_file(vhost->context, cert, mem_cert,
263 					  mem_cert_len, &p, &flen)) {
264 		lwsl_err("%s: couldn't read cert file\n", __func__);
265 
266 		return 1;
267 	}
268 
269 #if !defined(USE_WOLFSSL)
270 	ret = SSL_CTX_use_certificate_ASN1(vhost->tls.ssl_ctx,
271 #if defined(LWS_WITH_BORINGSSL)
272 				(size_t)
273 #else
274 				(int)
275 #endif
276 				flen, p);
277 #else
278 	ret = wolfSSL_CTX_use_certificate_buffer(vhost->tls.ssl_ctx,
279 						 (uint8_t *)p, (int)flen,
280 						 WOLFSSL_FILETYPE_ASN1);
281 #endif
282 	lws_free_set_NULL(p);
283 	if (ret != 1) {
284 		lwsl_err("%s: Problem loading cert\n", __func__);
285 
286 		return 1;
287 	}
288 
289 	if (lws_tls_alloc_pem_to_der_file(vhost->context, private_key,
290 					  mem_privkey, mem_privkey_len,
291 					  &p, &flen)) {
292 		lwsl_notice("unable to convert memory privkey\n");
293 
294 		return 1;
295 	}
296 
297 #if !defined(USE_WOLFSSL)
298 	ret = SSL_CTX_use_PrivateKey_ASN1(EVP_PKEY_RSA, vhost->tls.ssl_ctx, p,
299 #if defined(LWS_WITH_BORINGSSL)
300 			(size_t)
301 #else
302 					  (long)(long long)
303 #endif
304 					  flen);
305 	if (ret != 1) {
306 		ret = SSL_CTX_use_PrivateKey_ASN1(EVP_PKEY_EC,
307 						  vhost->tls.ssl_ctx, p,
308 #if defined(LWS_WITH_BORINGSSL)
309 			(size_t)
310 #else
311 					  (long)(long long)
312 #endif
313 						  flen);
314 	}
315 #else
316 	ret = wolfSSL_CTX_use_PrivateKey_buffer(vhost->tls.ssl_ctx, p, flen,
317 						WOLFSSL_FILETYPE_ASN1);
318 #endif
319 	lws_free_set_NULL(p);
320 	if (ret != 1)  {
321 		lwsl_notice("unable to use memory privkey\n");
322 
323 		return 1;
324 	}
325 
326 #else
327 		/*
328 		 * Although we have prepared update certs, we no longer have
329 		 * the rights to read our own cert + key we saved.
330 		 *
331 		 * If we were passed copies in memory buffers, use those
332 		 * instead.
333 		 *
334 		 * The passed memory-buffer cert image is in DER, and the
335 		 * memory-buffer private key image is PEM.
336 		 */
337 #ifndef USE_WOLFSSL
338 		if (lws_tls_alloc_pem_to_der_file(vhost->context, cert, mem_cert,
339 						  mem_cert_len, &p, &flen)) {
340 			lwsl_err("%s: couldn't convert pem to der\n", __func__);
341 			return 1;
342 		}
343 		if (SSL_CTX_use_certificate_ASN1(vhost->tls.ssl_ctx,
344 						 (int)flen,
345 						 (uint8_t *)p) != 1) {
346 #else
347 		if (wolfSSL_CTX_use_certificate_buffer(vhost->tls.ssl_ctx,
348 						 (uint8_t *)mem_cert,
349 						 (int)mem_cert_len,
350 						 WOLFSSL_FILETYPE_ASN1) != 1) {
351 
352 #endif
353 			lwsl_err("Problem loading update cert\n");
354 
355 			return 1;
356 		}
357 
358 		if (lws_tls_alloc_pem_to_der_file(vhost->context, NULL,
359 						  mem_privkey, mem_privkey_len,
360 						  &p, &flen)) {
361 			lwsl_notice("unable to convert memory privkey\n");
362 
363 			return 1;
364 		}
365 #ifndef USE_WOLFSSL
366 		if (SSL_CTX_use_PrivateKey_ASN1(EVP_PKEY_RSA,
367 						vhost->tls.ssl_ctx, p,
368 						(long)(long long)flen) != 1) {
369 #else
370 		if (wolfSSL_CTX_use_PrivateKey_buffer(vhost->tls.ssl_ctx, p,
371 					    (long)flen, WOLFSSL_FILETYPE_ASN1) != 1) {
372 #endif
373 			lwsl_notice("unable to use memory privkey\n");
374 
375 			return 1;
376 		}
377 
378 		goto check_key;
379 	}
380 
381 	/* set the local certificate from CertFile */
382 	m = SSL_CTX_use_certificate_chain_file(vhost->tls.ssl_ctx, cert);
383 	if (m != 1) {
384 		error = ERR_get_error();
385 		lwsl_err("problem getting cert '%s' %lu: %s\n",
386 			 cert, error, ERR_error_string(error,
387 			       (char *)vhost->context->pt[0].serv_buf));
388 
389 		return 1;
390 	}
391 
392 	if (n != LWS_TLS_EXTANT_ALTERNATIVE && private_key) {
393 		/* set the private key from KeyFile */
394 		if (SSL_CTX_use_PrivateKey_file(vhost->tls.ssl_ctx, private_key,
395 					        SSL_FILETYPE_PEM) != 1) {
396 			error = ERR_get_error();
397 			lwsl_err("ssl problem getting key '%s' %lu: %s\n",
398 				 private_key, error,
399 				 ERR_error_string(error,
400 				      (char *)vhost->context->pt[0].serv_buf));
401 			return 1;
402 		}
403 	} else {
404 		if (vhost->protocols[0].callback(wsi,
405 			      LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY,
406 						 vhost->tls.ssl_ctx, NULL, 0)) {
407 			lwsl_err("ssl private key not set\n");
408 
409 			return 1;
410 		}
411 	}
412 
413 check_key:
414 #endif
415 
416 	/* verify private key */
417 	if (!SSL_CTX_check_private_key(vhost->tls.ssl_ctx)) {
418 		lwsl_err("Private SSL key doesn't match cert\n");
419 
420 		return 1;
421 	}
422 
423 
424 #if !defined(OPENSSL_NO_EC) && defined(LWS_HAVE_EC_KEY_new_by_curve_name) && \
425     ((OPENSSL_VERSION_NUMBER < 0x30000000l) || \
426      defined(LWS_SUPPRESS_DEPRECATED_API_WARNINGS))
427 	if (vhost->tls.ecdh_curve[0])
428 		ecdh_curve = vhost->tls.ecdh_curve;
429 
430 	ecdh_nid = OBJ_sn2nid(ecdh_curve);
431 	if (NID_undef == ecdh_nid) {
432 		lwsl_err("SSL: Unknown curve name '%s'", ecdh_curve);
433 		return 1;
434 	}
435 
436 	ecdh = EC_KEY_new_by_curve_name(ecdh_nid);
437 	if (NULL == ecdh) {
438 		lwsl_err("SSL: Unable to create curve '%s'", ecdh_curve);
439 		return 1;
440 	}
441 	SSL_CTX_set_tmp_ecdh(vhost->tls.ssl_ctx, ecdh);
442 	EC_KEY_free(ecdh);
443 
444 	SSL_CTX_set_options(vhost->tls.ssl_ctx, SSL_OP_SINGLE_ECDH_USE);
445 
446 	lwsl_notice(" SSL ECDH curve '%s'\n", ecdh_curve);
447 
448 	if (lws_check_opt(vhost->context->options, LWS_SERVER_OPTION_SSL_ECDH))
449 		lwsl_notice(" Using ECDH certificate support\n");
450 
451 	/* Get X509 certificate from ssl context */
452 #if !defined(LWS_WITH_BORINGSSL)
453 #if !defined(LWS_HAVE_SSL_EXTRA_CHAIN_CERTS)
454 	x = sk_X509_value(vhost->tls.ssl_ctx->extra_certs, 0);
455 #else
456 	SSL_CTX_get_extra_chain_certs_only(vhost->tls.ssl_ctx, &extra_certs);
457 	if (extra_certs)
458 		x = sk_X509_value(extra_certs, 0);
459 	else
460 		lwsl_info("%s: no extra certs\n", __func__);
461 #endif
462 	if (!x) {
463 		//lwsl_err("%s: x is NULL\n", __func__);
464 		goto post_ecdh;
465 	}
466 #else
467 	return 0;
468 #endif /* !boringssl */
469 
470 	/* Get the public key from certificate */
471 	pkey = X509_get_pubkey(x);
472 	if (!pkey) {
473 		lwsl_err("%s: pkey is NULL\n", __func__);
474 
475 		return 1;
476 	}
477 	/* Get the key type */
478 	KeyType = EVP_PKEY_type(EVP_PKEY_id(pkey));
479 
480 	if (EVP_PKEY_EC != KeyType) {
481 		lwsl_notice("Key type is not EC\n");
482 		return 0;
483 	}
484 	/* Get the key */
485 	EC_key = EVP_PKEY_get1_EC_KEY(pkey);
486 	/* Set ECDH parameter */
487 	if (!EC_key) {
488 		lwsl_err("%s: ECDH key is NULL \n", __func__);
489 		return 1;
490 	}
491 	SSL_CTX_set_tmp_ecdh(vhost->tls.ssl_ctx, EC_key);
492 
493 	EC_KEY_free(EC_key);
494 
495 #if !defined(OPENSSL_NO_EC) && !defined(LWS_WITH_BORINGSSL)
496 post_ecdh:
497 #endif
498 	vhost->tls.skipped_certs = 0;
499 #else
500 	lwsl_notice(" OpenSSL doesn't support ECDH\n");
501 #endif
502 
503 	return 0;
504 }
505 
506 int
507 lws_tls_server_vhost_backend_init(const struct lws_context_creation_info *info,
508 				  struct lws_vhost *vhost, struct lws *wsi)
509 {
510 	unsigned long error;
511 	SSL_METHOD *method = (SSL_METHOD *)SSLv23_server_method();
512 
513 	if (!method) {
514 		const char *s;
515 		error = ERR_get_error();
516 		s = ERR_error_string(
517 #if defined(LWS_WITH_BORINGSSL)
518 			(uint32_t)
519 #endif
520 				error,
521 			       (char *)vhost->context->pt[0].serv_buf);
522 
523 		lwsl_err("problem creating ssl method %lu: %s\n",
524 				error, s);
525 		return 1;
526 	}
527 	vhost->tls.ssl_ctx = SSL_CTX_new(method);	/* create context */
528 	if (!vhost->tls.ssl_ctx) {
529 		const char *s;
530 
531 		error = ERR_get_error();
532 		s = ERR_error_string(
533 #if defined(LWS_WITH_BORINGSSL)
534 			(uint32_t)
535 #endif
536 				error,
537 			       (char *)vhost->context->pt[0].serv_buf);
538 		lwsl_err("problem creating ssl context %lu: %s\n",
539 				error, s);
540 		return 1;
541 	}
542 
543 	SSL_CTX_set_ex_data(vhost->tls.ssl_ctx,
544 			    openssl_SSL_CTX_private_data_index,
545 			    (char *)vhost->context);
546 	/* Disable SSLv2 and SSLv3 */
547 	SSL_CTX_set_options(vhost->tls.ssl_ctx, SSL_OP_NO_SSLv2 |
548 						SSL_OP_NO_SSLv3);
549 #ifdef SSL_OP_NO_COMPRESSION
550 	SSL_CTX_set_options(vhost->tls.ssl_ctx, SSL_OP_NO_COMPRESSION);
551 #endif
552 	SSL_CTX_set_options(vhost->tls.ssl_ctx, SSL_OP_SINGLE_DH_USE);
553 	SSL_CTX_set_options(vhost->tls.ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
554 
555 	if (info->ssl_cipher_list)
556 		SSL_CTX_set_cipher_list(vhost->tls.ssl_ctx, info->ssl_cipher_list);
557 
558 #if defined(LWS_HAVE_SSL_CTX_set_ciphersuites)
559 	if (info->tls1_3_plus_cipher_list)
560 		SSL_CTX_set_ciphersuites(vhost->tls.ssl_ctx,
561 					 info->tls1_3_plus_cipher_list);
562 #endif
563 
564 #if !defined(OPENSSL_NO_TLSEXT)
565 	SSL_CTX_set_tlsext_servername_callback(vhost->tls.ssl_ctx,
566 					       lws_ssl_server_name_cb);
567 	SSL_CTX_set_tlsext_servername_arg(vhost->tls.ssl_ctx, vhost->context);
568 #endif
569 
570 	if (info->ssl_ca_filepath &&
571 #if defined(LWS_HAVE_SSL_CTX_load_verify_file)
572 	    !SSL_CTX_load_verify_file(vhost->tls.ssl_ctx,
573 				      info->ssl_ca_filepath)) {
574 #else
575 	    !SSL_CTX_load_verify_locations(vhost->tls.ssl_ctx,
576 					   info->ssl_ca_filepath, NULL)) {
577 #endif
578 		lwsl_err("%s: SSL_CTX_load_verify_locations unhappy\n",
579 			 __func__);
580 	}
581 
582 	if (info->ssl_options_set)
583 		SSL_CTX_set_options(vhost->tls.ssl_ctx,
584 #if defined(USE_WOLFSSL)
585 				(long)
586 #else
587 #if defined(LWS_WITH_BORINGSSL)
588 				(uint32_t)
589 #else
590 #if (OPENSSL_VERSION_NUMBER >= 0x10003000l) && !defined(LIBRESSL_VERSION_NUMBER) /* not documented by openssl */
591 				    (unsigned long)
592 #else
593 				    (long)
594 #endif
595 #endif
596 #endif
597 				info->ssl_options_set);
598 
599 /* SSL_clear_options introduced in 0.9.8m */
600 #if (OPENSSL_VERSION_NUMBER >= 0x009080df) && !defined(USE_WOLFSSL)
601 	if (info->ssl_options_clear)
602 		SSL_CTX_clear_options(vhost->tls.ssl_ctx,
603 #if defined(LWS_WITH_BORINGSSL)
604 				(uint32_t)
605 #else
606 #if (OPENSSL_VERSION_NUMBER >= 0x10003000l)  && !defined(LIBRESSL_VERSION_NUMBER)/* not documented by openssl */
607 				    (unsigned long)
608 #else
609 				    (long)
610 #endif
611 #endif
612 				      info->ssl_options_clear);
613 #endif
614 
615 	lwsl_info(" SSL options 0x%lX\n",
616 			(unsigned long)SSL_CTX_get_options(vhost->tls.ssl_ctx));
617 	if (!vhost->tls.use_ssl ||
618 	    (!info->ssl_cert_filepath && !info->server_ssl_cert_mem))
619 		return 0;
620 
621 	lws_ssl_bind_passphrase(vhost->tls.ssl_ctx, 0, info);
622 
623 	return lws_tls_server_certs_load(vhost, wsi, info->ssl_cert_filepath,
624 					 info->ssl_private_key_filepath,
625 					 info->server_ssl_cert_mem,
626 					 info->server_ssl_cert_mem_len,
627 					 info->server_ssl_private_key_mem,
628 					 info->server_ssl_private_key_mem_len);
629 }
630 
631 int
632 lws_tls_server_new_nonblocking(struct lws *wsi, lws_sockfd_type accept_fd)
633 {
634 #if !defined(USE_WOLFSSL)
635 	BIO *bio;
636 #endif
637 
638 	errno = 0;
639 	ERR_clear_error();
640 	wsi->tls.ssl = SSL_new(wsi->a.vhost->tls.ssl_ctx);
641 	if (wsi->tls.ssl == NULL) {
642 		lwsl_err("SSL_new failed: %d (errno %d)\n",
643 			 lws_ssl_get_error(wsi, 0), errno);
644 
645 		lws_tls_err_describe_clear();
646 		return 1;
647 	}
648 
649 	SSL_set_ex_data(wsi->tls.ssl, openssl_websocket_private_data_index, wsi);
650 	SSL_set_fd(wsi->tls.ssl, (int)(lws_intptr_t)accept_fd);
651 
652 #ifdef USE_WOLFSSL
653 #ifdef USE_OLD_CYASSL
654 	CyaSSL_set_using_nonblock(wsi->tls.ssl, 1);
655 #else
656 	wolfSSL_set_using_nonblock(wsi->tls.ssl, 1);
657 #endif
658 #else
659 
660 	SSL_set_mode(wsi->tls.ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
661 				   SSL_MODE_RELEASE_BUFFERS);
662 	bio = SSL_get_rbio(wsi->tls.ssl);
663 	if (bio)
664 		BIO_set_nbio(bio, 1); /* nonblocking */
665 	else
666 		lwsl_notice("NULL rbio\n");
667 	bio = SSL_get_wbio(wsi->tls.ssl);
668 	if (bio)
669 		BIO_set_nbio(bio, 1); /* nonblocking */
670 	else
671 		lwsl_notice("NULL rbio\n");
672 #endif
673 
674 #if defined (LWS_HAVE_SSL_SET_INFO_CALLBACK)
675 		if (wsi->a.vhost->tls.ssl_info_event_mask)
676 			SSL_set_info_callback(wsi->tls.ssl, lws_ssl_info_callback);
677 #endif
678 
679 	return 0;
680 }
681 
682 int
683 lws_tls_server_abort_connection(struct lws *wsi)
684 {
685 	if (wsi->tls.use_ssl)
686 		SSL_shutdown(wsi->tls.ssl);
687 	SSL_free(wsi->tls.ssl);
688 
689 	return 0;
690 }
691 
692 enum lws_ssl_capable_status
693 lws_tls_server_accept(struct lws *wsi)
694 {
695 	struct lws_context_per_thread *pt = &wsi->a.context->pt[(int)wsi->tsi];
696 	union lws_tls_cert_info_results ir;
697 	int m, n;
698 
699 	errno = 0;
700 	ERR_clear_error();
701 	n = SSL_accept(wsi->tls.ssl);
702 
703 	wsi->skip_fallback = 1;
704 
705 	if (n == 1) {
706 		n = lws_tls_peer_cert_info(wsi, LWS_TLS_CERT_INFO_COMMON_NAME, &ir,
707 					   sizeof(ir.ns.name));
708 		if (!n)
709 			lwsl_notice("%s: client cert CN '%s'\n", __func__,
710 				    ir.ns.name);
711 		else
712 			lwsl_info("%s: no client cert CN\n", __func__);
713 
714 		lws_openssl_describe_cipher(wsi);
715 
716 		if (SSL_pending(wsi->tls.ssl) &&
717 		    lws_dll2_is_detached(&wsi->tls.dll_pending_tls))
718 			lws_dll2_add_head(&wsi->tls.dll_pending_tls,
719 					  &pt->tls.dll_pending_tls_owner);
720 
721 		return LWS_SSL_CAPABLE_DONE;
722 	}
723 
724 	m = lws_ssl_get_error(wsi, n);
725 	lws_tls_err_describe_clear();
726 
727 	if (m == SSL_ERROR_SYSCALL || m == SSL_ERROR_SSL)
728 		return LWS_SSL_CAPABLE_ERROR;
729 
730 	if (m == SSL_ERROR_WANT_READ ||
731 	    (m != SSL_ERROR_ZERO_RETURN && SSL_want_read(wsi->tls.ssl))) {
732 		if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
733 			lwsl_info("%s: WANT_READ change_pollfd failed\n",
734 				  __func__);
735 			return LWS_SSL_CAPABLE_ERROR;
736 		}
737 
738 		lwsl_info("SSL_ERROR_WANT_READ: m %d\n", m);
739 		return LWS_SSL_CAPABLE_MORE_SERVICE_READ;
740 	}
741 	if (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->tls.ssl)) {
742 		lwsl_debug("%s: WANT_WRITE\n", __func__);
743 
744 		if (lws_change_pollfd(wsi, 0, LWS_POLLOUT)) {
745 			lwsl_info("%s: WANT_WRITE change_pollfd failed\n",
746 				  __func__);
747 			return LWS_SSL_CAPABLE_ERROR;
748 		}
749 		return LWS_SSL_CAPABLE_MORE_SERVICE_WRITE;
750 	}
751 
752 	return LWS_SSL_CAPABLE_ERROR;
753 }
754 
755 #if defined(LWS_WITH_ACME)
756 static int
757 lws_tls_openssl_rsa_new_key(RSA **rsa, int bits)
758 {
759 	BIGNUM *bn = BN_new();
760 	int n;
761 
762 	if (!bn)
763 		return 1;
764 
765 	if (BN_set_word(bn, RSA_F4) != 1) {
766 		BN_free(bn);
767 		return 1;
768 	}
769 
770 	*rsa = RSA_new();
771 	if (!*rsa) {
772 		BN_free(bn);
773 		return 1;
774 	}
775 
776 	n = RSA_generate_key_ex(*rsa, bits, bn, NULL);
777 	BN_free(bn);
778 	if (n == 1)
779 		return 0;
780 
781 	RSA_free(*rsa);
782 	*rsa = NULL;
783 
784 	return 1;
785 }
786 
787 struct lws_tls_ss_pieces {
788 	X509 *x509;
789 	EVP_PKEY *pkey;
790 	RSA *rsa;
791 };
792 
793 int
794 lws_tls_acme_sni_cert_create(struct lws_vhost *vhost, const char *san_a,
795 			     const char *san_b)
796 {
797 	GENERAL_NAMES *gens = sk_GENERAL_NAME_new_null();
798 	GENERAL_NAME *gen = NULL;
799 	ASN1_IA5STRING *ia5 = NULL;
800 	X509_NAME *name;
801 
802 	if (!gens)
803 		return 1;
804 
805 	vhost->tls.ss = lws_zalloc(sizeof(*vhost->tls.ss), "sni cert");
806 	if (!vhost->tls.ss) {
807 		GENERAL_NAMES_free(gens);
808 		return 1;
809 	}
810 
811 	vhost->tls.ss->x509 = X509_new();
812 	if (!vhost->tls.ss->x509)
813 		goto bail;
814 
815 	ASN1_INTEGER_set(X509_get_serialNumber(vhost->tls.ss->x509), 1);
816 	X509_gmtime_adj(X509_get_notBefore(vhost->tls.ss->x509), 0);
817 	X509_gmtime_adj(X509_get_notAfter(vhost->tls.ss->x509), 3600);
818 
819 	vhost->tls.ss->pkey = EVP_PKEY_new();
820 	if (!vhost->tls.ss->pkey)
821 		goto bail0;
822 
823 	if (lws_tls_openssl_rsa_new_key(&vhost->tls.ss->rsa, 4096))
824 		goto bail1;
825 
826 	if (!EVP_PKEY_assign_RSA(vhost->tls.ss->pkey, vhost->tls.ss->rsa))
827 		goto bail2;
828 
829 	X509_set_pubkey(vhost->tls.ss->x509, vhost->tls.ss->pkey);
830 
831 	name = X509_get_subject_name(vhost->tls.ss->x509);
832 	X509_NAME_add_entry_by_txt(name, "C",  MBSTRING_ASC,
833 				   (unsigned char *)"GB",          -1, -1, 0);
834 	X509_NAME_add_entry_by_txt(name, "O",  MBSTRING_ASC,
835 				   (unsigned char *)"somecompany", -1, -1, 0);
836 	if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_UTF8,
837 				   (unsigned char *)"temp.acme.invalid",
838 				   	   	   -1, -1, 0) != 1) {
839 		lwsl_notice("failed to add CN\n");
840 		goto bail2;
841 	}
842 	X509_set_issuer_name(vhost->tls.ss->x509, name);
843 
844 	/* add the SAN payloads */
845 
846 	gen = GENERAL_NAME_new();
847 	ia5 = ASN1_IA5STRING_new();
848 	if (!ASN1_STRING_set(ia5, san_a, -1)) {
849 		lwsl_notice("failed to set ia5\n");
850 		GENERAL_NAME_free(gen);
851 		goto bail2;
852 	}
853 	GENERAL_NAME_set0_value(gen, GEN_DNS, ia5);
854 	sk_GENERAL_NAME_push(gens, gen);
855 
856 	if (X509_add1_ext_i2d(vhost->tls.ss->x509, NID_subject_alt_name,
857 			    gens, 0, X509V3_ADD_APPEND) != 1)
858 		goto bail2;
859 
860 	GENERAL_NAMES_free(gens);
861 
862 	if (san_b && san_b[0]) {
863 		gens = sk_GENERAL_NAME_new_null();
864 		gen = GENERAL_NAME_new();
865 		ia5 = ASN1_IA5STRING_new();
866 		if (!ASN1_STRING_set(ia5, san_a, -1)) {
867 			lwsl_notice("failed to set ia5\n");
868 			GENERAL_NAME_free(gen);
869 			goto bail2;
870 		}
871 		GENERAL_NAME_set0_value(gen, GEN_DNS, ia5);
872 		sk_GENERAL_NAME_push(gens, gen);
873 
874 		if (X509_add1_ext_i2d(vhost->tls.ss->x509, NID_subject_alt_name,
875 				    gens, 0, X509V3_ADD_APPEND) != 1)
876 			goto bail2;
877 
878 		GENERAL_NAMES_free(gens);
879 	}
880 
881 	/* sign it with our private key */
882 	if (!X509_sign(vhost->tls.ss->x509, vhost->tls.ss->pkey, EVP_sha256()))
883 		goto bail2;
884 
885 #if 0
886 	{/* useful to take a sample of a working cert for mbedtls to crib */
887 		FILE *fp = fopen("/tmp/acme-temp-cert", "w+");
888 
889 		i2d_X509_fp(fp, vhost->tls.ss->x509);
890 		fclose(fp);
891 	}
892 #endif
893 
894 	/* tell the vhost to use our crafted certificate */
895 	SSL_CTX_use_certificate(vhost->tls.ssl_ctx, vhost->tls.ss->x509);
896 	/* and to use our generated private key */
897 	SSL_CTX_use_PrivateKey(vhost->tls.ssl_ctx, vhost->tls.ss->pkey);
898 
899 	return 0;
900 
901 bail2:
902 	RSA_free(vhost->tls.ss->rsa);
903 bail1:
904 	EVP_PKEY_free(vhost->tls.ss->pkey);
905 bail0:
906 	X509_free(vhost->tls.ss->x509);
907 bail:
908 	lws_free(vhost->tls.ss);
909 	GENERAL_NAMES_free(gens);
910 
911 	return 1;
912 }
913 
914 void
915 lws_tls_acme_sni_cert_destroy(struct lws_vhost *vhost)
916 {
917 	if (!vhost->tls.ss)
918 		return;
919 
920 	EVP_PKEY_free(vhost->tls.ss->pkey);
921 	X509_free(vhost->tls.ss->x509);
922 	lws_free_set_NULL(vhost->tls.ss);
923 }
924 
925 static int
926 lws_tls_openssl_add_nid(X509_NAME *name, int nid, const char *value)
927 {
928 	X509_NAME_ENTRY *e;
929 	int n;
930 
931 	if (!value || value[0] == '\0')
932 		value = "none";
933 
934 	e = X509_NAME_ENTRY_create_by_NID(NULL, nid, MBSTRING_ASC,
935 					  (unsigned char *)value, -1);
936 	if (!e)
937 		return 1;
938 	n = X509_NAME_add_entry(name, e, -1, 0);
939 	X509_NAME_ENTRY_free(e);
940 
941 	return n != 1;
942 }
943 
944 static int nid_list[] = {
945 	NID_countryName,		/* LWS_TLS_REQ_ELEMENT_COUNTRY */
946 	NID_stateOrProvinceName,	/* LWS_TLS_REQ_ELEMENT_STATE */
947 	NID_localityName,		/* LWS_TLS_REQ_ELEMENT_LOCALITY */
948 	NID_organizationName,		/* LWS_TLS_REQ_ELEMENT_ORGANIZATION */
949 	NID_commonName,			/* LWS_TLS_REQ_ELEMENT_COMMON_NAME */
950 	NID_subject_alt_name,		/* LWS_TLS_REQ_ELEMENT_SUBJECT_ALT_NAME */
951 	NID_pkcs9_emailAddress,		/* LWS_TLS_REQ_ELEMENT_EMAIL */
952 };
953 
954 int
955 lws_tls_acme_sni_csr_create(struct lws_context *context, const char *elements[],
956 			    uint8_t *csr, size_t csr_len, char **privkey_pem,
957 			    size_t *privkey_len)
958 {
959 	uint8_t *csr_in = csr;
960 	RSA *rsakey;
961 	X509_REQ *req;
962 	X509_NAME *subj;
963 	EVP_PKEY *pkey;
964 	char *p, *end;
965 	BIO *bio;
966 	long bio_len;
967 	int n, ret = -1;
968 
969 	if (lws_tls_openssl_rsa_new_key(&rsakey, 4096))
970 		return -1;
971 
972 	pkey = EVP_PKEY_new();
973 	if (!pkey)
974 		goto bail0;
975 	if (!EVP_PKEY_set1_RSA(pkey, rsakey))
976 		goto bail1;
977 
978 	req = X509_REQ_new();
979 	if (!req)
980 	        goto bail1;
981 
982 	X509_REQ_set_pubkey(req, pkey);
983 
984 	subj = X509_NAME_new();
985 	if (!subj)
986 		goto bail2;
987 
988 	for (n = 0; n < LWS_TLS_REQ_ELEMENT_COUNT; n++)
989 		if (elements[n] &&
990 			lws_tls_openssl_add_nid(subj, nid_list[n],
991 				elements[n])) {
992 				lwsl_notice("%s: failed to add element %d\n",
993 						__func__, n);
994 			goto bail3;
995 		}
996 
997 	if (X509_REQ_set_subject_name(req, subj) != 1)
998 		goto bail3;
999 
1000 	if (elements[LWS_TLS_REQ_ELEMENT_SUBJECT_ALT_NAME]) {
1001 		STACK_OF(X509_EXTENSION) *exts;
1002 		X509_EXTENSION *ext;
1003 		char san[256];
1004 
1005 		exts = sk_X509_EXTENSION_new_null();
1006 		if (!exts)
1007 			goto bail3;
1008 
1009 		lws_snprintf(san, sizeof(san), "DNS:%s,DNS:%s",
1010 				elements[LWS_TLS_REQ_ELEMENT_COMMON_NAME],
1011 				elements[LWS_TLS_REQ_ELEMENT_SUBJECT_ALT_NAME]);
1012 
1013 		ext = X509V3_EXT_conf_nid(NULL, NULL, NID_subject_alt_name,
1014 				san);
1015 		if (!ext) {
1016 			sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1017 			goto bail3;
1018 		}
1019 		sk_X509_EXTENSION_push(exts, ext);
1020 
1021 		if (!X509_REQ_add_extensions(req, exts)) {
1022 			sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1023 			goto bail3;
1024 		}
1025 		sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1026 	}
1027 
1028 	if (!X509_REQ_sign(req, pkey, EVP_sha256()))
1029 		goto bail3;
1030 
1031 	/*
1032 	 * issue the CSR as PEM to a BIO, and translate to b64urlenc without
1033 	 * headers, trailers, or whitespace
1034 	 */
1035 
1036 	bio = BIO_new(BIO_s_mem());
1037 	if (!bio)
1038 		goto bail3;
1039 
1040 	if (PEM_write_bio_X509_REQ(bio, req) != 1) {
1041 		BIO_free(bio);
1042 		goto bail3;
1043 	}
1044 
1045 	bio_len = BIO_get_mem_data(bio, &p);
1046 	end = p + bio_len;
1047 
1048 	/* strip the header line */
1049 	while (p < end && *p != '\n')
1050 		p++;
1051 
1052 	while (p < end && csr_len) {
1053 		if (*p == '\n') {
1054 			p++;
1055 			continue;
1056 		}
1057 
1058 		if (*p == '-')
1059 			break;
1060 
1061 		if (*p == '+')
1062 			*csr++ = '-';
1063 		else
1064 			if (*p == '/')
1065 				*csr++ = '_';
1066 			else
1067 				*csr++ = (uint8_t)*p;
1068 		p++;
1069 		csr_len--;
1070 	}
1071 	BIO_free(bio);
1072 	if (!csr_len) {
1073 		lwsl_notice("%s: need %ld for CSR\n", __func__, bio_len);
1074 		goto bail3;
1075 	}
1076 
1077 	/*
1078 	 * Also return the private key as a PEM in memory
1079 	 * (platform may not have a filesystem)
1080 	 */
1081 	bio = BIO_new(BIO_s_mem());
1082 	if (!bio)
1083 		goto bail3;
1084 
1085 	if (PEM_write_bio_PrivateKey(bio, pkey, NULL, NULL, 0, 0, NULL) != 1) {
1086 		BIO_free(bio);
1087 		goto bail3;
1088 	}
1089 	bio_len = BIO_get_mem_data(bio, &p);
1090 	*privkey_pem = malloc((unsigned long)bio_len); /* malloc so user code can own / free */
1091 	*privkey_len = (size_t)bio_len;
1092 	if (!*privkey_pem) {
1093 		lwsl_notice("%s: need %ld for private key\n", __func__,
1094 			    bio_len);
1095 		BIO_free(bio);
1096 		goto bail3;
1097 	}
1098 	memcpy(*privkey_pem, p, (unsigned int)(int)(long long)bio_len);
1099 	BIO_free(bio);
1100 
1101 	ret = lws_ptr_diff(csr, csr_in);
1102 
1103 bail3:
1104 	X509_NAME_free(subj);
1105 bail2:
1106 	X509_REQ_free(req);
1107 bail1:
1108 	EVP_PKEY_free(pkey);
1109 bail0:
1110 	RSA_free(rsakey);
1111 
1112 	return ret;
1113 }
1114 #endif
1115