xref: /freebsd/contrib/wpa/src/crypto/tls_openssl.c (revision 71e72c9e91c4b8007a4292e09669e8b549c29e97)
1 /*
2  * SSL/TLS interface functions for OpenSSL
3  * Copyright (c) 2004-2015, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  */
8 
9 #include "includes.h"
10 #ifdef CONFIG_TLS_ENGINE_TRUSTED_PATH
11 #include <sys/stat.h>
12 #include <limits.h>
13 #endif /* CONFIG_TLS_ENGINE_TRUSTED_PATH */
14 #ifdef CONFIG_TESTING_OPTIONS
15 #include <fcntl.h>
16 #endif /* CONFIG_TESTING_OPTIONS */
17 
18 #ifndef CONFIG_SMARTCARD
19 #ifndef OPENSSL_NO_ENGINE
20 #ifndef ANDROID
21 #define OPENSSL_NO_ENGINE
22 #endif
23 #endif
24 #endif
25 
26 #ifndef OPENSSL_NO_ENGINE
27 /* OpenSSL 3.0 has moved away from the engine API */
28 #define OPENSSL_SUPPRESS_DEPRECATED
29 #include <openssl/engine.h>
30 #endif /* OPENSSL_NO_ENGINE */
31 #include <openssl/ssl.h>
32 #include <openssl/err.h>
33 #include <openssl/opensslv.h>
34 #include <openssl/pkcs12.h>
35 #include <openssl/x509v3.h>
36 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
37 #include <openssl/core_names.h>
38 #include <openssl/decoder.h>
39 #include <openssl/param_build.h>
40 #include <openssl/store.h>
41 #include <openssl/provider.h>
42 #else /* OpenSSL version >= 3.0 */
43 #ifndef OPENSSL_NO_DSA
44 #include <openssl/dsa.h>
45 #endif
46 #ifndef OPENSSL_NO_DH
47 #include <openssl/dh.h>
48 #endif
49 #endif /* OpenSSL version >= 3.0 */
50 
51 #include "common.h"
52 #include "utils/list.h"
53 #include "crypto.h"
54 #include "sha1.h"
55 #include "sha256.h"
56 #include "tls.h"
57 #include "tls_openssl.h"
58 
59 #if !defined(CONFIG_FIPS) &&                             \
60     (defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) ||   \
61      defined(EAP_SERVER_FAST))
62 #define OPENSSL_NEED_EAP_FAST_PRF
63 #endif
64 
65 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || \
66 	defined(EAP_SERVER_FAST) || defined(EAP_TEAP) || \
67 	defined(EAP_SERVER_TEAP)
68 #define EAP_FAST_OR_TEAP
69 #endif
70 
71 
72 #if defined(OPENSSL_IS_BORINGSSL)
73 /* stack_index_t is the return type of OpenSSL's sk_XXX_num() functions. */
74 typedef size_t stack_index_t;
75 #else
76 typedef int stack_index_t;
77 #endif
78 
79 #ifdef SSL_set_tlsext_status_type
80 #ifndef OPENSSL_NO_TLSEXT
81 #define HAVE_OCSP
82 #include <openssl/ocsp.h>
83 #endif /* OPENSSL_NO_TLSEXT */
84 #endif /* SSL_set_tlsext_status_type */
85 
86 #if OPENSSL_VERSION_NUMBER < 0x10100000L && \
87     !defined(BORINGSSL_API_VERSION)
88 /*
89  * SSL_get_client_random() and SSL_get_server_random() were added in OpenSSL
90  * 1.1.0 and newer BoringSSL revisions. Provide compatibility wrappers for
91  * older versions.
92  */
93 
SSL_get_client_random(const SSL * ssl,unsigned char * out,size_t outlen)94 static size_t SSL_get_client_random(const SSL *ssl, unsigned char *out,
95 				    size_t outlen)
96 {
97 	if (!ssl->s3 || outlen < SSL3_RANDOM_SIZE)
98 		return 0;
99 	os_memcpy(out, ssl->s3->client_random, SSL3_RANDOM_SIZE);
100 	return SSL3_RANDOM_SIZE;
101 }
102 
103 
SSL_get_server_random(const SSL * ssl,unsigned char * out,size_t outlen)104 static size_t SSL_get_server_random(const SSL *ssl, unsigned char *out,
105 				    size_t outlen)
106 {
107 	if (!ssl->s3 || outlen < SSL3_RANDOM_SIZE)
108 		return 0;
109 	os_memcpy(out, ssl->s3->server_random, SSL3_RANDOM_SIZE);
110 	return SSL3_RANDOM_SIZE;
111 }
112 
113 
114 #ifdef OPENSSL_NEED_EAP_FAST_PRF
SSL_SESSION_get_master_key(const SSL_SESSION * session,unsigned char * out,size_t outlen)115 static size_t SSL_SESSION_get_master_key(const SSL_SESSION *session,
116 					 unsigned char *out, size_t outlen)
117 {
118 	if (!session || session->master_key_length < 0 ||
119 	    (size_t) session->master_key_length > outlen)
120 		return 0;
121 	if ((size_t) session->master_key_length < outlen)
122 		outlen = session->master_key_length;
123 	os_memcpy(out, session->master_key, outlen);
124 	return outlen;
125 }
126 #endif /* OPENSSL_NEED_EAP_FAST_PRF */
127 
128 #endif
129 
130 #if OPENSSL_VERSION_NUMBER < 0x10100000L
ASN1_STRING_get0_data(const ASN1_STRING * x)131 static const unsigned char * ASN1_STRING_get0_data(const ASN1_STRING *x)
132 {
133 	return ASN1_STRING_data((ASN1_STRING *) x);
134 }
135 #endif
136 
137 #ifdef ANDROID
138 #include <openssl/pem.h>
139 #include <keystore/keystore_get.h>
140 
BIO_from_keystore(const char * key)141 static BIO * BIO_from_keystore(const char *key)
142 {
143 	BIO *bio = NULL;
144 	uint8_t *value = NULL;
145 	int length = keystore_get(key, strlen(key), &value);
146 	if (length != -1 && (bio = BIO_new(BIO_s_mem())) != NULL)
147 		BIO_write(bio, value, length);
148 	free(value);
149 	return bio;
150 }
151 
152 
tls_add_ca_from_keystore(X509_STORE * ctx,const char * key_alias)153 static int tls_add_ca_from_keystore(X509_STORE *ctx, const char *key_alias)
154 {
155 	BIO *bio = BIO_from_keystore(key_alias);
156 	STACK_OF(X509_INFO) *stack = NULL;
157 	stack_index_t i;
158 
159 	if (bio) {
160 		stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
161 		BIO_free(bio);
162 	}
163 
164 	if (!stack) {
165 		wpa_printf(MSG_WARNING, "TLS: Failed to parse certificate: %s",
166 			   key_alias);
167 		return -1;
168 	}
169 
170 	for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
171 		X509_INFO *info = sk_X509_INFO_value(stack, i);
172 
173 		if (info->x509)
174 			X509_STORE_add_cert(ctx, info->x509);
175 		if (info->crl)
176 			X509_STORE_add_crl(ctx, info->crl);
177 	}
178 
179 	sk_X509_INFO_pop_free(stack, X509_INFO_free);
180 
181 	return 0;
182 }
183 
184 
tls_add_ca_from_keystore_encoded(X509_STORE * ctx,const char * encoded_key_alias)185 static int tls_add_ca_from_keystore_encoded(X509_STORE *ctx,
186 					    const char *encoded_key_alias)
187 {
188 	int rc = -1;
189 	int len = os_strlen(encoded_key_alias);
190 	unsigned char *decoded_alias;
191 
192 	if (len & 1) {
193 		wpa_printf(MSG_WARNING, "Invalid hex-encoded alias: %s",
194 			   encoded_key_alias);
195 		return rc;
196 	}
197 
198 	decoded_alias = os_malloc(len / 2 + 1);
199 	if (decoded_alias) {
200 		if (!hexstr2bin(encoded_key_alias, decoded_alias, len / 2)) {
201 			decoded_alias[len / 2] = '\0';
202 			rc = tls_add_ca_from_keystore(
203 				ctx, (const char *) decoded_alias);
204 		}
205 		os_free(decoded_alias);
206 	}
207 
208 	return rc;
209 }
210 
211 #endif /* ANDROID */
212 
213 static int tls_openssl_ref_count = 0;
214 static int tls_ex_idx_session = -1;
215 
216 struct tls_session_data {
217 	struct dl_list list;
218 	struct wpabuf *buf;
219 };
220 
221 struct tls_context {
222 	void (*event_cb)(void *ctx, enum tls_event ev,
223 			 union tls_event_data *data);
224 	void *cb_ctx;
225 	int cert_in_cb;
226 	char *ocsp_stapling_response;
227 	struct dl_list sessions; /* struct tls_session_data */
228 };
229 
230 static struct tls_context *tls_global = NULL;
231 
232 
233 struct tls_data {
234 	SSL_CTX *ssl;
235 	unsigned int tls_session_lifetime;
236 	int check_crl;
237 	int check_crl_strict;
238 	char *ca_cert;
239 	unsigned int crl_reload_interval;
240 	struct os_reltime crl_last_reload;
241 	char *check_cert_subject;
242 	char *openssl_ciphers;
243 };
244 
245 struct tls_connection {
246 	struct tls_context *context;
247 	struct tls_data *data;
248 	SSL_CTX *ssl_ctx;
249 	SSL *ssl;
250 	BIO *ssl_in, *ssl_out;
251 #if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
252 	ENGINE *engine;        /* functional reference to the engine */
253 #endif /* OPENSSL_NO_ENGINE */
254 	EVP_PKEY *private_key; /* the private key if using engine/provider */
255 	char *subject_match, *altsubject_match, *suffix_match, *domain_match;
256 	char *check_cert_subject;
257 	int read_alerts, write_alerts, failed;
258 
259 	tls_session_ticket_cb session_ticket_cb;
260 	void *session_ticket_cb_ctx;
261 
262 	/* SessionTicket received from OpenSSL hello_extension_cb (server) */
263 	u8 *session_ticket;
264 	size_t session_ticket_len;
265 
266 	unsigned int ca_cert_verify:1;
267 	unsigned int cert_probe:1;
268 	unsigned int server_cert_only:1;
269 	unsigned int invalid_hb_used:1;
270 	unsigned int success_data:1;
271 	unsigned int client_hello_generated:1;
272 	unsigned int server:1;
273 
274 	u8 srv_cert_hash[32];
275 
276 	unsigned int flags;
277 
278 	X509 *peer_cert;
279 	X509 *peer_issuer;
280 	X509 *peer_issuer_issuer;
281 	char *peer_subject; /* peer subject info for authenticated peer */
282 
283 	unsigned char client_random[SSL3_RANDOM_SIZE];
284 	unsigned char server_random[SSL3_RANDOM_SIZE];
285 
286 	u16 cipher_suite;
287 	int server_dh_prime_len;
288 };
289 
290 
tls_context_new(const struct tls_config * conf)291 static struct tls_context * tls_context_new(const struct tls_config *conf)
292 {
293 	struct tls_context *context = os_zalloc(sizeof(*context));
294 	if (context == NULL)
295 		return NULL;
296 	dl_list_init(&context->sessions);
297 	if (conf) {
298 		context->event_cb = conf->event_cb;
299 		context->cb_ctx = conf->cb_ctx;
300 		context->cert_in_cb = conf->cert_in_cb;
301 	}
302 	return context;
303 }
304 
305 
306 #ifdef CONFIG_NO_STDOUT_DEBUG
307 
_tls_show_errors(void)308 static void _tls_show_errors(void)
309 {
310 	unsigned long err;
311 
312 	while ((err = ERR_get_error())) {
313 		/* Just ignore the errors, since stdout is disabled */
314 	}
315 }
316 #define tls_show_errors(l, f, t) _tls_show_errors()
317 
318 #else /* CONFIG_NO_STDOUT_DEBUG */
319 
tls_show_errors(int level,const char * func,const char * txt)320 static void tls_show_errors(int level, const char *func, const char *txt)
321 {
322 	unsigned long err;
323 
324 	wpa_printf(level, "OpenSSL: %s - %s %s",
325 		   func, txt, ERR_error_string(ERR_get_error(), NULL));
326 
327 	while ((err = ERR_get_error())) {
328 		wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
329 			   ERR_error_string(err, NULL));
330 	}
331 }
332 
333 #endif /* CONFIG_NO_STDOUT_DEBUG */
334 
335 
tls_crl_cert_reload(const char * ca_cert,int check_crl)336 static X509_STORE * tls_crl_cert_reload(const char *ca_cert, int check_crl)
337 {
338 	int flags;
339 	X509_STORE *store;
340 
341 	store = X509_STORE_new();
342 	if (!store) {
343 		wpa_printf(MSG_DEBUG,
344 			   "OpenSSL: %s - failed to allocate new certificate store",
345 			   __func__);
346 		return NULL;
347 	}
348 
349 	if (ca_cert && X509_STORE_load_locations(store, ca_cert, NULL) != 1) {
350 		tls_show_errors(MSG_WARNING, __func__,
351 				"Failed to load root certificates");
352 		X509_STORE_free(store);
353 		return NULL;
354 	}
355 
356 	flags = check_crl ? X509_V_FLAG_CRL_CHECK : 0;
357 	if (check_crl == 2)
358 		flags |= X509_V_FLAG_CRL_CHECK_ALL;
359 
360 	X509_STORE_set_flags(store, flags);
361 
362 	return store;
363 }
364 
365 
366 #ifndef ANDROID
367 #ifdef OPENSSL_NO_ENGINE
368 
369 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
370 static OSSL_PROVIDER *openssl_pkcs11_provider = NULL;
371 #endif /* OpenSSL version >= 3.0 */
372 
openssl_load_pkcs11_provider(void)373 static void openssl_load_pkcs11_provider(void)
374 {
375 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
376 	if (openssl_pkcs11_provider)
377 		return;
378 
379 	openssl_pkcs11_provider = OSSL_PROVIDER_try_load(NULL, "pkcs11", 1);
380 	if (!openssl_pkcs11_provider)
381 		wpa_printf(MSG_WARNING, "PKCS11 provider not present");
382 #endif /* OpenSSL version >= 3.0 */
383 }
384 
385 
openssl_unload_pkcs11_provider(void)386 static void openssl_unload_pkcs11_provider(void)
387 {
388 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
389 	if (openssl_pkcs11_provider) {
390 		OSSL_PROVIDER_unload(openssl_pkcs11_provider);
391 		openssl_pkcs11_provider = NULL;
392 	}
393 #endif /* OpenSSL version >= 3.0 */
394 }
395 
396 
openssl_can_use_provider(const char * engine_id,const char * req)397 static bool openssl_can_use_provider(const char *engine_id, const char *req)
398 {
399 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
400 	if (!os_strcmp(engine_id, "pkcs11") && openssl_pkcs11_provider)
401 		return true;
402 
403 	wpa_printf(MSG_ERROR,
404 		   "Cannot find OpenSSL provider for '%s' (missing '%s')",
405 		   req, engine_id);
406 #endif /* OpenSSL version >= 3.0 */
407 	return false;
408 }
409 
410 
provider_load_key(const char * uri)411 static EVP_PKEY * provider_load_key(const char *uri)
412 {
413 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
414 	OSSL_STORE_CTX *store;
415 	OSSL_STORE_INFO *info;
416 	EVP_PKEY *key = NULL;
417 
418 	if (!uri) {
419 		tls_show_errors(MSG_ERROR, __func__,
420 				"Invalid NULL uri for key");
421 		goto err_key;
422 	}
423 
424 	store = OSSL_STORE_open(uri, NULL, NULL, NULL, NULL);
425 	if (!store) {
426 		wpa_printf(MSG_DEBUG, "Bad uri for private key:%s", uri);
427 
428 		tls_show_errors(MSG_ERROR, __func__,
429 				"Failed to open key store");
430 		goto err_key;
431 	}
432 
433 	if (os_strncmp(uri, "pkcs11:", 7) &&
434 	    os_strstr(uri, "type=private") == NULL) {
435 		/* This is a workaround for OpenSSL < 3.2.0 where the code fails
436 		 * to correctly source public keys unless explicitly requested
437 		 * via an expect hint. */
438 		if (OSSL_STORE_expect(store, OSSL_STORE_INFO_PUBKEY) != 1) {
439 			tls_show_errors(MSG_ERROR, __func__,
440 					"Failed to expect Public Key File");
441 			goto err_store;
442 		}
443 	}
444 
445 	while (!OSSL_STORE_eof(store)) {
446 		info = OSSL_STORE_load(store);
447 		if (!info) {
448 			if (OSSL_STORE_error(store))
449 				break;
450 			continue;
451 		}
452 		if ((OSSL_STORE_INFO_get_type(info)) == OSSL_STORE_INFO_PKEY)
453 			key = OSSL_STORE_INFO_get1_PKEY(info);
454 
455 		OSSL_STORE_INFO_free(info);
456 		if (key)
457 			break;
458 	}
459 
460 err_store:
461 	OSSL_STORE_close(store);
462 err_key:
463 	if (!key)
464 		wpa_printf(MSG_ERROR, "OpenSSL: Failed to load key from URI");
465 
466 	return key;
467 #else /* OpenSSL version >= 3.0 */
468 	return NULL;
469 #endif /* OpenSSL version >= 3.0 */
470 }
471 
472 
provider_load_cert(const char * cert_id)473 static X509 * provider_load_cert(const char *cert_id)
474 {
475 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
476 	OSSL_STORE_CTX *store;
477 	OSSL_STORE_INFO *info;
478 	X509 *cert = NULL;
479 
480 	if (!cert_id) {
481 		tls_show_errors(MSG_ERROR, __func__, "Invalid NULL uri");
482 		goto err_cert;
483 	}
484 
485 	store = OSSL_STORE_open(cert_id, NULL, NULL, NULL, NULL);
486 	if (!store) {
487 		tls_show_errors(MSG_ERROR, __func__, "Failed to open store");
488 		goto err_cert;
489 	}
490 
491 	while (!OSSL_STORE_eof(store)) {
492 		info = OSSL_STORE_load(store);
493 		if (!info) {
494 			if (OSSL_STORE_error(store))
495 				break;
496 			continue;
497 		}
498 		if ((OSSL_STORE_INFO_get_type(info)) == OSSL_STORE_INFO_CERT)
499 			cert = OSSL_STORE_INFO_get1_CERT(info);
500 
501 		OSSL_STORE_INFO_free(info);
502 		if (cert)
503 			break;
504 	}
505 	OSSL_STORE_close(store);
506 
507 err_cert:
508 	if (!cert)
509 		tls_show_errors(MSG_ERROR, __func__,
510 				"Failed to load cert from URI");
511 	return cert;
512 #else /* OpenSSL version >= 3.0 */
513 	return NULL;
514 #endif /* OpenSSL version >= 3.0 */
515 }
516 
517 #endif /* OPENSSL_NO_ENGINE */
518 #endif /* !ANDROID */
519 
520 
521 #ifdef CONFIG_NATIVE_WINDOWS
522 
523 /* Windows CryptoAPI and access to certificate stores */
524 #include <wincrypt.h>
525 
526 #ifdef __MINGW32_VERSION
527 /*
528  * MinGW does not yet include all the needed definitions for CryptoAPI, so
529  * define here whatever extra is needed.
530  */
531 #define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
532 #define CERT_STORE_READONLY_FLAG 0x00008000
533 #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
534 
535 #endif /* __MINGW32_VERSION */
536 
537 
538 struct cryptoapi_rsa_data {
539 	const CERT_CONTEXT *cert;
540 	HCRYPTPROV crypt_prov;
541 	DWORD key_spec;
542 	BOOL free_crypt_prov;
543 };
544 
545 
cryptoapi_error(const char * msg)546 static void cryptoapi_error(const char *msg)
547 {
548 	wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
549 		   msg, (unsigned int) GetLastError());
550 }
551 
552 
cryptoapi_rsa_pub_enc(int flen,const unsigned char * from,unsigned char * to,RSA * rsa,int padding)553 static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
554 				 unsigned char *to, RSA *rsa, int padding)
555 {
556 	wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
557 	return 0;
558 }
559 
560 
cryptoapi_rsa_pub_dec(int flen,const unsigned char * from,unsigned char * to,RSA * rsa,int padding)561 static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
562 				 unsigned char *to, RSA *rsa, int padding)
563 {
564 	wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
565 	return 0;
566 }
567 
568 
cryptoapi_rsa_priv_enc(int flen,const unsigned char * from,unsigned char * to,RSA * rsa,int padding)569 static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
570 				  unsigned char *to, RSA *rsa, int padding)
571 {
572 	struct cryptoapi_rsa_data *priv =
573 		(struct cryptoapi_rsa_data *) rsa->meth->app_data;
574 	HCRYPTHASH hash;
575 	DWORD hash_size, len, i;
576 	unsigned char *buf = NULL;
577 	int ret = 0;
578 
579 	if (priv == NULL) {
580 		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
581 		       ERR_R_PASSED_NULL_PARAMETER);
582 		return 0;
583 	}
584 
585 	if (padding != RSA_PKCS1_PADDING) {
586 		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
587 		       RSA_R_UNKNOWN_PADDING_TYPE);
588 		return 0;
589 	}
590 
591 	if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
592 		wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
593 			   __func__);
594 		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
595 		       RSA_R_INVALID_MESSAGE_LENGTH);
596 		return 0;
597 	}
598 
599 	if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
600 	{
601 		cryptoapi_error("CryptCreateHash failed");
602 		return 0;
603 	}
604 
605 	len = sizeof(hash_size);
606 	if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
607 			       0)) {
608 		cryptoapi_error("CryptGetHashParam failed");
609 		goto err;
610 	}
611 
612 	if ((int) hash_size != flen) {
613 		wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
614 			   (unsigned) hash_size, flen);
615 		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
616 		       RSA_R_INVALID_MESSAGE_LENGTH);
617 		goto err;
618 	}
619 	if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
620 		cryptoapi_error("CryptSetHashParam failed");
621 		goto err;
622 	}
623 
624 	len = RSA_size(rsa);
625 	buf = os_malloc(len);
626 	if (buf == NULL) {
627 		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
628 		goto err;
629 	}
630 
631 	if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
632 		cryptoapi_error("CryptSignHash failed");
633 		goto err;
634 	}
635 
636 	for (i = 0; i < len; i++)
637 		to[i] = buf[len - i - 1];
638 	ret = len;
639 
640 err:
641 	os_free(buf);
642 	CryptDestroyHash(hash);
643 
644 	return ret;
645 }
646 
647 
cryptoapi_rsa_priv_dec(int flen,const unsigned char * from,unsigned char * to,RSA * rsa,int padding)648 static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
649 				  unsigned char *to, RSA *rsa, int padding)
650 {
651 	wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
652 	return 0;
653 }
654 
655 
cryptoapi_free_data(struct cryptoapi_rsa_data * priv)656 static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
657 {
658 	if (priv == NULL)
659 		return;
660 	if (priv->crypt_prov && priv->free_crypt_prov)
661 		CryptReleaseContext(priv->crypt_prov, 0);
662 	if (priv->cert)
663 		CertFreeCertificateContext(priv->cert);
664 	os_free(priv);
665 }
666 
667 
cryptoapi_finish(RSA * rsa)668 static int cryptoapi_finish(RSA *rsa)
669 {
670 	cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
671 	os_free((void *) rsa->meth);
672 	rsa->meth = NULL;
673 	return 1;
674 }
675 
676 
cryptoapi_find_cert(const char * name,DWORD store)677 static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
678 {
679 	HCERTSTORE cs;
680 	const CERT_CONTEXT *ret = NULL;
681 
682 	cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
683 			   store | CERT_STORE_OPEN_EXISTING_FLAG |
684 			   CERT_STORE_READONLY_FLAG, L"MY");
685 	if (cs == NULL) {
686 		cryptoapi_error("Failed to open 'My system store'");
687 		return NULL;
688 	}
689 
690 	if (strncmp(name, "cert://", 7) == 0) {
691 		unsigned short wbuf[255];
692 		MultiByteToWideChar(CP_ACP, 0, name + 7, -1, wbuf, 255);
693 		ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
694 						 PKCS_7_ASN_ENCODING,
695 						 0, CERT_FIND_SUBJECT_STR,
696 						 wbuf, NULL);
697 	} else if (strncmp(name, "hash://", 7) == 0) {
698 		CRYPT_HASH_BLOB blob;
699 		int len;
700 		const char *hash = name + 7;
701 		unsigned char *buf;
702 
703 		len = os_strlen(hash) / 2;
704 		buf = os_malloc(len);
705 		if (buf && hexstr2bin(hash, buf, len) == 0) {
706 			blob.cbData = len;
707 			blob.pbData = buf;
708 			ret = CertFindCertificateInStore(cs,
709 							 X509_ASN_ENCODING |
710 							 PKCS_7_ASN_ENCODING,
711 							 0, CERT_FIND_HASH,
712 							 &blob, NULL);
713 		}
714 		os_free(buf);
715 	}
716 
717 	CertCloseStore(cs, 0);
718 
719 	return ret;
720 }
721 
722 
tls_cryptoapi_cert(SSL * ssl,const char * name)723 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
724 {
725 	X509 *cert = NULL;
726 	RSA *rsa = NULL, *pub_rsa;
727 	struct cryptoapi_rsa_data *priv;
728 	RSA_METHOD *rsa_meth;
729 
730 	if (name == NULL ||
731 	    (strncmp(name, "cert://", 7) != 0 &&
732 	     strncmp(name, "hash://", 7) != 0))
733 		return -1;
734 
735 	priv = os_zalloc(sizeof(*priv));
736 	rsa_meth = os_zalloc(sizeof(*rsa_meth));
737 	if (priv == NULL || rsa_meth == NULL) {
738 		wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
739 			   "for CryptoAPI RSA method");
740 		os_free(priv);
741 		os_free(rsa_meth);
742 		return -1;
743 	}
744 
745 	priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
746 	if (priv->cert == NULL) {
747 		priv->cert = cryptoapi_find_cert(
748 			name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
749 	}
750 	if (priv->cert == NULL) {
751 		wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
752 			   "'%s'", name);
753 		goto err;
754 	}
755 
756 	cert = d2i_X509(NULL,
757 			(const unsigned char **) &priv->cert->pbCertEncoded,
758 			priv->cert->cbCertEncoded);
759 	if (cert == NULL) {
760 		wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
761 			   "encoding");
762 		goto err;
763 	}
764 
765 	if (!CryptAcquireCertificatePrivateKey(priv->cert,
766 					       CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
767 					       NULL, &priv->crypt_prov,
768 					       &priv->key_spec,
769 					       &priv->free_crypt_prov)) {
770 		cryptoapi_error("Failed to acquire a private key for the "
771 				"certificate");
772 		goto err;
773 	}
774 
775 	rsa_meth->name = "Microsoft CryptoAPI RSA Method";
776 	rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
777 	rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
778 	rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
779 	rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
780 	rsa_meth->finish = cryptoapi_finish;
781 	rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
782 	rsa_meth->app_data = (char *) priv;
783 
784 	rsa = RSA_new();
785 	if (rsa == NULL) {
786 		SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
787 		       ERR_R_MALLOC_FAILURE);
788 		goto err;
789 	}
790 
791 	if (!SSL_use_certificate(ssl, cert)) {
792 		RSA_free(rsa);
793 		rsa = NULL;
794 		goto err;
795 	}
796 	pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
797 	X509_free(cert);
798 	cert = NULL;
799 
800 	rsa->n = BN_dup(pub_rsa->n);
801 	rsa->e = BN_dup(pub_rsa->e);
802 	if (!RSA_set_method(rsa, rsa_meth))
803 		goto err;
804 
805 	if (!SSL_use_RSAPrivateKey(ssl, rsa))
806 		goto err;
807 	RSA_free(rsa);
808 
809 	return 0;
810 
811 err:
812 	if (cert)
813 		X509_free(cert);
814 	if (rsa)
815 		RSA_free(rsa);
816 	else {
817 		os_free(rsa_meth);
818 		cryptoapi_free_data(priv);
819 	}
820 	return -1;
821 }
822 
823 
tls_cryptoapi_ca_cert(SSL_CTX * ssl_ctx,SSL * ssl,const char * name)824 static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
825 {
826 	HCERTSTORE cs;
827 	PCCERT_CONTEXT ctx = NULL;
828 	X509 *cert;
829 	char buf[128];
830 	const char *store;
831 #ifdef UNICODE
832 	WCHAR *wstore;
833 #endif /* UNICODE */
834 
835 	if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
836 		return -1;
837 
838 	store = name + 13;
839 #ifdef UNICODE
840 	wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
841 	if (wstore == NULL)
842 		return -1;
843 	wsprintf(wstore, L"%S", store);
844 	cs = CertOpenSystemStore(0, wstore);
845 	os_free(wstore);
846 #else /* UNICODE */
847 	cs = CertOpenSystemStore(0, store);
848 #endif /* UNICODE */
849 	if (cs == NULL) {
850 		wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
851 			   "'%s': error=%d", __func__, store,
852 			   (int) GetLastError());
853 		return -1;
854 	}
855 
856 	while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
857 		cert = d2i_X509(NULL,
858 				(const unsigned char **) &ctx->pbCertEncoded,
859 				ctx->cbCertEncoded);
860 		if (cert == NULL) {
861 			wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
862 				   "X509 DER encoding for CA cert");
863 			continue;
864 		}
865 
866 		X509_NAME_oneline(X509_get_subject_name(cert), buf,
867 				  sizeof(buf));
868 		wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
869 			   "system certificate store: subject='%s'", buf);
870 
871 		if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx),
872 					 cert)) {
873 			tls_show_errors(MSG_WARNING, __func__,
874 					"Failed to add ca_cert to OpenSSL "
875 					"certificate store");
876 		}
877 
878 		X509_free(cert);
879 	}
880 
881 	if (!CertCloseStore(cs, 0)) {
882 		wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
883 			   "'%s': error=%d", __func__, name + 13,
884 			   (int) GetLastError());
885 	}
886 
887 	return 0;
888 }
889 
890 
891 #else /* CONFIG_NATIVE_WINDOWS */
892 
tls_cryptoapi_cert(SSL * ssl,const char * name)893 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
894 {
895 	return -1;
896 }
897 
898 #endif /* CONFIG_NATIVE_WINDOWS */
899 
900 
ssl_info_cb(const SSL * ssl,int where,int ret)901 static void ssl_info_cb(const SSL *ssl, int where, int ret)
902 {
903 	const char *str;
904 	int w;
905 
906 	wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
907 	w = where & ~SSL_ST_MASK;
908 	if (w & SSL_ST_CONNECT)
909 		str = "SSL_connect";
910 	else if (w & SSL_ST_ACCEPT)
911 		str = "SSL_accept";
912 	else
913 		str = "undefined";
914 
915 	if (where & SSL_CB_LOOP) {
916 		wpa_printf(MSG_DEBUG, "SSL: %s:%s",
917 			   str, SSL_state_string_long(ssl));
918 	} else if (where & SSL_CB_ALERT) {
919 		struct tls_connection *conn = SSL_get_app_data((SSL *) ssl);
920 		wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
921 			   where & SSL_CB_READ ?
922 			   "read (remote end reported an error)" :
923 			   "write (local SSL3 detected an error)",
924 			   SSL_alert_type_string_long(ret),
925 			   SSL_alert_desc_string_long(ret));
926 		if ((ret >> 8) == SSL3_AL_FATAL) {
927 			if (where & SSL_CB_READ)
928 				conn->read_alerts++;
929 			else
930 				conn->write_alerts++;
931 		}
932 		if (conn->context->event_cb != NULL) {
933 			union tls_event_data ev;
934 			struct tls_context *context = conn->context;
935 			os_memset(&ev, 0, sizeof(ev));
936 			ev.alert.is_local = !(where & SSL_CB_READ);
937 			ev.alert.type = SSL_alert_type_string_long(ret);
938 			ev.alert.description = SSL_alert_desc_string_long(ret);
939 			context->event_cb(context->cb_ctx, TLS_ALERT, &ev);
940 		}
941 	} else if (where & SSL_CB_EXIT && ret <= 0) {
942 		wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
943 			   str, ret == 0 ? "failed" : "error",
944 			   SSL_state_string_long(ssl));
945 	}
946 }
947 
948 
949 #ifndef OPENSSL_NO_ENGINE
950 /**
951  * tls_engine_load_dynamic_generic - load any openssl engine
952  * @pre: an array of commands and values that load an engine initialized
953  *       in the engine specific function
954  * @post: an array of commands and values that initialize an already loaded
955  *        engine (or %NULL if not required)
956  * @id: the engine id of the engine to load (only required if post is not %NULL
957  *
958  * This function is a generic function that loads any openssl engine.
959  *
960  * Returns: 0 on success, -1 on failure
961  */
tls_engine_load_dynamic_generic(const char * pre[],const char * post[],const char * id)962 static int tls_engine_load_dynamic_generic(const char *pre[],
963 					   const char *post[], const char *id)
964 {
965 	ENGINE *engine;
966 	const char *dynamic_id = "dynamic";
967 
968 	engine = ENGINE_by_id(id);
969 	if (engine) {
970 		wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
971 			   "available", id);
972 		/*
973 		 * If it was auto-loaded by ENGINE_by_id() we might still
974 		 * need to tell it which PKCS#11 module to use in legacy
975 		 * (non-p11-kit) environments. Do so now; even if it was
976 		 * properly initialised before, setting it again will be
977 		 * harmless.
978 		 */
979 		goto found;
980 	}
981 	ERR_clear_error();
982 
983 	engine = ENGINE_by_id(dynamic_id);
984 	if (engine == NULL) {
985 		wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
986 			   dynamic_id,
987 			   ERR_error_string(ERR_get_error(), NULL));
988 		return -1;
989 	}
990 
991 	/* Perform the pre commands. This will load the engine. */
992 	while (pre && pre[0]) {
993 		wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
994 		if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
995 			wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
996 				   "%s %s [%s]", pre[0], pre[1],
997 				   ERR_error_string(ERR_get_error(), NULL));
998 			ENGINE_free(engine);
999 			return -1;
1000 		}
1001 		pre += 2;
1002 	}
1003 
1004 	/*
1005 	 * Free the reference to the "dynamic" engine. The loaded engine can
1006 	 * now be looked up using ENGINE_by_id().
1007 	 */
1008 	ENGINE_free(engine);
1009 
1010 	engine = ENGINE_by_id(id);
1011 	if (engine == NULL) {
1012 		wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
1013 			   id, ERR_error_string(ERR_get_error(), NULL));
1014 		return -1;
1015 	}
1016  found:
1017 	while (post && post[0]) {
1018 		wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
1019 		if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
1020 			wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
1021 				" %s %s [%s]", post[0], post[1],
1022 				   ERR_error_string(ERR_get_error(), NULL));
1023 			ENGINE_remove(engine);
1024 			ENGINE_free(engine);
1025 			return -1;
1026 		}
1027 		post += 2;
1028 	}
1029 	ENGINE_free(engine);
1030 
1031 	return 0;
1032 }
1033 
1034 
1035 #ifdef CONFIG_TLS_ENGINE_TRUSTED_PATH
1036 
1037 #define TRUSTED_PATH "/usr/lib/"
1038 
1039 /**
1040  * tls_engine_path_trusted - Verify engine .so path is trusted for loading
1041  * @path: Engine/module path supplied via configuration or D-Bus
1042  * @real_path: Buffer for the canonical path (PATH_MAX bytes)
1043  * Returns: 0 if trusted (real_path filled), -1 otherwise
1044  *
1045  * The PKCS#11/OpenSC engine and module shared object paths are loaded with
1046  * dlopen() within this process, which may be running with elevated
1047  * privileges. Verify that the supplied path cannot be used to load an
1048  * attacker-controlled shared library by requiring, in addition to being
1049  * located under the trusted path, that the target is a regular file owned by
1050  * root, not writable by group or others, and that every ancestor directory up
1051  * to the file is itself a directory, owned by root and not writable by group
1052  * or others (otherwise a root-owned file could be swapped by whoever controls
1053  * such a directory). lstat() is used for the file check so that a symlink is
1054  * never followed, even though realpath() has already canonicalised the path.
1055  */
tls_engine_path_trusted(const char * path,char * real_path)1056 static int tls_engine_path_trusted(const char *path, char *real_path)
1057 {
1058 	struct stat st;
1059 	char dir[PATH_MAX];
1060 	char *slash, *next;
1061 
1062 	if (!path)
1063 		return -1;
1064 
1065 	if (!realpath(path, real_path)) {
1066 		wpa_printf(MSG_INFO,
1067 			   "ENGINE: Refusing to load %s: realpath: %s",
1068 			   path, strerror(errno));
1069 		return -1;
1070 	}
1071 
1072 	if (os_strncmp(TRUSTED_PATH, real_path, os_strlen(TRUSTED_PATH)) != 0) {
1073 		wpa_printf(MSG_INFO,
1074 			   "ENGINE: Refusing to load %s: not in trusted path %s",
1075 			   real_path, TRUSTED_PATH);
1076 		return -1;
1077 	}
1078 
1079 	if (lstat(real_path, &st) != 0 || !S_ISREG(st.st_mode) ||
1080 	    st.st_uid != 0 || (st.st_mode & (S_IWGRP | S_IWOTH))) {
1081 		wpa_printf(MSG_INFO,
1082 			   "ENGINE: Refusing to load %s: not a root-owned, non-writable regular file",
1083 			   real_path);
1084 		return -1;
1085 	}
1086 
1087 	os_strlcpy(dir, real_path, sizeof(dir));
1088 	slash = dir;
1089 	while ((next = os_strchr(slash + 1, '/')) {
1090 		*next = '\0';
1091 		if (stat(dir, &st) != 0 || !S_ISDIR(st.st_mode) ||
1092 		    st.st_uid != 0 || (st.st_mode & (S_IWGRP | S_IWOTH))) {
1093 			wpa_printf(MSG_INFO,
1094 				   "ENGINE: Refusing to load %s: insecure ancestor directory %s",
1095 				   real_path, dir);
1096 			return -1;
1097 		}
1098 		*next = '/';
1099 		slash = next;
1100 	}
1101 
1102 	return 0;
1103 }
1104 
1105 #endif /* CONFIG_TLS_ENGINE_TRUSTED_PATH */
1106 
1107 
1108 /**
1109  * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
1110  * @pkcs11_so_path: pksc11_so_path from the configuration
1111  * @pcks11_module_path: pkcs11_module_path from the configuration
1112  */
1113 static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
1114 					  const char *pkcs11_module_path)
1115 {
1116 	char *engine_id = "pkcs11";
1117 #ifdef CONFIG_TLS_ENGINE_TRUSTED_PATH
1118 	char real_pkcs11_so_path[PATH_MAX];
1119 	char real_pkcs11_module_path[PATH_MAX];
1120 #endif /* CONFIG_TLS_ENGINE_TRUSTED_PATH */
1121 	const char *pre_cmd[] = {
1122 		"SO_PATH", NULL /* pkcs11_so_path */,
1123 		"ID", NULL /* engine_id */,
1124 		"LIST_ADD", "1",
1125 		/* "NO_VCHECK", "1", */
1126 		"LOAD", NULL,
1127 		NULL, NULL
1128 	};
1129 	const char *post_cmd[] = {
1130 		"MODULE_PATH", NULL /* pkcs11_module_path */,
1131 		NULL, NULL
1132 	};
1133 
1134 	if (!pkcs11_so_path)
1135 		return 0;
1136 
1137 #ifdef CONFIG_TLS_ENGINE_TRUSTED_PATH
1138 	if (tls_engine_path_trusted(pkcs11_so_path, real_pkcs11_so_path) < 0)
1139 		return -1;
1140 	pre_cmd[1] = real_pkcs11_so_path;
1141 #else /* CONFIG_TLS_ENGINE_TRUSTED_PATH */
1142 	pre_cmd[1] = pkcs11_so_path;
1143 #endif /* CONFIG_TLS_ENGINE_TRUSTED_PATH */
1144 	pre_cmd[3] = engine_id;
1145 #ifdef CONFIG_TLS_ENGINE_TRUSTED_PATH
1146 	if (pkcs11_module_path) {
1147 		if (tls_engine_path_trusted(pkcs11_module_path,
1148 					    real_pkcs11_module_path) < 0)
1149 			return -1;
1150 		post_cmd[1] = real_pkcs11_module_path;
1151 	} else {
1152 		post_cmd[0] = NULL;
1153 	}
1154 #else /* CONFIG_TLS_ENGINE_TRUSTED_PATH */
1155 	if (pkcs11_module_path)
1156 		post_cmd[1] = pkcs11_module_path;
1157 	else
1158 		post_cmd[0] = NULL;
1159 #endif /* CONFIG_TLS_ENGINE_TRUSTED_PATH */
1160 
1161 	wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
1162 		   pkcs11_so_path);
1163 
1164 	return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
1165 }
1166 
1167 
1168 /**
1169  * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
1170  * @opensc_so_path: opensc_so_path from the configuration
1171  */
1172 static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
1173 {
1174 	char *engine_id = "opensc";
1175 #ifdef CONFIG_TLS_ENGINE_TRUSTED_PATH
1176 	char real_opensc_so_path[PATH_MAX];
1177 #endif /* CONFIG_TLS_ENGINE_TRUSTED_PATH */
1178 	const char *pre_cmd[] = {
1179 		"SO_PATH", NULL /* opensc_so_path */,
1180 		"ID", NULL /* engine_id */,
1181 		"LIST_ADD", "1",
1182 		"LOAD", NULL,
1183 		NULL, NULL
1184 	};
1185 
1186 	if (!opensc_so_path)
1187 		return 0;
1188 
1189 #ifdef CONFIG_TLS_ENGINE_TRUSTED_PATH
1190 	if (tls_engine_path_trusted(opensc_so_path, real_opensc_so_path) < 0)
1191 		return -1;
1192 	pre_cmd[1] = real_opensc_so_path;
1193 #else /* CONFIG_TLS_ENGINE_TRUSTED_PATH */
1194 	pre_cmd[1] = opensc_so_path;
1195 #endif /* CONFIG_TLS_ENGINE_TRUSTED_PATH */
1196 	pre_cmd[3] = engine_id;
1197 
1198 	wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
1199 		   opensc_so_path);
1200 
1201 	return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
1202 }
1203 #endif /* OPENSSL_NO_ENGINE */
1204 
1205 
1206 static struct tls_session_data * get_session_data(struct tls_context *context,
1207 						  const struct wpabuf *buf)
1208 {
1209 	struct tls_session_data *data;
1210 
1211 	dl_list_for_each(data, &context->sessions, struct tls_session_data,
1212 			 list) {
1213 		if (data->buf == buf)
1214 			return data;
1215 	}
1216 
1217 	return NULL;
1218 }
1219 
1220 
1221 static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *sess)
1222 {
1223 	struct wpabuf *buf;
1224 	struct tls_context *context;
1225 	struct tls_session_data *found;
1226 
1227 	wpa_printf(MSG_DEBUG,
1228 		   "OpenSSL: Remove session %p (tls_ex_idx_session=%d)", sess,
1229 		   tls_ex_idx_session);
1230 
1231 	if (tls_ex_idx_session < 0)
1232 		return;
1233 	buf = SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
1234 	if (!buf)
1235 		return;
1236 
1237 	context = SSL_CTX_get_app_data(ctx);
1238 	SSL_SESSION_set_ex_data(sess, tls_ex_idx_session, NULL);
1239 	found = get_session_data(context, buf);
1240 	if (!found) {
1241 		wpa_printf(MSG_DEBUG,
1242 			   "OpenSSL: Do not free application session data %p (sess %p)",
1243 			   buf, sess);
1244 		return;
1245 	}
1246 
1247 	dl_list_del(&found->list);
1248 	os_free(found);
1249 	wpa_printf(MSG_DEBUG,
1250 		   "OpenSSL: Free application session data %p (sess %p)",
1251 		   buf, sess);
1252 	wpabuf_free(buf);
1253 }
1254 
1255 
1256 void * tls_init(const struct tls_config *conf)
1257 {
1258 	struct tls_data *data;
1259 	SSL_CTX *ssl;
1260 	struct tls_context *context;
1261 	const char *ciphers;
1262 #ifndef OPENSSL_NO_ENGINE
1263 #ifdef CONFIG_OPENSC_ENGINE_PATH
1264 	char const * const opensc_engine_path = CONFIG_OPENSC_ENGINE_PATH;
1265 #else /* CONFIG_OPENSC_ENGINE_PATH */
1266 	char const * const opensc_engine_path =
1267 		conf ? conf->opensc_engine_path : NULL;
1268 #endif /* CONFIG_OPENSC_ENGINE_PATH */
1269 #ifdef CONFIG_PKCS11_ENGINE_PATH
1270 	char const * const pkcs11_engine_path = CONFIG_PKCS11_ENGINE_PATH;
1271 #else /* CONFIG_PKCS11_ENGINE_PATH */
1272 	char const * const pkcs11_engine_path =
1273 		conf ? conf->pkcs11_engine_path : NULL;
1274 #endif /* CONFIG_PKCS11_ENGINE_PATH */
1275 #ifdef CONFIG_PKCS11_MODULE_PATH
1276 	char const * const pkcs11_module_path = CONFIG_PKCS11_MODULE_PATH;
1277 #else /* CONFIG_PKCS11_MODULE_PATH */
1278 	char const * const pkcs11_module_path =
1279 		conf ? conf->pkcs11_module_path : NULL;
1280 #endif /* CONFIG_PKCS11_MODULE_PATH */
1281 #endif /* OPENSSL_NO_ENGINE */
1282 
1283 	if (tls_openssl_ref_count == 0) {
1284 		void openssl_load_legacy_provider(void);
1285 
1286 		openssl_load_legacy_provider();
1287 #if !defined(ANDROID) && defined(OPENSSL_NO_ENGINE)
1288 		openssl_load_pkcs11_provider();
1289 #endif /* !ANDROID && OPENSSL_NO_ENGINE */
1290 
1291 		tls_global = context = tls_context_new(conf);
1292 		if (context == NULL)
1293 			return NULL;
1294 #ifdef CONFIG_FIPS
1295 #ifdef OPENSSL_FIPS
1296 		if (conf && conf->fips_mode) {
1297 			static int fips_enabled = 0;
1298 
1299 			if (!fips_enabled && !FIPS_mode_set(1)) {
1300 				wpa_printf(MSG_ERROR, "Failed to enable FIPS "
1301 					   "mode");
1302 				ERR_load_crypto_strings();
1303 				ERR_print_errors_fp(stderr);
1304 				os_free(tls_global);
1305 				tls_global = NULL;
1306 				return NULL;
1307 			} else {
1308 				wpa_printf(MSG_INFO, "Running in FIPS mode");
1309 				fips_enabled = 1;
1310 			}
1311 		}
1312 #else /* OPENSSL_FIPS */
1313 		if (conf && conf->fips_mode) {
1314 			wpa_printf(MSG_ERROR, "FIPS mode requested, but not "
1315 				   "supported");
1316 			os_free(tls_global);
1317 			tls_global = NULL;
1318 			return NULL;
1319 		}
1320 #endif /* OPENSSL_FIPS */
1321 #endif /* CONFIG_FIPS */
1322 #if OPENSSL_VERSION_NUMBER < 0x10100000L
1323 		SSL_load_error_strings();
1324 		SSL_library_init();
1325 #ifndef OPENSSL_NO_SHA256
1326 		EVP_add_digest(EVP_sha256());
1327 #endif /* OPENSSL_NO_SHA256 */
1328 		/* TODO: if /dev/urandom is available, PRNG is seeded
1329 		 * automatically. If this is not the case, random data should
1330 		 * be added here. */
1331 
1332 #ifdef PKCS12_FUNCS
1333 #ifndef OPENSSL_NO_RC2
1334 		/*
1335 		 * 40-bit RC2 is commonly used in PKCS#12 files, so enable it.
1336 		 * This is enabled by PKCS12_PBE_add() in OpenSSL 0.9.8
1337 		 * versions, but it looks like OpenSSL 1.0.0 does not do that
1338 		 * anymore.
1339 		 */
1340 		EVP_add_cipher(EVP_rc2_40_cbc());
1341 #endif /* OPENSSL_NO_RC2 */
1342 		PKCS12_PBE_add();
1343 #endif  /* PKCS12_FUNCS */
1344 #endif /* < 1.1.0 */
1345 	} else {
1346 		context = tls_context_new(conf);
1347 		if (context == NULL)
1348 			return NULL;
1349 	}
1350 	tls_openssl_ref_count++;
1351 
1352 	data = os_zalloc(sizeof(*data));
1353 	if (data)
1354 		ssl = SSL_CTX_new(SSLv23_method());
1355 	else
1356 		ssl = NULL;
1357 	if (ssl == NULL) {
1358 		tls_show_errors(MSG_INFO, "SSL_CTX_new", "init");
1359 		tls_openssl_ref_count--;
1360 		if (context != tls_global)
1361 			os_free(context);
1362 		if (tls_openssl_ref_count == 0) {
1363 			os_free(tls_global);
1364 			tls_global = NULL;
1365 		}
1366 		os_free(data);
1367 		return NULL;
1368 	}
1369 	data->ssl = ssl;
1370 	if (conf) {
1371 		data->tls_session_lifetime = conf->tls_session_lifetime;
1372 		data->crl_reload_interval = conf->crl_reload_interval;
1373 	}
1374 
1375 	SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv2);
1376 	SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv3);
1377 
1378 	SSL_CTX_set_mode(ssl, SSL_MODE_AUTO_RETRY);
1379 
1380 #ifdef SSL_MODE_NO_AUTO_CHAIN
1381 	/* Number of deployed use cases assume the default OpenSSL behavior of
1382 	 * auto chaining the local certificate is in use. BoringSSL removed this
1383 	 * functionality by default, so we need to restore it here to avoid
1384 	 * breaking existing use cases. */
1385 	SSL_CTX_clear_mode(ssl, SSL_MODE_NO_AUTO_CHAIN);
1386 #endif /* SSL_MODE_NO_AUTO_CHAIN */
1387 
1388 	SSL_CTX_set_info_callback(ssl, ssl_info_cb);
1389 	SSL_CTX_set_app_data(ssl, context);
1390 	if (data->tls_session_lifetime > 0) {
1391 		SSL_CTX_set_quiet_shutdown(ssl, 1);
1392 		/*
1393 		 * Set default context here. In practice, this will be replaced
1394 		 * by the per-EAP method context in tls_connection_set_verify().
1395 		 */
1396 		SSL_CTX_set_session_id_context(ssl, (u8 *) "hostapd", 7);
1397 		SSL_CTX_set_session_cache_mode(ssl, SSL_SESS_CACHE_SERVER);
1398 		SSL_CTX_set_timeout(ssl, data->tls_session_lifetime);
1399 		SSL_CTX_sess_set_remove_cb(ssl, remove_session_cb);
1400 #if OPENSSL_VERSION_NUMBER >= 0x10101000L && \
1401 	!defined(LIBRESSL_VERSION_NUMBER) && \
1402 	!defined(OPENSSL_IS_BORINGSSL)
1403 		/* One session ticket is sufficient for EAP-TLS */
1404 		SSL_CTX_set_num_tickets(ssl, 1);
1405 #endif
1406 	} else {
1407 		SSL_CTX_set_session_cache_mode(ssl, SSL_SESS_CACHE_OFF);
1408 #if OPENSSL_VERSION_NUMBER >= 0x10101000L && \
1409 	!defined(LIBRESSL_VERSION_NUMBER) && \
1410 	!defined(OPENSSL_IS_BORINGSSL)
1411 		SSL_CTX_set_num_tickets(ssl, 0);
1412 #endif
1413 	}
1414 
1415 	if (tls_ex_idx_session < 0) {
1416 		tls_ex_idx_session = SSL_SESSION_get_ex_new_index(
1417 			0, NULL, NULL, NULL, NULL);
1418 		if (tls_ex_idx_session < 0) {
1419 			tls_deinit(data);
1420 			return NULL;
1421 		}
1422 	}
1423 
1424 #ifndef OPENSSL_NO_ENGINE
1425 	wpa_printf(MSG_DEBUG, "ENGINE: Loading builtin engines");
1426 	ENGINE_load_builtin_engines();
1427 
1428 	if (opensc_engine_path || pkcs11_engine_path || pkcs11_module_path) {
1429 		if (tls_engine_load_dynamic_opensc(opensc_engine_path) ||
1430 		    tls_engine_load_dynamic_pkcs11(pkcs11_engine_path,
1431 						   pkcs11_module_path)) {
1432 			tls_deinit(data);
1433 			return NULL;
1434 		}
1435 	}
1436 #endif /* OPENSSL_NO_ENGINE */
1437 
1438 	if (conf && conf->openssl_ciphers)
1439 		ciphers = conf->openssl_ciphers;
1440 	else
1441 		ciphers = TLS_DEFAULT_CIPHERS;
1442 	if (SSL_CTX_set_cipher_list(ssl, ciphers) != 1) {
1443 		wpa_printf(MSG_ERROR,
1444 			   "OpenSSL: Failed to set cipher string '%s'",
1445 			   ciphers);
1446 		tls_deinit(data);
1447 		return NULL;
1448 	}
1449 
1450 	return data;
1451 }
1452 
1453 
1454 void tls_deinit(void *ssl_ctx)
1455 {
1456 	struct tls_data *data = ssl_ctx;
1457 	SSL_CTX *ssl = data->ssl;
1458 	struct tls_context *context = SSL_CTX_get_app_data(ssl);
1459 	struct tls_session_data *sess_data;
1460 
1461 	if (data->tls_session_lifetime > 0) {
1462 		wpa_printf(MSG_DEBUG, "OpenSSL: Flush sessions");
1463 #if OPENSSL_VERSION_NUMBER >= 0x30400000L && \
1464 	!defined(LIBRESSL_VERSION_NUMBER) && \
1465 	!defined(OPENSSL_IS_BORINGSSL)
1466 		SSL_CTX_flush_sessions_ex(ssl, 0);
1467 #else /* OpenSSL version >= 3.4 */
1468 		SSL_CTX_flush_sessions(ssl, 0);
1469 #endif /* OpenSSL version >= 3.4 */
1470 		wpa_printf(MSG_DEBUG, "OpenSSL: Flush sessions - done");
1471 	}
1472 	while ((sess_data = dl_list_first(&context->sessions,
1473 					  struct tls_session_data, list))) {
1474 		wpa_printf(MSG_DEBUG,
1475 			   "OpenSSL: Freeing not-flushed session data %p",
1476 			   sess_data->buf);
1477 		wpabuf_free(sess_data->buf);
1478 		dl_list_del(&sess_data->list);
1479 		os_free(sess_data);
1480 	}
1481 	if (context != tls_global)
1482 		os_free(context);
1483 	os_free(data->ca_cert);
1484 	SSL_CTX_free(ssl);
1485 
1486 	tls_openssl_ref_count--;
1487 	if (tls_openssl_ref_count == 0) {
1488 #if !defined(ANDROID) && defined(OPENSSL_NO_ENGINE)
1489 		openssl_unload_pkcs11_provider();
1490 #endif /* !ANDROID && OPENSSL_NO_ENGINE */
1491 #if OPENSSL_VERSION_NUMBER < 0x10100000L
1492 #ifndef OPENSSL_NO_ENGINE
1493 		ENGINE_cleanup();
1494 #endif /* OPENSSL_NO_ENGINE */
1495 		CRYPTO_cleanup_all_ex_data();
1496 		ERR_remove_thread_state(NULL);
1497 		ERR_free_strings();
1498 		EVP_cleanup();
1499 #endif /* < 1.1.0 */
1500 		os_free(tls_global->ocsp_stapling_response);
1501 		tls_global->ocsp_stapling_response = NULL;
1502 		os_free(tls_global);
1503 		tls_global = NULL;
1504 	}
1505 
1506 	os_free(data->check_cert_subject);
1507 	os_free(data->openssl_ciphers);
1508 	os_free(data);
1509 }
1510 
1511 
1512 #ifndef OPENSSL_NO_ENGINE
1513 
1514 /* Cryptoki return values */
1515 #define CKR_PIN_INCORRECT 0x000000a0
1516 #define CKR_PIN_INVALID 0x000000a1
1517 #define CKR_PIN_LEN_RANGE 0x000000a2
1518 
1519 /* libp11 */
1520 #define ERR_LIB_PKCS11	ERR_LIB_USER
1521 
1522 static int tls_is_pin_error(unsigned int err)
1523 {
1524 	return ERR_GET_LIB(err) == ERR_LIB_PKCS11 &&
1525 		(ERR_GET_REASON(err) == CKR_PIN_INCORRECT ||
1526 		 ERR_GET_REASON(err) == CKR_PIN_INVALID ||
1527 		 ERR_GET_REASON(err) == CKR_PIN_LEN_RANGE);
1528 }
1529 
1530 #endif /* OPENSSL_NO_ENGINE */
1531 
1532 
1533 #ifdef ANDROID
1534 /* EVP_PKEY_from_keystore comes from system/security/keystore-engine. */
1535 EVP_PKEY * EVP_PKEY_from_keystore(const char *key_id);
1536 #endif /* ANDROID */
1537 
1538 static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
1539 			   const char *pin, const char *key_id,
1540 			   const char *cert_id, const char *ca_cert_id)
1541 {
1542 #if defined(ANDROID) && defined(OPENSSL_IS_BORINGSSL)
1543 #if !defined(OPENSSL_NO_ENGINE)
1544 #error "This code depends on OPENSSL_NO_ENGINE being defined by BoringSSL."
1545 #endif
1546 	if (!key_id)
1547 		return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1548 	conn->engine = NULL;
1549 	conn->private_key = EVP_PKEY_from_keystore(key_id);
1550 	if (!conn->private_key) {
1551 		wpa_printf(MSG_ERROR,
1552 			   "ENGINE: cannot load private key with id '%s' [%s]",
1553 			   key_id,
1554 			   ERR_error_string(ERR_get_error(), NULL));
1555 		return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1556 	}
1557 #endif /* ANDROID && OPENSSL_IS_BORINGSSL */
1558 
1559 #ifndef OPENSSL_NO_ENGINE
1560 	int ret = -1;
1561 	if (engine_id == NULL) {
1562 		wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
1563 		return -1;
1564 	}
1565 
1566 	ERR_clear_error();
1567 #ifdef ANDROID
1568 	ENGINE_load_dynamic();
1569 #endif
1570 	conn->engine = ENGINE_by_id(engine_id);
1571 	if (!conn->engine) {
1572 		wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
1573 			   engine_id, ERR_error_string(ERR_get_error(), NULL));
1574 		goto err;
1575 	}
1576 	if (ENGINE_init(conn->engine) != 1) {
1577 		wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
1578 			   "(engine: %s) [%s]", engine_id,
1579 			   ERR_error_string(ERR_get_error(), NULL));
1580 		goto err;
1581 	}
1582 	wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
1583 
1584 #ifndef ANDROID
1585 	if (pin && ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
1586 		wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
1587 			   ERR_error_string(ERR_get_error(), NULL));
1588 		goto err;
1589 	}
1590 #endif
1591 	if (key_id) {
1592 		/*
1593 		 * Ensure that the ENGINE does not attempt to use the OpenSSL
1594 		 * UI system to obtain a PIN, if we didn't provide one.
1595 		 */
1596 		struct {
1597 			const void *password;
1598 			const char *prompt_info;
1599 		} key_cb = { "", NULL };
1600 
1601 		/* load private key first in-case PIN is required for cert */
1602 		conn->private_key = ENGINE_load_private_key(conn->engine,
1603 							    key_id, NULL,
1604 							    &key_cb);
1605 		if (!conn->private_key) {
1606 			unsigned long err = ERR_get_error();
1607 
1608 			wpa_printf(MSG_ERROR,
1609 				   "ENGINE: cannot load private key with id '%s' [%s]",
1610 				   key_id,
1611 				   ERR_error_string(err, NULL));
1612 			if (tls_is_pin_error(err))
1613 				ret = TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
1614 			else
1615 				ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1616 			goto err;
1617 		}
1618 	}
1619 
1620 	/* handle a certificate and/or CA certificate */
1621 	if (cert_id || ca_cert_id) {
1622 		const char *cmd_name = "LOAD_CERT_CTRL";
1623 
1624 		/* test if the engine supports a LOAD_CERT_CTRL */
1625 		if (!ENGINE_ctrl(conn->engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
1626 				 0, (void *)cmd_name, NULL)) {
1627 			wpa_printf(MSG_ERROR, "ENGINE: engine does not support"
1628 				   " loading certificates");
1629 			ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1630 			goto err;
1631 		}
1632 	}
1633 
1634 	return 0;
1635 
1636 err:
1637 	if (conn->engine) {
1638 		ENGINE_free(conn->engine);
1639 		conn->engine = NULL;
1640 	}
1641 
1642 	if (conn->private_key) {
1643 		EVP_PKEY_free(conn->private_key);
1644 		conn->private_key = NULL;
1645 	}
1646 
1647 	return ret;
1648 #else /* OPENSSL_NO_ENGINE */
1649 #ifndef ANDROID
1650 	conn->private_key = provider_load_key(key_id);
1651 	if (!conn->private_key)
1652 		return -1;
1653 #endif /* !ANDROID */
1654 
1655 	return 0;
1656 #endif /* OPENSSL_NO_ENGINE */
1657 }
1658 
1659 
1660 static void tls_engine_deinit(struct tls_connection *conn)
1661 {
1662 	if (conn->private_key) {
1663 		EVP_PKEY_free(conn->private_key);
1664 		conn->private_key = NULL;
1665 	}
1666 #if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
1667 	wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
1668 	if (conn->engine) {
1669 #if !defined(OPENSSL_IS_BORINGSSL)
1670 		ENGINE_finish(conn->engine);
1671 #endif /* !OPENSSL_IS_BORINGSSL */
1672 		conn->engine = NULL;
1673 	}
1674 #endif /* ANDROID || !OPENSSL_NO_ENGINE */
1675 }
1676 
1677 
1678 int tls_get_errors(void *ssl_ctx)
1679 {
1680 	int count = 0;
1681 	unsigned long err;
1682 
1683 	while ((err = ERR_get_error())) {
1684 		wpa_printf(MSG_INFO, "TLS - SSL error: %s",
1685 			   ERR_error_string(err, NULL));
1686 		count++;
1687 	}
1688 
1689 	return count;
1690 }
1691 
1692 
1693 static const char * openssl_content_type(int content_type)
1694 {
1695 	switch (content_type) {
1696 	case 20:
1697 		return "change cipher spec";
1698 	case 21:
1699 		return "alert";
1700 	case 22:
1701 		return "handshake";
1702 	case 23:
1703 		return "application data";
1704 	case 24:
1705 		return "heartbeat";
1706 	case 256:
1707 		return "TLS header info"; /* pseudo content type */
1708 	case 257:
1709 		return "inner content type"; /* pseudo content type */
1710 	default:
1711 		return "?";
1712 	}
1713 }
1714 
1715 
1716 static const char * openssl_handshake_type(int content_type, const u8 *buf,
1717 					   size_t len)
1718 {
1719 	if (content_type == 257 && buf && len == 1)
1720 		return openssl_content_type(buf[0]);
1721 	if (content_type != 22 || !buf || len == 0)
1722 		return "";
1723 	switch (buf[0]) {
1724 	case 0:
1725 		return "hello request";
1726 	case 1:
1727 		return "client hello";
1728 	case 2:
1729 		return "server hello";
1730 	case 3:
1731 		return "hello verify request";
1732 	case 4:
1733 		return "new session ticket";
1734 	case 5:
1735 		return "end of early data";
1736 	case 6:
1737 		return "hello retry request";
1738 	case 8:
1739 		return "encrypted extensions";
1740 	case 11:
1741 		return "certificate";
1742 	case 12:
1743 		return "server key exchange";
1744 	case 13:
1745 		return "certificate request";
1746 	case 14:
1747 		return "server hello done";
1748 	case 15:
1749 		return "certificate verify";
1750 	case 16:
1751 		return "client key exchange";
1752 	case 20:
1753 		return "finished";
1754 	case 21:
1755 		return "certificate url";
1756 	case 22:
1757 		return "certificate status";
1758 	case 23:
1759 		return "supplemental data";
1760 	case 24:
1761 		return "key update";
1762 	case 254:
1763 		return "message hash";
1764 	default:
1765 		return "?";
1766 	}
1767 }
1768 
1769 
1770 #ifdef CONFIG_SUITEB
1771 
1772 static void check_server_hello(struct tls_connection *conn,
1773 			       const u8 *pos, const u8 *end)
1774 {
1775 	size_t payload_len, id_len;
1776 
1777 	/*
1778 	 * Parse ServerHello to get the selected cipher suite since OpenSSL does
1779 	 * not make it cleanly available during handshake and we need to know
1780 	 * whether DHE was selected.
1781 	 */
1782 
1783 	if (end - pos < 3)
1784 		return;
1785 	payload_len = WPA_GET_BE24(pos);
1786 	pos += 3;
1787 
1788 	if ((size_t) (end - pos) < payload_len)
1789 		return;
1790 	end = pos + payload_len;
1791 
1792 	/* Skip Version and Random */
1793 	if (end - pos < 2 + SSL3_RANDOM_SIZE)
1794 		return;
1795 	pos += 2 + SSL3_RANDOM_SIZE;
1796 
1797 	/* Skip Session ID */
1798 	if (end - pos < 1)
1799 		return;
1800 	id_len = *pos++;
1801 	if ((size_t) (end - pos) < id_len)
1802 		return;
1803 	pos += id_len;
1804 
1805 	if (end - pos < 2)
1806 		return;
1807 	conn->cipher_suite = WPA_GET_BE16(pos);
1808 	wpa_printf(MSG_DEBUG, "OpenSSL: Server selected cipher suite 0x%x",
1809 		   conn->cipher_suite);
1810 }
1811 
1812 
1813 static void check_server_key_exchange(SSL *ssl, struct tls_connection *conn,
1814 				      const u8 *pos, const u8 *end)
1815 {
1816 	size_t payload_len;
1817 	u16 dh_len;
1818 	BIGNUM *p;
1819 	int bits;
1820 
1821 	if (!(conn->flags & TLS_CONN_SUITEB))
1822 		return;
1823 
1824 	/* DHE is enabled only with DHE-RSA-AES256-GCM-SHA384 */
1825 	if (conn->cipher_suite != 0x9f)
1826 		return;
1827 
1828 	if (end - pos < 3)
1829 		return;
1830 	payload_len = WPA_GET_BE24(pos);
1831 	pos += 3;
1832 
1833 	if ((size_t) (end - pos) < payload_len)
1834 		return;
1835 	end = pos + payload_len;
1836 
1837 	if (end - pos < 2)
1838 		return;
1839 	dh_len = WPA_GET_BE16(pos);
1840 	pos += 2;
1841 
1842 	if ((size_t) (end - pos) < dh_len)
1843 		return;
1844 	p = BN_bin2bn(pos, dh_len, NULL);
1845 	if (!p)
1846 		return;
1847 
1848 	bits = BN_num_bits(p);
1849 	BN_free(p);
1850 
1851 	conn->server_dh_prime_len = bits;
1852 	wpa_printf(MSG_DEBUG, "OpenSSL: Server DH prime length: %d bits",
1853 		   conn->server_dh_prime_len);
1854 }
1855 
1856 #endif /* CONFIG_SUITEB */
1857 
1858 
1859 static void tls_msg_cb(int write_p, int version, int content_type,
1860 		       const void *buf, size_t len, SSL *ssl, void *arg)
1861 {
1862 	struct tls_connection *conn = arg;
1863 	const u8 *pos = buf;
1864 
1865 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
1866 	if ((SSL_version(ssl) == TLS1_VERSION ||
1867 	     SSL_version(ssl) == TLS1_1_VERSION) &&
1868 	    SSL_get_security_level(ssl) > 0) {
1869 		wpa_printf(MSG_DEBUG,
1870 			   "OpenSSL: Drop security level to 0 to allow TLS 1.0/1.1 use of MD5-SHA1 signature algorithm");
1871 		SSL_set_security_level(ssl, 0);
1872 	}
1873 #endif /* OpenSSL version >= 3.0 */
1874 	if (write_p == 2) {
1875 		wpa_printf(MSG_DEBUG,
1876 			   "OpenSSL: session ver=0x%x content_type=%d",
1877 			   version, content_type);
1878 		wpa_hexdump_key(MSG_MSGDUMP, "OpenSSL: Data", buf, len);
1879 		return;
1880 	}
1881 
1882 	wpa_printf(MSG_DEBUG, "OpenSSL: %s ver=0x%x content_type=%d (%s/%s)",
1883 		   write_p ? "TX" : "RX", version, content_type,
1884 		   openssl_content_type(content_type),
1885 		   openssl_handshake_type(content_type, buf, len));
1886 	wpa_hexdump_key(MSG_MSGDUMP, "OpenSSL: Message", buf, len);
1887 	if (content_type == 24 && len >= 3 && pos[0] == 1) {
1888 		size_t payload_len = WPA_GET_BE16(pos + 1);
1889 		if (payload_len + 3 > len) {
1890 			wpa_printf(MSG_ERROR, "OpenSSL: Heartbeat attack detected");
1891 			conn->invalid_hb_used = 1;
1892 		}
1893 	}
1894 
1895 #ifdef CONFIG_SUITEB
1896 	/*
1897 	 * Need to parse these handshake messages to be able to check DH prime
1898 	 * length since OpenSSL does not expose the new cipher suite and DH
1899 	 * parameters during handshake (e.g., for cert_cb() callback).
1900 	 */
1901 	if (content_type == 22 && pos && len > 0 && pos[0] == 2)
1902 		check_server_hello(conn, pos + 1, pos + len);
1903 	if (content_type == 22 && pos && len > 0 && pos[0] == 12)
1904 		check_server_key_exchange(ssl, conn, pos + 1, pos + len);
1905 #endif /* CONFIG_SUITEB */
1906 }
1907 
1908 
1909 #ifdef CONFIG_TESTING_OPTIONS
1910 #if OPENSSL_VERSION_NUMBER >= 0x10101000L && !defined(LIBRESSL_VERSION_NUMBER)
1911 /*
1912  * By setting the environment variable SSLKEYLOGFILE to a filename keying
1913  * material will be exported that you may use with Wireshark to decode any
1914  * TLS flows. Please see the following for more details:
1915  *
1916  *	https://gitlab.com/wireshark/wireshark/-/wikis/TLS#tls-decryption
1917  *
1918  * Example logging sessions are (you should delete the file on each run):
1919  *
1920  *	rm -f /tmp/sslkey.log
1921  *	env SSLKEYLOGFILE=/tmp/sslkey.log hostapd ...
1922  *
1923  *	rm -f /tmp/sslkey.log
1924  *	env SSLKEYLOGFILE=/tmp/sslkey.log wpa_supplicant ...
1925  *
1926  *	rm -f /tmp/sslkey.log
1927  *	env SSLKEYLOGFILE=/tmp/sslkey.log eapol_test ...
1928  */
1929 static void tls_keylog_cb(const SSL *ssl, const char *line)
1930 {
1931 	int fd;
1932 	const char *filename;
1933 	struct iovec iov[2];
1934 
1935 	filename = getenv("SSLKEYLOGFILE");
1936 	if (!filename)
1937 		return;
1938 
1939 	fd = open(filename, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR);
1940 	if (fd < 0) {
1941 		wpa_printf(MSG_ERROR,
1942 			   "OpenSSL: Failed to open keylog file %s: %s",
1943 			   filename, strerror(errno));
1944 		return;
1945 	}
1946 
1947 	/* Assume less than _POSIX_PIPE_BUF (512) where writes are guaranteed
1948 	 * to be atomic for O_APPEND. */
1949 	iov[0].iov_base = (void *) line;
1950 	iov[0].iov_len = os_strlen(line);
1951 	iov[1].iov_base = "\n";
1952 	iov[1].iov_len = 1;
1953 
1954 	if (writev(fd, iov, ARRAY_SIZE(iov)) < 01) {
1955 		wpa_printf(MSG_DEBUG,
1956 			   "OpenSSL: Failed to write to keylog file %s: %s",
1957 			   filename, strerror(errno));
1958 	}
1959 
1960 	close(fd);
1961 }
1962 #endif
1963 #endif /* CONFIG_TESTING_OPTIONS */
1964 
1965 
1966 struct tls_connection * tls_connection_init(void *ssl_ctx)
1967 {
1968 	struct tls_data *data = ssl_ctx;
1969 	SSL_CTX *ssl = data->ssl;
1970 	struct tls_connection *conn;
1971 	long options;
1972 	X509_STORE *new_cert_store;
1973 	struct os_reltime now;
1974 	struct tls_context *context = SSL_CTX_get_app_data(ssl);
1975 
1976 	/* Replace X509 store if it is time to update CRL. */
1977 	if (data->crl_reload_interval > 0 && os_get_reltime(&now) == 0 &&
1978 	    os_reltime_expired(&now, &data->crl_last_reload,
1979 			       data->crl_reload_interval)) {
1980 		wpa_printf(MSG_INFO,
1981 			   "OpenSSL: Flushing X509 store with ca_cert file");
1982 		new_cert_store = tls_crl_cert_reload(data->ca_cert,
1983 						     data->check_crl);
1984 		if (!new_cert_store) {
1985 			wpa_printf(MSG_ERROR,
1986 				   "OpenSSL: Error replacing X509 store with ca_cert file");
1987 		} else {
1988 			/* Replace old store */
1989 			SSL_CTX_set_cert_store(ssl, new_cert_store);
1990 			data->crl_last_reload = now;
1991 		}
1992 	}
1993 
1994 	conn = os_zalloc(sizeof(*conn));
1995 	if (conn == NULL)
1996 		return NULL;
1997 	conn->data = data;
1998 	conn->ssl_ctx = ssl;
1999 	conn->ssl = SSL_new(ssl);
2000 	if (conn->ssl == NULL) {
2001 		tls_show_errors(MSG_INFO, __func__,
2002 				"Failed to initialize new SSL connection");
2003 		os_free(conn);
2004 		return NULL;
2005 	}
2006 
2007 	conn->context = context;
2008 	SSL_set_app_data(conn->ssl, conn);
2009 	SSL_set_msg_callback(conn->ssl, tls_msg_cb);
2010 	SSL_set_msg_callback_arg(conn->ssl, conn);
2011 	options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
2012 		SSL_OP_SINGLE_DH_USE;
2013 #ifdef SSL_OP_NO_COMPRESSION
2014 	options |= SSL_OP_NO_COMPRESSION;
2015 #endif /* SSL_OP_NO_COMPRESSION */
2016 	SSL_set_options(conn->ssl, options);
2017 #ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
2018 	/* Hopefully there is no need for middlebox compatibility mechanisms
2019 	 * when going through EAP authentication. */
2020 	SSL_clear_options(conn->ssl, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
2021 #endif
2022 
2023 #ifdef CONFIG_TESTING_OPTIONS
2024 #if OPENSSL_VERSION_NUMBER >= 0x10101000L && !defined(LIBRESSL_VERSION_NUMBER)
2025 	/* Set the keylog file if the admin requested it. */
2026 	if (getenv("SSLKEYLOGFILE"))
2027 		SSL_CTX_set_keylog_callback(conn->ssl_ctx, tls_keylog_cb);
2028 #endif
2029 #endif /* CONFIG_TESTING_OPTIONS */
2030 
2031 	conn->ssl_in = BIO_new(BIO_s_mem());
2032 	if (!conn->ssl_in) {
2033 		tls_show_errors(MSG_INFO, __func__,
2034 				"Failed to create a new BIO for ssl_in");
2035 		SSL_free(conn->ssl);
2036 		os_free(conn);
2037 		return NULL;
2038 	}
2039 
2040 	conn->ssl_out = BIO_new(BIO_s_mem());
2041 	if (!conn->ssl_out) {
2042 		tls_show_errors(MSG_INFO, __func__,
2043 				"Failed to create a new BIO for ssl_out");
2044 		SSL_free(conn->ssl);
2045 		BIO_free(conn->ssl_in);
2046 		os_free(conn);
2047 		return NULL;
2048 	}
2049 
2050 	SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
2051 
2052 	return conn;
2053 }
2054 
2055 
2056 void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
2057 {
2058 	if (conn == NULL)
2059 		return;
2060 	if (conn->success_data) {
2061 		/*
2062 		 * Make sure ssl_clear_bad_session() does not remove this
2063 		 * session.
2064 		 */
2065 		SSL_set_quiet_shutdown(conn->ssl, 1);
2066 		SSL_shutdown(conn->ssl);
2067 	}
2068 	SSL_free(conn->ssl);
2069 	tls_engine_deinit(conn);
2070 	os_free(conn->subject_match);
2071 	os_free(conn->altsubject_match);
2072 	os_free(conn->suffix_match);
2073 	os_free(conn->domain_match);
2074 	os_free(conn->check_cert_subject);
2075 	os_free(conn->session_ticket);
2076 	os_free(conn->peer_subject);
2077 	os_free(conn);
2078 }
2079 
2080 
2081 int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
2082 {
2083 	return conn ? SSL_is_init_finished(conn->ssl) : 0;
2084 }
2085 
2086 
2087 char * tls_connection_peer_serial_num(void *tls_ctx,
2088 				      struct tls_connection *conn)
2089 {
2090 	ASN1_INTEGER *ser;
2091 	char *serial_num;
2092 	size_t len;
2093 
2094 	if (!conn->peer_cert)
2095 		return NULL;
2096 
2097 	ser = X509_get_serialNumber(conn->peer_cert);
2098 	if (!ser)
2099 		return NULL;
2100 
2101 	len = ASN1_STRING_length(ser) * 2 + 1;
2102 	serial_num = os_malloc(len);
2103 	if (!serial_num)
2104 		return NULL;
2105 	wpa_snprintf_hex_uppercase(serial_num, len,
2106 				   ASN1_STRING_get0_data(ser),
2107 				   ASN1_STRING_length(ser));
2108 	return serial_num;
2109 }
2110 
2111 
2112 int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
2113 {
2114 	if (conn == NULL)
2115 		return -1;
2116 
2117 	/* Shutdown previous TLS connection without notifying the peer
2118 	 * because the connection was already terminated in practice
2119 	 * and "close notify" shutdown alert would confuse AS. */
2120 	SSL_set_quiet_shutdown(conn->ssl, 1);
2121 	SSL_shutdown(conn->ssl);
2122 	return SSL_clear(conn->ssl) == 1 ? 0 : -1;
2123 }
2124 
2125 
2126 static int tls_match_altsubject_component(X509 *cert, int type,
2127 					  const char *value, size_t len)
2128 {
2129 	GENERAL_NAME *gen;
2130 	void *ext;
2131 	int found = 0;
2132 	stack_index_t i;
2133 
2134 	ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
2135 
2136 	for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
2137 		gen = sk_GENERAL_NAME_value(ext, i);
2138 		if (gen->type != type)
2139 			continue;
2140 		if ((size_t) ASN1_STRING_length(gen->d.ia5) == len &&
2141 		    os_memcmp(value, ASN1_STRING_get0_data(gen->d.ia5), len) ==
2142 		    0)
2143 			found++;
2144 	}
2145 
2146 	sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
2147 
2148 	return found;
2149 }
2150 
2151 
2152 static int tls_match_altsubject(X509 *cert, const char *match)
2153 {
2154 	int type;
2155 	const char *pos, *end;
2156 	size_t len;
2157 
2158 	pos = match;
2159 	do {
2160 		if (os_strncmp(pos, "EMAIL:", 6) == 0) {
2161 			type = GEN_EMAIL;
2162 			pos += 6;
2163 		} else if (os_strncmp(pos, "DNS:", 4) == 0) {
2164 			type = GEN_DNS;
2165 			pos += 4;
2166 		} else if (os_strncmp(pos, "URI:", 4) == 0) {
2167 			type = GEN_URI;
2168 			pos += 4;
2169 		} else {
2170 			wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
2171 				   "match '%s'", pos);
2172 			return 0;
2173 		}
2174 		end = os_strchr(pos, ';');
2175 		while (end) {
2176 			if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
2177 			    os_strncmp(end + 1, "DNS:", 4) == 0 ||
2178 			    os_strncmp(end + 1, "URI:", 4) == 0)
2179 				break;
2180 			end = os_strchr(end + 1, ';');
2181 		}
2182 		if (end)
2183 			len = end - pos;
2184 		else
2185 			len = os_strlen(pos);
2186 		if (tls_match_altsubject_component(cert, type, pos, len) > 0)
2187 			return 1;
2188 		if (!end)
2189 			break;
2190 		pos = end + 1;
2191 	} while (end);
2192 
2193 	return 0;
2194 }
2195 
2196 
2197 #ifndef CONFIG_NATIVE_WINDOWS
2198 static int domain_suffix_match(const u8 *val, size_t len, const char *match,
2199 			       size_t match_len, int full)
2200 {
2201 	size_t i;
2202 
2203 	/* Check for embedded nuls that could mess up suffix matching */
2204 	for (i = 0; i < len; i++) {
2205 		if (val[i] == '\0') {
2206 			wpa_printf(MSG_DEBUG, "TLS: Embedded null in a string - reject");
2207 			return 0;
2208 		}
2209 	}
2210 
2211 	if (match_len > len || (full && match_len != len))
2212 		return 0;
2213 
2214 	if (os_strncasecmp((const char *) val + len - match_len, match,
2215 			   match_len) != 0)
2216 		return 0; /* no match */
2217 
2218 	if (match_len == len)
2219 		return 1; /* exact match */
2220 
2221 	if (val[len - match_len - 1] == '.')
2222 		return 1; /* full label match completes suffix match */
2223 
2224 	wpa_printf(MSG_DEBUG, "TLS: Reject due to incomplete label match");
2225 	return 0;
2226 }
2227 #endif /* CONFIG_NATIVE_WINDOWS */
2228 
2229 
2230 struct tls_dn_field_order_cnt {
2231 	u8 cn;
2232 	u8 c;
2233 	u8 l;
2234 	u8 st;
2235 	u8 o;
2236 	u8 ou;
2237 	u8 email;
2238 };
2239 
2240 
2241 static int get_dn_field_index(const struct tls_dn_field_order_cnt *dn_cnt,
2242 			      int nid)
2243 {
2244 	switch (nid) {
2245 	case NID_commonName:
2246 		return dn_cnt->cn;
2247 	case NID_countryName:
2248 		return dn_cnt->c;
2249 	case NID_localityName:
2250 		return dn_cnt->l;
2251 	case NID_stateOrProvinceName:
2252 		return dn_cnt->st;
2253 	case NID_organizationName:
2254 		return dn_cnt->o;
2255 	case NID_organizationalUnitName:
2256 		return dn_cnt->ou;
2257 	case NID_pkcs9_emailAddress:
2258 		return dn_cnt->email;
2259 	default:
2260 		wpa_printf(MSG_ERROR,
2261 			   "TLS: Unknown NID '%d' in check_cert_subject",
2262 			   nid);
2263 		return -1;
2264 	}
2265 }
2266 
2267 
2268 /**
2269  * match_dn_field - Match configuration DN field against Certificate DN field
2270  * @cert: Certificate
2271  * @nid: NID of DN field
2272  * @field: Field name
2273  * @value DN field value which is passed from configuration
2274  *	e.g., if configuration have C=US and this argument will point to US.
2275  * @dn_cnt: DN matching context
2276  * Returns: 1 on success and 0 on failure
2277  */
2278 static int match_dn_field(const X509 *cert, int nid, const char *field,
2279 			  const char *value,
2280 			  const struct tls_dn_field_order_cnt *dn_cnt)
2281 {
2282 	int i, ret = 0, len, config_dn_field_index, match_index = 0;
2283 	const X509_NAME *name;
2284 
2285 	len = os_strlen(value);
2286 	name = X509_get_subject_name((X509 *) cert);
2287 
2288 	/* Assign incremented cnt for every field of DN to check DN field in
2289 	 * right order */
2290 	config_dn_field_index = get_dn_field_index(dn_cnt, nid);
2291 	if (config_dn_field_index < 0)
2292 		return 0;
2293 
2294 	/* Fetch value based on NID */
2295 	for (i = -1; (i = X509_NAME_get_index_by_NID((X509_NAME *) name, nid,
2296 						     i)) > -1;) {
2297 		const X509_NAME_ENTRY *e;
2298 		const ASN1_STRING *cn;
2299 
2300 		e = X509_NAME_get_entry(name, i);
2301 		if (!e)
2302 			continue;
2303 
2304 		cn = X509_NAME_ENTRY_get_data(e);
2305 		if (!cn)
2306 			continue;
2307 
2308 		match_index++;
2309 
2310 		/* check for more than one DN field with same name */
2311 		if (match_index != config_dn_field_index)
2312 			continue;
2313 
2314 		/* Check wildcard at the right end side */
2315 		/* E.g., if OU=develop* mentioned in configuration, allow 'OU'
2316 		 * of the subject in the client certificate to start with
2317 		 * 'develop' */
2318 		if (len > 0 && value[len - 1] == '*') {
2319 			/* Compare actual certificate DN field value with
2320 			 * configuration DN field value up to the specified
2321 			 * length. */
2322 			ret = ASN1_STRING_length(cn) >= len - 1 &&
2323 				os_memcmp(ASN1_STRING_get0_data(cn), value,
2324 					  len - 1) == 0;
2325 		} else {
2326 			/* Compare actual certificate DN field value with
2327 			 * configuration DN field value */
2328 			ret = ASN1_STRING_length(cn) == len &&
2329 				os_memcmp(ASN1_STRING_get0_data(cn), value,
2330 					  len) == 0;
2331 		}
2332 		if (!ret) {
2333 			wpa_printf(MSG_ERROR,
2334 				   "OpenSSL: Failed to match %s '%s' with certificate DN field value '%s'",
2335 				   field, value, ASN1_STRING_get0_data(cn));
2336 		}
2337 		break;
2338 	}
2339 
2340 	return ret;
2341 }
2342 
2343 
2344 /**
2345  * get_value_from_field - Get value from DN field
2346  * @cert: Certificate
2347  * @field_str: DN field string which is passed from configuration file (e.g.,
2348  *	 C=US)
2349  * @dn_cnt: DN matching context
2350  * Returns: 1 on success and 0 on failure
2351  */
2352 static int get_value_from_field(const X509 *cert, char *field_str,
2353 				struct tls_dn_field_order_cnt *dn_cnt)
2354 {
2355 	int nid;
2356 	char *context = NULL, *name, *value;
2357 
2358 	if (os_strcmp(field_str, "*") == 0)
2359 		return 1; /* wildcard matches everything */
2360 
2361 	name = str_token(field_str, "=", &context);
2362 	if (!name)
2363 		return 0;
2364 
2365 	/* Compare all configured DN fields and assign nid based on that to
2366 	 * fetch correct value from certificate subject */
2367 	if (os_strcmp(name, "CN") == 0) {
2368 		nid = NID_commonName;
2369 		dn_cnt->cn++;
2370 	} else if(os_strcmp(name, "C") == 0) {
2371 		nid = NID_countryName;
2372 		dn_cnt->c++;
2373 	} else if (os_strcmp(name, "L") == 0) {
2374 		nid = NID_localityName;
2375 		dn_cnt->l++;
2376 	} else if (os_strcmp(name, "ST") == 0) {
2377 		nid = NID_stateOrProvinceName;
2378 		dn_cnt->st++;
2379 	} else if (os_strcmp(name, "O") == 0) {
2380 		nid = NID_organizationName;
2381 		dn_cnt->o++;
2382 	} else if (os_strcmp(name, "OU") == 0) {
2383 		nid = NID_organizationalUnitName;
2384 		dn_cnt->ou++;
2385 	} else if (os_strcmp(name, "emailAddress") == 0) {
2386 		nid = NID_pkcs9_emailAddress;
2387 		dn_cnt->email++;
2388 	} else {
2389 		wpa_printf(MSG_ERROR,
2390 			"TLS: Unknown field '%s' in check_cert_subject", name);
2391 		return 0;
2392 	}
2393 
2394 	value = str_token(field_str, "=", &context);
2395 	if (!value) {
2396 		wpa_printf(MSG_ERROR,
2397 			   "TLS: Distinguished Name field '%s' value is not defined in check_cert_subject",
2398 			   name);
2399 		return 0;
2400 	}
2401 
2402 	return match_dn_field(cert, nid, name, value, dn_cnt);
2403 }
2404 
2405 
2406 /**
2407  * tls_match_dn_field - Match subject DN field with check_cert_subject
2408  * @cert: Certificate
2409  * @match: check_cert_subject string
2410  * Returns: Return 1 on success and 0 on failure
2411 */
2412 static int tls_match_dn_field(X509 *cert, const char *match)
2413 {
2414 	const char *token, *last = NULL;
2415 	char field[256];
2416 	struct tls_dn_field_order_cnt dn_cnt;
2417 
2418 	os_memset(&dn_cnt, 0, sizeof(dn_cnt));
2419 
2420 	/* Maximum length of each DN field is 255 characters */
2421 
2422 	/* Process each '/' delimited field */
2423 	while ((token = cstr_token(match, "/", &last))) {
2424 		if (last - token >= (int) sizeof(field)) {
2425 			wpa_printf(MSG_ERROR,
2426 				   "OpenSSL: Too long DN matching field value in '%s'",
2427 				   match);
2428 			return 0;
2429 		}
2430 		os_memcpy(field, token, last - token);
2431 		field[last - token] = '\0';
2432 
2433 		if (!get_value_from_field(cert, field, &dn_cnt)) {
2434 			wpa_printf(MSG_DEBUG, "OpenSSL: No match for DN '%s'",
2435 				   field);
2436 			return 0;
2437 		}
2438 	}
2439 
2440 	return 1;
2441 }
2442 
2443 
2444 #ifndef CONFIG_NATIVE_WINDOWS
2445 static int tls_match_suffix_helper(X509 *cert, const char *match,
2446 				   size_t match_len, int full)
2447 {
2448 	GENERAL_NAME *gen;
2449 	void *ext;
2450 	int i;
2451 	stack_index_t j;
2452 	int dns_name = 0;
2453 	const X509_NAME *name;
2454 
2455 	wpa_printf(MSG_DEBUG, "TLS: Match domain against %s%s",
2456 		   full ? "": "suffix ", match);
2457 
2458 	ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
2459 
2460 	for (j = 0; ext && j < sk_GENERAL_NAME_num(ext); j++) {
2461 		gen = sk_GENERAL_NAME_value(ext, j);
2462 		if (gen->type != GEN_DNS)
2463 			continue;
2464 		dns_name++;
2465 		wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate dNSName",
2466 				  ASN1_STRING_get0_data(gen->d.dNSName),
2467 				  ASN1_STRING_length(gen->d.dNSName));
2468 		if (domain_suffix_match(ASN1_STRING_get0_data(gen->d.dNSName),
2469 					ASN1_STRING_length(gen->d.dNSName),
2470 					match, match_len, full) == 1) {
2471 			wpa_printf(MSG_DEBUG, "TLS: %s in dNSName found",
2472 				   full ? "Match" : "Suffix match");
2473 			sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
2474 			return 1;
2475 		}
2476 	}
2477 	sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
2478 
2479 	if (dns_name) {
2480 		wpa_printf(MSG_DEBUG, "TLS: None of the dNSName(s) matched");
2481 		return 0;
2482 	}
2483 
2484 	name = X509_get_subject_name(cert);
2485 	i = -1;
2486 	for (;;) {
2487 		const X509_NAME_ENTRY *e;
2488 		const ASN1_STRING *cn;
2489 
2490 		i = X509_NAME_get_index_by_NID((X509_NAME *) name,
2491 					       NID_commonName, i);
2492 		if (i == -1)
2493 			break;
2494 		e = X509_NAME_get_entry(name, i);
2495 		if (e == NULL)
2496 			continue;
2497 		cn = X509_NAME_ENTRY_get_data(e);
2498 		if (cn == NULL)
2499 			continue;
2500 		wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate commonName",
2501 				  ASN1_STRING_get0_data(cn),
2502 				  ASN1_STRING_length(cn));
2503 		if (domain_suffix_match(ASN1_STRING_get0_data(cn),
2504 					ASN1_STRING_length(cn),
2505 					match, match_len, full) == 1) {
2506 			wpa_printf(MSG_DEBUG, "TLS: %s in commonName found",
2507 				   full ? "Match" : "Suffix match");
2508 			return 1;
2509 		}
2510 	}
2511 
2512 	wpa_printf(MSG_DEBUG, "TLS: No CommonName %smatch found",
2513 		   full ? "": "suffix ");
2514 	return 0;
2515 }
2516 #endif /* CONFIG_NATIVE_WINDOWS */
2517 
2518 
2519 static int tls_match_suffix(X509 *cert, const char *match, int full)
2520 {
2521 #ifdef CONFIG_NATIVE_WINDOWS
2522 	/* wincrypt.h has conflicting X509_NAME definition */
2523 	return -1;
2524 #else /* CONFIG_NATIVE_WINDOWS */
2525 	const char *token, *last = NULL;
2526 
2527 	/* Process each match alternative separately until a match is found */
2528 	while ((token = cstr_token(match, ";", &last))) {
2529 		if (tls_match_suffix_helper(cert, token, last - token, full))
2530 			return 1;
2531 	}
2532 
2533 	return 0;
2534 #endif /* CONFIG_NATIVE_WINDOWS */
2535 }
2536 
2537 
2538 static enum tls_fail_reason openssl_tls_fail_reason(int err)
2539 {
2540 	switch (err) {
2541 	case X509_V_ERR_CERT_REVOKED:
2542 		return TLS_FAIL_REVOKED;
2543 	case X509_V_ERR_CERT_NOT_YET_VALID:
2544 	case X509_V_ERR_CRL_NOT_YET_VALID:
2545 		return TLS_FAIL_NOT_YET_VALID;
2546 	case X509_V_ERR_CERT_HAS_EXPIRED:
2547 	case X509_V_ERR_CRL_HAS_EXPIRED:
2548 		return TLS_FAIL_EXPIRED;
2549 	case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
2550 	case X509_V_ERR_UNABLE_TO_GET_CRL:
2551 	case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
2552 	case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
2553 	case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
2554 	case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
2555 	case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
2556 	case X509_V_ERR_CERT_CHAIN_TOO_LONG:
2557 	case X509_V_ERR_PATH_LENGTH_EXCEEDED:
2558 	case X509_V_ERR_INVALID_CA:
2559 		return TLS_FAIL_UNTRUSTED;
2560 	case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
2561 	case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
2562 	case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
2563 	case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
2564 	case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
2565 	case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
2566 	case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
2567 	case X509_V_ERR_CERT_UNTRUSTED:
2568 	case X509_V_ERR_CERT_REJECTED:
2569 		return TLS_FAIL_BAD_CERTIFICATE;
2570 	default:
2571 		return TLS_FAIL_UNSPECIFIED;
2572 	}
2573 }
2574 
2575 
2576 static struct wpabuf * get_x509_cert(X509 *cert)
2577 {
2578 	struct wpabuf *buf;
2579 	u8 *tmp;
2580 
2581 	int cert_len = i2d_X509(cert, NULL);
2582 	if (cert_len <= 0)
2583 		return NULL;
2584 
2585 	buf = wpabuf_alloc(cert_len);
2586 	if (buf == NULL)
2587 		return NULL;
2588 
2589 	tmp = wpabuf_put(buf, cert_len);
2590 	i2d_X509(cert, &tmp);
2591 	return buf;
2592 }
2593 
2594 
2595 static void openssl_tls_fail_event(struct tls_connection *conn,
2596 				   X509 *err_cert, int err, int depth,
2597 				   const char *subject, const char *err_str,
2598 				   enum tls_fail_reason reason)
2599 {
2600 	union tls_event_data ev;
2601 	struct wpabuf *cert = NULL;
2602 	struct tls_context *context = conn->context;
2603 
2604 	if (context->event_cb == NULL)
2605 		return;
2606 
2607 	cert = get_x509_cert(err_cert);
2608 	os_memset(&ev, 0, sizeof(ev));
2609 	ev.cert_fail.reason = reason != TLS_FAIL_UNSPECIFIED ?
2610 		reason : openssl_tls_fail_reason(err);
2611 	ev.cert_fail.depth = depth;
2612 	ev.cert_fail.subject = subject;
2613 	ev.cert_fail.reason_txt = err_str;
2614 	ev.cert_fail.cert = cert;
2615 	context->event_cb(context->cb_ctx, TLS_CERT_CHAIN_FAILURE, &ev);
2616 	wpabuf_free(cert);
2617 }
2618 
2619 
2620 static int openssl_cert_tod(X509 *cert)
2621 {
2622 	CERTIFICATEPOLICIES *ext;
2623 	stack_index_t i;
2624 	char buf[100];
2625 	int res;
2626 	int tod = 0;
2627 
2628 	ext = X509_get_ext_d2i(cert, NID_certificate_policies, NULL, NULL);
2629 	if (!ext)
2630 		return 0;
2631 
2632 	for (i = 0; i < sk_POLICYINFO_num(ext); i++) {
2633 		POLICYINFO *policy;
2634 
2635 		policy = sk_POLICYINFO_value(ext, i);
2636 		res = OBJ_obj2txt(buf, sizeof(buf), policy->policyid, 0);
2637 		if (res < 0 || (size_t) res >= sizeof(buf))
2638 			continue;
2639 		wpa_printf(MSG_DEBUG, "OpenSSL: Certificate Policy %s", buf);
2640 		if (os_strcmp(buf, "1.3.6.1.4.1.40808.1.3.1") == 0)
2641 			tod = 1; /* TOD-STRICT */
2642 		else if (os_strcmp(buf, "1.3.6.1.4.1.40808.1.3.2") == 0 && !tod)
2643 			tod = 2; /* TOD-TOFU */
2644 	}
2645 	sk_POLICYINFO_pop_free(ext, POLICYINFO_free);
2646 
2647 	return tod;
2648 }
2649 
2650 
2651 static void openssl_tls_cert_event(struct tls_connection *conn,
2652 				   X509 *err_cert, int depth,
2653 				   const char *subject)
2654 {
2655 	struct wpabuf *cert = NULL;
2656 	union tls_event_data ev;
2657 	struct tls_context *context = conn->context;
2658 	char *altsubject[TLS_MAX_ALT_SUBJECT];
2659 	int alt, num_altsubject = 0;
2660 	GENERAL_NAME *gen;
2661 	void *ext;
2662 	stack_index_t i;
2663 	ASN1_INTEGER *ser;
2664 	char serial_num[128];
2665 #ifdef CONFIG_SHA256
2666 	u8 hash[32];
2667 #endif /* CONFIG_SHA256 */
2668 
2669 	if (context->event_cb == NULL)
2670 		return;
2671 
2672 	os_memset(&ev, 0, sizeof(ev));
2673 	if (conn->cert_probe || (conn->flags & TLS_CONN_EXT_CERT_CHECK) ||
2674 	    context->cert_in_cb) {
2675 		cert = get_x509_cert(err_cert);
2676 		ev.peer_cert.cert = cert;
2677 	}
2678 #ifdef CONFIG_SHA256
2679 	if (cert) {
2680 		const u8 *addr[1];
2681 		size_t len[1];
2682 		addr[0] = wpabuf_head(cert);
2683 		len[0] = wpabuf_len(cert);
2684 		if (sha256_vector(1, addr, len, hash) == 0) {
2685 			ev.peer_cert.hash = hash;
2686 			ev.peer_cert.hash_len = sizeof(hash);
2687 		}
2688 	}
2689 #endif /* CONFIG_SHA256 */
2690 	ev.peer_cert.depth = depth;
2691 	ev.peer_cert.subject = subject;
2692 
2693 	ser = X509_get_serialNumber(err_cert);
2694 	if (ser) {
2695 		wpa_snprintf_hex_uppercase(serial_num, sizeof(serial_num),
2696 					   ASN1_STRING_get0_data(ser),
2697 					   ASN1_STRING_length(ser));
2698 		ev.peer_cert.serial_num = serial_num;
2699 	}
2700 
2701 	ext = X509_get_ext_d2i(err_cert, NID_subject_alt_name, NULL, NULL);
2702 	for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
2703 		char *pos;
2704 
2705 		if (num_altsubject == TLS_MAX_ALT_SUBJECT)
2706 			break;
2707 		gen = sk_GENERAL_NAME_value(ext, i);
2708 		if (gen->type != GEN_EMAIL &&
2709 		    gen->type != GEN_DNS &&
2710 		    gen->type != GEN_URI)
2711 			continue;
2712 
2713 		pos = os_malloc(10 + ASN1_STRING_length(gen->d.ia5) + 1);
2714 		if (pos == NULL)
2715 			break;
2716 		altsubject[num_altsubject++] = pos;
2717 
2718 		switch (gen->type) {
2719 		case GEN_EMAIL:
2720 			os_memcpy(pos, "EMAIL:", 6);
2721 			pos += 6;
2722 			break;
2723 		case GEN_DNS:
2724 			os_memcpy(pos, "DNS:", 4);
2725 			pos += 4;
2726 			break;
2727 		case GEN_URI:
2728 			os_memcpy(pos, "URI:", 4);
2729 			pos += 4;
2730 			break;
2731 		}
2732 
2733 		os_memcpy(pos, ASN1_STRING_get0_data(gen->d.ia5),
2734 			  ASN1_STRING_length(gen->d.ia5));
2735 		pos += ASN1_STRING_length(gen->d.ia5);
2736 		*pos = '\0';
2737 	}
2738 	sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
2739 
2740 	for (alt = 0; alt < num_altsubject; alt++)
2741 		ev.peer_cert.altsubject[alt] = altsubject[alt];
2742 	ev.peer_cert.num_altsubject = num_altsubject;
2743 
2744 	ev.peer_cert.tod = openssl_cert_tod(err_cert);
2745 
2746 	context->event_cb(context->cb_ctx, TLS_PEER_CERTIFICATE, &ev);
2747 	wpabuf_free(cert);
2748 	for (alt = 0; alt < num_altsubject; alt++)
2749 		os_free(altsubject[alt]);
2750 }
2751 
2752 
2753 static void debug_print_cert(X509 *cert, const char *title)
2754 {
2755 #ifndef CONFIG_NO_STDOUT_DEBUG
2756 	BIO *out;
2757 	size_t rlen;
2758 	char *txt;
2759 	int res;
2760 
2761 	if (wpa_debug_level > MSG_DEBUG)
2762 		return;
2763 
2764 	out = BIO_new(BIO_s_mem());
2765 	if (!out)
2766 		return;
2767 
2768 	X509_print(out, cert);
2769 	rlen = BIO_ctrl_pending(out);
2770 	txt = os_malloc(rlen + 1);
2771 	if (txt) {
2772 		res = BIO_read(out, txt, rlen);
2773 		if (res > 0) {
2774 			txt[res] = '\0';
2775 			wpa_printf(MSG_DEBUG, "OpenSSL: %s\n%s", title, txt);
2776 		}
2777 		os_free(txt);
2778 	}
2779 
2780 	BIO_free(out);
2781 #endif /* CONFIG_NO_STDOUT_DEBUG */
2782 }
2783 
2784 
2785 static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
2786 {
2787 	char buf[256];
2788 	X509 *err_cert;
2789 	int err, depth;
2790 	SSL *ssl;
2791 	struct tls_connection *conn;
2792 	struct tls_context *context;
2793 	char *match, *altmatch, *suffix_match, *domain_match;
2794 	const char *check_cert_subject;
2795 	const char *err_str;
2796 
2797 	err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
2798 	if (!err_cert)
2799 		return 0;
2800 
2801 	err = X509_STORE_CTX_get_error(x509_ctx);
2802 	depth = X509_STORE_CTX_get_error_depth(x509_ctx);
2803 	ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
2804 					 SSL_get_ex_data_X509_STORE_CTX_idx());
2805 	os_snprintf(buf, sizeof(buf), "Peer certificate - depth %d", depth);
2806 	debug_print_cert(err_cert, buf);
2807 	X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
2808 
2809 	conn = SSL_get_app_data(ssl);
2810 	if (conn == NULL)
2811 		return 0;
2812 
2813 	if (depth == 0)
2814 		conn->peer_cert = err_cert;
2815 	else if (depth == 1)
2816 		conn->peer_issuer = err_cert;
2817 	else if (depth == 2)
2818 		conn->peer_issuer_issuer = err_cert;
2819 
2820 	context = conn->context;
2821 	match = conn->subject_match;
2822 	altmatch = conn->altsubject_match;
2823 	suffix_match = conn->suffix_match;
2824 	domain_match = conn->domain_match;
2825 
2826 	if (!conn->ca_cert_verify && depth == 0 &&
2827 	    !(conn->flags & TLS_CONN_DISABLE_TIME_CHECKS)) {
2828 		if (X509_cmp_current_time(X509_get_notBefore(err_cert)) > 0) {
2829 			wpa_printf(MSG_INFO,
2830 				   "OpenSSL: Server certificate is not valid at the current time");
2831 			err = X509_V_ERR_CERT_NOT_YET_VALID;
2832 			X509_STORE_CTX_set_error(x509_ctx, err);
2833 			preverify_ok = 0;
2834 		} else if (X509_cmp_current_time(X509_get_notAfter(err_cert)) <
2835 			   0) {
2836 			wpa_printf(MSG_INFO,
2837 				   "TLS: Server certificate has expired");
2838 			err = X509_V_ERR_CERT_HAS_EXPIRED;
2839 			X509_STORE_CTX_set_error(x509_ctx, err);
2840 			preverify_ok = 0;
2841 		}
2842 	}
2843 
2844 	if (!preverify_ok && !conn->ca_cert_verify &&
2845 	    !(err == X509_V_ERR_CERT_HAS_EXPIRED ||
2846 	      err == X509_V_ERR_CERT_NOT_YET_VALID))
2847 		preverify_ok = 1;
2848 	if (!preverify_ok && depth > 0 && conn->server_cert_only)
2849 		preverify_ok = 1;
2850 	if (!preverify_ok && (conn->flags & TLS_CONN_DISABLE_TIME_CHECKS) &&
2851 	    (err == X509_V_ERR_CERT_HAS_EXPIRED ||
2852 	     err == X509_V_ERR_CERT_NOT_YET_VALID)) {
2853 		wpa_printf(MSG_DEBUG, "OpenSSL: Ignore certificate validity "
2854 			   "time mismatch");
2855 		preverify_ok = 1;
2856 	}
2857 	if (!preverify_ok && !conn->data->check_crl_strict &&
2858 	    (err == X509_V_ERR_CRL_HAS_EXPIRED ||
2859 	     err == X509_V_ERR_CRL_NOT_YET_VALID)) {
2860 		wpa_printf(MSG_DEBUG,
2861 			   "OpenSSL: Ignore certificate validity CRL time mismatch");
2862 		preverify_ok = 1;
2863 	}
2864 
2865 	err_str = X509_verify_cert_error_string(err);
2866 
2867 #ifdef CONFIG_SHA256
2868 	/*
2869 	 * Do not require preverify_ok so we can explicity allow otherwise
2870 	 * invalid pinned server certificates.
2871 	 */
2872 	if (depth == 0 && conn->server_cert_only) {
2873 		struct wpabuf *cert;
2874 		cert = get_x509_cert(err_cert);
2875 		if (!cert) {
2876 			wpa_printf(MSG_DEBUG, "OpenSSL: Could not fetch "
2877 				   "server certificate data");
2878 			preverify_ok = 0;
2879 		} else {
2880 			u8 hash[32];
2881 			const u8 *addr[1];
2882 			size_t len[1];
2883 			addr[0] = wpabuf_head(cert);
2884 			len[0] = wpabuf_len(cert);
2885 			if (sha256_vector(1, addr, len, hash) < 0 ||
2886 			    os_memcmp(conn->srv_cert_hash, hash, 32) != 0) {
2887 				err_str = "Server certificate mismatch";
2888 				err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
2889 				preverify_ok = 0;
2890 			} else if (!preverify_ok &&
2891 				   err != X509_V_ERR_CERT_HAS_EXPIRED &&
2892 				   err != X509_V_ERR_CERT_NOT_YET_VALID) {
2893 				/*
2894 				 * Certificate matches pinned certificate, allow
2895 				 * regardless of other problems.
2896 				 */
2897 				wpa_printf(MSG_DEBUG,
2898 					   "OpenSSL: Ignore validation issues for a pinned server certificate");
2899 				preverify_ok = 1;
2900 			}
2901 			wpabuf_free(cert);
2902 		}
2903 	}
2904 #endif /* CONFIG_SHA256 */
2905 
2906 	openssl_tls_cert_event(conn, err_cert, depth, buf);
2907 
2908 	if (!preverify_ok) {
2909 		if (depth > 0) {
2910 			/* Send cert event for the peer certificate so that
2911 			 * the upper layers get information about it even if
2912 			 * validation of a CA certificate fails. */
2913 			STACK_OF(X509) *chain;
2914 
2915 			chain = X509_STORE_CTX_get1_chain(x509_ctx);
2916 			if (chain && sk_X509_num(chain) > 0) {
2917 				char buf2[256];
2918 				X509 *cert;
2919 
2920 				cert = sk_X509_value(chain, 0);
2921 				X509_NAME_oneline(X509_get_subject_name(cert),
2922 						  buf2, sizeof(buf2));
2923 
2924 				openssl_tls_cert_event(conn, cert, 0, buf2);
2925 			}
2926 			if (chain)
2927 				sk_X509_pop_free(chain, X509_free);
2928 		}
2929 
2930 		wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
2931 			   " error %d (%s) depth %d for '%s'", err, err_str,
2932 			   depth, buf);
2933 		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2934 				       err_str, TLS_FAIL_UNSPECIFIED);
2935 		return preverify_ok;
2936 	}
2937 
2938 	wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - preverify_ok=%d "
2939 		   "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
2940 		   preverify_ok, err, err_str,
2941 		   conn->ca_cert_verify, depth, buf);
2942 	check_cert_subject = conn->check_cert_subject;
2943 	if (!check_cert_subject)
2944 		check_cert_subject = conn->data->check_cert_subject;
2945 	if (check_cert_subject) {
2946 		if (depth == 0 &&
2947 		    !tls_match_dn_field(err_cert, check_cert_subject)) {
2948 			preverify_ok = 0;
2949 			openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2950 					       "Distinguished Name",
2951 					       TLS_FAIL_DN_MISMATCH);
2952 		}
2953 	}
2954 	if (depth == 0 && match && os_strstr(buf, match) == NULL) {
2955 		wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
2956 			   "match with '%s'", buf, match);
2957 		preverify_ok = 0;
2958 		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2959 				       "Subject mismatch",
2960 				       TLS_FAIL_SUBJECT_MISMATCH);
2961 	} else if (depth == 0 && altmatch &&
2962 		   !tls_match_altsubject(err_cert, altmatch)) {
2963 		wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
2964 			   "'%s' not found", altmatch);
2965 		preverify_ok = 0;
2966 		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2967 				       "AltSubject mismatch",
2968 				       TLS_FAIL_ALTSUBJECT_MISMATCH);
2969 	} else if (depth == 0 && suffix_match &&
2970 		   !tls_match_suffix(err_cert, suffix_match, 0)) {
2971 		wpa_printf(MSG_WARNING, "TLS: Domain suffix match '%s' not found",
2972 			   suffix_match);
2973 		preverify_ok = 0;
2974 		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2975 				       "Domain suffix mismatch",
2976 				       TLS_FAIL_DOMAIN_SUFFIX_MISMATCH);
2977 	} else if (depth == 0 && domain_match &&
2978 		   !tls_match_suffix(err_cert, domain_match, 1)) {
2979 		wpa_printf(MSG_WARNING, "TLS: Domain match '%s' not found",
2980 			   domain_match);
2981 		preverify_ok = 0;
2982 		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2983 				       "Domain mismatch",
2984 				       TLS_FAIL_DOMAIN_MISMATCH);
2985 	}
2986 
2987 	if (conn->cert_probe && preverify_ok && depth == 0) {
2988 		wpa_printf(MSG_DEBUG, "OpenSSL: Reject server certificate "
2989 			   "on probe-only run");
2990 		preverify_ok = 0;
2991 		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2992 				       "Server certificate chain probe",
2993 				       TLS_FAIL_SERVER_CHAIN_PROBE);
2994 	}
2995 
2996 #ifdef CONFIG_SUITEB
2997 	if (conn->flags & TLS_CONN_SUITEB) {
2998 		EVP_PKEY *pk;
2999 		int len = -1;
3000 
3001 		pk = X509_get_pubkey(err_cert);
3002 		if (pk) {
3003 			len = EVP_PKEY_bits(pk);
3004 			EVP_PKEY_free(pk);
3005 		}
3006 
3007 		if (len >= 0) {
3008 			wpa_printf(MSG_DEBUG,
3009 				   "OpenSSL: RSA modulus size: %d bits", len);
3010 			if (len < 3072) {
3011 				preverify_ok = 0;
3012 				openssl_tls_fail_event(
3013 					conn, err_cert, err,
3014 					depth, buf,
3015 					"Insufficient RSA modulus size",
3016 					TLS_FAIL_INSUFFICIENT_KEY_LEN);
3017 			}
3018 		}
3019 	}
3020 #endif /* CONFIG_SUITEB */
3021 
3022 #ifdef OPENSSL_IS_BORINGSSL
3023 	if (depth == 0 && (conn->flags & TLS_CONN_REQUEST_OCSP) &&
3024 	    preverify_ok) {
3025 		enum ocsp_result res;
3026 
3027 		res = check_ocsp_resp(conn->ssl_ctx, conn->ssl, err_cert,
3028 				      conn->peer_issuer,
3029 				      conn->peer_issuer_issuer);
3030 		if (res == OCSP_REVOKED) {
3031 			preverify_ok = 0;
3032 			openssl_tls_fail_event(conn, err_cert, err, depth, buf,
3033 					       "certificate revoked",
3034 					       TLS_FAIL_REVOKED);
3035 			if (err == X509_V_OK)
3036 				X509_STORE_CTX_set_error(
3037 					x509_ctx, X509_V_ERR_CERT_REVOKED);
3038 		} else if (res != OCSP_GOOD &&
3039 			   (conn->flags & TLS_CONN_REQUIRE_OCSP)) {
3040 			preverify_ok = 0;
3041 			openssl_tls_fail_event(conn, err_cert, err, depth, buf,
3042 					       "bad certificate status response",
3043 					       TLS_FAIL_UNSPECIFIED);
3044 		}
3045 	}
3046 #endif /* OPENSSL_IS_BORINGSSL */
3047 
3048 	if (depth == 0 && preverify_ok && context->event_cb != NULL)
3049 		context->event_cb(context->cb_ctx,
3050 				  TLS_CERT_CHAIN_SUCCESS, NULL);
3051 
3052 	if (depth == 0 && preverify_ok) {
3053 		os_free(conn->peer_subject);
3054 		conn->peer_subject = os_strdup(buf);
3055 	}
3056 
3057 	return preverify_ok;
3058 }
3059 
3060 
3061 #ifndef OPENSSL_NO_STDIO
3062 static int tls_load_ca_der(struct tls_data *data, const char *ca_cert)
3063 {
3064 	SSL_CTX *ssl_ctx = data->ssl;
3065 	X509_LOOKUP *lookup;
3066 	int ret = 0;
3067 
3068 	lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(ssl_ctx),
3069 				       X509_LOOKUP_file());
3070 	if (lookup == NULL) {
3071 		tls_show_errors(MSG_WARNING, __func__,
3072 				"Failed add lookup for X509 store");
3073 		return -1;
3074 	}
3075 
3076 	if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
3077 		unsigned long err = ERR_peek_error();
3078 		tls_show_errors(MSG_WARNING, __func__,
3079 				"Failed load CA in DER format");
3080 		if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
3081 		    ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
3082 			wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
3083 				   "cert already in hash table error",
3084 				   __func__);
3085 		} else
3086 			ret = -1;
3087 	}
3088 
3089 	return ret;
3090 }
3091 #endif /* OPENSSL_NO_STDIO */
3092 
3093 
3094 static int tls_add_ca_cert(SSL_CTX *ssl_ctx, X509 *cert)
3095 {
3096 	unsigned long err;
3097 
3098 	if (X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx), cert) == 1)
3099 		return 0;
3100 
3101 	err = ERR_peek_error();
3102 
3103 	if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
3104 	    ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
3105 		ERR_get_error();
3106 		wpa_printf(MSG_DEBUG,
3107 			   "OpenSSL: %s - ignoring cert already in hash table error",
3108 			   __func__);
3109 		return 0;
3110 	}
3111 
3112 	tls_show_errors(MSG_WARNING, __func__,
3113 			"Failed to add ca_cert_blob to certificate store");
3114 
3115 	return -1;
3116 }
3117 
3118 
3119 static int tls_connection_ca_cert(struct tls_data *data,
3120 				  struct tls_connection *conn,
3121 				  const char *ca_cert, const u8 *ca_cert_blob,
3122 				  size_t ca_cert_blob_len, const char *ca_path)
3123 {
3124 	SSL_CTX *ssl_ctx = data->ssl;
3125 	X509_STORE *store;
3126 
3127 	/*
3128 	 * Remove previously configured trusted CA certificates before adding
3129 	 * new ones.
3130 	 */
3131 	store = X509_STORE_new();
3132 	if (store == NULL) {
3133 		wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
3134 			   "certificate store", __func__);
3135 		return -1;
3136 	}
3137 	SSL_CTX_set_cert_store(ssl_ctx, store);
3138 
3139 	SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
3140 	conn->ca_cert_verify = 1;
3141 
3142 	if (ca_cert && os_strncmp(ca_cert, "probe://", 8) == 0) {
3143 		wpa_printf(MSG_DEBUG, "OpenSSL: Probe for server certificate "
3144 			   "chain");
3145 		conn->cert_probe = 1;
3146 		conn->ca_cert_verify = 0;
3147 		return 0;
3148 	}
3149 
3150 	if (ca_cert && os_strncmp(ca_cert, "hash://", 7) == 0) {
3151 #ifdef CONFIG_SHA256
3152 		const char *pos = ca_cert + 7;
3153 		if (os_strncmp(pos, "server/sha256/", 14) != 0) {
3154 			wpa_printf(MSG_DEBUG, "OpenSSL: Unsupported ca_cert "
3155 				   "hash value '%s'", ca_cert);
3156 			return -1;
3157 		}
3158 		pos += 14;
3159 		if (os_strlen(pos) != 32 * 2) {
3160 			wpa_printf(MSG_DEBUG, "OpenSSL: Unexpected SHA256 "
3161 				   "hash length in ca_cert '%s'", ca_cert);
3162 			return -1;
3163 		}
3164 		if (hexstr2bin(pos, conn->srv_cert_hash, 32) < 0) {
3165 			wpa_printf(MSG_DEBUG, "OpenSSL: Invalid SHA256 hash "
3166 				   "value in ca_cert '%s'", ca_cert);
3167 			return -1;
3168 		}
3169 		conn->server_cert_only = 1;
3170 		wpa_printf(MSG_DEBUG, "OpenSSL: Checking only server "
3171 			   "certificate match");
3172 		return 0;
3173 #else /* CONFIG_SHA256 */
3174 		wpa_printf(MSG_INFO, "No SHA256 included in the build - "
3175 			   "cannot validate server certificate hash");
3176 		return -1;
3177 #endif /* CONFIG_SHA256 */
3178 	}
3179 
3180 	if (ca_cert_blob) {
3181 		unsigned long err;
3182 		X509 *cert;
3183 		int count;
3184 		BIO *bio;
3185 
3186 		cert = d2i_X509(NULL,
3187 				(const unsigned char **) &ca_cert_blob,
3188 				ca_cert_blob_len);
3189 		if (cert) {
3190 			if (tls_add_ca_cert(ssl_ctx, cert) < 0) {
3191 				X509_free(cert);
3192 				return -1;
3193 			}
3194 
3195 			wpa_printf(MSG_DEBUG,
3196 				   "OpenSSL: %s - added ca_cert_blob to certificate store",
3197 				   __func__);
3198 			X509_free(cert);
3199 			return 0;
3200 		}
3201 
3202 		count = 0;
3203 		bio = BIO_new_mem_buf(ca_cert_blob, ca_cert_blob_len);
3204 		if (bio) {
3205 			while ((cert = PEM_read_bio_X509(bio, NULL, NULL,
3206 							 NULL))) {
3207 				if (count == 0) {
3208 					/* Ignore errors from DER conversion
3209 					 * if we detect a certificate in PEM
3210 					 * format. */
3211 					ERR_clear_error();
3212 				}
3213 				count++;
3214 				if (tls_add_ca_cert(ssl_ctx, cert) < 0) {
3215 					X509_free(cert);
3216 					BIO_free(bio);
3217 					return -1;
3218 				}
3219 				X509_free(cert);
3220 			}
3221 			BIO_free(bio);
3222 		}
3223 
3224 		if (count == 0) {
3225 			tls_show_errors(MSG_WARNING, __func__,
3226 					"Failed to parse ca_cert_blob");
3227 			return -1;
3228 		}
3229 
3230 		/* When the loop ends successfully, it's because of EOF */
3231 		err = ERR_peek_last_error();
3232 		if (ERR_GET_LIB(err) != ERR_LIB_PEM ||
3233 		    ERR_GET_REASON(err) != PEM_R_NO_START_LINE) {
3234 			tls_show_errors(MSG_WARNING, __func__,
3235 					"Failed to parse ca_cert_blob bundle");
3236 			return -1;
3237 		}
3238 
3239 		ERR_clear_error();
3240 
3241 		wpa_printf(MSG_DEBUG,
3242 			   "OpenSSL: %s - added %d ca_cert_blob certificates to certificate store",
3243 			   __func__, count);
3244 		return 0;
3245 	}
3246 
3247 #ifdef ANDROID
3248 	/* Single alias */
3249 	if (ca_cert && os_strncmp("keystore://", ca_cert, 11) == 0) {
3250 		if (tls_add_ca_from_keystore(SSL_CTX_get_cert_store(ssl_ctx),
3251 					     &ca_cert[11]) < 0)
3252 			return -1;
3253 		SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
3254 		return 0;
3255 	}
3256 
3257 	/* Multiple aliases separated by space */
3258 	if (ca_cert && os_strncmp("keystores://", ca_cert, 12) == 0) {
3259 		char *aliases = os_strdup(&ca_cert[12]);
3260 		const char *delim = " ";
3261 		int rc = 0;
3262 		char *savedptr;
3263 		char *alias;
3264 
3265 		if (!aliases)
3266 			return -1;
3267 		alias = strtok_r(aliases, delim, &savedptr);
3268 		for (; alias; alias = strtok_r(NULL, delim, &savedptr)) {
3269 			if (tls_add_ca_from_keystore_encoded(
3270 				    SSL_CTX_get_cert_store(ssl_ctx), alias)) {
3271 				wpa_printf(MSG_WARNING,
3272 					   "OpenSSL: %s - Failed to add ca_cert %s from keystore",
3273 					   __func__, alias);
3274 				rc = -1;
3275 				break;
3276 			}
3277 		}
3278 		os_free(aliases);
3279 		if (rc)
3280 			return rc;
3281 
3282 		SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
3283 		return 0;
3284 	}
3285 #endif /* ANDROID */
3286 
3287 #ifdef CONFIG_NATIVE_WINDOWS
3288 	if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
3289 	    0) {
3290 		wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
3291 			   "system certificate store");
3292 		return 0;
3293 	}
3294 #endif /* CONFIG_NATIVE_WINDOWS */
3295 
3296 	if (ca_cert || ca_path) {
3297 #ifndef OPENSSL_NO_STDIO
3298 		if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
3299 		    1) {
3300 			tls_show_errors(MSG_WARNING, __func__,
3301 					"Failed to load root certificates");
3302 			if (ca_cert &&
3303 			    tls_load_ca_der(data, ca_cert) == 0) {
3304 				wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
3305 					   "DER format CA certificate",
3306 					   __func__);
3307 			} else
3308 				return -1;
3309 		} else {
3310 			wpa_printf(MSG_DEBUG, "TLS: Trusted root "
3311 				   "certificate(s) loaded");
3312 			tls_get_errors(data);
3313 		}
3314 #else /* OPENSSL_NO_STDIO */
3315 		wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
3316 			   __func__);
3317 		return -1;
3318 #endif /* OPENSSL_NO_STDIO */
3319 	} else {
3320 		/* No ca_cert configured - do not try to verify server
3321 		 * certificate */
3322 		conn->ca_cert_verify = 0;
3323 	}
3324 
3325 	return 0;
3326 }
3327 
3328 
3329 static int tls_global_ca_cert(struct tls_data *data, const char *ca_cert)
3330 {
3331 	SSL_CTX *ssl_ctx = data->ssl;
3332 
3333 	if (ca_cert) {
3334 		if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
3335 		{
3336 			tls_show_errors(MSG_WARNING, __func__,
3337 					"Failed to load root certificates");
3338 			return -1;
3339 		}
3340 
3341 		wpa_printf(MSG_DEBUG, "TLS: Trusted root "
3342 			   "certificate(s) loaded");
3343 
3344 #ifndef OPENSSL_NO_STDIO
3345 		/* Add the same CAs to the client certificate requests */
3346 		SSL_CTX_set_client_CA_list(ssl_ctx,
3347 					   SSL_load_client_CA_file(ca_cert));
3348 #endif /* OPENSSL_NO_STDIO */
3349 
3350 		os_free(data->ca_cert);
3351 		data->ca_cert = os_strdup(ca_cert);
3352 	}
3353 
3354 	return 0;
3355 }
3356 
3357 
3358 int tls_global_set_verify(void *ssl_ctx, int check_crl, int strict)
3359 {
3360 	int flags;
3361 
3362 	if (check_crl) {
3363 		struct tls_data *data = ssl_ctx;
3364 		X509_STORE *cs = SSL_CTX_get_cert_store(data->ssl);
3365 		if (cs == NULL) {
3366 			tls_show_errors(MSG_INFO, __func__, "Failed to get "
3367 					"certificate store when enabling "
3368 					"check_crl");
3369 			return -1;
3370 		}
3371 		flags = X509_V_FLAG_CRL_CHECK;
3372 		if (check_crl == 2)
3373 			flags |= X509_V_FLAG_CRL_CHECK_ALL;
3374 		X509_STORE_set_flags(cs, flags);
3375 
3376 		data->check_crl = check_crl;
3377 		data->check_crl_strict = strict;
3378 		os_get_reltime(&data->crl_last_reload);
3379 	}
3380 	return 0;
3381 }
3382 
3383 
3384 static int tls_connection_set_subject_match(struct tls_connection *conn,
3385 					    const char *subject_match,
3386 					    const char *altsubject_match,
3387 					    const char *suffix_match,
3388 					    const char *domain_match,
3389 					    const char *check_cert_subject)
3390 {
3391 	os_free(conn->subject_match);
3392 	conn->subject_match = NULL;
3393 	if (subject_match) {
3394 		conn->subject_match = os_strdup(subject_match);
3395 		if (conn->subject_match == NULL)
3396 			return -1;
3397 	}
3398 
3399 	os_free(conn->altsubject_match);
3400 	conn->altsubject_match = NULL;
3401 	if (altsubject_match) {
3402 		conn->altsubject_match = os_strdup(altsubject_match);
3403 		if (conn->altsubject_match == NULL)
3404 			return -1;
3405 	}
3406 
3407 	os_free(conn->suffix_match);
3408 	conn->suffix_match = NULL;
3409 	if (suffix_match) {
3410 		conn->suffix_match = os_strdup(suffix_match);
3411 		if (conn->suffix_match == NULL)
3412 			return -1;
3413 	}
3414 
3415 	os_free(conn->domain_match);
3416 	conn->domain_match = NULL;
3417 	if (domain_match) {
3418 		conn->domain_match = os_strdup(domain_match);
3419 		if (conn->domain_match == NULL)
3420 			return -1;
3421 	}
3422 
3423 	os_free(conn->check_cert_subject);
3424 	conn->check_cert_subject = NULL;
3425 	if (check_cert_subject) {
3426 		conn->check_cert_subject = os_strdup(check_cert_subject);
3427 		if (!conn->check_cert_subject)
3428 			return -1;
3429 	}
3430 
3431 	return 0;
3432 }
3433 
3434 
3435 #ifdef CONFIG_SUITEB
3436 static int suiteb_cert_cb(SSL *ssl, void *arg)
3437 {
3438 	struct tls_connection *conn = arg;
3439 
3440 	/*
3441 	 * This cert_cb() is not really the best location for doing a
3442 	 * constraint check for the ServerKeyExchange message, but this seems to
3443 	 * be the only place where the current OpenSSL sequence can be
3444 	 * terminated cleanly with an TLS alert going out to the server.
3445 	 */
3446 
3447 	if (!(conn->flags & TLS_CONN_SUITEB))
3448 		return 1;
3449 
3450 	/* DHE is enabled only with DHE-RSA-AES256-GCM-SHA384 */
3451 	if (conn->cipher_suite != 0x9f)
3452 		return 1;
3453 
3454 	if (conn->server_dh_prime_len >= 3072)
3455 		return 1;
3456 
3457 	wpa_printf(MSG_DEBUG,
3458 		   "OpenSSL: Server DH prime length (%d bits) not sufficient for Suite B RSA - reject handshake",
3459 		   conn->server_dh_prime_len);
3460 	return 0;
3461 }
3462 #endif /* CONFIG_SUITEB */
3463 
3464 
3465 static int tls_set_conn_flags(struct tls_connection *conn, unsigned int flags,
3466 			      const char *openssl_ciphers)
3467 {
3468 	SSL *ssl = conn->ssl;
3469 
3470 #ifdef SSL_OP_NO_TICKET
3471 	if (flags & TLS_CONN_DISABLE_SESSION_TICKET)
3472 		SSL_set_options(ssl, SSL_OP_NO_TICKET);
3473 	else
3474 		SSL_clear_options(ssl, SSL_OP_NO_TICKET);
3475 #endif /* SSL_OP_NO_TICKET */
3476 
3477 #ifdef SSL_OP_LEGACY_SERVER_CONNECT
3478 	if (flags & TLS_CONN_ALLOW_UNSAFE_RENEGOTIATION)
3479 		SSL_set_options(ssl, SSL_OP_LEGACY_SERVER_CONNECT);
3480 #endif /* SSL_OP_LEGACY_SERVER_CONNECT */
3481 
3482 #ifdef SSL_OP_NO_TLSv1
3483 	if (flags & TLS_CONN_DISABLE_TLSv1_0)
3484 		SSL_set_options(ssl, SSL_OP_NO_TLSv1);
3485 	else
3486 		SSL_clear_options(ssl, SSL_OP_NO_TLSv1);
3487 #endif /* SSL_OP_NO_TLSv1 */
3488 #ifdef SSL_OP_NO_TLSv1_1
3489 	if (flags & TLS_CONN_DISABLE_TLSv1_1)
3490 		SSL_set_options(ssl, SSL_OP_NO_TLSv1_1);
3491 	else
3492 		SSL_clear_options(ssl, SSL_OP_NO_TLSv1_1);
3493 #endif /* SSL_OP_NO_TLSv1_1 */
3494 #ifdef SSL_OP_NO_TLSv1_2
3495 	if (flags & TLS_CONN_DISABLE_TLSv1_2)
3496 		SSL_set_options(ssl, SSL_OP_NO_TLSv1_2);
3497 	else
3498 		SSL_clear_options(ssl, SSL_OP_NO_TLSv1_2);
3499 #endif /* SSL_OP_NO_TLSv1_2 */
3500 #ifdef SSL_OP_NO_TLSv1_3
3501 	if (flags & TLS_CONN_DISABLE_TLSv1_3)
3502 		SSL_set_options(ssl, SSL_OP_NO_TLSv1_3);
3503 	else
3504 		SSL_clear_options(ssl, SSL_OP_NO_TLSv1_3);
3505 #endif /* SSL_OP_NO_TLSv1_3 */
3506 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
3507 	if (flags & (TLS_CONN_ENABLE_TLSv1_0 |
3508 		     TLS_CONN_ENABLE_TLSv1_1 |
3509 		     TLS_CONN_ENABLE_TLSv1_2)) {
3510 		int version = 0;
3511 
3512 		/* Explicit request to enable TLS versions even if needing to
3513 		 * override systemwide policies. */
3514 		if (flags & TLS_CONN_ENABLE_TLSv1_0)
3515 			version = TLS1_VERSION;
3516 		else if (flags & TLS_CONN_ENABLE_TLSv1_1)
3517 			version = TLS1_1_VERSION;
3518 		else if (flags & TLS_CONN_ENABLE_TLSv1_2)
3519 			version = TLS1_2_VERSION;
3520 		if (!version) {
3521 			wpa_printf(MSG_DEBUG,
3522 				   "OpenSSL: Invalid TLS version configuration");
3523 			return -1;
3524 		}
3525 
3526 		if (SSL_set_min_proto_version(ssl, version) != 1) {
3527 			wpa_printf(MSG_DEBUG,
3528 				   "OpenSSL: Failed to set minimum TLS version");
3529 			return -1;
3530 		}
3531 	}
3532 #endif /* >= 1.1.0 */
3533 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
3534 	!defined(LIBRESSL_VERSION_NUMBER) && \
3535 	!defined(OPENSSL_IS_BORINGSSL)
3536 	{
3537 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
3538 		int need_level = 0;
3539 #else
3540 		int need_level = 1;
3541 #endif
3542 
3543 		if ((flags &
3544 		     (TLS_CONN_ENABLE_TLSv1_0 | TLS_CONN_ENABLE_TLSv1_1)) &&
3545 		    SSL_get_security_level(ssl) > need_level) {
3546 			/*
3547 			 * Need to drop to security level 1 (or 0  with OpenSSL
3548 			 * 3.0) to allow TLS versions older than 1.2 to be used
3549 			 * when explicitly enabled in configuration.
3550 			 */
3551 			SSL_set_security_level(conn->ssl, need_level);
3552 		}
3553 	}
3554 #endif
3555 
3556 	if (!openssl_ciphers)
3557 		openssl_ciphers = conn->data->openssl_ciphers;
3558 
3559 #ifdef CONFIG_SUITEB
3560 #ifdef OPENSSL_IS_BORINGSSL
3561 	/* Start with defaults from BoringSSL */
3562 	SSL_CTX_set_verify_algorithm_prefs(conn->ssl_ctx, NULL, 0);
3563 #endif /* OPENSSL_IS_BORINGSSL */
3564 	if (flags & TLS_CONN_SUITEB_NO_ECDH) {
3565 		const char *ciphers = "DHE-RSA-AES256-GCM-SHA384";
3566 
3567 		if (openssl_ciphers) {
3568 			wpa_printf(MSG_DEBUG,
3569 				   "OpenSSL: Override ciphers for Suite B (no ECDH): %s",
3570 				   openssl_ciphers);
3571 			ciphers = openssl_ciphers;
3572 		}
3573 		if (SSL_set_cipher_list(ssl, ciphers) != 1) {
3574 			wpa_printf(MSG_INFO,
3575 				   "OpenSSL: Failed to set Suite B ciphers");
3576 			return -1;
3577 		}
3578 	} else if (flags & TLS_CONN_SUITEB) {
3579 #if OPENSSL_VERSION_NUMBER < 0x30000000L
3580 		EC_KEY *ecdh;
3581 #endif
3582 		const char *ciphers =
3583 			"ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384";
3584 		int nid[1] = { NID_secp384r1 };
3585 
3586 		if (openssl_ciphers) {
3587 			wpa_printf(MSG_DEBUG,
3588 				   "OpenSSL: Override ciphers for Suite B: %s",
3589 				   openssl_ciphers);
3590 			ciphers = openssl_ciphers;
3591 		}
3592 		if (SSL_set_cipher_list(ssl, ciphers) != 1) {
3593 			wpa_printf(MSG_INFO,
3594 				   "OpenSSL: Failed to set Suite B ciphers");
3595 			return -1;
3596 		}
3597 
3598 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
3599 		if (SSL_set1_groups(ssl, nid, 1) != 1) {
3600 			wpa_printf(MSG_INFO,
3601 				   "OpenSSL: Failed to set Suite B groups");
3602 			return -1;
3603 		}
3604 
3605 #else
3606 		if (SSL_set1_curves(ssl, nid, 1) != 1) {
3607 			wpa_printf(MSG_INFO,
3608 				   "OpenSSL: Failed to set Suite B curves");
3609 			return -1;
3610 		}
3611 
3612 		ecdh = EC_KEY_new_by_curve_name(NID_secp384r1);
3613 		if (!ecdh || SSL_set_tmp_ecdh(ssl, ecdh) != 1) {
3614 			EC_KEY_free(ecdh);
3615 			wpa_printf(MSG_INFO,
3616 				   "OpenSSL: Failed to set ECDH parameter");
3617 			return -1;
3618 		}
3619 		EC_KEY_free(ecdh);
3620 #endif
3621 	}
3622 	if (flags & (TLS_CONN_SUITEB | TLS_CONN_SUITEB_NO_ECDH)) {
3623 #ifdef OPENSSL_IS_BORINGSSL
3624 		uint16_t sigalgs[3] = { SSL_SIGN_RSA_PKCS1_SHA384 };
3625 		int num = 1;
3626 
3627 		if (!(flags & TLS_CONN_DISABLE_TLSv1_3)) {
3628 #ifdef SSL_SIGN_ECDSA_SECP384R1_SHA384
3629 			sigalgs[num++] = SSL_SIGN_ECDSA_SECP384R1_SHA384;
3630 #endif
3631 #ifdef SSL_SIGN_RSA_PSS_RSAE_SHA384
3632 			sigalgs[num++] = SSL_SIGN_RSA_PSS_RSAE_SHA384;
3633 #endif
3634 		}
3635 
3636 		if (SSL_CTX_set_verify_algorithm_prefs(conn->ssl_ctx, sigalgs,
3637 						       num) != 1) {
3638 			wpa_printf(MSG_INFO,
3639 				   "OpenSSL: Failed to set Suite B sigalgs");
3640 			return -1;
3641 		}
3642 #else /* OPENSSL_IS_BORINGSSL */
3643 		/* ECDSA+SHA384 if need to add EC support here */
3644 		const char *algs = "RSA+SHA384";
3645 
3646 		if (!(flags & TLS_CONN_DISABLE_TLSv1_3))
3647 			algs = "RSA+SHA384:ecdsa_secp384r1_sha384:rsa_pss_rsae_sha384";
3648 		if (SSL_set1_sigalgs_list(ssl, algs) != 1) {
3649 			wpa_printf(MSG_INFO,
3650 				   "OpenSSL: Failed to set Suite B sigalgs");
3651 			return -1;
3652 		}
3653 #endif /* OPENSSL_IS_BORINGSSL */
3654 
3655 		SSL_set_options(ssl, SSL_OP_NO_TLSv1);
3656 		SSL_set_options(ssl, SSL_OP_NO_TLSv1_1);
3657 		SSL_set_cert_cb(ssl, suiteb_cert_cb, conn);
3658 	}
3659 
3660 #ifdef OPENSSL_IS_BORINGSSL
3661 	if (openssl_ciphers && os_strcmp(openssl_ciphers, "SUITEB192") == 0) {
3662 		uint16_t sigalgs[1] = { SSL_SIGN_ECDSA_SECP384R1_SHA384 };
3663 		int nid[1] = { NID_secp384r1 };
3664 
3665 		if (SSL_set1_curves(ssl, nid, 1) != 1) {
3666 			wpa_printf(MSG_INFO,
3667 				   "OpenSSL: Failed to set Suite B curves");
3668 			return -1;
3669 		}
3670 
3671 		if (SSL_CTX_set_verify_algorithm_prefs(conn->ssl_ctx, sigalgs,
3672 						       1) != 1) {
3673 			wpa_printf(MSG_INFO,
3674 				   "OpenSSL: Failed to set Suite B sigalgs");
3675 			return -1;
3676 		}
3677 	}
3678 #else /* OPENSSL_IS_BORINGSSL */
3679 	if (!(flags & (TLS_CONN_SUITEB | TLS_CONN_SUITEB_NO_ECDH)) &&
3680 	    openssl_ciphers && SSL_set_cipher_list(ssl, openssl_ciphers) != 1) {
3681 		wpa_printf(MSG_INFO,
3682 			   "OpenSSL: Failed to set openssl_ciphers '%s'",
3683 			   openssl_ciphers);
3684 		return -1;
3685 	}
3686 #endif /* OPENSSL_IS_BORINGSSL */
3687 #else /* CONFIG_SUITEB */
3688 	if (openssl_ciphers && SSL_set_cipher_list(ssl, openssl_ciphers) != 1) {
3689 		wpa_printf(MSG_INFO,
3690 			   "OpenSSL: Failed to set openssl_ciphers '%s'",
3691 			   openssl_ciphers);
3692 		return -1;
3693 	}
3694 #endif /* CONFIG_SUITEB */
3695 
3696 	if (flags & TLS_CONN_TEAP_ANON_DH) {
3697 #ifndef TEAP_DH_ANON_CS
3698 #define TEAP_DH_ANON_CS \
3699 	"ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:" \
3700 	"ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:" \
3701 	"ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:" \
3702 	"DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:" \
3703 	"DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:" \
3704 	"DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:" \
3705 	"ADH-AES256-GCM-SHA384:ADH-AES128-GCM-SHA256:" \
3706 	"ADH-AES256-SHA256:ADH-AES128-SHA256:ADH-AES256-SHA:ADH-AES128-SHA"
3707 #endif
3708 		static const char *cs = TEAP_DH_ANON_CS;
3709 
3710 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
3711 	!defined(LIBRESSL_VERSION_NUMBER) && \
3712 	!defined(OPENSSL_IS_BORINGSSL)
3713 		/*
3714 		 * Need to drop to security level 0 to allow anonymous
3715 		 * cipher suites for EAP-TEAP.
3716 		 */
3717 		SSL_set_security_level(conn->ssl, 0);
3718 #endif
3719 
3720 		wpa_printf(MSG_DEBUG,
3721 			   "OpenSSL: Enable cipher suites for anonymous EAP-TEAP provisioning: %s",
3722 			   cs);
3723 		if (SSL_set_cipher_list(conn->ssl, cs) != 1) {
3724 			tls_show_errors(MSG_INFO, __func__,
3725 					"Cipher suite configuration failed");
3726 			return -1;
3727 		}
3728 	}
3729 
3730 	return 0;
3731 }
3732 
3733 
3734 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
3735 			      int verify_peer, unsigned int flags,
3736 			      const u8 *session_ctx, size_t session_ctx_len)
3737 {
3738 	static int counter = 0;
3739 	struct tls_data *data = ssl_ctx;
3740 
3741 	if (conn == NULL)
3742 		return -1;
3743 
3744 	if (verify_peer == 2) {
3745 		conn->ca_cert_verify = 1;
3746 		SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
3747 			       SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
3748 	} else if (verify_peer) {
3749 		conn->ca_cert_verify = 1;
3750 		SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
3751 			       SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
3752 			       SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
3753 	} else {
3754 		conn->ca_cert_verify = 0;
3755 		SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
3756 	}
3757 
3758 	if (tls_set_conn_flags(conn, flags, NULL) < 0)
3759 		return -1;
3760 	conn->flags = flags;
3761 
3762 	SSL_set_accept_state(conn->ssl);
3763 
3764 	if (data->tls_session_lifetime == 0) {
3765 		/*
3766 		 * Set session id context to a unique value to make sure
3767 		 * session resumption cannot be used either through session
3768 		 * caching or TLS ticket extension.
3769 		 */
3770 		counter++;
3771 		SSL_set_session_id_context(conn->ssl,
3772 					   (const unsigned char *) &counter,
3773 					   sizeof(counter));
3774 	} else if (session_ctx) {
3775 		SSL_set_session_id_context(conn->ssl, session_ctx,
3776 					   session_ctx_len);
3777 	}
3778 
3779 	return 0;
3780 }
3781 
3782 
3783 static int tls_connection_client_cert(struct tls_connection *conn,
3784 				      const char *client_cert,
3785 				      const u8 *client_cert_blob,
3786 				      size_t client_cert_blob_len)
3787 {
3788 	if (client_cert == NULL && client_cert_blob == NULL)
3789 		return 0;
3790 
3791 #ifdef PKCS12_FUNCS
3792 #ifdef LIBRESSL_VERSION_NUMBER
3793 	/*
3794 	 * Clear previously set extra chain certificates, if any, from PKCS#12
3795 	 * processing in tls_parse_pkcs12() to allow LibreSSL to build a new
3796 	 * chain properly.
3797 	 */
3798 	SSL_CTX_clear_extra_chain_certs(conn->ssl_ctx);
3799 #endif /* LIBRESSL_VERSION_NUMBER */
3800 #endif /* PKCS12_FUNCS */
3801 
3802 	if (client_cert_blob &&
3803 	    SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
3804 				     client_cert_blob_len) == 1) {
3805 		wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
3806 			   "OK");
3807 		return 0;
3808 	} else if (client_cert_blob) {
3809 #if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20901000L
3810 		tls_show_errors(MSG_DEBUG, __func__,
3811 				"SSL_use_certificate_ASN1 failed");
3812 #else
3813 		BIO *bio;
3814 		X509 *x509;
3815 
3816 		tls_show_errors(MSG_DEBUG, __func__,
3817 				"SSL_use_certificate_ASN1 failed");
3818 		bio = BIO_new(BIO_s_mem());
3819 		if (!bio)
3820 			return -1;
3821 		BIO_write(bio, client_cert_blob, client_cert_blob_len);
3822 		x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
3823 		if (!x509 || SSL_use_certificate(conn->ssl, x509) != 1) {
3824 			X509_free(x509);
3825 			BIO_free(bio);
3826 			return -1;
3827 		}
3828 		X509_free(x509);
3829 		wpa_printf(MSG_DEBUG,
3830 			   "OpenSSL: Found PEM encoded certificate from blob");
3831 		while ((x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL))) {
3832 			wpa_printf(MSG_DEBUG,
3833 				   "OpenSSL: Added an additional certificate into the chain");
3834 			SSL_add0_chain_cert(conn->ssl, x509);
3835 		}
3836 		BIO_free(bio);
3837 		return 0;
3838 #endif
3839 	}
3840 
3841 	if (client_cert == NULL)
3842 		return -1;
3843 
3844 #ifdef ANDROID
3845 	if (os_strncmp("keystore://", client_cert, 11) == 0) {
3846 		BIO *bio = BIO_from_keystore(&client_cert[11]);
3847 		X509 *x509 = NULL;
3848 		int ret = -1;
3849 		if (bio) {
3850 			x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
3851 		}
3852 		if (x509) {
3853 			if (SSL_use_certificate(conn->ssl, x509) == 1)
3854 				ret = 0;
3855 			X509_free(x509);
3856 		}
3857 
3858 		/* Read additional certificates into the chain. */
3859 		while (bio) {
3860 			x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
3861 			if (x509) {
3862 				/* Takes ownership of x509 */
3863 				SSL_add0_chain_cert(conn->ssl, x509);
3864 			} else {
3865 				BIO_free(bio);
3866 				bio = NULL;
3867 			}
3868 		}
3869 		return ret;
3870 	}
3871 #endif /* ANDROID */
3872 
3873 #ifndef OPENSSL_NO_STDIO
3874 	if (SSL_use_certificate_file(conn->ssl, client_cert,
3875 				     SSL_FILETYPE_ASN1) == 1) {
3876 		wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
3877 			   " --> OK");
3878 		return 0;
3879 	}
3880 
3881 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
3882 	!defined(LIBRESSL_VERSION_NUMBER) && !defined(OPENSSL_IS_BORINGSSL)
3883 	if (SSL_use_certificate_chain_file(conn->ssl, client_cert) == 1) {
3884 		ERR_clear_error();
3885 		wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_chain_file"
3886 			   " --> OK");
3887 		return 0;
3888 	}
3889 #else
3890 	if (SSL_use_certificate_file(conn->ssl, client_cert,
3891 				     SSL_FILETYPE_PEM) == 1) {
3892 		ERR_clear_error();
3893 		wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
3894 			   " --> OK");
3895 		return 0;
3896 	}
3897 #endif
3898 
3899 	tls_show_errors(MSG_DEBUG, __func__,
3900 			"SSL_use_certificate_file failed");
3901 #else /* OPENSSL_NO_STDIO */
3902 	wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
3903 #endif /* OPENSSL_NO_STDIO */
3904 
3905 	return -1;
3906 }
3907 
3908 
3909 static int tls_global_client_cert(struct tls_data *data,
3910 				  const char *client_cert)
3911 {
3912 #ifndef OPENSSL_NO_STDIO
3913 	SSL_CTX *ssl_ctx = data->ssl;
3914 
3915 	if (client_cert == NULL)
3916 		return 0;
3917 
3918 	if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
3919 					 SSL_FILETYPE_ASN1) != 1 &&
3920 	    SSL_CTX_use_certificate_chain_file(ssl_ctx, client_cert) != 1 &&
3921 	    SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
3922 					 SSL_FILETYPE_PEM) != 1) {
3923 		tls_show_errors(MSG_INFO, __func__,
3924 				"Failed to load client certificate");
3925 		return -1;
3926 	}
3927 	return 0;
3928 #else /* OPENSSL_NO_STDIO */
3929 	if (client_cert == NULL)
3930 		return 0;
3931 	wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
3932 	return -1;
3933 #endif /* OPENSSL_NO_STDIO */
3934 }
3935 
3936 
3937 #ifdef PKCS12_FUNCS
3938 static int tls_parse_pkcs12(struct tls_data *data, SSL *ssl, PKCS12 *p12,
3939 			    const char *passwd)
3940 {
3941 	EVP_PKEY *pkey;
3942 	X509 *cert;
3943 	STACK_OF(X509) *certs;
3944 	int res = 0;
3945 	char buf[256];
3946 
3947 	pkey = NULL;
3948 	cert = NULL;
3949 	certs = NULL;
3950 	if (!passwd)
3951 		passwd = "";
3952 	if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
3953 		tls_show_errors(MSG_DEBUG, __func__,
3954 				"Failed to parse PKCS12 file");
3955 		PKCS12_free(p12);
3956 		return -1;
3957 	}
3958 	wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
3959 
3960 	if (cert) {
3961 		X509_NAME_oneline(X509_get_subject_name(cert), buf,
3962 				  sizeof(buf));
3963 		wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
3964 			   "subject='%s'", buf);
3965 		if (ssl) {
3966 			if (SSL_use_certificate(ssl, cert) != 1)
3967 				res = -1;
3968 		} else {
3969 			if (SSL_CTX_use_certificate(data->ssl, cert) != 1)
3970 				res = -1;
3971 		}
3972 		X509_free(cert);
3973 	}
3974 
3975 	if (pkey) {
3976 		wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
3977 		if (ssl) {
3978 			if (SSL_use_PrivateKey(ssl, pkey) != 1)
3979 				res = -1;
3980 		} else {
3981 			if (SSL_CTX_use_PrivateKey(data->ssl, pkey) != 1)
3982 				res = -1;
3983 		}
3984 		EVP_PKEY_free(pkey);
3985 	}
3986 
3987 	if (certs) {
3988 #ifndef LIBRESSL_VERSION_NUMBER
3989 		if (ssl)
3990 			SSL_clear_chain_certs(ssl);
3991 		else
3992 			SSL_CTX_clear_chain_certs(data->ssl);
3993 		while ((cert = sk_X509_pop(certs)) != NULL) {
3994 			X509_NAME_oneline(X509_get_subject_name(cert), buf,
3995 					  sizeof(buf));
3996 			wpa_printf(MSG_DEBUG, "TLS: additional certificate"
3997 				   " from PKCS12: subject='%s'", buf);
3998 			if ((ssl && SSL_add1_chain_cert(ssl, cert) != 1) ||
3999 			    (!ssl && SSL_CTX_add1_chain_cert(data->ssl,
4000 							     cert) != 1)) {
4001 				tls_show_errors(MSG_DEBUG, __func__,
4002 						"Failed to add additional certificate");
4003 				res = -1;
4004 				X509_free(cert);
4005 				break;
4006 			}
4007 			X509_free(cert);
4008 		}
4009 		if (!res) {
4010 			/* Try to continue anyway */
4011 		}
4012 		sk_X509_pop_free(certs, X509_free);
4013 #ifndef OPENSSL_IS_BORINGSSL
4014 		if (ssl)
4015 			res = SSL_build_cert_chain(
4016 				ssl,
4017 				SSL_BUILD_CHAIN_FLAG_CHECK |
4018 				SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR);
4019 		else
4020 			res = SSL_CTX_build_cert_chain(
4021 				data->ssl,
4022 				SSL_BUILD_CHAIN_FLAG_CHECK |
4023 				SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR);
4024 		if (!res) {
4025 			tls_show_errors(MSG_DEBUG, __func__,
4026 					"Failed to build certificate chain");
4027 		} else if (res == 2) {
4028 			wpa_printf(MSG_DEBUG,
4029 				   "TLS: Ignore certificate chain verification error when building chain with PKCS#12 extra certificates");
4030 		}
4031 #endif /* OPENSSL_IS_BORINGSSL */
4032 		/*
4033 		 * Try to continue regardless of result since it is possible for
4034 		 * the extra certificates not to be required.
4035 		 */
4036 		res = 0;
4037 #else /* LIBRESSL_VERSION_NUMBER */
4038 		SSL_CTX_clear_extra_chain_certs(data->ssl);
4039 		while ((cert = sk_X509_pop(certs)) != NULL) {
4040 			X509_NAME_oneline(X509_get_subject_name(cert), buf,
4041 					  sizeof(buf));
4042 			wpa_printf(MSG_DEBUG, "TLS: additional certificate"
4043 				   " from PKCS12: subject='%s'", buf);
4044 			/*
4045 			 * There is no SSL equivalent for the chain cert - so
4046 			 * always add it to the context...
4047 			 */
4048 			if (SSL_CTX_add_extra_chain_cert(data->ssl, cert) != 1)
4049 			{
4050 				X509_free(cert);
4051 				res = -1;
4052 				break;
4053 			}
4054 		}
4055 		sk_X509_pop_free(certs, X509_free);
4056 #endif /* LIBRSESSL_VERSION_NUMBER */
4057 	}
4058 
4059 	PKCS12_free(p12);
4060 
4061 	if (res < 0)
4062 		tls_get_errors(data);
4063 
4064 	return res;
4065 }
4066 #endif  /* PKCS12_FUNCS */
4067 
4068 
4069 static int tls_read_pkcs12(struct tls_data *data, SSL *ssl,
4070 			   const char *private_key, const char *passwd)
4071 {
4072 #ifdef PKCS12_FUNCS
4073 	FILE *f;
4074 	PKCS12 *p12;
4075 
4076 	f = fopen(private_key, "rb");
4077 	if (f == NULL)
4078 		return -1;
4079 
4080 	p12 = d2i_PKCS12_fp(f, NULL);
4081 	fclose(f);
4082 
4083 	if (p12 == NULL) {
4084 		tls_show_errors(MSG_INFO, __func__,
4085 				"Failed to use PKCS#12 file");
4086 		return -1;
4087 	}
4088 
4089 	return tls_parse_pkcs12(data, ssl, p12, passwd);
4090 
4091 #else /* PKCS12_FUNCS */
4092 	wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
4093 		   "p12/pfx files");
4094 	return -1;
4095 #endif  /* PKCS12_FUNCS */
4096 }
4097 
4098 
4099 static int tls_read_pkcs12_blob(struct tls_data *data, SSL *ssl,
4100 				const u8 *blob, size_t len, const char *passwd)
4101 {
4102 #ifdef PKCS12_FUNCS
4103 	PKCS12 *p12;
4104 
4105 	p12 = d2i_PKCS12(NULL, (const unsigned char **) &blob, len);
4106 	if (p12 == NULL) {
4107 		tls_show_errors(MSG_INFO, __func__,
4108 				"Failed to use PKCS#12 blob");
4109 		return -1;
4110 	}
4111 
4112 	return tls_parse_pkcs12(data, ssl, p12, passwd);
4113 
4114 #else /* PKCS12_FUNCS */
4115 	wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
4116 		   "p12/pfx blobs");
4117 	return -1;
4118 #endif  /* PKCS12_FUNCS */
4119 }
4120 
4121 
4122 #ifndef OPENSSL_NO_ENGINE
4123 static int tls_engine_get_cert(struct tls_connection *conn,
4124 			       const char *cert_id,
4125 			       X509 **cert)
4126 {
4127 	/* this runs after the private key is loaded so no PIN is required */
4128 	struct {
4129 		const char *cert_id;
4130 		X509 *cert;
4131 	} params;
4132 	params.cert_id = cert_id;
4133 	params.cert = NULL;
4134 
4135 	if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
4136 			     0, &params, NULL, 1)) {
4137 		unsigned long err = ERR_get_error();
4138 
4139 		wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
4140 			   " '%s' [%s]", cert_id,
4141 			   ERR_error_string(err, NULL));
4142 		if (tls_is_pin_error(err))
4143 			return TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
4144 		return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
4145 	}
4146 	if (!params.cert) {
4147 		wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
4148 			   " '%s'", cert_id);
4149 		return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
4150 	}
4151 	*cert = params.cert;
4152 	return 0;
4153 }
4154 #endif /* OPENSSL_NO_ENGINE */
4155 
4156 
4157 static int tls_connection_engine_client_cert(struct tls_connection *conn,
4158 					     const char *cert_id)
4159 {
4160 #ifndef ANDROID
4161 	X509 *cert;
4162 
4163 #ifndef OPENSSL_NO_ENGINE
4164 	if (tls_engine_get_cert(conn, cert_id, &cert))
4165 		return -1;
4166 #else /* OPENSSL_NO_ENGINE */
4167 	cert = provider_load_cert(cert_id);
4168 	if (!cert)
4169 		return -1;
4170 #endif /* OPENSSL_NO_ENGINE */
4171 
4172 	if (!SSL_use_certificate(conn->ssl, cert)) {
4173 		tls_show_errors(MSG_ERROR, __func__,
4174 				"SSL_use_certificate failed");
4175                 X509_free(cert);
4176 		return -1;
4177 	}
4178 	X509_free(cert);
4179 	wpa_printf(MSG_DEBUG, "ENGINE/provider: SSL_use_certificate --> "
4180 		   "OK");
4181 	return 0;
4182 #else /* ANDROID */
4183 	return -1;
4184 #endif /* ANDROID */
4185 }
4186 
4187 
4188 static int tls_connection_engine_ca_cert(struct tls_data *data,
4189 					 struct tls_connection *conn,
4190 					 const char *ca_cert_id)
4191 {
4192 #ifndef ANDROID
4193 	X509 *cert;
4194 	SSL_CTX *ssl_ctx = data->ssl;
4195 	X509_STORE *store;
4196 
4197 #ifndef OPENSSL_NO_ENGINE
4198 	if (tls_engine_get_cert(conn, ca_cert_id, &cert))
4199 		return -1;
4200 #else /* OPENSSL_NO_ENGINE */
4201 	cert = provider_load_cert(ca_cert_id);
4202 	if (!cert)
4203 		return -1;
4204 #endif /* OPENSSL_NO_ENGINE */
4205 
4206 	/* start off the same as tls_connection_ca_cert */
4207 	store = X509_STORE_new();
4208 	if (store == NULL) {
4209 		wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
4210 			   "certificate store", __func__);
4211 		X509_free(cert);
4212 		return -1;
4213 	}
4214 	SSL_CTX_set_cert_store(ssl_ctx, store);
4215 	if (!X509_STORE_add_cert(store, cert)) {
4216 		unsigned long err = ERR_peek_error();
4217 		tls_show_errors(MSG_WARNING, __func__,
4218 				"Failed to add CA certificate from engine/provider "
4219 				"to certificate store");
4220 		if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
4221 		    ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
4222 			wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
4223 				   " already in hash table error",
4224 				   __func__);
4225 		} else {
4226 			X509_free(cert);
4227 			return -1;
4228 		}
4229 	}
4230 	X509_free(cert);
4231 	wpa_printf(MSG_DEBUG,
4232 		   "OpenSSL: %s - added CA certificate from engine/provider to certificate store",
4233 		   __func__);
4234 	SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
4235 	conn->ca_cert_verify = 1;
4236 
4237 	return 0;
4238 #else /* ANDROID */
4239 	return -1;
4240 #endif /* ANDROID */
4241 }
4242 
4243 
4244 static int tls_connection_engine_private_key(struct tls_connection *conn)
4245 {
4246 	if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
4247 		tls_show_errors(MSG_ERROR, __func__,
4248 				"ENGINE/provider: cannot use private key for TLS");
4249 		return -1;
4250 	}
4251 	if (!SSL_check_private_key(conn->ssl)) {
4252 		tls_show_errors(MSG_INFO, __func__,
4253 				"Private key failed verification");
4254 		return -1;
4255 	}
4256 	return 0;
4257 }
4258 
4259 
4260 #ifndef OPENSSL_NO_STDIO
4261 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
4262 {
4263 	if (!password)
4264 		return 0;
4265 	os_strlcpy(buf, (const char *) password, size);
4266 	return os_strlen(buf);
4267 }
4268 #endif /* OPENSSL_NO_STDIO */
4269 
4270 
4271 static int tls_use_private_key_file(struct tls_data *data, SSL *ssl,
4272 				    const char *private_key,
4273 				    const char *private_key_passwd)
4274 {
4275 #ifndef OPENSSL_NO_STDIO
4276 	BIO *bio;
4277 	EVP_PKEY *pkey;
4278 	int ret;
4279 
4280 	/* First try ASN.1 (DER). */
4281 	bio = BIO_new_file(private_key, "r");
4282 	if (!bio)
4283 		return -1;
4284 	pkey = d2i_PrivateKey_bio(bio, NULL);
4285 	BIO_free(bio);
4286 
4287 	if (pkey) {
4288 		wpa_printf(MSG_DEBUG, "OpenSSL: %s (DER) --> loaded", __func__);
4289 	} else {
4290 		/* Try PEM with the provided password. */
4291 		bio = BIO_new_file(private_key, "r");
4292 		if (!bio)
4293 			return -1;
4294 		pkey = PEM_read_bio_PrivateKey(bio, NULL, tls_passwd_cb,
4295 					       (void *) private_key_passwd);
4296 		BIO_free(bio);
4297 		if (!pkey)
4298 			return -1;
4299 		wpa_printf(MSG_DEBUG, "OpenSSL: %s (PEM) --> loaded", __func__);
4300 		/* Clear errors from the previous failed load. */
4301 		ERR_clear_error();
4302 	}
4303 
4304 	if (ssl)
4305 		ret = SSL_use_PrivateKey(ssl, pkey);
4306 	else
4307 		ret = SSL_CTX_use_PrivateKey(data->ssl, pkey);
4308 
4309 	EVP_PKEY_free(pkey);
4310 	return ret == 1 ? 0 : -1;
4311 #else /* OPENSSL_NO_STDIO */
4312 	wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
4313 	return -1;
4314 #endif /* OPENSSL_NO_STDIO */
4315 }
4316 
4317 
4318 static int tls_connection_private_key(struct tls_data *data,
4319 				      struct tls_connection *conn,
4320 				      const char *private_key,
4321 				      const char *private_key_passwd,
4322 				      const u8 *private_key_blob,
4323 				      size_t private_key_blob_len)
4324 {
4325 	BIO *bio;
4326 	int ok;
4327 
4328 	if (private_key == NULL && private_key_blob == NULL)
4329 		return 0;
4330 
4331 	ok = 0;
4332 	while (private_key_blob) {
4333 		if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
4334 					    (u8 *) private_key_blob,
4335 					    private_key_blob_len) == 1) {
4336 			wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
4337 				   "ASN1(EVP_PKEY_RSA) --> OK");
4338 			ok = 1;
4339 			break;
4340 		}
4341 
4342 		if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
4343 					    (u8 *) private_key_blob,
4344 					    private_key_blob_len) == 1) {
4345 			wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
4346 				   "ASN1(EVP_PKEY_DSA) --> OK");
4347 			ok = 1;
4348 			break;
4349 		}
4350 
4351 #ifndef OPENSSL_NO_EC
4352 		if (SSL_use_PrivateKey_ASN1(EVP_PKEY_EC, conn->ssl,
4353 					    (u8 *) private_key_blob,
4354 					    private_key_blob_len) == 1) {
4355 			wpa_printf(MSG_DEBUG,
4356 				   "OpenSSL: SSL_use_PrivateKey_ASN1(EVP_PKEY_EC) --> OK");
4357 			ok = 1;
4358 			break;
4359 		}
4360 #endif /* OPENSSL_NO_EC */
4361 
4362 #if OPENSSL_VERSION_NUMBER < 0x30000000L
4363 		if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
4364 					       (u8 *) private_key_blob,
4365 					       private_key_blob_len) == 1) {
4366 			wpa_printf(MSG_DEBUG, "OpenSSL: "
4367 				   "SSL_use_RSAPrivateKey_ASN1 --> OK");
4368 			ok = 1;
4369 			break;
4370 		}
4371 #endif
4372 
4373 		bio = BIO_new_mem_buf((u8 *) private_key_blob,
4374 				      private_key_blob_len);
4375 		if (bio) {
4376 			EVP_PKEY *pkey;
4377 
4378 			pkey = PEM_read_bio_PrivateKey(
4379 				bio, NULL, tls_passwd_cb,
4380 				(void *) private_key_passwd);
4381 			if (pkey) {
4382 				if (SSL_use_PrivateKey(conn->ssl, pkey) == 1) {
4383 					wpa_printf(MSG_DEBUG,
4384 						   "OpenSSL: SSL_use_PrivateKey --> OK");
4385 					ok = 1;
4386 					EVP_PKEY_free(pkey);
4387 					BIO_free(bio);
4388 					break;
4389 				}
4390 				EVP_PKEY_free(pkey);
4391 			}
4392 			BIO_free(bio);
4393 		}
4394 
4395 		if (tls_read_pkcs12_blob(data, conn->ssl, private_key_blob,
4396 					 private_key_blob_len,
4397 					 private_key_passwd) == 0) {
4398 			wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
4399 				   "OK");
4400 			ok = 1;
4401 			break;
4402 		}
4403 
4404 		break;
4405 	}
4406 
4407 	while (!ok && private_key) {
4408 		if (tls_use_private_key_file(data, conn->ssl, private_key,
4409 					     private_key_passwd) == 0) {
4410 			ok = 1;
4411 			break;
4412 		}
4413 
4414 		if (tls_read_pkcs12(data, conn->ssl, private_key,
4415 				    private_key_passwd) == 0) {
4416 			wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
4417 				   "--> OK");
4418 			ok = 1;
4419 			break;
4420 		}
4421 
4422 		if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
4423 			wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
4424 				   "access certificate store --> OK");
4425 			ok = 1;
4426 			break;
4427 		}
4428 
4429 		break;
4430 	}
4431 
4432 	if (!ok) {
4433 		tls_show_errors(MSG_INFO, __func__,
4434 				"Failed to load private key");
4435 		return -1;
4436 	}
4437 	ERR_clear_error();
4438 
4439 	if (!SSL_check_private_key(conn->ssl)) {
4440 		tls_show_errors(MSG_INFO, __func__, "Private key failed "
4441 				"verification");
4442 		return -1;
4443 	}
4444 
4445 	wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
4446 	return 0;
4447 }
4448 
4449 
4450 static int tls_global_private_key(struct tls_data *data,
4451 				  const char *private_key,
4452 				  const char *private_key_passwd)
4453 {
4454 	SSL_CTX *ssl_ctx = data->ssl;
4455 
4456 	if (private_key == NULL)
4457 		return 0;
4458 
4459 	if (tls_use_private_key_file(data, NULL, private_key,
4460 				     private_key_passwd) &&
4461 	    tls_read_pkcs12(data, NULL, private_key, private_key_passwd)) {
4462 		tls_show_errors(MSG_INFO, __func__,
4463 				"Failed to load private key");
4464 		ERR_clear_error();
4465 		return -1;
4466 	}
4467 	ERR_clear_error();
4468 
4469 	if (!SSL_CTX_check_private_key(ssl_ctx)) {
4470 		tls_show_errors(MSG_INFO, __func__,
4471 				"Private key failed verification");
4472 		return -1;
4473 	}
4474 
4475 	return 0;
4476 }
4477 
4478 
4479 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
4480 #ifndef OPENSSL_NO_DH
4481 #ifndef OPENSSL_NO_DSA
4482 /* This is needed to replace the deprecated DSA_dup_DH() function */
4483 static EVP_PKEY * openssl_dsa_to_dh(EVP_PKEY *dsa)
4484 {
4485 	OSSL_PARAM_BLD *bld = NULL;
4486 	OSSL_PARAM *params = NULL;
4487 	BIGNUM *p = NULL, *q = NULL, *g = NULL;
4488 	EVP_PKEY_CTX *ctx = NULL;
4489 	EVP_PKEY *pkey = NULL;
4490 
4491 	if (!EVP_PKEY_get_bn_param(dsa, OSSL_PKEY_PARAM_FFC_P, &p) ||
4492 	    !EVP_PKEY_get_bn_param(dsa, OSSL_PKEY_PARAM_FFC_Q, &q) ||
4493 	    !EVP_PKEY_get_bn_param(dsa, OSSL_PKEY_PARAM_FFC_G, &g) ||
4494 	    !(bld = OSSL_PARAM_BLD_new()) ||
4495 	    !OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_P, p) ||
4496 	    !OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_Q, q) ||
4497 	    !OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_G, g) ||
4498 	    !(params = OSSL_PARAM_BLD_to_param(bld)) ||
4499 	    !(ctx = EVP_PKEY_CTX_new_from_name(NULL, "DHX", NULL)) ||
4500 	    EVP_PKEY_fromdata_init(ctx) != 1 ||
4501 	    EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS,
4502 			      params) != 1)
4503 		wpa_printf(MSG_INFO,
4504 			   "TLS: Failed to convert DSA parameters to DH parameters");
4505 
4506 	EVP_PKEY_CTX_free(ctx);
4507 	OSSL_PARAM_free(params);
4508 	OSSL_PARAM_BLD_free(bld);
4509 	BN_free(p);
4510 	BN_free(q);
4511 	BN_free(g);
4512 	return pkey;
4513 }
4514 #endif /* !OPENSSL_NO_DSA */
4515 #endif /* OPENSSL_NO_DH */
4516 #endif /* OpenSSL version >= 3.0 */
4517 
4518 static int tls_global_dh(struct tls_data *data, const char *dh_file)
4519 {
4520 #ifdef OPENSSL_NO_DH
4521 	if (dh_file == NULL)
4522 		return 0;
4523 	wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
4524 		   "dh_file specified");
4525 	return -1;
4526 #else /* OPENSSL_NO_DH */
4527 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
4528 	SSL_CTX *ssl_ctx = data->ssl;
4529 	BIO *bio;
4530 	OSSL_DECODER_CTX *ctx = NULL;
4531 	EVP_PKEY *pkey = NULL, *tmpkey = NULL;
4532 	bool dsa = false;
4533 
4534 	if (!ssl_ctx)
4535 		return -1;
4536 	if (!dh_file) {
4537 		SSL_CTX_set_dh_auto(ssl_ctx, 1);
4538 		return 0;
4539 	}
4540 
4541 	bio = BIO_new_file(dh_file, "r");
4542 	if (!bio) {
4543 		wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
4544 			   dh_file, ERR_error_string(ERR_get_error(), NULL));
4545 		return -1;
4546 	}
4547 	ctx = OSSL_DECODER_CTX_new_for_pkey(
4548 		&tmpkey, "PEM", NULL, NULL,
4549 		OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS, NULL, NULL);
4550 	if (!ctx ||
4551 	    OSSL_DECODER_from_bio(ctx, bio) != 1) {
4552 		wpa_printf(MSG_INFO,
4553 			   "TLS: Failed to decode domain parameters from '%s': %s",
4554 			   dh_file, ERR_error_string(ERR_get_error(), NULL));
4555 		BIO_free(bio);
4556 		OSSL_DECODER_CTX_free(ctx);
4557 		return -1;
4558 	}
4559 	OSSL_DECODER_CTX_free(ctx);
4560 	BIO_free(bio);
4561 
4562 	if (!tmpkey) {
4563 		wpa_printf(MSG_INFO, "TLS: Failed to load domain parameters");
4564 		return -1;
4565 	}
4566 
4567 #ifndef OPENSSL_NO_DSA
4568 	if (EVP_PKEY_is_a(tmpkey, "DSA")) {
4569 		pkey = openssl_dsa_to_dh(tmpkey);
4570 		EVP_PKEY_free(tmpkey);
4571 		if (!pkey)
4572 			return -1;
4573 		dsa = true;
4574 	}
4575 #endif /* !OPENSSL_NO_DSA */
4576 	if (!dsa) {
4577 		if (EVP_PKEY_is_a(tmpkey, "DH") ||
4578 		    EVP_PKEY_is_a(tmpkey, "DHX")) {
4579 		} else {
4580 			wpa_printf(MSG_INFO,
4581 				   "TLS: No DH parameters found in %s",
4582 				   dh_file);
4583 			EVP_PKEY_free(tmpkey);
4584 			return -1;
4585 		}
4586 		pkey = tmpkey;
4587 		tmpkey = NULL;
4588 	}
4589 
4590 	if (SSL_CTX_set0_tmp_dh_pkey(ssl_ctx, pkey) != 1) {
4591 		wpa_printf(MSG_INFO,
4592 			   "TLS: Failed to set DH params from '%s': %s",
4593 			   dh_file, ERR_error_string(ERR_get_error(), NULL));
4594 		EVP_PKEY_free(pkey);
4595 		return -1;
4596 	}
4597 	return 0;
4598 #else /* OpenSSL version >= 3.0 */
4599 	SSL_CTX *ssl_ctx = data->ssl;
4600 	DH *dh;
4601 	BIO *bio;
4602 
4603 	if (!ssl_ctx)
4604 		return -1;
4605 	if (!dh_file) {
4606 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(OPENSSL_IS_BORINGSSL)
4607 		SSL_CTX_set_dh_auto(ssl_ctx, 1);
4608 #endif
4609 		return 0;
4610 	}
4611 
4612 	bio = BIO_new_file(dh_file, "r");
4613 	if (bio == NULL) {
4614 		wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
4615 			   dh_file, ERR_error_string(ERR_get_error(), NULL));
4616 		return -1;
4617 	}
4618 	dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
4619 	BIO_free(bio);
4620 #ifndef OPENSSL_NO_DSA
4621 	while (dh == NULL) {
4622 		DSA *dsa;
4623 		wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
4624 			   " trying to parse as DSA params", dh_file,
4625 			   ERR_error_string(ERR_get_error(), NULL));
4626 		bio = BIO_new_file(dh_file, "r");
4627 		if (bio == NULL)
4628 			break;
4629 		dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
4630 		BIO_free(bio);
4631 		if (!dsa) {
4632 			wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
4633 				   "'%s': %s", dh_file,
4634 				   ERR_error_string(ERR_get_error(), NULL));
4635 			break;
4636 		}
4637 
4638 		wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
4639 		dh = DSA_dup_DH(dsa);
4640 		DSA_free(dsa);
4641 		if (dh == NULL) {
4642 			wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
4643 				   "params into DH params");
4644 			break;
4645 		}
4646 		break;
4647 	}
4648 #endif /* !OPENSSL_NO_DSA */
4649 	if (dh == NULL) {
4650 		wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
4651 			   "'%s'", dh_file);
4652 		return -1;
4653 	}
4654 
4655 	if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
4656 		wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
4657 			   "%s", dh_file,
4658 			   ERR_error_string(ERR_get_error(), NULL));
4659 		DH_free(dh);
4660 		return -1;
4661 	}
4662 	DH_free(dh);
4663 	return 0;
4664 #endif /* OpenSSL version >= 3.0 */
4665 #endif /* OPENSSL_NO_DH */
4666 }
4667 
4668 
4669 int tls_connection_get_random(void *ssl_ctx, struct tls_connection *conn,
4670 			      struct tls_random *keys)
4671 {
4672 	SSL *ssl;
4673 
4674 	if (conn == NULL || keys == NULL)
4675 		return -1;
4676 	ssl = conn->ssl;
4677 	if (ssl == NULL)
4678 		return -1;
4679 
4680 	os_memset(keys, 0, sizeof(*keys));
4681 	keys->client_random = conn->client_random;
4682 	keys->client_random_len = SSL_get_client_random(
4683 		ssl, conn->client_random, sizeof(conn->client_random));
4684 	keys->server_random = conn->server_random;
4685 	keys->server_random_len = SSL_get_server_random(
4686 		ssl, conn->server_random, sizeof(conn->server_random));
4687 
4688 	return 0;
4689 }
4690 
4691 
4692 #ifdef OPENSSL_NEED_EAP_FAST_PRF
4693 static int openssl_get_keyblock_size(SSL *ssl)
4694 {
4695 #if OPENSSL_VERSION_NUMBER < 0x10100000L
4696 	const EVP_CIPHER *c;
4697 	const EVP_MD *h;
4698 	int md_size;
4699 
4700 	if (ssl->enc_read_ctx == NULL || ssl->enc_read_ctx->cipher == NULL ||
4701 	    ssl->read_hash == NULL)
4702 		return -1;
4703 
4704 	c = ssl->enc_read_ctx->cipher;
4705 	h = EVP_MD_CTX_md(ssl->read_hash);
4706 	if (h)
4707 		md_size = EVP_MD_size(h);
4708 	else if (ssl->s3)
4709 		md_size = ssl->s3->tmp.new_mac_secret_size;
4710 	else
4711 		return -1;
4712 
4713 	wpa_printf(MSG_DEBUG, "OpenSSL: keyblock size: key_len=%d MD_size=%d "
4714 		   "IV_len=%d", EVP_CIPHER_key_length(c), md_size,
4715 		   EVP_CIPHER_iv_length(c));
4716 	return 2 * (EVP_CIPHER_key_length(c) +
4717 		    md_size +
4718 		    EVP_CIPHER_iv_length(c));
4719 #else
4720 	const SSL_CIPHER *ssl_cipher;
4721 	int cipher, digest;
4722 	const EVP_CIPHER *c;
4723 	const EVP_MD *h;
4724 	int mac_key_len, enc_key_len, fixed_iv_len;
4725 
4726 	ssl_cipher = SSL_get_current_cipher(ssl);
4727 	if (!ssl_cipher)
4728 		return -1;
4729 	cipher = SSL_CIPHER_get_cipher_nid(ssl_cipher);
4730 	digest = SSL_CIPHER_get_digest_nid(ssl_cipher);
4731 	wpa_printf(MSG_DEBUG, "OpenSSL: cipher nid %d digest nid %d",
4732 		   cipher, digest);
4733 	if (cipher < 0 || digest < 0)
4734 		return -1;
4735 	if (cipher == NID_undef) {
4736 		wpa_printf(MSG_DEBUG, "OpenSSL: no cipher in use?!");
4737 		return -1;
4738 	}
4739 	c = EVP_get_cipherbynid(cipher);
4740 	if (!c)
4741 		return -1;
4742 	enc_key_len = EVP_CIPHER_key_length(c);
4743 	if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE ||
4744 	    EVP_CIPHER_mode(c) == EVP_CIPH_CCM_MODE)
4745 		fixed_iv_len = 4; /* only part of IV from PRF */
4746 	else
4747 		fixed_iv_len = EVP_CIPHER_iv_length(c);
4748 	if (digest == NID_undef) {
4749 		wpa_printf(MSG_DEBUG, "OpenSSL: no digest in use (e.g., AEAD)");
4750 		mac_key_len = 0;
4751 	} else {
4752 		h = EVP_get_digestbynid(digest);
4753 		if (!h)
4754 			return -1;
4755 		mac_key_len = EVP_MD_size(h);
4756 	}
4757 
4758 	wpa_printf(MSG_DEBUG,
4759 		   "OpenSSL: keyblock size: mac_key_len=%d enc_key_len=%d fixed_iv_len=%d",
4760 		   mac_key_len, enc_key_len, fixed_iv_len);
4761 	return 2 * (mac_key_len + enc_key_len + fixed_iv_len);
4762 #endif
4763 }
4764 #endif /* OPENSSL_NEED_EAP_FAST_PRF */
4765 
4766 
4767 int tls_connection_export_key(void *tls_ctx, struct tls_connection *conn,
4768 			      const char *label, const u8 *context,
4769 			      size_t context_len, u8 *out, size_t out_len)
4770 {
4771 	if (!conn ||
4772 	    SSL_export_keying_material(conn->ssl, out, out_len, label,
4773 				       os_strlen(label), context, context_len,
4774 				       context != NULL) != 1)
4775 		return -1;
4776 	return 0;
4777 }
4778 
4779 
4780 int tls_connection_get_eap_fast_key(void *tls_ctx, struct tls_connection *conn,
4781 				    u8 *out, size_t out_len)
4782 {
4783 #ifdef OPENSSL_NEED_EAP_FAST_PRF
4784 	SSL *ssl;
4785 	SSL_SESSION *sess;
4786 	u8 *rnd;
4787 	int ret = -1;
4788 	int skip = 0;
4789 	u8 *tmp_out = NULL;
4790 	u8 *_out = out;
4791 	unsigned char client_random[SSL3_RANDOM_SIZE];
4792 	unsigned char server_random[SSL3_RANDOM_SIZE];
4793 	unsigned char master_key[64];
4794 	size_t master_key_len;
4795 	const char *ver;
4796 
4797 	/*
4798 	 * TLS library did not support EAP-FAST key generation, so get the
4799 	 * needed TLS session parameters and use an internal implementation of
4800 	 * TLS PRF to derive the key.
4801 	 */
4802 
4803 	if (conn == NULL)
4804 		return -1;
4805 	ssl = conn->ssl;
4806 	if (ssl == NULL)
4807 		return -1;
4808 	ver = SSL_get_version(ssl);
4809 	sess = SSL_get_session(ssl);
4810 	if (!ver || !sess)
4811 		return -1;
4812 
4813 	skip = openssl_get_keyblock_size(ssl);
4814 	if (skip < 0)
4815 		return -1;
4816 	tmp_out = os_malloc(skip + out_len);
4817 	if (!tmp_out)
4818 		return -1;
4819 	_out = tmp_out;
4820 
4821 	rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
4822 	if (!rnd) {
4823 		os_free(tmp_out);
4824 		return -1;
4825 	}
4826 
4827 	SSL_get_client_random(ssl, client_random, sizeof(client_random));
4828 	SSL_get_server_random(ssl, server_random, sizeof(server_random));
4829 	master_key_len = SSL_SESSION_get_master_key(sess, master_key,
4830 						    sizeof(master_key));
4831 
4832 	os_memcpy(rnd, server_random, SSL3_RANDOM_SIZE);
4833 	os_memcpy(rnd + SSL3_RANDOM_SIZE, client_random, SSL3_RANDOM_SIZE);
4834 
4835 	if (os_strcmp(ver, "TLSv1.2") == 0) {
4836 		tls_prf_sha256(master_key, master_key_len,
4837 			       "key expansion", rnd, 2 * SSL3_RANDOM_SIZE,
4838 			       _out, skip + out_len);
4839 		ret = 0;
4840 	} else if (tls_prf_sha1_md5(master_key, master_key_len,
4841 				    "key expansion", rnd, 2 * SSL3_RANDOM_SIZE,
4842 				    _out, skip + out_len) == 0) {
4843 		ret = 0;
4844 	}
4845 	forced_memzero(master_key, sizeof(master_key));
4846 	os_free(rnd);
4847 	if (ret == 0)
4848 		os_memcpy(out, _out + skip, out_len);
4849 	bin_clear_free(tmp_out, skip);
4850 
4851 	return ret;
4852 #else /* OPENSSL_NEED_EAP_FAST_PRF */
4853 	wpa_printf(MSG_ERROR,
4854 		   "OpenSSL: EAP-FAST keys cannot be exported in FIPS mode");
4855 	return -1;
4856 #endif /* OPENSSL_NEED_EAP_FAST_PRF */
4857 }
4858 
4859 
4860 static struct wpabuf *
4861 openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data)
4862 {
4863 	struct tls_context *context = conn->context;
4864 	int res;
4865 	struct wpabuf *out_data;
4866 
4867 	/*
4868 	 * Give TLS handshake data from the server (if available) to OpenSSL
4869 	 * for processing.
4870 	 */
4871 	if (in_data && wpabuf_len(in_data) > 0 &&
4872 	    BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
4873 	    < 0) {
4874 		tls_show_errors(MSG_INFO, __func__,
4875 				"Handshake failed - BIO_write");
4876 		return NULL;
4877 	}
4878 
4879 	/* Initiate TLS handshake or continue the existing handshake */
4880 	if (conn->server)
4881 		res = SSL_accept(conn->ssl);
4882 	else
4883 		res = SSL_connect(conn->ssl);
4884 	if (res != 1) {
4885 		int err = SSL_get_error(conn->ssl, res);
4886 		if (err == SSL_ERROR_WANT_READ)
4887 			wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
4888 				   "more data");
4889 		else if (err == SSL_ERROR_WANT_WRITE)
4890 			wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
4891 				   "write");
4892 		else {
4893 			unsigned long error = ERR_peek_last_error();
4894 
4895 			tls_show_errors(MSG_INFO, __func__, "SSL_connect");
4896 
4897 			if (context->event_cb &&
4898 			    ERR_GET_LIB(error) == ERR_LIB_SSL &&
4899 			    ERR_GET_REASON(error) ==
4900 			    SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED) {
4901 				context->event_cb(
4902 					context->cb_ctx,
4903 					TLS_UNSAFE_RENEGOTIATION_DISABLED,
4904 					NULL);
4905 			}
4906 			conn->failed++;
4907 			if (!conn->server && !conn->client_hello_generated) {
4908 				/* The server would not understand TLS Alert
4909 				 * before ClientHello, so simply terminate
4910 				 * handshake on this type of error case caused
4911 				 * by a likely internal error like no ciphers
4912 				 * available. */
4913 				wpa_printf(MSG_DEBUG,
4914 					   "OpenSSL: Could not generate ClientHello");
4915 				conn->write_alerts++;
4916 				return NULL;
4917 			}
4918 		}
4919 	}
4920 
4921 	if (!conn->server && !conn->failed)
4922 		conn->client_hello_generated = 1;
4923 
4924 #ifdef CONFIG_SUITEB
4925 	if ((conn->flags & TLS_CONN_SUITEB) && !conn->server &&
4926 	    os_strncmp(SSL_get_cipher(conn->ssl), "DHE-", 4) == 0 &&
4927 	    conn->server_dh_prime_len < 3072) {
4928 		/*
4929 		 * This should not be reached since earlier cert_cb should have
4930 		 * terminated the handshake. Keep this check here for extra
4931 		 * protection if anything goes wrong with the more low-level
4932 		 * checks based on having to parse the TLS handshake messages.
4933 		 */
4934 		wpa_printf(MSG_DEBUG,
4935 			   "OpenSSL: Server DH prime length: %d bits",
4936 			   conn->server_dh_prime_len);
4937 
4938 		if (context->event_cb) {
4939 			union tls_event_data ev;
4940 
4941 			os_memset(&ev, 0, sizeof(ev));
4942 			ev.alert.is_local = 1;
4943 			ev.alert.type = "fatal";
4944 			ev.alert.description = "insufficient security";
4945 			context->event_cb(context->cb_ctx, TLS_ALERT, &ev);
4946 		}
4947 		/*
4948 		 * Could send a TLS Alert to the server, but for now, simply
4949 		 * terminate handshake.
4950 		 */
4951 		conn->failed++;
4952 		conn->write_alerts++;
4953 		return NULL;
4954 	}
4955 #endif /* CONFIG_SUITEB */
4956 
4957 	/* Get the TLS handshake data to be sent to the server */
4958 	res = BIO_ctrl_pending(conn->ssl_out);
4959 	wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
4960 	out_data = wpabuf_alloc(res);
4961 	if (out_data == NULL) {
4962 		wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
4963 			   "handshake output (%d bytes)", res);
4964 		if (BIO_reset(conn->ssl_out) < 0) {
4965 			tls_show_errors(MSG_INFO, __func__,
4966 					"BIO_reset failed");
4967 		}
4968 		return NULL;
4969 	}
4970 	res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
4971 				      res);
4972 	if (res < 0) {
4973 		tls_show_errors(MSG_INFO, __func__,
4974 				"Handshake failed - BIO_read");
4975 		if (BIO_reset(conn->ssl_out) < 0) {
4976 			tls_show_errors(MSG_INFO, __func__,
4977 					"BIO_reset failed");
4978 		}
4979 		wpabuf_free(out_data);
4980 		return NULL;
4981 	}
4982 	wpabuf_put(out_data, res);
4983 
4984 	return out_data;
4985 }
4986 
4987 
4988 static struct wpabuf *
4989 openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
4990 {
4991 	struct wpabuf *appl_data;
4992 	int res;
4993 
4994 	appl_data = wpabuf_alloc(max_len + 100);
4995 	if (appl_data == NULL)
4996 		return NULL;
4997 
4998 	res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
4999 		       wpabuf_size(appl_data));
5000 	if (res < 0) {
5001 		int err = SSL_get_error(conn->ssl, res);
5002 		if (err == SSL_ERROR_WANT_READ ||
5003 		    err == SSL_ERROR_WANT_WRITE) {
5004 			wpa_printf(MSG_DEBUG, "SSL: No Application Data "
5005 				   "included");
5006 		} else {
5007 			tls_show_errors(MSG_INFO, __func__,
5008 					"Failed to read possible "
5009 					"Application Data");
5010 		}
5011 		wpabuf_free(appl_data);
5012 		return NULL;
5013 	}
5014 
5015 	wpabuf_put(appl_data, res);
5016 	wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
5017 			    "message", appl_data);
5018 
5019 	return appl_data;
5020 }
5021 
5022 
5023 static struct wpabuf *
5024 openssl_connection_handshake(struct tls_connection *conn,
5025 			     const struct wpabuf *in_data,
5026 			     struct wpabuf **appl_data)
5027 {
5028 	struct wpabuf *out_data;
5029 
5030 	if (appl_data)
5031 		*appl_data = NULL;
5032 
5033 	out_data = openssl_handshake(conn, in_data);
5034 	if (out_data == NULL)
5035 		return NULL;
5036 	if (conn->invalid_hb_used) {
5037 		wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
5038 		wpabuf_free(out_data);
5039 		return NULL;
5040 	}
5041 
5042 	if (SSL_is_init_finished(conn->ssl)) {
5043 		wpa_printf(MSG_DEBUG,
5044 			   "OpenSSL: Handshake finished - resumed=%d",
5045 			   tls_connection_resumed(conn->ssl_ctx, conn));
5046 		if (conn->server) {
5047 			char *buf;
5048 			size_t buflen = 2000;
5049 
5050 			buf = os_malloc(buflen);
5051 			if (buf) {
5052 				if (SSL_get_shared_ciphers(conn->ssl, buf,
5053 							   buflen)) {
5054 					buf[buflen - 1] = '\0';
5055 					wpa_printf(MSG_DEBUG,
5056 						   "OpenSSL: Shared ciphers: %s",
5057 						   buf);
5058 				}
5059 				os_free(buf);
5060 			}
5061 		}
5062 		if (appl_data && in_data)
5063 			*appl_data = openssl_get_appl_data(conn,
5064 							   wpabuf_len(in_data));
5065 	}
5066 
5067 	if (conn->invalid_hb_used) {
5068 		wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
5069 		if (appl_data) {
5070 			wpabuf_free(*appl_data);
5071 			*appl_data = NULL;
5072 		}
5073 		wpabuf_free(out_data);
5074 		return NULL;
5075 	}
5076 
5077 	return out_data;
5078 }
5079 
5080 
5081 struct wpabuf *
5082 tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
5083 			 const struct wpabuf *in_data,
5084 			 struct wpabuf **appl_data)
5085 {
5086 	return openssl_connection_handshake(conn, in_data, appl_data);
5087 }
5088 
5089 
5090 struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
5091 						struct tls_connection *conn,
5092 						const struct wpabuf *in_data,
5093 						struct wpabuf **appl_data)
5094 {
5095 	conn->server = 1;
5096 	return openssl_connection_handshake(conn, in_data, appl_data);
5097 }
5098 
5099 
5100 struct wpabuf * tls_connection_encrypt(void *tls_ctx,
5101 				       struct tls_connection *conn,
5102 				       const struct wpabuf *in_data)
5103 {
5104 	int res;
5105 	struct wpabuf *buf;
5106 
5107 	if (conn == NULL)
5108 		return NULL;
5109 
5110 	/* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
5111 	if ((res = BIO_reset(conn->ssl_in)) < 0 ||
5112 	    (res = BIO_reset(conn->ssl_out)) < 0) {
5113 		tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
5114 		return NULL;
5115 	}
5116 	res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
5117 	if (res < 0) {
5118 		tls_show_errors(MSG_INFO, __func__,
5119 				"Encryption failed - SSL_write");
5120 		return NULL;
5121 	}
5122 
5123 	/* Read encrypted data to be sent to the server */
5124 	buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
5125 	if (buf == NULL)
5126 		return NULL;
5127 	res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
5128 	if (res < 0) {
5129 		tls_show_errors(MSG_INFO, __func__,
5130 				"Encryption failed - BIO_read");
5131 		wpabuf_free(buf);
5132 		return NULL;
5133 	}
5134 	wpabuf_put(buf, res);
5135 
5136 	return buf;
5137 }
5138 
5139 
5140 struct wpabuf * tls_connection_decrypt(void *tls_ctx,
5141 				       struct tls_connection *conn,
5142 				       const struct wpabuf *in_data)
5143 {
5144 	int res;
5145 	struct wpabuf *buf;
5146 
5147 	/* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
5148 	res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
5149 			wpabuf_len(in_data));
5150 	if (res < 0) {
5151 		tls_show_errors(MSG_INFO, __func__,
5152 				"Decryption failed - BIO_write");
5153 		return NULL;
5154 	}
5155 	if (BIO_reset(conn->ssl_out) < 0) {
5156 		tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
5157 		return NULL;
5158 	}
5159 
5160 	/* Read decrypted data for further processing */
5161 	/*
5162 	 * Even though we try to disable TLS compression, it is possible that
5163 	 * this cannot be done with all TLS libraries. Add extra buffer space
5164 	 * to handle the possibility of the decrypted data being longer than
5165 	 * input data.
5166 	 */
5167 	buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
5168 	if (buf == NULL)
5169 		return NULL;
5170 	res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
5171 	if (res < 0) {
5172 		int err = SSL_get_error(conn->ssl, res);
5173 
5174 		if (err == SSL_ERROR_WANT_READ) {
5175 			wpa_printf(MSG_DEBUG,
5176 				   "SSL: SSL_connect - want more data");
5177 			res = 0;
5178 		} else {
5179 			tls_show_errors(MSG_INFO, __func__,
5180 					"Decryption failed - SSL_read");
5181 			wpabuf_free(buf);
5182 			return NULL;
5183 		}
5184 	}
5185 	wpabuf_put(buf, res);
5186 
5187 	if (conn->invalid_hb_used) {
5188 		wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
5189 		wpabuf_free(buf);
5190 		return NULL;
5191 	}
5192 
5193 	return buf;
5194 }
5195 
5196 
5197 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
5198 {
5199 	return conn ? SSL_session_reused(conn->ssl) : 0;
5200 }
5201 
5202 
5203 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
5204 				   u8 *ciphers)
5205 {
5206 	char buf[500], *pos, *end;
5207 	u8 *c;
5208 	int ret;
5209 
5210 	if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
5211 		return -1;
5212 
5213 	buf[0] = '\0';
5214 	pos = buf;
5215 	end = pos + sizeof(buf);
5216 
5217 	c = ciphers;
5218 	while (*c != TLS_CIPHER_NONE) {
5219 		const char *suite;
5220 
5221 		switch (*c) {
5222 		case TLS_CIPHER_RC4_SHA:
5223 			suite = "RC4-SHA";
5224 			break;
5225 		case TLS_CIPHER_AES128_SHA:
5226 			suite = "AES128-SHA";
5227 			break;
5228 		case TLS_CIPHER_RSA_DHE_AES128_SHA:
5229 			suite = "DHE-RSA-AES128-SHA";
5230 			break;
5231 		case TLS_CIPHER_ANON_DH_AES128_SHA:
5232 			suite = "ADH-AES128-SHA";
5233 			break;
5234 		case TLS_CIPHER_RSA_DHE_AES256_SHA:
5235 			suite = "DHE-RSA-AES256-SHA";
5236 			break;
5237 		case TLS_CIPHER_AES256_SHA:
5238 			suite = "AES256-SHA";
5239 			break;
5240 		default:
5241 			wpa_printf(MSG_DEBUG, "TLS: Unsupported "
5242 				   "cipher selection: %d", *c);
5243 			return -1;
5244 		}
5245 		ret = os_snprintf(pos, end - pos, ":%s", suite);
5246 		if (os_snprintf_error(end - pos, ret))
5247 			break;
5248 		pos += ret;
5249 
5250 		c++;
5251 	}
5252 	if (!buf[0]) {
5253 		wpa_printf(MSG_DEBUG, "OpenSSL: No ciphers listed");
5254 		return -1;
5255 	}
5256 
5257 	wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
5258 
5259 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
5260 #ifdef EAP_FAST_OR_TEAP
5261 	if (os_strstr(buf, ":ADH-")) {
5262 		/*
5263 		 * Need to drop to security level 0 to allow anonymous
5264 		 * cipher suites for EAP-FAST.
5265 		 */
5266 		SSL_set_security_level(conn->ssl, 0);
5267 	} else if (SSL_get_security_level(conn->ssl) == 0) {
5268 		/* Force at least security level 1 */
5269 		SSL_set_security_level(conn->ssl, 1);
5270 	}
5271 #endif /* EAP_FAST_OR_TEAP */
5272 #endif
5273 
5274 	if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
5275 		tls_show_errors(MSG_INFO, __func__,
5276 				"Cipher suite configuration failed");
5277 		return -1;
5278 	}
5279 
5280 	return 0;
5281 }
5282 
5283 
5284 int tls_get_version(void *ssl_ctx, struct tls_connection *conn,
5285 		    char *buf, size_t buflen)
5286 {
5287 	const char *name;
5288 	if (conn == NULL || conn->ssl == NULL)
5289 		return -1;
5290 
5291 	name = SSL_get_version(conn->ssl);
5292 	if (name == NULL)
5293 		return -1;
5294 
5295 	os_strlcpy(buf, name, buflen);
5296 	return 0;
5297 }
5298 
5299 
5300 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
5301 		   char *buf, size_t buflen)
5302 {
5303 	const char *name;
5304 	if (conn == NULL || conn->ssl == NULL)
5305 		return -1;
5306 
5307 	name = SSL_get_cipher(conn->ssl);
5308 	if (name == NULL)
5309 		return -1;
5310 
5311 	os_strlcpy(buf, name, buflen);
5312 	return 0;
5313 }
5314 
5315 
5316 int tls_connection_enable_workaround(void *ssl_ctx,
5317 				     struct tls_connection *conn)
5318 {
5319 	SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
5320 
5321 	return 0;
5322 }
5323 
5324 
5325 #ifdef EAP_FAST_OR_TEAP
5326 /* ClientHello TLS extensions require a patch to openssl, so this function is
5327  * commented out unless explicitly needed for EAP-FAST in order to be able to
5328  * build this file with unmodified openssl. */
5329 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
5330 				    int ext_type, const u8 *data,
5331 				    size_t data_len)
5332 {
5333 	if (conn == NULL || conn->ssl == NULL || ext_type != 35)
5334 		return -1;
5335 
5336 	if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
5337 				       data_len) != 1)
5338 		return -1;
5339 
5340 	return 0;
5341 }
5342 #endif /* EAP_FAST_OR_TEAP */
5343 
5344 
5345 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
5346 {
5347 	if (conn == NULL)
5348 		return -1;
5349 	return conn->failed;
5350 }
5351 
5352 
5353 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
5354 {
5355 	if (conn == NULL)
5356 		return -1;
5357 	return conn->read_alerts;
5358 }
5359 
5360 
5361 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
5362 {
5363 	if (conn == NULL)
5364 		return -1;
5365 	return conn->write_alerts;
5366 }
5367 
5368 
5369 #ifdef HAVE_OCSP
5370 
5371 static void ocsp_debug_print_resp(OCSP_RESPONSE *rsp)
5372 {
5373 #ifndef CONFIG_NO_STDOUT_DEBUG
5374 	BIO *out;
5375 	size_t rlen;
5376 	char *txt;
5377 	int res;
5378 
5379 	if (wpa_debug_level > MSG_DEBUG)
5380 		return;
5381 
5382 	out = BIO_new(BIO_s_mem());
5383 	if (!out)
5384 		return;
5385 
5386 	OCSP_RESPONSE_print(out, rsp, 0);
5387 	rlen = BIO_ctrl_pending(out);
5388 	txt = os_malloc(rlen + 1);
5389 	if (!txt) {
5390 		BIO_free(out);
5391 		return;
5392 	}
5393 
5394 	res = BIO_read(out, txt, rlen);
5395 	if (res > 0) {
5396 		txt[res] = '\0';
5397 		wpa_printf(MSG_DEBUG, "OpenSSL: OCSP Response\n%s", txt);
5398 	}
5399 	os_free(txt);
5400 	BIO_free(out);
5401 #endif /* CONFIG_NO_STDOUT_DEBUG */
5402 }
5403 
5404 
5405 static int ocsp_resp_cb(SSL *s, void *arg)
5406 {
5407 	struct tls_connection *conn = arg;
5408 	const unsigned char *p;
5409 	int len, status, reason, res;
5410 	OCSP_RESPONSE *rsp;
5411 	OCSP_BASICRESP *basic;
5412 	OCSP_CERTID *id;
5413 	ASN1_GENERALIZEDTIME *produced_at, *this_update, *next_update;
5414 	X509_STORE *store;
5415 	STACK_OF(X509) *certs = NULL;
5416 
5417 	len = SSL_get_tlsext_status_ocsp_resp(s, &p);
5418 	if (!p) {
5419 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
5420 #if !defined(LIBRESSL_VERSION_NUMBER) || LIBRESSL_VERSION_NUMBER >= 0x30400000L
5421 		if (SSL_version(s) == TLS1_3_VERSION && SSL_session_reused(s)) {
5422 			/* TLS 1.3 sends the OCSP response with the server
5423 			 * Certificate message. Since that Certificate message
5424 			 * is not sent when resuming a session, there can be no
5425 			 * new OCSP response. Allow this since the OCSP response
5426 			 * was validated when checking the initial certificate
5427 			 * exchange. */
5428 			wpa_printf(MSG_DEBUG,
5429 				   "OpenSSL: Allow no OCSP response when using TLS 1.3 and a resumed session");
5430 			return 1;
5431 		}
5432 #endif
5433 #endif
5434 		wpa_printf(MSG_DEBUG, "OpenSSL: No OCSP response received");
5435 		return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
5436 	}
5437 
5438 	wpa_hexdump(MSG_DEBUG, "OpenSSL: OCSP response", p, len);
5439 
5440 	rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
5441 	if (!rsp) {
5442 		wpa_printf(MSG_INFO, "OpenSSL: Failed to parse OCSP response");
5443 		return 0;
5444 	}
5445 
5446 	ocsp_debug_print_resp(rsp);
5447 
5448 	status = OCSP_response_status(rsp);
5449 	if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
5450 		wpa_printf(MSG_INFO, "OpenSSL: OCSP responder error %d (%s)",
5451 			   status, OCSP_response_status_str(status));
5452 		return 0;
5453 	}
5454 
5455 	basic = OCSP_response_get1_basic(rsp);
5456 	if (!basic) {
5457 		wpa_printf(MSG_INFO, "OpenSSL: Could not find BasicOCSPResponse");
5458 		return 0;
5459 	}
5460 
5461 	store = SSL_CTX_get_cert_store(conn->ssl_ctx);
5462 	if (conn->peer_issuer) {
5463 		debug_print_cert(conn->peer_issuer, "Add OCSP issuer");
5464 
5465 		if (X509_STORE_add_cert(store, conn->peer_issuer) != 1) {
5466 			tls_show_errors(MSG_INFO, __func__,
5467 					"OpenSSL: Could not add issuer to certificate store");
5468 		}
5469 		certs = sk_X509_new_null();
5470 		if (certs) {
5471 			X509 *cert;
5472 			cert = X509_dup(conn->peer_issuer);
5473 			if (cert && !sk_X509_push(certs, cert)) {
5474 				tls_show_errors(
5475 					MSG_INFO, __func__,
5476 					"OpenSSL: Could not add issuer to OCSP responder trust store");
5477 				X509_free(cert);
5478 				sk_X509_free(certs);
5479 				certs = NULL;
5480 			}
5481 			if (certs && conn->peer_issuer_issuer) {
5482 				cert = X509_dup(conn->peer_issuer_issuer);
5483 				if (cert && !sk_X509_push(certs, cert)) {
5484 					tls_show_errors(
5485 						MSG_INFO, __func__,
5486 						"OpenSSL: Could not add issuer's issuer to OCSP responder trust store");
5487 					X509_free(cert);
5488 				}
5489 			}
5490 		}
5491 	}
5492 
5493 	status = OCSP_basic_verify(basic, certs, store, OCSP_TRUSTOTHER);
5494 	sk_X509_pop_free(certs, X509_free);
5495 	if (status <= 0) {
5496 		tls_show_errors(MSG_INFO, __func__,
5497 				"OpenSSL: OCSP response failed verification");
5498 		OCSP_BASICRESP_free(basic);
5499 		OCSP_RESPONSE_free(rsp);
5500 		return 0;
5501 	}
5502 
5503 	wpa_printf(MSG_DEBUG, "OpenSSL: OCSP response verification succeeded");
5504 
5505 	if (!conn->peer_cert) {
5506 		wpa_printf(MSG_DEBUG, "OpenSSL: Peer certificate not available for OCSP status check");
5507 		OCSP_BASICRESP_free(basic);
5508 		OCSP_RESPONSE_free(rsp);
5509 		return 0;
5510 	}
5511 
5512 	if (!conn->peer_issuer) {
5513 		wpa_printf(MSG_DEBUG, "OpenSSL: Peer issuer certificate not available for OCSP status check");
5514 		OCSP_BASICRESP_free(basic);
5515 		OCSP_RESPONSE_free(rsp);
5516 		return 0;
5517 	}
5518 
5519 	id = OCSP_cert_to_id(EVP_sha256(), conn->peer_cert, conn->peer_issuer);
5520 	if (!id) {
5521 		wpa_printf(MSG_DEBUG,
5522 			   "OpenSSL: Could not create OCSP certificate identifier (SHA256)");
5523 		OCSP_BASICRESP_free(basic);
5524 		OCSP_RESPONSE_free(rsp);
5525 		return 0;
5526 	}
5527 
5528 	res = OCSP_resp_find_status(basic, id, &status, &reason, &produced_at,
5529 				    &this_update, &next_update);
5530 	if (!res) {
5531 		OCSP_CERTID_free(id);
5532 		id = OCSP_cert_to_id(NULL, conn->peer_cert, conn->peer_issuer);
5533 		if (!id) {
5534 			wpa_printf(MSG_DEBUG,
5535 				   "OpenSSL: Could not create OCSP certificate identifier (SHA1)");
5536 			OCSP_BASICRESP_free(basic);
5537 			OCSP_RESPONSE_free(rsp);
5538 			return 0;
5539 		}
5540 
5541 		res = OCSP_resp_find_status(basic, id, &status, &reason,
5542 					    &produced_at, &this_update,
5543 					    &next_update);
5544 	}
5545 
5546 	if (!res) {
5547 		wpa_printf(MSG_INFO, "OpenSSL: Could not find current server certificate from OCSP response%s",
5548 			   (conn->flags & TLS_CONN_REQUIRE_OCSP) ? "" :
5549 			   " (OCSP not required)");
5550 		OCSP_CERTID_free(id);
5551 		OCSP_BASICRESP_free(basic);
5552 		OCSP_RESPONSE_free(rsp);
5553 		return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
5554 	}
5555 	OCSP_CERTID_free(id);
5556 
5557 	if (!OCSP_check_validity(this_update, next_update, 5 * 60, -1)) {
5558 		tls_show_errors(MSG_INFO, __func__,
5559 				"OpenSSL: OCSP status times invalid");
5560 		OCSP_BASICRESP_free(basic);
5561 		OCSP_RESPONSE_free(rsp);
5562 		return 0;
5563 	}
5564 
5565 	OCSP_BASICRESP_free(basic);
5566 	OCSP_RESPONSE_free(rsp);
5567 
5568 	wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status for server certificate: %s",
5569 		   OCSP_cert_status_str(status));
5570 
5571 	if (status == V_OCSP_CERTSTATUS_GOOD)
5572 		return 1;
5573 	if (status == V_OCSP_CERTSTATUS_REVOKED)
5574 		return 0;
5575 	if (conn->flags & TLS_CONN_REQUIRE_OCSP) {
5576 		wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP required");
5577 		return 0;
5578 	}
5579 	wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP was not required, so allow connection to continue");
5580 	return 1;
5581 }
5582 
5583 
5584 static int ocsp_status_cb(SSL *s, void *arg)
5585 {
5586 	char *tmp;
5587 	char *resp;
5588 	size_t len;
5589 
5590 	if (tls_global->ocsp_stapling_response == NULL) {
5591 		wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - no response configured");
5592 		return SSL_TLSEXT_ERR_OK;
5593 	}
5594 
5595 	resp = os_readfile(tls_global->ocsp_stapling_response, &len);
5596 	if (resp == NULL) {
5597 		wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - could not read response file");
5598 		/* TODO: Build OCSPResponse with responseStatus = internalError
5599 		 */
5600 		return SSL_TLSEXT_ERR_OK;
5601 	}
5602 	wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - send cached response");
5603 	tmp = OPENSSL_malloc(len);
5604 	if (tmp == NULL) {
5605 		os_free(resp);
5606 		return SSL_TLSEXT_ERR_ALERT_FATAL;
5607 	}
5608 
5609 	os_memcpy(tmp, resp, len);
5610 	os_free(resp);
5611 	SSL_set_tlsext_status_ocsp_resp(s, tmp, len);
5612 
5613 	return SSL_TLSEXT_ERR_OK;
5614 }
5615 
5616 #endif /* HAVE_OCSP */
5617 
5618 
5619 static size_t max_str_len(const char **lines)
5620 {
5621 	const char **p;
5622 	size_t max_len = 0;
5623 
5624 	for (p = lines; *p; p++) {
5625 		size_t len = os_strlen(*p);
5626 
5627 		if (len > max_len)
5628 			max_len = len;
5629 	}
5630 
5631 	return max_len;
5632 }
5633 
5634 
5635 static int match_lines_in_file(const char *path, const char **lines)
5636 {
5637 	FILE *f;
5638 	char *buf;
5639 	size_t bufsize;
5640 	int found = 0, is_linestart = 1;
5641 
5642 	bufsize = max_str_len(lines) + sizeof("\r\n");
5643 	buf = os_malloc(bufsize);
5644 	if (!buf)
5645 		return 0;
5646 
5647 	f = fopen(path, "r");
5648 	if (!f) {
5649 		os_free(buf);
5650 		return 0;
5651 	}
5652 
5653 	while (!found && fgets(buf, bufsize, f)) {
5654 		int is_lineend;
5655 		size_t len;
5656 		const char **p;
5657 
5658 		len = strcspn(buf, "\r\n");
5659 		is_lineend = buf[len] != '\0';
5660 		buf[len] = '\0';
5661 
5662 		if (is_linestart && is_lineend) {
5663 			for (p = lines; !found && *p; p++)
5664 				found = os_strcmp(buf, *p) == 0;
5665 		}
5666 		is_linestart = is_lineend;
5667 	}
5668 
5669 	fclose(f);
5670 	bin_clear_free(buf, bufsize);
5671 
5672 	return found;
5673 }
5674 
5675 
5676 static int is_tpm2_key(const char *path)
5677 {
5678 	/* Check both new and old format of TPM2 PEM guard tag */
5679 	static const char *tpm2_tags[] = {
5680 		"-----BEGIN TSS2 PRIVATE KEY-----",
5681 		"-----BEGIN TSS2 KEY BLOB-----",
5682 		NULL
5683 	};
5684 
5685 	return match_lines_in_file(path, tpm2_tags);
5686 }
5687 
5688 
5689 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
5690 			      const struct tls_connection_params *params)
5691 {
5692 	struct tls_data *data = tls_ctx;
5693 	int ret;
5694 	unsigned long err;
5695 	int can_pkcs11 = 0;
5696 	const char *key_id = params->key_id;
5697 	const char *cert_id = params->cert_id;
5698 	const char *ca_cert_id = params->ca_cert_id;
5699 	const char *engine_id = params->engine ? params->engine_id : NULL;
5700 	const char *ciphers;
5701 
5702 	if (conn == NULL)
5703 		return -1;
5704 
5705 	if (params->flags & TLS_CONN_REQUIRE_OCSP_ALL) {
5706 		wpa_printf(MSG_INFO,
5707 			   "OpenSSL: ocsp=3 not supported");
5708 		return -1;
5709 	}
5710 
5711 	/*
5712 	 * If the engine isn't explicitly configured, and any of the
5713 	 * cert/key fields are actually PKCS#11 URIs, then automatically
5714 	 * use the PKCS#11 ENGINE.
5715 	 */
5716 	if (!engine_id || os_strcmp(engine_id, "pkcs11") == 0)
5717 		can_pkcs11 = 1;
5718 
5719 	if (!key_id && params->private_key && can_pkcs11 &&
5720 	    os_strncmp(params->private_key, "pkcs11:", 7) == 0) {
5721 		can_pkcs11 = 2;
5722 		key_id = params->private_key;
5723 	}
5724 
5725 	if (!cert_id && params->client_cert && can_pkcs11 &&
5726 	    os_strncmp(params->client_cert, "pkcs11:", 7) == 0) {
5727 		can_pkcs11 = 2;
5728 		cert_id = params->client_cert;
5729 	}
5730 
5731 	if (!ca_cert_id && params->ca_cert && can_pkcs11 &&
5732 	    os_strncmp(params->ca_cert, "pkcs11:", 7) == 0) {
5733 		can_pkcs11 = 2;
5734 		ca_cert_id = params->ca_cert;
5735 	}
5736 
5737 	/* If we need to automatically enable the PKCS#11 ENGINE, do so. */
5738 	if (can_pkcs11 == 2 && !engine_id)
5739 		engine_id = "pkcs11";
5740 
5741 	/* If private_key points to a TPM2-wrapped key, automatically enable
5742 	 * tpm2 engine and use it to unwrap the key. */
5743 	if (params->private_key &&
5744 	    (!engine_id || os_strcmp(engine_id, "tpm2") == 0) &&
5745 	    is_tpm2_key(params->private_key)) {
5746 		wpa_printf(MSG_DEBUG, "OpenSSL: Found TPM2 wrapped key %s",
5747 			   params->private_key);
5748 		key_id = key_id ? key_id : params->private_key;
5749 		engine_id = engine_id ? engine_id : "tpm2";
5750 	}
5751 
5752 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
5753 #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
5754 	if (params->flags & TLS_CONN_EAP_FAST) {
5755 		wpa_printf(MSG_DEBUG,
5756 			   "OpenSSL: Use TLSv1_method() for EAP-FAST");
5757 		if (SSL_set_ssl_method(conn->ssl, TLSv1_method()) != 1) {
5758 			tls_show_errors(MSG_INFO, __func__,
5759 					"Failed to set TLSv1_method() for EAP-FAST");
5760 			return -1;
5761 		}
5762 	}
5763 #endif
5764 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
5765 #ifdef SSL_OP_NO_TLSv1_3
5766 	if (params->flags & TLS_CONN_EAP_FAST) {
5767 		/* Need to disable TLS v1.3 at least for now since OpenSSL 1.1.1
5768 		 * refuses to start the handshake with the modified ciphersuite
5769 		 * list (no TLS v1.3 ciphersuites included) for EAP-FAST. */
5770 		wpa_printf(MSG_DEBUG, "OpenSSL: Disable TLSv1.3 for EAP-FAST");
5771 		SSL_set_options(conn->ssl, SSL_OP_NO_TLSv1_3);
5772 	}
5773 #endif /* SSL_OP_NO_TLSv1_3 */
5774 #endif
5775 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
5776 
5777 	while ((err = ERR_get_error())) {
5778 		wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
5779 			   __func__, ERR_error_string(err, NULL));
5780 	}
5781 
5782 	if (tls_set_conn_flags(conn, params->flags,
5783 			       params->openssl_ciphers) < 0)
5784 		return -1;
5785 
5786 	if (engine_id) {
5787 		wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine %s",
5788 			   engine_id);
5789 		ret = tls_engine_init(conn, engine_id, params->pin,
5790 				      key_id, cert_id, ca_cert_id);
5791 		if (ret)
5792 			return ret;
5793 	}
5794 	if (tls_connection_set_subject_match(conn,
5795 					     params->subject_match,
5796 					     params->altsubject_match,
5797 					     params->suffix_match,
5798 					     params->domain_match,
5799 					     params->check_cert_subject))
5800 		return -1;
5801 
5802 	if (engine_id && ca_cert_id) {
5803 #if !defined(ANDROID) && defined(OPENSSL_NO_ENGINE)
5804 		if (!openssl_can_use_provider(engine_id, ca_cert_id))
5805 			return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
5806 #endif /* !ANDROID && OPENSSL_NO_ENGINE */
5807 		if (tls_connection_engine_ca_cert(data, conn, ca_cert_id))
5808 			return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
5809 	} else if (tls_connection_ca_cert(data, conn, params->ca_cert,
5810 					  params->ca_cert_blob,
5811 					  params->ca_cert_blob_len,
5812 					  params->ca_path))
5813 		return -1;
5814 
5815 	if (engine_id && cert_id) {
5816 #if !defined(ANDROID) && defined(OPENSSL_NO_ENGINE)
5817 		if (!openssl_can_use_provider(engine_id, cert_id))
5818 			return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
5819 #endif /* !ANDROID && OPENSSL_NO_ENGINE */
5820 		if (tls_connection_engine_client_cert(conn, cert_id))
5821 			return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
5822 	} else if (tls_connection_client_cert(conn, params->client_cert,
5823 					      params->client_cert_blob,
5824 					      params->client_cert_blob_len))
5825 		return -1;
5826 
5827 	if (engine_id && key_id) {
5828 #if !defined(ANDROID) && defined(OPENSSL_NO_ENGINE)
5829 		if (!openssl_can_use_provider(engine_id, key_id))
5830 			return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
5831 #endif /* !ANDROID && OPENSSL_NO_ENGINE */
5832 		wpa_printf(MSG_DEBUG,
5833 			   "TLS: Using private key from engine/provider");
5834 		if (tls_connection_engine_private_key(conn))
5835 			return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
5836 	} else if (tls_connection_private_key(data, conn,
5837 					      params->private_key,
5838 					      params->private_key_passwd,
5839 					      params->private_key_blob,
5840 					      params->private_key_blob_len)) {
5841 		wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
5842 			   params->private_key);
5843 		return -1;
5844 	}
5845 
5846 	ciphers = params->openssl_ciphers;
5847 #ifdef CONFIG_SUITEB
5848 #ifdef OPENSSL_IS_BORINGSSL
5849 	if (ciphers && os_strcmp(ciphers, "SUITEB192") == 0) {
5850 		/* BoringSSL removed support for SUITEB192, so need to handle
5851 		 * this with hardcoded ciphersuite and additional checks for
5852 		 * other parameters. */
5853 		ciphers = "ECDHE-ECDSA-AES256-GCM-SHA384";
5854 	}
5855 #endif /* OPENSSL_IS_BORINGSSL */
5856 #endif /* CONFIG_SUITEB */
5857 	if (ciphers && SSL_set_cipher_list(conn->ssl, ciphers) != 1) {
5858 		wpa_printf(MSG_INFO,
5859 			   "OpenSSL: Failed to set cipher string '%s'",
5860 			   ciphers);
5861 		return -1;
5862 	}
5863 
5864 	if (!params->openssl_ecdh_curves) {
5865 #ifndef OPENSSL_IS_BORINGSSL
5866 #ifndef OPENSSL_NO_EC
5867 #if OPENSSL_VERSION_NUMBER < 0x10100000L
5868 		if (SSL_set_ecdh_auto(conn->ssl, 1) != 1) {
5869 			wpa_printf(MSG_INFO,
5870 				   "OpenSSL: Failed to set ECDH curves to auto");
5871 			return -1;
5872 		}
5873 #endif /* < 1.1.0 */
5874 #endif /* OPENSSL_NO_EC */
5875 #endif /* OPENSSL_IS_BORINGSSL */
5876 	} else if (params->openssl_ecdh_curves[0]) {
5877 #ifdef OPENSSL_IS_BORINGSSL
5878 		wpa_printf(MSG_INFO,
5879 			"OpenSSL: ECDH configuration not supported");
5880 		return -1;
5881 #else /* !OPENSSL_IS_BORINGSSL */
5882 #ifndef OPENSSL_NO_EC
5883 		if (SSL_set1_curves_list(conn->ssl,
5884 					 params->openssl_ecdh_curves) != 1) {
5885 			wpa_printf(MSG_INFO,
5886 				   "OpenSSL: Failed to set ECDH curves '%s'",
5887 				   params->openssl_ecdh_curves);
5888 			return -1;
5889 		}
5890 #else /* OPENSSL_NO_EC */
5891 		wpa_printf(MSG_INFO, "OpenSSL: ECDH not supported");
5892 		return -1;
5893 #endif /* OPENSSL_NO_EC */
5894 #endif /* OPENSSL_IS_BORINGSSL */
5895 	}
5896 
5897 #ifdef OPENSSL_IS_BORINGSSL
5898 	if (params->flags & TLS_CONN_REQUEST_OCSP) {
5899 		SSL_enable_ocsp_stapling(conn->ssl);
5900 	}
5901 #else /* OPENSSL_IS_BORINGSSL */
5902 #ifdef HAVE_OCSP
5903 	if (params->flags & TLS_CONN_REQUEST_OCSP) {
5904 		SSL_CTX *ssl_ctx = data->ssl;
5905 		SSL_set_tlsext_status_type(conn->ssl, TLSEXT_STATUSTYPE_ocsp);
5906 		SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
5907 		SSL_CTX_set_tlsext_status_arg(ssl_ctx, conn);
5908 	}
5909 #else /* HAVE_OCSP */
5910 	if (params->flags & TLS_CONN_REQUIRE_OCSP) {
5911 		wpa_printf(MSG_INFO,
5912 			   "OpenSSL: No OCSP support included - reject configuration");
5913 		return -1;
5914 	}
5915 	if (params->flags & TLS_CONN_REQUEST_OCSP) {
5916 		wpa_printf(MSG_DEBUG,
5917 			   "OpenSSL: No OCSP support included - allow optional OCSP case to continue");
5918 	}
5919 #endif /* HAVE_OCSP */
5920 #endif /* OPENSSL_IS_BORINGSSL */
5921 
5922 	conn->flags = params->flags;
5923 
5924 	tls_get_errors(data);
5925 
5926 	return 0;
5927 }
5928 
5929 
5930 static void openssl_debug_dump_cipher_list(SSL_CTX *ssl_ctx)
5931 {
5932 	SSL *ssl;
5933 	int i;
5934 
5935 	ssl = SSL_new(ssl_ctx);
5936 	if (!ssl)
5937 		return;
5938 
5939 	wpa_printf(MSG_DEBUG,
5940 		   "OpenSSL: Enabled cipher suites in priority order");
5941 	for (i = 0; ; i++) {
5942 		const char *cipher;
5943 
5944 		cipher = SSL_get_cipher_list(ssl, i);
5945 		if (!cipher)
5946 			break;
5947 		wpa_printf(MSG_DEBUG, "Cipher %d: %s", i, cipher);
5948 	}
5949 
5950 	SSL_free(ssl);
5951 }
5952 
5953 
5954 #if !defined(LIBRESSL_VERSION_NUMBER) && !defined(BORINGSSL_API_VERSION)
5955 
5956 static const char * openssl_pkey_type_str(const EVP_PKEY *pkey)
5957 {
5958 	if (!pkey)
5959 		return "NULL";
5960 	switch (EVP_PKEY_type(EVP_PKEY_id(pkey))) {
5961 	case EVP_PKEY_RSA:
5962 		return "RSA";
5963 	case EVP_PKEY_DSA:
5964 		return "DSA";
5965 	case EVP_PKEY_DH:
5966 		return "DH";
5967 	case EVP_PKEY_EC:
5968 		return "EC";
5969 	default:
5970 		return "?";
5971 	}
5972 }
5973 
5974 
5975 static void openssl_debug_dump_certificate(int i, X509 *cert)
5976 {
5977 	char buf[256];
5978 	EVP_PKEY *pkey;
5979 	ASN1_INTEGER *ser;
5980 	char serial_num[128];
5981 
5982 	if (!cert)
5983 		return;
5984 
5985 	X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
5986 
5987 	ser = X509_get_serialNumber(cert);
5988 	if (ser)
5989 		wpa_snprintf_hex_uppercase(serial_num, sizeof(serial_num),
5990 					   ASN1_STRING_get0_data(ser),
5991 					   ASN1_STRING_length(ser));
5992 	else
5993 		serial_num[0] = '\0';
5994 
5995 	pkey = X509_get_pubkey(cert);
5996 	wpa_printf(MSG_DEBUG, "%d: %s (%s) %s", i, buf,
5997 		   openssl_pkey_type_str(pkey), serial_num);
5998 	EVP_PKEY_free(pkey);
5999 }
6000 
6001 
6002 static void openssl_debug_dump_certificates(SSL_CTX *ssl_ctx)
6003 {
6004 	STACK_OF(X509) *certs;
6005 
6006 	wpa_printf(MSG_DEBUG, "OpenSSL: Configured certificate chain");
6007 	if (SSL_CTX_get0_chain_certs(ssl_ctx, &certs) == 1) {
6008 		int i;
6009 
6010 		for (i = sk_X509_num(certs); i > 0; i--)
6011 			openssl_debug_dump_certificate(i, sk_X509_value(certs,
6012 									i - 1));
6013 	}
6014 	openssl_debug_dump_certificate(0, SSL_CTX_get0_certificate(ssl_ctx));
6015 }
6016 
6017 #endif
6018 
6019 
6020 static void openssl_debug_dump_certificate_chains(SSL_CTX *ssl_ctx)
6021 {
6022 #if !defined(LIBRESSL_VERSION_NUMBER) && !defined(BORINGSSL_API_VERSION)
6023 	int res;
6024 
6025 	for (res = SSL_CTX_set_current_cert(ssl_ctx, SSL_CERT_SET_FIRST);
6026 	     res == 1;
6027 	     res = SSL_CTX_set_current_cert(ssl_ctx, SSL_CERT_SET_NEXT))
6028 		openssl_debug_dump_certificates(ssl_ctx);
6029 
6030 	SSL_CTX_set_current_cert(ssl_ctx, SSL_CERT_SET_FIRST);
6031 #endif
6032 }
6033 
6034 
6035 static void openssl_debug_dump_ctx(SSL_CTX *ssl_ctx)
6036 {
6037 	openssl_debug_dump_cipher_list(ssl_ctx);
6038 	openssl_debug_dump_certificate_chains(ssl_ctx);
6039 }
6040 
6041 
6042 int tls_global_set_params(void *tls_ctx,
6043 			  const struct tls_connection_params *params)
6044 {
6045 	struct tls_data *data = tls_ctx;
6046 	SSL_CTX *ssl_ctx = data->ssl;
6047 	unsigned long err;
6048 
6049 	while ((err = ERR_get_error())) {
6050 		wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
6051 			   __func__, ERR_error_string(err, NULL));
6052 	}
6053 
6054 	os_free(data->check_cert_subject);
6055 	data->check_cert_subject = NULL;
6056 	if (params->check_cert_subject) {
6057 		data->check_cert_subject =
6058 			os_strdup(params->check_cert_subject);
6059 		if (!data->check_cert_subject)
6060 			return -1;
6061 	}
6062 
6063 	if (tls_global_ca_cert(data, params->ca_cert) ||
6064 	    tls_global_client_cert(data, params->client_cert) ||
6065 	    tls_global_private_key(data, params->private_key,
6066 				   params->private_key_passwd) ||
6067 	    tls_global_client_cert(data, params->client_cert2) ||
6068 	    tls_global_private_key(data, params->private_key2,
6069 				   params->private_key_passwd2) ||
6070 	    tls_global_dh(data, params->dh_file)) {
6071 		wpa_printf(MSG_INFO, "TLS: Failed to set global parameters");
6072 		return -1;
6073 	}
6074 
6075 	os_free(data->openssl_ciphers);
6076 	if (params->openssl_ciphers) {
6077 		data->openssl_ciphers = os_strdup(params->openssl_ciphers);
6078 		if (!data->openssl_ciphers)
6079 			return -1;
6080 	} else {
6081 		data->openssl_ciphers = NULL;
6082 	}
6083 	if (params->openssl_ciphers &&
6084 	    SSL_CTX_set_cipher_list(ssl_ctx, params->openssl_ciphers) != 1) {
6085 		wpa_printf(MSG_INFO,
6086 			   "OpenSSL: Failed to set cipher string '%s'",
6087 			   params->openssl_ciphers);
6088 		return -1;
6089 	}
6090 
6091 	if (!params->openssl_ecdh_curves) {
6092 #ifndef OPENSSL_IS_BORINGSSL
6093 #ifndef OPENSSL_NO_EC
6094 #if OPENSSL_VERSION_NUMBER < 0x10100000L
6095 		if (SSL_CTX_set_ecdh_auto(ssl_ctx, 1) != 1) {
6096 			wpa_printf(MSG_INFO,
6097 				   "OpenSSL: Failed to set ECDH curves to auto");
6098 			return -1;
6099 		}
6100 #endif /* < 1.1.0 */
6101 #endif /* OPENSSL_NO_EC */
6102 #endif /* OPENSSL_IS_BORINGSSL */
6103 	} else if (params->openssl_ecdh_curves[0]) {
6104 #ifdef OPENSSL_IS_BORINGSSL
6105 		wpa_printf(MSG_INFO,
6106 			"OpenSSL: ECDH configuration not supported");
6107 		return -1;
6108 #else /* !OPENSSL_IS_BORINGSSL */
6109 #ifndef OPENSSL_NO_EC
6110 #if OPENSSL_VERSION_NUMBER < 0x10100000L
6111 		SSL_CTX_set_ecdh_auto(ssl_ctx, 1);
6112 #endif
6113 		if (SSL_CTX_set1_curves_list(ssl_ctx,
6114 					     params->openssl_ecdh_curves) !=
6115 		    1) {
6116 			wpa_printf(MSG_INFO,
6117 				   "OpenSSL: Failed to set ECDH curves '%s'",
6118 				   params->openssl_ecdh_curves);
6119 			return -1;
6120 		}
6121 #else /* OPENSSL_NO_EC */
6122 		wpa_printf(MSG_INFO, "OpenSSL: ECDH not supported");
6123 		return -1;
6124 #endif /* OPENSSL_NO_EC */
6125 #endif /* OPENSSL_IS_BORINGSSL */
6126 	}
6127 
6128 #ifdef SSL_OP_NO_TICKET
6129 	if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
6130 		SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
6131 	else
6132 		SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TICKET);
6133 #endif /*  SSL_OP_NO_TICKET */
6134 
6135 #ifdef HAVE_OCSP
6136 	SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_status_cb);
6137 	SSL_CTX_set_tlsext_status_arg(ssl_ctx, ssl_ctx);
6138 	os_free(tls_global->ocsp_stapling_response);
6139 	if (params->ocsp_stapling_response)
6140 		tls_global->ocsp_stapling_response =
6141 			os_strdup(params->ocsp_stapling_response);
6142 	else
6143 		tls_global->ocsp_stapling_response = NULL;
6144 #endif /* HAVE_OCSP */
6145 
6146 	openssl_debug_dump_ctx(ssl_ctx);
6147 
6148 	return 0;
6149 }
6150 
6151 
6152 #ifdef EAP_FAST_OR_TEAP
6153 /* Pre-shared secred requires a patch to openssl, so this function is
6154  * commented out unless explicitly needed for EAP-FAST in order to be able to
6155  * build this file with unmodified openssl. */
6156 
6157 #if (defined(OPENSSL_IS_BORINGSSL) || \
6158      (OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)) || \
6159      LIBRESSL_VERSION_NUMBER >= 0x4020000fL)
6160 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
6161 			   STACK_OF(SSL_CIPHER) *peer_ciphers,
6162 			   const SSL_CIPHER **cipher, void *arg)
6163 #else /* OPENSSL_IS_BORINGSSL */
6164 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
6165 			   STACK_OF(SSL_CIPHER) *peer_ciphers,
6166 			   SSL_CIPHER **cipher, void *arg)
6167 #endif /* OPENSSL_IS_BORINGSSL */
6168 {
6169 	struct tls_connection *conn = arg;
6170 	int ret;
6171 
6172 #if OPENSSL_VERSION_NUMBER < 0x10100000L
6173 	if (conn == NULL || conn->session_ticket_cb == NULL)
6174 		return 0;
6175 
6176 	ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
6177 				      conn->session_ticket,
6178 				      conn->session_ticket_len,
6179 				      s->s3->client_random,
6180 				      s->s3->server_random, secret);
6181 #else
6182 	unsigned char client_random[SSL3_RANDOM_SIZE];
6183 	unsigned char server_random[SSL3_RANDOM_SIZE];
6184 
6185 	if (conn == NULL || conn->session_ticket_cb == NULL)
6186 		return 0;
6187 
6188 	SSL_get_client_random(s, client_random, sizeof(client_random));
6189 	SSL_get_server_random(s, server_random, sizeof(server_random));
6190 
6191 	ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
6192 				      conn->session_ticket,
6193 				      conn->session_ticket_len,
6194 				      client_random,
6195 				      server_random, secret);
6196 #endif
6197 
6198 	os_free(conn->session_ticket);
6199 	conn->session_ticket = NULL;
6200 
6201 	if (ret <= 0)
6202 		return 0;
6203 
6204 	*secret_len = SSL_MAX_MASTER_KEY_LENGTH;
6205 	return 1;
6206 }
6207 
6208 
6209 static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
6210 				     int len, void *arg)
6211 {
6212 	struct tls_connection *conn = arg;
6213 
6214 	if (conn == NULL || conn->session_ticket_cb == NULL)
6215 		return 0;
6216 
6217 	wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
6218 
6219 	os_free(conn->session_ticket);
6220 	conn->session_ticket = NULL;
6221 
6222 	wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
6223 		    "extension", data, len);
6224 
6225 	conn->session_ticket = os_memdup(data, len);
6226 	if (conn->session_ticket == NULL)
6227 		return 0;
6228 
6229 	conn->session_ticket_len = len;
6230 
6231 	return 1;
6232 }
6233 #endif /* EAP_FAST_OR_TEAP */
6234 
6235 
6236 int tls_connection_set_session_ticket_cb(void *tls_ctx,
6237 					 struct tls_connection *conn,
6238 					 tls_session_ticket_cb cb,
6239 					 void *ctx)
6240 {
6241 #ifdef EAP_FAST_OR_TEAP
6242 	conn->session_ticket_cb = cb;
6243 	conn->session_ticket_cb_ctx = ctx;
6244 
6245 	if (cb) {
6246 		if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
6247 					      conn) != 1)
6248 			return -1;
6249 		SSL_set_session_ticket_ext_cb(conn->ssl,
6250 					      tls_session_ticket_ext_cb, conn);
6251 	} else {
6252 		if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
6253 			return -1;
6254 		SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
6255 	}
6256 
6257 	return 0;
6258 #else /* EAP_FAST_OR_TEAP */
6259 	return -1;
6260 #endif /* EAP_FAST_OR_TEAP */
6261 }
6262 
6263 
6264 int tls_get_library_version(char *buf, size_t buf_len)
6265 {
6266 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
6267 	return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
6268 			   OPENSSL_VERSION_TEXT,
6269 			   OpenSSL_version(OPENSSL_VERSION));
6270 #else
6271 	return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
6272 			   OPENSSL_VERSION_TEXT,
6273 			   SSLeay_version(SSLEAY_VERSION));
6274 #endif
6275 }
6276 
6277 
6278 void tls_connection_set_success_data(struct tls_connection *conn,
6279 				     struct wpabuf *data)
6280 {
6281 	SSL_SESSION *sess;
6282 	struct wpabuf *old;
6283 	struct tls_session_data *sess_data = NULL;
6284 
6285 	if (tls_ex_idx_session < 0)
6286 		goto fail;
6287 	sess = SSL_get_session(conn->ssl);
6288 	if (!sess)
6289 		goto fail;
6290 	old = SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
6291 	if (old) {
6292 		struct tls_session_data *found;
6293 
6294 		found = get_session_data(conn->context, old);
6295 		wpa_printf(MSG_DEBUG,
6296 			   "OpenSSL: Replacing old success data %p (sess %p)%s",
6297 			   old, sess, found ? "" : " (not freeing)");
6298 		if (found) {
6299 			dl_list_del(&found->list);
6300 			os_free(found);
6301 			wpabuf_free(old);
6302 		}
6303 	}
6304 
6305 	sess_data = os_zalloc(sizeof(*sess_data));
6306 	if (!sess_data ||
6307 	    SSL_SESSION_set_ex_data(sess, tls_ex_idx_session, data) != 1)
6308 		goto fail;
6309 
6310 	sess_data->buf = data;
6311 	dl_list_add(&conn->context->sessions, &sess_data->list);
6312 	wpa_printf(MSG_DEBUG, "OpenSSL: Stored success data %p (sess %p)",
6313 		   data, sess);
6314 	conn->success_data = 1;
6315 	return;
6316 
6317 fail:
6318 	wpa_printf(MSG_INFO, "OpenSSL: Failed to store success data");
6319 	wpabuf_free(data);
6320 	os_free(sess_data);
6321 }
6322 
6323 
6324 void tls_connection_set_success_data_resumed(struct tls_connection *conn)
6325 {
6326 	wpa_printf(MSG_DEBUG,
6327 		   "OpenSSL: Success data accepted for resumed session");
6328 	conn->success_data = 1;
6329 }
6330 
6331 
6332 const struct wpabuf *
6333 tls_connection_get_success_data(struct tls_connection *conn)
6334 {
6335 	SSL_SESSION *sess;
6336 
6337 	if (tls_ex_idx_session < 0 ||
6338 	    !(sess = SSL_get_session(conn->ssl)))
6339 		return NULL;
6340 	return SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
6341 }
6342 
6343 
6344 void tls_connection_remove_session(struct tls_connection *conn)
6345 {
6346 	SSL_SESSION *sess;
6347 
6348 	sess = SSL_get_session(conn->ssl);
6349 	if (!sess)
6350 		return;
6351 
6352 	if (SSL_CTX_remove_session(conn->ssl_ctx, sess) != 1)
6353 		wpa_printf(MSG_DEBUG,
6354 			   "OpenSSL: Session was not cached");
6355 	else
6356 		wpa_printf(MSG_DEBUG,
6357 			   "OpenSSL: Removed cached session to disable session resumption");
6358 }
6359 
6360 
6361 int tls_get_tls_unique(struct tls_connection *conn, u8 *buf, size_t max_len)
6362 {
6363 	size_t len;
6364 	int reused;
6365 
6366 	reused = SSL_session_reused(conn->ssl);
6367 	if ((conn->server && !reused) || (!conn->server && reused))
6368 		len = SSL_get_peer_finished(conn->ssl, buf, max_len);
6369 	else
6370 		len = SSL_get_finished(conn->ssl, buf, max_len);
6371 
6372 	if (len == 0 || len > max_len)
6373 		return -1;
6374 
6375 	return len;
6376 }
6377 
6378 
6379 u16 tls_connection_get_cipher_suite(struct tls_connection *conn)
6380 {
6381 	const SSL_CIPHER *cipher;
6382 
6383 	cipher = SSL_get_current_cipher(conn->ssl);
6384 	if (!cipher)
6385 		return 0;
6386 #if OPENSSL_VERSION_NUMBER >= 0x10101000L && !defined(LIBRESSL_VERSION_NUMBER)
6387 	return SSL_CIPHER_get_protocol_id(cipher);
6388 #else
6389 	return SSL_CIPHER_get_id(cipher) & 0xFFFF;
6390 #endif
6391 }
6392 
6393 
6394 const char * tls_connection_get_peer_subject(struct tls_connection *conn)
6395 {
6396 	if (conn)
6397 		return conn->peer_subject;
6398 	return NULL;
6399 }
6400 
6401 
6402 bool tls_connection_get_own_cert_used(struct tls_connection *conn)
6403 {
6404 	if (conn)
6405 		return SSL_get_certificate(conn->ssl) != NULL;
6406 	return false;
6407 }
6408