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