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