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