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