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