1/*
2 * SSL/TLS interface functions for OpenSSL
3 * Copyright (c) 2004-2013, 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
27#include "common.h"
28#include "crypto.h"
29#include "tls.h"
30
31#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
32#define OPENSSL_d2i_TYPE const unsigned char **
33#else
34#define OPENSSL_d2i_TYPE unsigned char **
35#endif
36
37#if defined(SSL_CTX_get_app_data) && defined(SSL_CTX_set_app_data)
38#define OPENSSL_SUPPORTS_CTX_APP_DATA
39#endif
40
41#ifdef SSL_F_SSL_SET_SESSION_TICKET_EXT
42#ifdef SSL_OP_NO_TICKET
43/*
44 * Session ticket override patch was merged into OpenSSL 0.9.9 tree on
45 * 2008-11-15. This version uses a bit different API compared to the old patch.
46 */
47#define CONFIG_OPENSSL_TICKET_OVERRIDE
48#endif
49#endif
50
51#ifdef ANDROID
52#include <openssl/pem.h>
53#include <keystore/keystore_get.h>
54
55static BIO * BIO_from_keystore(const char *key)
56{
57    BIO *bio = NULL;
58    uint8_t *value = NULL;
59    int length = keystore_get(key, strlen(key), &value);
60    if (length != -1 && (bio = BIO_new(BIO_s_mem())) != NULL) {
61        BIO_write(bio, value, length);
62    }
63    free(value);
64    return bio;
65}
66#endif /* ANDROID */
67
68#ifdef SSL_set_tlsext_status_type
69#ifndef OPENSSL_NO_TLSEXT
70#define HAVE_OCSP
71#include <openssl/ocsp.h>
72#endif /* OPENSSL_NO_TLSEXT */
73#endif /* SSL_set_tlsext_status_type */
74
75static int tls_openssl_ref_count = 0;
76
77struct tls_context {
78	void (*event_cb)(void *ctx, enum tls_event ev,
79			 union tls_event_data *data);
80	void *cb_ctx;
81	int cert_in_cb;
82	char *ocsp_stapling_response;
83};
84
85static struct tls_context *tls_global = NULL;
86
87
88struct tls_connection {
89	struct tls_context *context;
90	SSL *ssl;
91	BIO *ssl_in, *ssl_out;
92#ifndef OPENSSL_NO_ENGINE
93	ENGINE *engine;        /* functional reference to the engine */
94	EVP_PKEY *private_key; /* the private key if using engine */
95#endif /* OPENSSL_NO_ENGINE */
96	char *subject_match, *altsubject_match;
97	int read_alerts, write_alerts, failed;
98
99	tls_session_ticket_cb session_ticket_cb;
100	void *session_ticket_cb_ctx;
101
102	/* SessionTicket received from OpenSSL hello_extension_cb (server) */
103	u8 *session_ticket;
104	size_t session_ticket_len;
105
106	unsigned int ca_cert_verify:1;
107	unsigned int cert_probe:1;
108	unsigned int server_cert_only:1;
109
110	u8 srv_cert_hash[32];
111
112	unsigned int flags;
113
114	X509 *peer_cert;
115	X509 *peer_issuer;
116};
117
118
119static struct tls_context * tls_context_new(const struct tls_config *conf)
120{
121	struct tls_context *context = os_zalloc(sizeof(*context));
122	if (context == NULL)
123		return NULL;
124	if (conf) {
125		context->event_cb = conf->event_cb;
126		context->cb_ctx = conf->cb_ctx;
127		context->cert_in_cb = conf->cert_in_cb;
128	}
129	return context;
130}
131
132
133#ifdef CONFIG_NO_STDOUT_DEBUG
134
135static void _tls_show_errors(void)
136{
137	unsigned long err;
138
139	while ((err = ERR_get_error())) {
140		/* Just ignore the errors, since stdout is disabled */
141	}
142}
143#define tls_show_errors(l, f, t) _tls_show_errors()
144
145#else /* CONFIG_NO_STDOUT_DEBUG */
146
147static void tls_show_errors(int level, const char *func, const char *txt)
148{
149	unsigned long err;
150
151	wpa_printf(level, "OpenSSL: %s - %s %s",
152		   func, txt, ERR_error_string(ERR_get_error(), NULL));
153
154	while ((err = ERR_get_error())) {
155		wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
156			   ERR_error_string(err, NULL));
157	}
158}
159
160#endif /* CONFIG_NO_STDOUT_DEBUG */
161
162
163#ifdef CONFIG_NATIVE_WINDOWS
164
165/* Windows CryptoAPI and access to certificate stores */
166#include <wincrypt.h>
167
168#ifdef __MINGW32_VERSION
169/*
170 * MinGW does not yet include all the needed definitions for CryptoAPI, so
171 * define here whatever extra is needed.
172 */
173#define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
174#define CERT_STORE_READONLY_FLAG 0x00008000
175#define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
176
177#endif /* __MINGW32_VERSION */
178
179
180struct cryptoapi_rsa_data {
181	const CERT_CONTEXT *cert;
182	HCRYPTPROV crypt_prov;
183	DWORD key_spec;
184	BOOL free_crypt_prov;
185};
186
187
188static void cryptoapi_error(const char *msg)
189{
190	wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
191		   msg, (unsigned int) GetLastError());
192}
193
194
195static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
196				 unsigned char *to, RSA *rsa, int padding)
197{
198	wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
199	return 0;
200}
201
202
203static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
204				 unsigned char *to, RSA *rsa, int padding)
205{
206	wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
207	return 0;
208}
209
210
211static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
212				  unsigned char *to, RSA *rsa, int padding)
213{
214	struct cryptoapi_rsa_data *priv =
215		(struct cryptoapi_rsa_data *) rsa->meth->app_data;
216	HCRYPTHASH hash;
217	DWORD hash_size, len, i;
218	unsigned char *buf = NULL;
219	int ret = 0;
220
221	if (priv == NULL) {
222		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
223		       ERR_R_PASSED_NULL_PARAMETER);
224		return 0;
225	}
226
227	if (padding != RSA_PKCS1_PADDING) {
228		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
229		       RSA_R_UNKNOWN_PADDING_TYPE);
230		return 0;
231	}
232
233	if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
234		wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
235			   __func__);
236		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
237		       RSA_R_INVALID_MESSAGE_LENGTH);
238		return 0;
239	}
240
241	if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
242	{
243		cryptoapi_error("CryptCreateHash failed");
244		return 0;
245	}
246
247	len = sizeof(hash_size);
248	if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
249			       0)) {
250		cryptoapi_error("CryptGetHashParam failed");
251		goto err;
252	}
253
254	if ((int) hash_size != flen) {
255		wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
256			   (unsigned) hash_size, flen);
257		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
258		       RSA_R_INVALID_MESSAGE_LENGTH);
259		goto err;
260	}
261	if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
262		cryptoapi_error("CryptSetHashParam failed");
263		goto err;
264	}
265
266	len = RSA_size(rsa);
267	buf = os_malloc(len);
268	if (buf == NULL) {
269		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
270		goto err;
271	}
272
273	if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
274		cryptoapi_error("CryptSignHash failed");
275		goto err;
276	}
277
278	for (i = 0; i < len; i++)
279		to[i] = buf[len - i - 1];
280	ret = len;
281
282err:
283	os_free(buf);
284	CryptDestroyHash(hash);
285
286	return ret;
287}
288
289
290static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
291				  unsigned char *to, RSA *rsa, int padding)
292{
293	wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
294	return 0;
295}
296
297
298static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
299{
300	if (priv == NULL)
301		return;
302	if (priv->crypt_prov && priv->free_crypt_prov)
303		CryptReleaseContext(priv->crypt_prov, 0);
304	if (priv->cert)
305		CertFreeCertificateContext(priv->cert);
306	os_free(priv);
307}
308
309
310static int cryptoapi_finish(RSA *rsa)
311{
312	cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
313	os_free((void *) rsa->meth);
314	rsa->meth = NULL;
315	return 1;
316}
317
318
319static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
320{
321	HCERTSTORE cs;
322	const CERT_CONTEXT *ret = NULL;
323
324	cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
325			   store | CERT_STORE_OPEN_EXISTING_FLAG |
326			   CERT_STORE_READONLY_FLAG, L"MY");
327	if (cs == NULL) {
328		cryptoapi_error("Failed to open 'My system store'");
329		return NULL;
330	}
331
332	if (strncmp(name, "cert://", 7) == 0) {
333		unsigned short wbuf[255];
334		MultiByteToWideChar(CP_ACP, 0, name + 7, -1, wbuf, 255);
335		ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
336						 PKCS_7_ASN_ENCODING,
337						 0, CERT_FIND_SUBJECT_STR,
338						 wbuf, NULL);
339	} else if (strncmp(name, "hash://", 7) == 0) {
340		CRYPT_HASH_BLOB blob;
341		int len;
342		const char *hash = name + 7;
343		unsigned char *buf;
344
345		len = os_strlen(hash) / 2;
346		buf = os_malloc(len);
347		if (buf && hexstr2bin(hash, buf, len) == 0) {
348			blob.cbData = len;
349			blob.pbData = buf;
350			ret = CertFindCertificateInStore(cs,
351							 X509_ASN_ENCODING |
352							 PKCS_7_ASN_ENCODING,
353							 0, CERT_FIND_HASH,
354							 &blob, NULL);
355		}
356		os_free(buf);
357	}
358
359	CertCloseStore(cs, 0);
360
361	return ret;
362}
363
364
365static int tls_cryptoapi_cert(SSL *ssl, const char *name)
366{
367	X509 *cert = NULL;
368	RSA *rsa = NULL, *pub_rsa;
369	struct cryptoapi_rsa_data *priv;
370	RSA_METHOD *rsa_meth;
371
372	if (name == NULL ||
373	    (strncmp(name, "cert://", 7) != 0 &&
374	     strncmp(name, "hash://", 7) != 0))
375		return -1;
376
377	priv = os_zalloc(sizeof(*priv));
378	rsa_meth = os_zalloc(sizeof(*rsa_meth));
379	if (priv == NULL || rsa_meth == NULL) {
380		wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
381			   "for CryptoAPI RSA method");
382		os_free(priv);
383		os_free(rsa_meth);
384		return -1;
385	}
386
387	priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
388	if (priv->cert == NULL) {
389		priv->cert = cryptoapi_find_cert(
390			name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
391	}
392	if (priv->cert == NULL) {
393		wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
394			   "'%s'", name);
395		goto err;
396	}
397
398	cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &priv->cert->pbCertEncoded,
399			priv->cert->cbCertEncoded);
400	if (cert == NULL) {
401		wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
402			   "encoding");
403		goto err;
404	}
405
406	if (!CryptAcquireCertificatePrivateKey(priv->cert,
407					       CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
408					       NULL, &priv->crypt_prov,
409					       &priv->key_spec,
410					       &priv->free_crypt_prov)) {
411		cryptoapi_error("Failed to acquire a private key for the "
412				"certificate");
413		goto err;
414	}
415
416	rsa_meth->name = "Microsoft CryptoAPI RSA Method";
417	rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
418	rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
419	rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
420	rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
421	rsa_meth->finish = cryptoapi_finish;
422	rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
423	rsa_meth->app_data = (char *) priv;
424
425	rsa = RSA_new();
426	if (rsa == NULL) {
427		SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
428		       ERR_R_MALLOC_FAILURE);
429		goto err;
430	}
431
432	if (!SSL_use_certificate(ssl, cert)) {
433		RSA_free(rsa);
434		rsa = NULL;
435		goto err;
436	}
437	pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
438	X509_free(cert);
439	cert = NULL;
440
441	rsa->n = BN_dup(pub_rsa->n);
442	rsa->e = BN_dup(pub_rsa->e);
443	if (!RSA_set_method(rsa, rsa_meth))
444		goto err;
445
446	if (!SSL_use_RSAPrivateKey(ssl, rsa))
447		goto err;
448	RSA_free(rsa);
449
450	return 0;
451
452err:
453	if (cert)
454		X509_free(cert);
455	if (rsa)
456		RSA_free(rsa);
457	else {
458		os_free(rsa_meth);
459		cryptoapi_free_data(priv);
460	}
461	return -1;
462}
463
464
465static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
466{
467	HCERTSTORE cs;
468	PCCERT_CONTEXT ctx = NULL;
469	X509 *cert;
470	char buf[128];
471	const char *store;
472#ifdef UNICODE
473	WCHAR *wstore;
474#endif /* UNICODE */
475
476	if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
477		return -1;
478
479	store = name + 13;
480#ifdef UNICODE
481	wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
482	if (wstore == NULL)
483		return -1;
484	wsprintf(wstore, L"%S", store);
485	cs = CertOpenSystemStore(0, wstore);
486	os_free(wstore);
487#else /* UNICODE */
488	cs = CertOpenSystemStore(0, store);
489#endif /* UNICODE */
490	if (cs == NULL) {
491		wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
492			   "'%s': error=%d", __func__, store,
493			   (int) GetLastError());
494		return -1;
495	}
496
497	while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
498		cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ctx->pbCertEncoded,
499				ctx->cbCertEncoded);
500		if (cert == NULL) {
501			wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
502				   "X509 DER encoding for CA cert");
503			continue;
504		}
505
506		X509_NAME_oneline(X509_get_subject_name(cert), buf,
507				  sizeof(buf));
508		wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
509			   "system certificate store: subject='%s'", buf);
510
511		if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
512			tls_show_errors(MSG_WARNING, __func__,
513					"Failed to add ca_cert to OpenSSL "
514					"certificate store");
515		}
516
517		X509_free(cert);
518	}
519
520	if (!CertCloseStore(cs, 0)) {
521		wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
522			   "'%s': error=%d", __func__, name + 13,
523			   (int) GetLastError());
524	}
525
526	return 0;
527}
528
529
530#else /* CONFIG_NATIVE_WINDOWS */
531
532static int tls_cryptoapi_cert(SSL *ssl, const char *name)
533{
534	return -1;
535}
536
537#endif /* CONFIG_NATIVE_WINDOWS */
538
539
540static void ssl_info_cb(const SSL *ssl, int where, int ret)
541{
542	const char *str;
543	int w;
544
545	wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
546	w = where & ~SSL_ST_MASK;
547	if (w & SSL_ST_CONNECT)
548		str = "SSL_connect";
549	else if (w & SSL_ST_ACCEPT)
550		str = "SSL_accept";
551	else
552		str = "undefined";
553
554	if (where & SSL_CB_LOOP) {
555		wpa_printf(MSG_DEBUG, "SSL: %s:%s",
556			   str, SSL_state_string_long(ssl));
557	} else if (where & SSL_CB_ALERT) {
558		struct tls_connection *conn = SSL_get_app_data((SSL *) ssl);
559		wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
560			   where & SSL_CB_READ ?
561			   "read (remote end reported an error)" :
562			   "write (local SSL3 detected an error)",
563			   SSL_alert_type_string_long(ret),
564			   SSL_alert_desc_string_long(ret));
565		if ((ret >> 8) == SSL3_AL_FATAL) {
566			if (where & SSL_CB_READ)
567				conn->read_alerts++;
568			else
569				conn->write_alerts++;
570		}
571		if (conn->context->event_cb != NULL) {
572			union tls_event_data ev;
573			struct tls_context *context = conn->context;
574			os_memset(&ev, 0, sizeof(ev));
575			ev.alert.is_local = !(where & SSL_CB_READ);
576			ev.alert.type = SSL_alert_type_string_long(ret);
577			ev.alert.description = SSL_alert_desc_string_long(ret);
578			context->event_cb(context->cb_ctx, TLS_ALERT, &ev);
579		}
580	} else if (where & SSL_CB_EXIT && ret <= 0) {
581		wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
582			   str, ret == 0 ? "failed" : "error",
583			   SSL_state_string_long(ssl));
584	}
585}
586
587
588#ifndef OPENSSL_NO_ENGINE
589/**
590 * tls_engine_load_dynamic_generic - load any openssl engine
591 * @pre: an array of commands and values that load an engine initialized
592 *       in the engine specific function
593 * @post: an array of commands and values that initialize an already loaded
594 *        engine (or %NULL if not required)
595 * @id: the engine id of the engine to load (only required if post is not %NULL
596 *
597 * This function is a generic function that loads any openssl engine.
598 *
599 * Returns: 0 on success, -1 on failure
600 */
601static int tls_engine_load_dynamic_generic(const char *pre[],
602					   const char *post[], const char *id)
603{
604	ENGINE *engine;
605	const char *dynamic_id = "dynamic";
606
607	engine = ENGINE_by_id(id);
608	if (engine) {
609		ENGINE_free(engine);
610		wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
611			   "available", id);
612		return 0;
613	}
614	ERR_clear_error();
615
616	engine = ENGINE_by_id(dynamic_id);
617	if (engine == NULL) {
618		wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
619			   dynamic_id,
620			   ERR_error_string(ERR_get_error(), NULL));
621		return -1;
622	}
623
624	/* Perform the pre commands. This will load the engine. */
625	while (pre && pre[0]) {
626		wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
627		if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
628			wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
629				   "%s %s [%s]", pre[0], pre[1],
630				   ERR_error_string(ERR_get_error(), NULL));
631			ENGINE_free(engine);
632			return -1;
633		}
634		pre += 2;
635	}
636
637	/*
638	 * Free the reference to the "dynamic" engine. The loaded engine can
639	 * now be looked up using ENGINE_by_id().
640	 */
641	ENGINE_free(engine);
642
643	engine = ENGINE_by_id(id);
644	if (engine == NULL) {
645		wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
646			   id, ERR_error_string(ERR_get_error(), NULL));
647		return -1;
648	}
649
650	while (post && post[0]) {
651		wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
652		if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
653			wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
654				" %s %s [%s]", post[0], post[1],
655				   ERR_error_string(ERR_get_error(), NULL));
656			ENGINE_remove(engine);
657			ENGINE_free(engine);
658			return -1;
659		}
660		post += 2;
661	}
662	ENGINE_free(engine);
663
664	return 0;
665}
666
667
668/**
669 * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
670 * @pkcs11_so_path: pksc11_so_path from the configuration
671 * @pcks11_module_path: pkcs11_module_path from the configuration
672 */
673static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
674					  const char *pkcs11_module_path)
675{
676	char *engine_id = "pkcs11";
677	const char *pre_cmd[] = {
678		"SO_PATH", NULL /* pkcs11_so_path */,
679		"ID", NULL /* engine_id */,
680		"LIST_ADD", "1",
681		/* "NO_VCHECK", "1", */
682		"LOAD", NULL,
683		NULL, NULL
684	};
685	const char *post_cmd[] = {
686		"MODULE_PATH", NULL /* pkcs11_module_path */,
687		NULL, NULL
688	};
689
690	if (!pkcs11_so_path || !pkcs11_module_path)
691		return 0;
692
693	pre_cmd[1] = pkcs11_so_path;
694	pre_cmd[3] = engine_id;
695	post_cmd[1] = pkcs11_module_path;
696
697	wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
698		   pkcs11_so_path);
699
700	return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
701}
702
703
704/**
705 * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
706 * @opensc_so_path: opensc_so_path from the configuration
707 */
708static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
709{
710	char *engine_id = "opensc";
711	const char *pre_cmd[] = {
712		"SO_PATH", NULL /* opensc_so_path */,
713		"ID", NULL /* engine_id */,
714		"LIST_ADD", "1",
715		"LOAD", NULL,
716		NULL, NULL
717	};
718
719	if (!opensc_so_path)
720		return 0;
721
722	pre_cmd[1] = opensc_so_path;
723	pre_cmd[3] = engine_id;
724
725	wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
726		   opensc_so_path);
727
728	return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
729}
730#endif /* OPENSSL_NO_ENGINE */
731
732
733void * tls_init(const struct tls_config *conf)
734{
735	SSL_CTX *ssl;
736	struct tls_context *context;
737
738	if (tls_openssl_ref_count == 0) {
739		tls_global = context = tls_context_new(conf);
740		if (context == NULL)
741			return NULL;
742#ifdef CONFIG_FIPS
743#ifdef OPENSSL_FIPS
744		if (conf && conf->fips_mode) {
745			if (!FIPS_mode_set(1)) {
746				wpa_printf(MSG_ERROR, "Failed to enable FIPS "
747					   "mode");
748				ERR_load_crypto_strings();
749				ERR_print_errors_fp(stderr);
750				os_free(tls_global);
751				tls_global = NULL;
752				return NULL;
753			} else
754				wpa_printf(MSG_INFO, "Running in FIPS mode");
755		}
756#else /* OPENSSL_FIPS */
757		if (conf && conf->fips_mode) {
758			wpa_printf(MSG_ERROR, "FIPS mode requested, but not "
759				   "supported");
760			os_free(tls_global);
761			tls_global = NULL;
762			return NULL;
763		}
764#endif /* OPENSSL_FIPS */
765#endif /* CONFIG_FIPS */
766		SSL_load_error_strings();
767		SSL_library_init();
768#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
769		EVP_add_digest(EVP_sha256());
770#endif /* OPENSSL_NO_SHA256 */
771		/* TODO: if /dev/urandom is available, PRNG is seeded
772		 * automatically. If this is not the case, random data should
773		 * be added here. */
774
775#ifdef PKCS12_FUNCS
776#ifndef OPENSSL_NO_RC2
777		/*
778		 * 40-bit RC2 is commonly used in PKCS#12 files, so enable it.
779		 * This is enabled by PKCS12_PBE_add() in OpenSSL 0.9.8
780		 * versions, but it looks like OpenSSL 1.0.0 does not do that
781		 * anymore.
782		 */
783		EVP_add_cipher(EVP_rc2_40_cbc());
784#endif /* OPENSSL_NO_RC2 */
785		PKCS12_PBE_add();
786#endif  /* PKCS12_FUNCS */
787	} else {
788		context = tls_global;
789#ifdef OPENSSL_SUPPORTS_CTX_APP_DATA
790		/* Newer OpenSSL can store app-data per-SSL */
791		context = tls_context_new(conf);
792		if (context == NULL)
793			return NULL;
794#endif /* OPENSSL_SUPPORTS_CTX_APP_DATA */
795	}
796	tls_openssl_ref_count++;
797
798	ssl = SSL_CTX_new(TLSv1_method());
799	if (ssl == NULL) {
800		tls_openssl_ref_count--;
801		if (tls_openssl_ref_count == 0) {
802			os_free(tls_global);
803			tls_global = NULL;
804		} else if (context != tls_global) {
805			os_free(context);
806		}
807		return NULL;
808	}
809
810	SSL_CTX_set_info_callback(ssl, ssl_info_cb);
811#ifdef OPENSSL_SUPPORTS_CTX_APP_DATA
812	SSL_CTX_set_app_data(ssl, context);
813#endif /* OPENSSL_SUPPORTS_CTX_APP_DATA */
814
815#ifndef OPENSSL_NO_ENGINE
816	if (conf &&
817	    (conf->opensc_engine_path || conf->pkcs11_engine_path ||
818	     conf->pkcs11_module_path)) {
819		wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
820		ERR_load_ENGINE_strings();
821		ENGINE_load_dynamic();
822
823		if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
824		    tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
825						   conf->pkcs11_module_path)) {
826			tls_deinit(ssl);
827			return NULL;
828		}
829	}
830#endif /* OPENSSL_NO_ENGINE */
831
832	return ssl;
833}
834
835
836void tls_deinit(void *ssl_ctx)
837{
838	SSL_CTX *ssl = ssl_ctx;
839#ifdef OPENSSL_SUPPORTS_CTX_APP_DATA
840	struct tls_context *context = SSL_CTX_get_app_data(ssl);
841	if (context != tls_global)
842		os_free(context);
843#endif /* OPENSSL_SUPPORTS_CTX_APP_DATA */
844	SSL_CTX_free(ssl);
845
846	tls_openssl_ref_count--;
847	if (tls_openssl_ref_count == 0) {
848#ifndef OPENSSL_NO_ENGINE
849		ENGINE_cleanup();
850#endif /* OPENSSL_NO_ENGINE */
851		CRYPTO_cleanup_all_ex_data();
852		ERR_remove_state(0);
853		ERR_free_strings();
854		EVP_cleanup();
855		os_free(tls_global->ocsp_stapling_response);
856		tls_global->ocsp_stapling_response = NULL;
857		os_free(tls_global);
858		tls_global = NULL;
859	}
860}
861
862
863static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
864			   const char *pin, const char *key_id,
865			   const char *cert_id, const char *ca_cert_id)
866{
867#ifndef OPENSSL_NO_ENGINE
868	int ret = -1;
869	if (engine_id == NULL) {
870		wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
871		return -1;
872	}
873#ifndef ANDROID
874	if (pin == NULL) {
875		wpa_printf(MSG_ERROR, "ENGINE: Smartcard PIN not set");
876		return -1;
877	}
878#endif
879	if (key_id == NULL) {
880		wpa_printf(MSG_ERROR, "ENGINE: Key Id not set");
881		return -1;
882	}
883
884	ERR_clear_error();
885#ifdef ANDROID
886	ENGINE_load_dynamic();
887#endif
888	conn->engine = ENGINE_by_id(engine_id);
889	if (!conn->engine) {
890		wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
891			   engine_id, ERR_error_string(ERR_get_error(), NULL));
892		goto err;
893	}
894	if (ENGINE_init(conn->engine) != 1) {
895		wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
896			   "(engine: %s) [%s]", engine_id,
897			   ERR_error_string(ERR_get_error(), NULL));
898		goto err;
899	}
900	wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
901
902#ifndef ANDROID
903	if (ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
904		wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
905			   ERR_error_string(ERR_get_error(), NULL));
906		goto err;
907	}
908#endif
909	/* load private key first in-case PIN is required for cert */
910	conn->private_key = ENGINE_load_private_key(conn->engine,
911						    key_id, NULL, NULL);
912	if (!conn->private_key) {
913		wpa_printf(MSG_ERROR, "ENGINE: cannot load private key with id"
914				" '%s' [%s]", key_id,
915			   ERR_error_string(ERR_get_error(), NULL));
916		ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
917		goto err;
918	}
919
920	/* handle a certificate and/or CA certificate */
921	if (cert_id || ca_cert_id) {
922		const char *cmd_name = "LOAD_CERT_CTRL";
923
924		/* test if the engine supports a LOAD_CERT_CTRL */
925		if (!ENGINE_ctrl(conn->engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
926				 0, (void *)cmd_name, NULL)) {
927			wpa_printf(MSG_ERROR, "ENGINE: engine does not support"
928				   " loading certificates");
929			ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
930			goto err;
931		}
932	}
933
934	return 0;
935
936err:
937	if (conn->engine) {
938		ENGINE_free(conn->engine);
939		conn->engine = NULL;
940	}
941
942	if (conn->private_key) {
943		EVP_PKEY_free(conn->private_key);
944		conn->private_key = NULL;
945	}
946
947	return ret;
948#else /* OPENSSL_NO_ENGINE */
949	return 0;
950#endif /* OPENSSL_NO_ENGINE */
951}
952
953
954static void tls_engine_deinit(struct tls_connection *conn)
955{
956#ifndef OPENSSL_NO_ENGINE
957	wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
958	if (conn->private_key) {
959		EVP_PKEY_free(conn->private_key);
960		conn->private_key = NULL;
961	}
962	if (conn->engine) {
963		ENGINE_finish(conn->engine);
964		conn->engine = NULL;
965	}
966#endif /* OPENSSL_NO_ENGINE */
967}
968
969
970int tls_get_errors(void *ssl_ctx)
971{
972	int count = 0;
973	unsigned long err;
974
975	while ((err = ERR_get_error())) {
976		wpa_printf(MSG_INFO, "TLS - SSL error: %s",
977			   ERR_error_string(err, NULL));
978		count++;
979	}
980
981	return count;
982}
983
984struct tls_connection * tls_connection_init(void *ssl_ctx)
985{
986	SSL_CTX *ssl = ssl_ctx;
987	struct tls_connection *conn;
988	long options;
989	struct tls_context *context = tls_global;
990#ifdef OPENSSL_SUPPORTS_CTX_APP_DATA
991	context = SSL_CTX_get_app_data(ssl);
992#endif /* OPENSSL_SUPPORTS_CTX_APP_DATA */
993
994	conn = os_zalloc(sizeof(*conn));
995	if (conn == NULL)
996		return NULL;
997	conn->ssl = SSL_new(ssl);
998	if (conn->ssl == NULL) {
999		tls_show_errors(MSG_INFO, __func__,
1000				"Failed to initialize new SSL connection");
1001		os_free(conn);
1002		return NULL;
1003	}
1004
1005	conn->context = context;
1006	SSL_set_app_data(conn->ssl, conn);
1007	options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
1008		SSL_OP_SINGLE_DH_USE;
1009#ifdef SSL_OP_NO_COMPRESSION
1010	options |= SSL_OP_NO_COMPRESSION;
1011#endif /* SSL_OP_NO_COMPRESSION */
1012#ifdef ANDROID
1013	options |= SSL_OP_NO_TLSv1_1;
1014	options |= SSL_OP_NO_TLSv1_2;
1015	options |= SSL_OP_NO_TICKET;
1016#endif /* ANDROID */
1017	SSL_set_options(conn->ssl, options);
1018
1019	conn->ssl_in = BIO_new(BIO_s_mem());
1020	if (!conn->ssl_in) {
1021		tls_show_errors(MSG_INFO, __func__,
1022				"Failed to create a new BIO for ssl_in");
1023		SSL_free(conn->ssl);
1024		os_free(conn);
1025		return NULL;
1026	}
1027
1028	conn->ssl_out = BIO_new(BIO_s_mem());
1029	if (!conn->ssl_out) {
1030		tls_show_errors(MSG_INFO, __func__,
1031				"Failed to create a new BIO for ssl_out");
1032		SSL_free(conn->ssl);
1033		BIO_free(conn->ssl_in);
1034		os_free(conn);
1035		return NULL;
1036	}
1037
1038	SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
1039
1040	return conn;
1041}
1042
1043
1044void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
1045{
1046	if (conn == NULL)
1047		return;
1048	SSL_free(conn->ssl);
1049	tls_engine_deinit(conn);
1050	os_free(conn->subject_match);
1051	os_free(conn->altsubject_match);
1052	os_free(conn->session_ticket);
1053	os_free(conn);
1054}
1055
1056
1057int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
1058{
1059	return conn ? SSL_is_init_finished(conn->ssl) : 0;
1060}
1061
1062
1063int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
1064{
1065	if (conn == NULL)
1066		return -1;
1067
1068	/* Shutdown previous TLS connection without notifying the peer
1069	 * because the connection was already terminated in practice
1070	 * and "close notify" shutdown alert would confuse AS. */
1071	SSL_set_quiet_shutdown(conn->ssl, 1);
1072	SSL_shutdown(conn->ssl);
1073	return 0;
1074}
1075
1076
1077static int tls_match_altsubject_component(X509 *cert, int type,
1078					  const char *value, size_t len)
1079{
1080	GENERAL_NAME *gen;
1081	void *ext;
1082	int i, found = 0;
1083
1084	ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
1085
1086	for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
1087		gen = sk_GENERAL_NAME_value(ext, i);
1088		if (gen->type != type)
1089			continue;
1090		if (os_strlen((char *) gen->d.ia5->data) == len &&
1091		    os_memcmp(value, gen->d.ia5->data, len) == 0)
1092			found++;
1093	}
1094
1095	return found;
1096}
1097
1098
1099static int tls_match_altsubject(X509 *cert, const char *match)
1100{
1101	int type;
1102	const char *pos, *end;
1103	size_t len;
1104
1105	pos = match;
1106	do {
1107		if (os_strncmp(pos, "EMAIL:", 6) == 0) {
1108			type = GEN_EMAIL;
1109			pos += 6;
1110		} else if (os_strncmp(pos, "DNS:", 4) == 0) {
1111			type = GEN_DNS;
1112			pos += 4;
1113		} else if (os_strncmp(pos, "URI:", 4) == 0) {
1114			type = GEN_URI;
1115			pos += 4;
1116		} else {
1117			wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
1118				   "match '%s'", pos);
1119			return 0;
1120		}
1121		end = os_strchr(pos, ';');
1122		while (end) {
1123			if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
1124			    os_strncmp(end + 1, "DNS:", 4) == 0 ||
1125			    os_strncmp(end + 1, "URI:", 4) == 0)
1126				break;
1127			end = os_strchr(end + 1, ';');
1128		}
1129		if (end)
1130			len = end - pos;
1131		else
1132			len = os_strlen(pos);
1133		if (tls_match_altsubject_component(cert, type, pos, len) > 0)
1134			return 1;
1135		pos = end + 1;
1136	} while (end);
1137
1138	return 0;
1139}
1140
1141
1142static enum tls_fail_reason openssl_tls_fail_reason(int err)
1143{
1144	switch (err) {
1145	case X509_V_ERR_CERT_REVOKED:
1146		return TLS_FAIL_REVOKED;
1147	case X509_V_ERR_CERT_NOT_YET_VALID:
1148	case X509_V_ERR_CRL_NOT_YET_VALID:
1149		return TLS_FAIL_NOT_YET_VALID;
1150	case X509_V_ERR_CERT_HAS_EXPIRED:
1151	case X509_V_ERR_CRL_HAS_EXPIRED:
1152		return TLS_FAIL_EXPIRED;
1153	case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1154	case X509_V_ERR_UNABLE_TO_GET_CRL:
1155	case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
1156	case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1157	case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1158	case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1159	case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1160	case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1161	case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1162	case X509_V_ERR_INVALID_CA:
1163		return TLS_FAIL_UNTRUSTED;
1164	case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1165	case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1166	case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1167	case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1168	case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1169	case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1170	case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1171	case X509_V_ERR_CERT_UNTRUSTED:
1172	case X509_V_ERR_CERT_REJECTED:
1173		return TLS_FAIL_BAD_CERTIFICATE;
1174	default:
1175		return TLS_FAIL_UNSPECIFIED;
1176	}
1177}
1178
1179
1180static struct wpabuf * get_x509_cert(X509 *cert)
1181{
1182	struct wpabuf *buf;
1183	u8 *tmp;
1184
1185	int cert_len = i2d_X509(cert, NULL);
1186	if (cert_len <= 0)
1187		return NULL;
1188
1189	buf = wpabuf_alloc(cert_len);
1190	if (buf == NULL)
1191		return NULL;
1192
1193	tmp = wpabuf_put(buf, cert_len);
1194	i2d_X509(cert, &tmp);
1195	return buf;
1196}
1197
1198
1199static void openssl_tls_fail_event(struct tls_connection *conn,
1200				   X509 *err_cert, int err, int depth,
1201				   const char *subject, const char *err_str,
1202				   enum tls_fail_reason reason)
1203{
1204	union tls_event_data ev;
1205	struct wpabuf *cert = NULL;
1206	struct tls_context *context = conn->context;
1207
1208	if (context->event_cb == NULL)
1209		return;
1210
1211	cert = get_x509_cert(err_cert);
1212	os_memset(&ev, 0, sizeof(ev));
1213	ev.cert_fail.reason = reason != TLS_FAIL_UNSPECIFIED ?
1214		reason : openssl_tls_fail_reason(err);
1215	ev.cert_fail.depth = depth;
1216	ev.cert_fail.subject = subject;
1217	ev.cert_fail.reason_txt = err_str;
1218	ev.cert_fail.cert = cert;
1219	context->event_cb(context->cb_ctx, TLS_CERT_CHAIN_FAILURE, &ev);
1220	wpabuf_free(cert);
1221}
1222
1223
1224static void openssl_tls_cert_event(struct tls_connection *conn,
1225				   X509 *err_cert, int depth,
1226				   const char *subject)
1227{
1228	struct wpabuf *cert = NULL;
1229	union tls_event_data ev;
1230	struct tls_context *context = conn->context;
1231#ifdef CONFIG_SHA256
1232	u8 hash[32];
1233#endif /* CONFIG_SHA256 */
1234
1235	if (context->event_cb == NULL)
1236		return;
1237
1238	os_memset(&ev, 0, sizeof(ev));
1239	if (conn->cert_probe || context->cert_in_cb) {
1240		cert = get_x509_cert(err_cert);
1241		ev.peer_cert.cert = cert;
1242	}
1243#ifdef CONFIG_SHA256
1244	if (cert) {
1245		const u8 *addr[1];
1246		size_t len[1];
1247		addr[0] = wpabuf_head(cert);
1248		len[0] = wpabuf_len(cert);
1249		if (sha256_vector(1, addr, len, hash) == 0) {
1250			ev.peer_cert.hash = hash;
1251			ev.peer_cert.hash_len = sizeof(hash);
1252		}
1253	}
1254#endif /* CONFIG_SHA256 */
1255	ev.peer_cert.depth = depth;
1256	ev.peer_cert.subject = subject;
1257	context->event_cb(context->cb_ctx, TLS_PEER_CERTIFICATE, &ev);
1258	wpabuf_free(cert);
1259}
1260
1261
1262static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
1263{
1264	char buf[256];
1265	X509 *err_cert;
1266	int err, depth;
1267	SSL *ssl;
1268	struct tls_connection *conn;
1269	struct tls_context *context;
1270	char *match, *altmatch;
1271	const char *err_str;
1272
1273	err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
1274	err = X509_STORE_CTX_get_error(x509_ctx);
1275	depth = X509_STORE_CTX_get_error_depth(x509_ctx);
1276	ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1277					 SSL_get_ex_data_X509_STORE_CTX_idx());
1278	X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
1279
1280	conn = SSL_get_app_data(ssl);
1281	if (conn == NULL)
1282		return 0;
1283
1284	if (depth == 0)
1285		conn->peer_cert = err_cert;
1286	else if (depth == 1)
1287		conn->peer_issuer = err_cert;
1288
1289	context = conn->context;
1290	match = conn->subject_match;
1291	altmatch = conn->altsubject_match;
1292
1293	if (!preverify_ok && !conn->ca_cert_verify)
1294		preverify_ok = 1;
1295	if (!preverify_ok && depth > 0 && conn->server_cert_only)
1296		preverify_ok = 1;
1297	if (!preverify_ok && (conn->flags & TLS_CONN_DISABLE_TIME_CHECKS) &&
1298	    (err == X509_V_ERR_CERT_HAS_EXPIRED ||
1299	     err == X509_V_ERR_CERT_NOT_YET_VALID)) {
1300		wpa_printf(MSG_DEBUG, "OpenSSL: Ignore certificate validity "
1301			   "time mismatch");
1302		preverify_ok = 1;
1303	}
1304
1305	err_str = X509_verify_cert_error_string(err);
1306
1307#ifdef CONFIG_SHA256
1308	if (preverify_ok && depth == 0 && conn->server_cert_only) {
1309		struct wpabuf *cert;
1310		cert = get_x509_cert(err_cert);
1311		if (!cert) {
1312			wpa_printf(MSG_DEBUG, "OpenSSL: Could not fetch "
1313				   "server certificate data");
1314			preverify_ok = 0;
1315		} else {
1316			u8 hash[32];
1317			const u8 *addr[1];
1318			size_t len[1];
1319			addr[0] = wpabuf_head(cert);
1320			len[0] = wpabuf_len(cert);
1321			if (sha256_vector(1, addr, len, hash) < 0 ||
1322			    os_memcmp(conn->srv_cert_hash, hash, 32) != 0) {
1323				err_str = "Server certificate mismatch";
1324				err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
1325				preverify_ok = 0;
1326			}
1327			wpabuf_free(cert);
1328		}
1329	}
1330#endif /* CONFIG_SHA256 */
1331
1332	if (!preverify_ok) {
1333		wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
1334			   " error %d (%s) depth %d for '%s'", err, err_str,
1335			   depth, buf);
1336		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1337				       err_str, TLS_FAIL_UNSPECIFIED);
1338		return preverify_ok;
1339	}
1340
1341	wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - preverify_ok=%d "
1342		   "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
1343		   preverify_ok, err, err_str,
1344		   conn->ca_cert_verify, depth, buf);
1345	if (depth == 0 && match && os_strstr(buf, match) == NULL) {
1346		wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
1347			   "match with '%s'", buf, match);
1348		preverify_ok = 0;
1349		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1350				       "Subject mismatch",
1351				       TLS_FAIL_SUBJECT_MISMATCH);
1352	} else if (depth == 0 && altmatch &&
1353		   !tls_match_altsubject(err_cert, altmatch)) {
1354		wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
1355			   "'%s' not found", altmatch);
1356		preverify_ok = 0;
1357		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1358				       "AltSubject mismatch",
1359				       TLS_FAIL_ALTSUBJECT_MISMATCH);
1360	} else
1361		openssl_tls_cert_event(conn, err_cert, depth, buf);
1362
1363	if (conn->cert_probe && preverify_ok && depth == 0) {
1364		wpa_printf(MSG_DEBUG, "OpenSSL: Reject server certificate "
1365			   "on probe-only run");
1366		preverify_ok = 0;
1367		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1368				       "Server certificate chain probe",
1369				       TLS_FAIL_SERVER_CHAIN_PROBE);
1370	}
1371
1372	if (preverify_ok && context->event_cb != NULL)
1373		context->event_cb(context->cb_ctx,
1374				  TLS_CERT_CHAIN_SUCCESS, NULL);
1375
1376	return preverify_ok;
1377}
1378
1379
1380#ifndef OPENSSL_NO_STDIO
1381static int tls_load_ca_der(void *_ssl_ctx, const char *ca_cert)
1382{
1383	SSL_CTX *ssl_ctx = _ssl_ctx;
1384	X509_LOOKUP *lookup;
1385	int ret = 0;
1386
1387	lookup = X509_STORE_add_lookup(ssl_ctx->cert_store,
1388				       X509_LOOKUP_file());
1389	if (lookup == NULL) {
1390		tls_show_errors(MSG_WARNING, __func__,
1391				"Failed add lookup for X509 store");
1392		return -1;
1393	}
1394
1395	if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
1396		unsigned long err = ERR_peek_error();
1397		tls_show_errors(MSG_WARNING, __func__,
1398				"Failed load CA in DER format");
1399		if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1400		    ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1401			wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1402				   "cert already in hash table error",
1403				   __func__);
1404		} else
1405			ret = -1;
1406	}
1407
1408	return ret;
1409}
1410#endif /* OPENSSL_NO_STDIO */
1411
1412
1413static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
1414				  const char *ca_cert, const u8 *ca_cert_blob,
1415				  size_t ca_cert_blob_len, const char *ca_path)
1416{
1417	SSL_CTX *ssl_ctx = _ssl_ctx;
1418
1419	/*
1420	 * Remove previously configured trusted CA certificates before adding
1421	 * new ones.
1422	 */
1423	X509_STORE_free(ssl_ctx->cert_store);
1424	ssl_ctx->cert_store = X509_STORE_new();
1425	if (ssl_ctx->cert_store == NULL) {
1426		wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1427			   "certificate store", __func__);
1428		return -1;
1429	}
1430
1431	SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1432	conn->ca_cert_verify = 1;
1433
1434	if (ca_cert && os_strncmp(ca_cert, "probe://", 8) == 0) {
1435		wpa_printf(MSG_DEBUG, "OpenSSL: Probe for server certificate "
1436			   "chain");
1437		conn->cert_probe = 1;
1438		conn->ca_cert_verify = 0;
1439		return 0;
1440	}
1441
1442	if (ca_cert && os_strncmp(ca_cert, "hash://", 7) == 0) {
1443#ifdef CONFIG_SHA256
1444		const char *pos = ca_cert + 7;
1445		if (os_strncmp(pos, "server/sha256/", 14) != 0) {
1446			wpa_printf(MSG_DEBUG, "OpenSSL: Unsupported ca_cert "
1447				   "hash value '%s'", ca_cert);
1448			return -1;
1449		}
1450		pos += 14;
1451		if (os_strlen(pos) != 32 * 2) {
1452			wpa_printf(MSG_DEBUG, "OpenSSL: Unexpected SHA256 "
1453				   "hash length in ca_cert '%s'", ca_cert);
1454			return -1;
1455		}
1456		if (hexstr2bin(pos, conn->srv_cert_hash, 32) < 0) {
1457			wpa_printf(MSG_DEBUG, "OpenSSL: Invalid SHA256 hash "
1458				   "value in ca_cert '%s'", ca_cert);
1459			return -1;
1460		}
1461		conn->server_cert_only = 1;
1462		wpa_printf(MSG_DEBUG, "OpenSSL: Checking only server "
1463			   "certificate match");
1464		return 0;
1465#else /* CONFIG_SHA256 */
1466		wpa_printf(MSG_INFO, "No SHA256 included in the build - "
1467			   "cannot validate server certificate hash");
1468		return -1;
1469#endif /* CONFIG_SHA256 */
1470	}
1471
1472	if (ca_cert_blob) {
1473		X509 *cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ca_cert_blob,
1474				      ca_cert_blob_len);
1475		if (cert == NULL) {
1476			tls_show_errors(MSG_WARNING, __func__,
1477					"Failed to parse ca_cert_blob");
1478			return -1;
1479		}
1480
1481		if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
1482			unsigned long err = ERR_peek_error();
1483			tls_show_errors(MSG_WARNING, __func__,
1484					"Failed to add ca_cert_blob to "
1485					"certificate store");
1486			if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1487			    ERR_GET_REASON(err) ==
1488			    X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1489				wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1490					   "cert already in hash table error",
1491					   __func__);
1492			} else {
1493				X509_free(cert);
1494				return -1;
1495			}
1496		}
1497		X509_free(cert);
1498		wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
1499			   "to certificate store", __func__);
1500		return 0;
1501	}
1502
1503#ifdef ANDROID
1504	if (ca_cert && os_strncmp("keystore://", ca_cert, 11) == 0) {
1505		BIO *bio = BIO_from_keystore(&ca_cert[11]);
1506		STACK_OF(X509_INFO) *stack = NULL;
1507		int i;
1508
1509		if (bio) {
1510			stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
1511			BIO_free(bio);
1512		}
1513		if (!stack)
1514			return -1;
1515
1516		for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
1517			X509_INFO *info = sk_X509_INFO_value(stack, i);
1518			if (info->x509) {
1519				X509_STORE_add_cert(ssl_ctx->cert_store,
1520						    info->x509);
1521			}
1522			if (info->crl) {
1523				X509_STORE_add_crl(ssl_ctx->cert_store,
1524						   info->crl);
1525			}
1526		}
1527		sk_X509_INFO_pop_free(stack, X509_INFO_free);
1528		SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1529		return 0;
1530	}
1531#endif /* ANDROID */
1532
1533#ifdef CONFIG_NATIVE_WINDOWS
1534	if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
1535	    0) {
1536		wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
1537			   "system certificate store");
1538		return 0;
1539	}
1540#endif /* CONFIG_NATIVE_WINDOWS */
1541
1542	if (ca_cert || ca_path) {
1543#ifndef OPENSSL_NO_STDIO
1544		if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
1545		    1) {
1546			tls_show_errors(MSG_WARNING, __func__,
1547					"Failed to load root certificates");
1548			if (ca_cert &&
1549			    tls_load_ca_der(ssl_ctx, ca_cert) == 0) {
1550				wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
1551					   "DER format CA certificate",
1552					   __func__);
1553			} else
1554				return -1;
1555		} else {
1556			wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1557				   "certificate(s) loaded");
1558			tls_get_errors(ssl_ctx);
1559		}
1560#else /* OPENSSL_NO_STDIO */
1561		wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1562			   __func__);
1563		return -1;
1564#endif /* OPENSSL_NO_STDIO */
1565	} else {
1566		/* No ca_cert configured - do not try to verify server
1567		 * certificate */
1568		conn->ca_cert_verify = 0;
1569	}
1570
1571	return 0;
1572}
1573
1574
1575static int tls_global_ca_cert(SSL_CTX *ssl_ctx, const char *ca_cert)
1576{
1577	if (ca_cert) {
1578		if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
1579		{
1580			tls_show_errors(MSG_WARNING, __func__,
1581					"Failed to load root certificates");
1582			return -1;
1583		}
1584
1585		wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1586			   "certificate(s) loaded");
1587
1588#ifndef OPENSSL_NO_STDIO
1589		/* Add the same CAs to the client certificate requests */
1590		SSL_CTX_set_client_CA_list(ssl_ctx,
1591					   SSL_load_client_CA_file(ca_cert));
1592#endif /* OPENSSL_NO_STDIO */
1593	}
1594
1595	return 0;
1596}
1597
1598
1599int tls_global_set_verify(void *ssl_ctx, int check_crl)
1600{
1601	int flags;
1602
1603	if (check_crl) {
1604		X509_STORE *cs = SSL_CTX_get_cert_store(ssl_ctx);
1605		if (cs == NULL) {
1606			tls_show_errors(MSG_INFO, __func__, "Failed to get "
1607					"certificate store when enabling "
1608					"check_crl");
1609			return -1;
1610		}
1611		flags = X509_V_FLAG_CRL_CHECK;
1612		if (check_crl == 2)
1613			flags |= X509_V_FLAG_CRL_CHECK_ALL;
1614		X509_STORE_set_flags(cs, flags);
1615	}
1616	return 0;
1617}
1618
1619
1620static int tls_connection_set_subject_match(struct tls_connection *conn,
1621					    const char *subject_match,
1622					    const char *altsubject_match)
1623{
1624	os_free(conn->subject_match);
1625	conn->subject_match = NULL;
1626	if (subject_match) {
1627		conn->subject_match = os_strdup(subject_match);
1628		if (conn->subject_match == NULL)
1629			return -1;
1630	}
1631
1632	os_free(conn->altsubject_match);
1633	conn->altsubject_match = NULL;
1634	if (altsubject_match) {
1635		conn->altsubject_match = os_strdup(altsubject_match);
1636		if (conn->altsubject_match == NULL)
1637			return -1;
1638	}
1639
1640	return 0;
1641}
1642
1643
1644int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
1645			      int verify_peer)
1646{
1647	static int counter = 0;
1648
1649	if (conn == NULL)
1650		return -1;
1651
1652	if (verify_peer) {
1653		conn->ca_cert_verify = 1;
1654		SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
1655			       SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1656			       SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
1657	} else {
1658		conn->ca_cert_verify = 0;
1659		SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1660	}
1661
1662	SSL_set_accept_state(conn->ssl);
1663
1664	/*
1665	 * Set session id context in order to avoid fatal errors when client
1666	 * tries to resume a session. However, set the context to a unique
1667	 * value in order to effectively disable session resumption for now
1668	 * since not all areas of the server code are ready for it (e.g.,
1669	 * EAP-TTLS needs special handling for Phase 2 after abbreviated TLS
1670	 * handshake).
1671	 */
1672	counter++;
1673	SSL_set_session_id_context(conn->ssl,
1674				   (const unsigned char *) &counter,
1675				   sizeof(counter));
1676
1677	return 0;
1678}
1679
1680
1681static int tls_connection_client_cert(struct tls_connection *conn,
1682				      const char *client_cert,
1683				      const u8 *client_cert_blob,
1684				      size_t client_cert_blob_len)
1685{
1686	if (client_cert == NULL && client_cert_blob == NULL)
1687		return 0;
1688
1689	if (client_cert_blob &&
1690	    SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
1691				     client_cert_blob_len) == 1) {
1692		wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
1693			   "OK");
1694		return 0;
1695	} else if (client_cert_blob) {
1696		tls_show_errors(MSG_DEBUG, __func__,
1697				"SSL_use_certificate_ASN1 failed");
1698	}
1699
1700	if (client_cert == NULL)
1701		return -1;
1702
1703#ifdef ANDROID
1704	if (os_strncmp("keystore://", client_cert, 11) == 0) {
1705		BIO *bio = BIO_from_keystore(&client_cert[11]);
1706		X509 *x509 = NULL;
1707		int ret = -1;
1708		if (bio) {
1709			x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
1710			BIO_free(bio);
1711		}
1712		if (x509) {
1713			if (SSL_use_certificate(conn->ssl, x509) == 1)
1714				ret = 0;
1715			X509_free(x509);
1716		}
1717		return ret;
1718	}
1719#endif /* ANDROID */
1720
1721#ifndef OPENSSL_NO_STDIO
1722	if (SSL_use_certificate_file(conn->ssl, client_cert,
1723				     SSL_FILETYPE_ASN1) == 1) {
1724		wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
1725			   " --> OK");
1726		return 0;
1727	}
1728
1729	if (SSL_use_certificate_file(conn->ssl, client_cert,
1730				     SSL_FILETYPE_PEM) == 1) {
1731		ERR_clear_error();
1732		wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
1733			   " --> OK");
1734		return 0;
1735	}
1736
1737	tls_show_errors(MSG_DEBUG, __func__,
1738			"SSL_use_certificate_file failed");
1739#else /* OPENSSL_NO_STDIO */
1740	wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1741#endif /* OPENSSL_NO_STDIO */
1742
1743	return -1;
1744}
1745
1746
1747static int tls_global_client_cert(SSL_CTX *ssl_ctx, const char *client_cert)
1748{
1749#ifndef OPENSSL_NO_STDIO
1750	if (client_cert == NULL)
1751		return 0;
1752
1753	if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1754					 SSL_FILETYPE_ASN1) != 1 &&
1755	    SSL_CTX_use_certificate_chain_file(ssl_ctx, client_cert) != 1 &&
1756	    SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1757					 SSL_FILETYPE_PEM) != 1) {
1758		tls_show_errors(MSG_INFO, __func__,
1759				"Failed to load client certificate");
1760		return -1;
1761	}
1762	return 0;
1763#else /* OPENSSL_NO_STDIO */
1764	if (client_cert == NULL)
1765		return 0;
1766	wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1767	return -1;
1768#endif /* OPENSSL_NO_STDIO */
1769}
1770
1771
1772static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
1773{
1774	if (password == NULL) {
1775		return 0;
1776	}
1777	os_strlcpy(buf, (char *) password, size);
1778	return os_strlen(buf);
1779}
1780
1781
1782#ifdef PKCS12_FUNCS
1783static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
1784			    const char *passwd)
1785{
1786	EVP_PKEY *pkey;
1787	X509 *cert;
1788	STACK_OF(X509) *certs;
1789	int res = 0;
1790	char buf[256];
1791
1792	pkey = NULL;
1793	cert = NULL;
1794	certs = NULL;
1795	if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
1796		tls_show_errors(MSG_DEBUG, __func__,
1797				"Failed to parse PKCS12 file");
1798		PKCS12_free(p12);
1799		return -1;
1800	}
1801	wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
1802
1803	if (cert) {
1804		X509_NAME_oneline(X509_get_subject_name(cert), buf,
1805				  sizeof(buf));
1806		wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
1807			   "subject='%s'", buf);
1808		if (ssl) {
1809			if (SSL_use_certificate(ssl, cert) != 1)
1810				res = -1;
1811		} else {
1812			if (SSL_CTX_use_certificate(ssl_ctx, cert) != 1)
1813				res = -1;
1814		}
1815		X509_free(cert);
1816	}
1817
1818	if (pkey) {
1819		wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
1820		if (ssl) {
1821			if (SSL_use_PrivateKey(ssl, pkey) != 1)
1822				res = -1;
1823		} else {
1824			if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1)
1825				res = -1;
1826		}
1827		EVP_PKEY_free(pkey);
1828	}
1829
1830	if (certs) {
1831		while ((cert = sk_X509_pop(certs)) != NULL) {
1832			X509_NAME_oneline(X509_get_subject_name(cert), buf,
1833					  sizeof(buf));
1834			wpa_printf(MSG_DEBUG, "TLS: additional certificate"
1835				   " from PKCS12: subject='%s'", buf);
1836			/*
1837			 * There is no SSL equivalent for the chain cert - so
1838			 * always add it to the context...
1839			 */
1840			if (SSL_CTX_add_extra_chain_cert(ssl_ctx, cert) != 1) {
1841				res = -1;
1842				break;
1843			}
1844		}
1845		sk_X509_free(certs);
1846	}
1847
1848	PKCS12_free(p12);
1849
1850	if (res < 0)
1851		tls_get_errors(ssl_ctx);
1852
1853	return res;
1854}
1855#endif  /* PKCS12_FUNCS */
1856
1857
1858static int tls_read_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, const char *private_key,
1859			   const char *passwd)
1860{
1861#ifdef PKCS12_FUNCS
1862	FILE *f;
1863	PKCS12 *p12;
1864
1865	f = fopen(private_key, "rb");
1866	if (f == NULL)
1867		return -1;
1868
1869	p12 = d2i_PKCS12_fp(f, NULL);
1870	fclose(f);
1871
1872	if (p12 == NULL) {
1873		tls_show_errors(MSG_INFO, __func__,
1874				"Failed to use PKCS#12 file");
1875		return -1;
1876	}
1877
1878	return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1879
1880#else /* PKCS12_FUNCS */
1881	wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
1882		   "p12/pfx files");
1883	return -1;
1884#endif  /* PKCS12_FUNCS */
1885}
1886
1887
1888static int tls_read_pkcs12_blob(SSL_CTX *ssl_ctx, SSL *ssl,
1889				const u8 *blob, size_t len, const char *passwd)
1890{
1891#ifdef PKCS12_FUNCS
1892	PKCS12 *p12;
1893
1894	p12 = d2i_PKCS12(NULL, (OPENSSL_d2i_TYPE) &blob, len);
1895	if (p12 == NULL) {
1896		tls_show_errors(MSG_INFO, __func__,
1897				"Failed to use PKCS#12 blob");
1898		return -1;
1899	}
1900
1901	return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1902
1903#else /* PKCS12_FUNCS */
1904	wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
1905		   "p12/pfx blobs");
1906	return -1;
1907#endif  /* PKCS12_FUNCS */
1908}
1909
1910
1911#ifndef OPENSSL_NO_ENGINE
1912static int tls_engine_get_cert(struct tls_connection *conn,
1913			       const char *cert_id,
1914			       X509 **cert)
1915{
1916	/* this runs after the private key is loaded so no PIN is required */
1917	struct {
1918		const char *cert_id;
1919		X509 *cert;
1920	} params;
1921	params.cert_id = cert_id;
1922	params.cert = NULL;
1923
1924	if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
1925			     0, &params, NULL, 1)) {
1926		wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
1927			   " '%s' [%s]", cert_id,
1928			   ERR_error_string(ERR_get_error(), NULL));
1929		return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1930	}
1931	if (!params.cert) {
1932		wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
1933			   " '%s'", cert_id);
1934		return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1935	}
1936	*cert = params.cert;
1937	return 0;
1938}
1939#endif /* OPENSSL_NO_ENGINE */
1940
1941
1942static int tls_connection_engine_client_cert(struct tls_connection *conn,
1943					     const char *cert_id)
1944{
1945#ifndef OPENSSL_NO_ENGINE
1946	X509 *cert;
1947
1948	if (tls_engine_get_cert(conn, cert_id, &cert))
1949		return -1;
1950
1951	if (!SSL_use_certificate(conn->ssl, cert)) {
1952		tls_show_errors(MSG_ERROR, __func__,
1953				"SSL_use_certificate failed");
1954                X509_free(cert);
1955		return -1;
1956	}
1957	X509_free(cert);
1958	wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
1959		   "OK");
1960	return 0;
1961
1962#else /* OPENSSL_NO_ENGINE */
1963	return -1;
1964#endif /* OPENSSL_NO_ENGINE */
1965}
1966
1967
1968static int tls_connection_engine_ca_cert(void *_ssl_ctx,
1969					 struct tls_connection *conn,
1970					 const char *ca_cert_id)
1971{
1972#ifndef OPENSSL_NO_ENGINE
1973	X509 *cert;
1974	SSL_CTX *ssl_ctx = _ssl_ctx;
1975
1976	if (tls_engine_get_cert(conn, ca_cert_id, &cert))
1977		return -1;
1978
1979	/* start off the same as tls_connection_ca_cert */
1980	X509_STORE_free(ssl_ctx->cert_store);
1981	ssl_ctx->cert_store = X509_STORE_new();
1982	if (ssl_ctx->cert_store == NULL) {
1983		wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1984			   "certificate store", __func__);
1985		X509_free(cert);
1986		return -1;
1987	}
1988	if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
1989		unsigned long err = ERR_peek_error();
1990		tls_show_errors(MSG_WARNING, __func__,
1991				"Failed to add CA certificate from engine "
1992				"to certificate store");
1993		if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1994		    ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1995			wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
1996				   " already in hash table error",
1997				   __func__);
1998		} else {
1999			X509_free(cert);
2000			return -1;
2001		}
2002	}
2003	X509_free(cert);
2004	wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
2005		   "to certificate store", __func__);
2006	SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
2007	conn->ca_cert_verify = 1;
2008
2009	return 0;
2010
2011#else /* OPENSSL_NO_ENGINE */
2012	return -1;
2013#endif /* OPENSSL_NO_ENGINE */
2014}
2015
2016
2017static int tls_connection_engine_private_key(struct tls_connection *conn)
2018{
2019#ifndef OPENSSL_NO_ENGINE
2020	if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
2021		tls_show_errors(MSG_ERROR, __func__,
2022				"ENGINE: cannot use private key for TLS");
2023		return -1;
2024	}
2025	if (!SSL_check_private_key(conn->ssl)) {
2026		tls_show_errors(MSG_INFO, __func__,
2027				"Private key failed verification");
2028		return -1;
2029	}
2030	return 0;
2031#else /* OPENSSL_NO_ENGINE */
2032	wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
2033		   "engine support was not compiled in");
2034	return -1;
2035#endif /* OPENSSL_NO_ENGINE */
2036}
2037
2038
2039static int tls_connection_private_key(void *_ssl_ctx,
2040				      struct tls_connection *conn,
2041				      const char *private_key,
2042				      const char *private_key_passwd,
2043				      const u8 *private_key_blob,
2044				      size_t private_key_blob_len)
2045{
2046	SSL_CTX *ssl_ctx = _ssl_ctx;
2047	char *passwd;
2048	int ok;
2049
2050	if (private_key == NULL && private_key_blob == NULL)
2051		return 0;
2052
2053	if (private_key_passwd) {
2054		passwd = os_strdup(private_key_passwd);
2055		if (passwd == NULL)
2056			return -1;
2057	} else
2058		passwd = NULL;
2059
2060	SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2061	SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2062
2063	ok = 0;
2064	while (private_key_blob) {
2065		if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
2066					    (u8 *) private_key_blob,
2067					    private_key_blob_len) == 1) {
2068			wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
2069				   "ASN1(EVP_PKEY_RSA) --> OK");
2070			ok = 1;
2071			break;
2072		}
2073
2074		if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
2075					    (u8 *) private_key_blob,
2076					    private_key_blob_len) == 1) {
2077			wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
2078				   "ASN1(EVP_PKEY_DSA) --> OK");
2079			ok = 1;
2080			break;
2081		}
2082
2083		if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
2084					       (u8 *) private_key_blob,
2085					       private_key_blob_len) == 1) {
2086			wpa_printf(MSG_DEBUG, "OpenSSL: "
2087				   "SSL_use_RSAPrivateKey_ASN1 --> OK");
2088			ok = 1;
2089			break;
2090		}
2091
2092		if (tls_read_pkcs12_blob(ssl_ctx, conn->ssl, private_key_blob,
2093					 private_key_blob_len, passwd) == 0) {
2094			wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
2095				   "OK");
2096			ok = 1;
2097			break;
2098		}
2099
2100		break;
2101	}
2102
2103	while (!ok && private_key) {
2104#ifndef OPENSSL_NO_STDIO
2105		if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2106					    SSL_FILETYPE_ASN1) == 1) {
2107			wpa_printf(MSG_DEBUG, "OpenSSL: "
2108				   "SSL_use_PrivateKey_File (DER) --> OK");
2109			ok = 1;
2110			break;
2111		}
2112
2113		if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2114					    SSL_FILETYPE_PEM) == 1) {
2115			wpa_printf(MSG_DEBUG, "OpenSSL: "
2116				   "SSL_use_PrivateKey_File (PEM) --> OK");
2117			ok = 1;
2118			break;
2119		}
2120#else /* OPENSSL_NO_STDIO */
2121		wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
2122			   __func__);
2123#endif /* OPENSSL_NO_STDIO */
2124
2125		if (tls_read_pkcs12(ssl_ctx, conn->ssl, private_key, passwd)
2126		    == 0) {
2127			wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
2128				   "--> OK");
2129			ok = 1;
2130			break;
2131		}
2132
2133		if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
2134			wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
2135				   "access certificate store --> OK");
2136			ok = 1;
2137			break;
2138		}
2139
2140		break;
2141	}
2142
2143	if (!ok) {
2144		tls_show_errors(MSG_INFO, __func__,
2145				"Failed to load private key");
2146		os_free(passwd);
2147		return -1;
2148	}
2149	ERR_clear_error();
2150	SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2151	os_free(passwd);
2152
2153	if (!SSL_check_private_key(conn->ssl)) {
2154		tls_show_errors(MSG_INFO, __func__, "Private key failed "
2155				"verification");
2156		return -1;
2157	}
2158
2159	wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
2160	return 0;
2161}
2162
2163
2164static int tls_global_private_key(SSL_CTX *ssl_ctx, const char *private_key,
2165				  const char *private_key_passwd)
2166{
2167	char *passwd;
2168
2169	if (private_key == NULL)
2170		return 0;
2171
2172	if (private_key_passwd) {
2173		passwd = os_strdup(private_key_passwd);
2174		if (passwd == NULL)
2175			return -1;
2176	} else
2177		passwd = NULL;
2178
2179	SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2180	SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2181	if (
2182#ifndef OPENSSL_NO_STDIO
2183	    SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2184					SSL_FILETYPE_ASN1) != 1 &&
2185	    SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2186					SSL_FILETYPE_PEM) != 1 &&
2187#endif /* OPENSSL_NO_STDIO */
2188	    tls_read_pkcs12(ssl_ctx, NULL, private_key, passwd)) {
2189		tls_show_errors(MSG_INFO, __func__,
2190				"Failed to load private key");
2191		os_free(passwd);
2192		ERR_clear_error();
2193		return -1;
2194	}
2195	os_free(passwd);
2196	ERR_clear_error();
2197	SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2198
2199	if (!SSL_CTX_check_private_key(ssl_ctx)) {
2200		tls_show_errors(MSG_INFO, __func__,
2201				"Private key failed verification");
2202		return -1;
2203	}
2204
2205	return 0;
2206}
2207
2208
2209static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
2210{
2211#ifdef OPENSSL_NO_DH
2212	if (dh_file == NULL)
2213		return 0;
2214	wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2215		   "dh_file specified");
2216	return -1;
2217#else /* OPENSSL_NO_DH */
2218	DH *dh;
2219	BIO *bio;
2220
2221	/* TODO: add support for dh_blob */
2222	if (dh_file == NULL)
2223		return 0;
2224	if (conn == NULL)
2225		return -1;
2226
2227	bio = BIO_new_file(dh_file, "r");
2228	if (bio == NULL) {
2229		wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2230			   dh_file, ERR_error_string(ERR_get_error(), NULL));
2231		return -1;
2232	}
2233	dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2234	BIO_free(bio);
2235#ifndef OPENSSL_NO_DSA
2236	while (dh == NULL) {
2237		DSA *dsa;
2238		wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2239			   " trying to parse as DSA params", dh_file,
2240			   ERR_error_string(ERR_get_error(), NULL));
2241		bio = BIO_new_file(dh_file, "r");
2242		if (bio == NULL)
2243			break;
2244		dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2245		BIO_free(bio);
2246		if (!dsa) {
2247			wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2248				   "'%s': %s", dh_file,
2249				   ERR_error_string(ERR_get_error(), NULL));
2250			break;
2251		}
2252
2253		wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2254		dh = DSA_dup_DH(dsa);
2255		DSA_free(dsa);
2256		if (dh == NULL) {
2257			wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2258				   "params into DH params");
2259			break;
2260		}
2261		break;
2262	}
2263#endif /* !OPENSSL_NO_DSA */
2264	if (dh == NULL) {
2265		wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2266			   "'%s'", dh_file);
2267		return -1;
2268	}
2269
2270	if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
2271		wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2272			   "%s", dh_file,
2273			   ERR_error_string(ERR_get_error(), NULL));
2274		DH_free(dh);
2275		return -1;
2276	}
2277	DH_free(dh);
2278	return 0;
2279#endif /* OPENSSL_NO_DH */
2280}
2281
2282
2283static int tls_global_dh(SSL_CTX *ssl_ctx, const char *dh_file)
2284{
2285#ifdef OPENSSL_NO_DH
2286	if (dh_file == NULL)
2287		return 0;
2288	wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2289		   "dh_file specified");
2290	return -1;
2291#else /* OPENSSL_NO_DH */
2292	DH *dh;
2293	BIO *bio;
2294
2295	/* TODO: add support for dh_blob */
2296	if (dh_file == NULL)
2297		return 0;
2298	if (ssl_ctx == NULL)
2299		return -1;
2300
2301	bio = BIO_new_file(dh_file, "r");
2302	if (bio == NULL) {
2303		wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2304			   dh_file, ERR_error_string(ERR_get_error(), NULL));
2305		return -1;
2306	}
2307	dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2308	BIO_free(bio);
2309#ifndef OPENSSL_NO_DSA
2310	while (dh == NULL) {
2311		DSA *dsa;
2312		wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2313			   " trying to parse as DSA params", dh_file,
2314			   ERR_error_string(ERR_get_error(), NULL));
2315		bio = BIO_new_file(dh_file, "r");
2316		if (bio == NULL)
2317			break;
2318		dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2319		BIO_free(bio);
2320		if (!dsa) {
2321			wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2322				   "'%s': %s", dh_file,
2323				   ERR_error_string(ERR_get_error(), NULL));
2324			break;
2325		}
2326
2327		wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2328		dh = DSA_dup_DH(dsa);
2329		DSA_free(dsa);
2330		if (dh == NULL) {
2331			wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2332				   "params into DH params");
2333			break;
2334		}
2335		break;
2336	}
2337#endif /* !OPENSSL_NO_DSA */
2338	if (dh == NULL) {
2339		wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2340			   "'%s'", dh_file);
2341		return -1;
2342	}
2343
2344	if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
2345		wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2346			   "%s", dh_file,
2347			   ERR_error_string(ERR_get_error(), NULL));
2348		DH_free(dh);
2349		return -1;
2350	}
2351	DH_free(dh);
2352	return 0;
2353#endif /* OPENSSL_NO_DH */
2354}
2355
2356
2357int tls_connection_get_keys(void *ssl_ctx, struct tls_connection *conn,
2358			    struct tls_keys *keys)
2359{
2360#ifdef CONFIG_FIPS
2361	wpa_printf(MSG_ERROR, "OpenSSL: TLS keys cannot be exported in FIPS "
2362		   "mode");
2363	return -1;
2364#else /* CONFIG_FIPS */
2365	SSL *ssl;
2366
2367	if (conn == NULL || keys == NULL)
2368		return -1;
2369	ssl = conn->ssl;
2370	if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
2371		return -1;
2372
2373	os_memset(keys, 0, sizeof(*keys));
2374	keys->master_key = ssl->session->master_key;
2375	keys->master_key_len = ssl->session->master_key_length;
2376	keys->client_random = ssl->s3->client_random;
2377	keys->client_random_len = SSL3_RANDOM_SIZE;
2378	keys->server_random = ssl->s3->server_random;
2379	keys->server_random_len = SSL3_RANDOM_SIZE;
2380
2381	return 0;
2382#endif /* CONFIG_FIPS */
2383}
2384
2385
2386int tls_connection_prf(void *tls_ctx, struct tls_connection *conn,
2387		       const char *label, int server_random_first,
2388		       u8 *out, size_t out_len)
2389{
2390#if OPENSSL_VERSION_NUMBER >= 0x10001000L
2391	SSL *ssl;
2392	if (conn == NULL)
2393		return -1;
2394	if (server_random_first)
2395		return -1;
2396	ssl = conn->ssl;
2397	if (SSL_export_keying_material(ssl, out, out_len, label,
2398				       os_strlen(label), NULL, 0, 0) == 1) {
2399		wpa_printf(MSG_DEBUG, "OpenSSL: Using internal PRF");
2400		return 0;
2401	}
2402#endif
2403	return -1;
2404}
2405
2406
2407static struct wpabuf *
2408openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data,
2409		  int server)
2410{
2411	int res;
2412	struct wpabuf *out_data;
2413
2414	/*
2415	 * Give TLS handshake data from the server (if available) to OpenSSL
2416	 * for processing.
2417	 */
2418	if (in_data &&
2419	    BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
2420	    < 0) {
2421		tls_show_errors(MSG_INFO, __func__,
2422				"Handshake failed - BIO_write");
2423		return NULL;
2424	}
2425
2426	/* Initiate TLS handshake or continue the existing handshake */
2427	if (server)
2428		res = SSL_accept(conn->ssl);
2429	else
2430		res = SSL_connect(conn->ssl);
2431	if (res != 1) {
2432		int err = SSL_get_error(conn->ssl, res);
2433		if (err == SSL_ERROR_WANT_READ)
2434			wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
2435				   "more data");
2436		else if (err == SSL_ERROR_WANT_WRITE)
2437			wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
2438				   "write");
2439		else {
2440			tls_show_errors(MSG_INFO, __func__, "SSL_connect");
2441			conn->failed++;
2442		}
2443	}
2444
2445	/* Get the TLS handshake data to be sent to the server */
2446	res = BIO_ctrl_pending(conn->ssl_out);
2447	wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
2448	out_data = wpabuf_alloc(res);
2449	if (out_data == NULL) {
2450		wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
2451			   "handshake output (%d bytes)", res);
2452		if (BIO_reset(conn->ssl_out) < 0) {
2453			tls_show_errors(MSG_INFO, __func__,
2454					"BIO_reset failed");
2455		}
2456		return NULL;
2457	}
2458	res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
2459				      res);
2460	if (res < 0) {
2461		tls_show_errors(MSG_INFO, __func__,
2462				"Handshake failed - BIO_read");
2463		if (BIO_reset(conn->ssl_out) < 0) {
2464			tls_show_errors(MSG_INFO, __func__,
2465					"BIO_reset failed");
2466		}
2467		wpabuf_free(out_data);
2468		return NULL;
2469	}
2470	wpabuf_put(out_data, res);
2471
2472	return out_data;
2473}
2474
2475
2476static struct wpabuf *
2477openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
2478{
2479	struct wpabuf *appl_data;
2480	int res;
2481
2482	appl_data = wpabuf_alloc(max_len + 100);
2483	if (appl_data == NULL)
2484		return NULL;
2485
2486	res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
2487		       wpabuf_size(appl_data));
2488	if (res < 0) {
2489		int err = SSL_get_error(conn->ssl, res);
2490		if (err == SSL_ERROR_WANT_READ ||
2491		    err == SSL_ERROR_WANT_WRITE) {
2492			wpa_printf(MSG_DEBUG, "SSL: No Application Data "
2493				   "included");
2494		} else {
2495			tls_show_errors(MSG_INFO, __func__,
2496					"Failed to read possible "
2497					"Application Data");
2498		}
2499		wpabuf_free(appl_data);
2500		return NULL;
2501	}
2502
2503	wpabuf_put(appl_data, res);
2504	wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
2505			    "message", appl_data);
2506
2507	return appl_data;
2508}
2509
2510
2511static struct wpabuf *
2512openssl_connection_handshake(struct tls_connection *conn,
2513			     const struct wpabuf *in_data,
2514			     struct wpabuf **appl_data, int server)
2515{
2516	struct wpabuf *out_data;
2517
2518	if (appl_data)
2519		*appl_data = NULL;
2520
2521	out_data = openssl_handshake(conn, in_data, server);
2522	if (out_data == NULL)
2523		return NULL;
2524
2525	if (SSL_is_init_finished(conn->ssl) && appl_data && in_data)
2526		*appl_data = openssl_get_appl_data(conn, wpabuf_len(in_data));
2527
2528	return out_data;
2529}
2530
2531
2532struct wpabuf *
2533tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
2534			 const struct wpabuf *in_data,
2535			 struct wpabuf **appl_data)
2536{
2537	return openssl_connection_handshake(conn, in_data, appl_data, 0);
2538}
2539
2540
2541struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
2542						struct tls_connection *conn,
2543						const struct wpabuf *in_data,
2544						struct wpabuf **appl_data)
2545{
2546	return openssl_connection_handshake(conn, in_data, appl_data, 1);
2547}
2548
2549
2550struct wpabuf * tls_connection_encrypt(void *tls_ctx,
2551				       struct tls_connection *conn,
2552				       const struct wpabuf *in_data)
2553{
2554	int res;
2555	struct wpabuf *buf;
2556
2557	if (conn == NULL)
2558		return NULL;
2559
2560	/* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
2561	if ((res = BIO_reset(conn->ssl_in)) < 0 ||
2562	    (res = BIO_reset(conn->ssl_out)) < 0) {
2563		tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2564		return NULL;
2565	}
2566	res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
2567	if (res < 0) {
2568		tls_show_errors(MSG_INFO, __func__,
2569				"Encryption failed - SSL_write");
2570		return NULL;
2571	}
2572
2573	/* Read encrypted data to be sent to the server */
2574	buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
2575	if (buf == NULL)
2576		return NULL;
2577	res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
2578	if (res < 0) {
2579		tls_show_errors(MSG_INFO, __func__,
2580				"Encryption failed - BIO_read");
2581		wpabuf_free(buf);
2582		return NULL;
2583	}
2584	wpabuf_put(buf, res);
2585
2586	return buf;
2587}
2588
2589
2590struct wpabuf * tls_connection_decrypt(void *tls_ctx,
2591				       struct tls_connection *conn,
2592				       const struct wpabuf *in_data)
2593{
2594	int res;
2595	struct wpabuf *buf;
2596
2597	/* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
2598	res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
2599			wpabuf_len(in_data));
2600	if (res < 0) {
2601		tls_show_errors(MSG_INFO, __func__,
2602				"Decryption failed - BIO_write");
2603		return NULL;
2604	}
2605	if (BIO_reset(conn->ssl_out) < 0) {
2606		tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2607		return NULL;
2608	}
2609
2610	/* Read decrypted data for further processing */
2611	/*
2612	 * Even though we try to disable TLS compression, it is possible that
2613	 * this cannot be done with all TLS libraries. Add extra buffer space
2614	 * to handle the possibility of the decrypted data being longer than
2615	 * input data.
2616	 */
2617	buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
2618	if (buf == NULL)
2619		return NULL;
2620	res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
2621	if (res < 0) {
2622		tls_show_errors(MSG_INFO, __func__,
2623				"Decryption failed - SSL_read");
2624		wpabuf_free(buf);
2625		return NULL;
2626	}
2627	wpabuf_put(buf, res);
2628
2629	return buf;
2630}
2631
2632
2633int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
2634{
2635	return conn ? conn->ssl->hit : 0;
2636}
2637
2638
2639int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
2640				   u8 *ciphers)
2641{
2642	char buf[100], *pos, *end;
2643	u8 *c;
2644	int ret;
2645
2646	if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
2647		return -1;
2648
2649	buf[0] = '\0';
2650	pos = buf;
2651	end = pos + sizeof(buf);
2652
2653	c = ciphers;
2654	while (*c != TLS_CIPHER_NONE) {
2655		const char *suite;
2656
2657		switch (*c) {
2658		case TLS_CIPHER_RC4_SHA:
2659			suite = "RC4-SHA";
2660			break;
2661		case TLS_CIPHER_AES128_SHA:
2662			suite = "AES128-SHA";
2663			break;
2664		case TLS_CIPHER_RSA_DHE_AES128_SHA:
2665			suite = "DHE-RSA-AES128-SHA";
2666			break;
2667		case TLS_CIPHER_ANON_DH_AES128_SHA:
2668			suite = "ADH-AES128-SHA";
2669			break;
2670		default:
2671			wpa_printf(MSG_DEBUG, "TLS: Unsupported "
2672				   "cipher selection: %d", *c);
2673			return -1;
2674		}
2675		ret = os_snprintf(pos, end - pos, ":%s", suite);
2676		if (ret < 0 || ret >= end - pos)
2677			break;
2678		pos += ret;
2679
2680		c++;
2681	}
2682
2683	wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
2684
2685	if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
2686		tls_show_errors(MSG_INFO, __func__,
2687				"Cipher suite configuration failed");
2688		return -1;
2689	}
2690
2691	return 0;
2692}
2693
2694
2695int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
2696		   char *buf, size_t buflen)
2697{
2698	const char *name;
2699	if (conn == NULL || conn->ssl == NULL)
2700		return -1;
2701
2702	name = SSL_get_cipher(conn->ssl);
2703	if (name == NULL)
2704		return -1;
2705
2706	os_strlcpy(buf, name, buflen);
2707	return 0;
2708}
2709
2710
2711int tls_connection_enable_workaround(void *ssl_ctx,
2712				     struct tls_connection *conn)
2713{
2714	SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
2715
2716	return 0;
2717}
2718
2719
2720#if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2721/* ClientHello TLS extensions require a patch to openssl, so this function is
2722 * commented out unless explicitly needed for EAP-FAST in order to be able to
2723 * build this file with unmodified openssl. */
2724int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
2725				    int ext_type, const u8 *data,
2726				    size_t data_len)
2727{
2728	if (conn == NULL || conn->ssl == NULL || ext_type != 35)
2729		return -1;
2730
2731#ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2732	if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
2733				       data_len) != 1)
2734		return -1;
2735#else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2736	if (SSL_set_hello_extension(conn->ssl, ext_type, (void *) data,
2737				    data_len) != 1)
2738		return -1;
2739#endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2740
2741	return 0;
2742}
2743#endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2744
2745
2746int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
2747{
2748	if (conn == NULL)
2749		return -1;
2750	return conn->failed;
2751}
2752
2753
2754int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
2755{
2756	if (conn == NULL)
2757		return -1;
2758	return conn->read_alerts;
2759}
2760
2761
2762int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
2763{
2764	if (conn == NULL)
2765		return -1;
2766	return conn->write_alerts;
2767}
2768
2769
2770#ifdef HAVE_OCSP
2771
2772static void ocsp_debug_print_resp(OCSP_RESPONSE *rsp)
2773{
2774#ifndef CONFIG_NO_STDOUT_DEBUG
2775	extern int wpa_debug_level;
2776	BIO *out;
2777	size_t rlen;
2778	char *txt;
2779	int res;
2780
2781	if (wpa_debug_level > MSG_DEBUG)
2782		return;
2783
2784	out = BIO_new(BIO_s_mem());
2785	if (!out)
2786		return;
2787
2788	OCSP_RESPONSE_print(out, rsp, 0);
2789	rlen = BIO_ctrl_pending(out);
2790	txt = os_malloc(rlen + 1);
2791	if (!txt) {
2792		BIO_free(out);
2793		return;
2794	}
2795
2796	res = BIO_read(out, txt, rlen);
2797	if (res > 0) {
2798		txt[res] = '\0';
2799		wpa_printf(MSG_DEBUG, "OpenSSL: OCSP Response\n%s", txt);
2800	}
2801	os_free(txt);
2802	BIO_free(out);
2803#endif /* CONFIG_NO_STDOUT_DEBUG */
2804}
2805
2806
2807static int ocsp_resp_cb(SSL *s, void *arg)
2808{
2809	struct tls_connection *conn = arg;
2810	const unsigned char *p;
2811	int len, status, reason;
2812	OCSP_RESPONSE *rsp;
2813	OCSP_BASICRESP *basic;
2814	OCSP_CERTID *id;
2815	ASN1_GENERALIZEDTIME *produced_at, *this_update, *next_update;
2816
2817	len = SSL_get_tlsext_status_ocsp_resp(s, &p);
2818	if (!p) {
2819		wpa_printf(MSG_DEBUG, "OpenSSL: No OCSP response received");
2820		return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
2821	}
2822
2823	wpa_hexdump(MSG_DEBUG, "OpenSSL: OCSP response", p, len);
2824
2825	rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
2826	if (!rsp) {
2827		wpa_printf(MSG_INFO, "OpenSSL: Failed to parse OCSP response");
2828		return 0;
2829	}
2830
2831	ocsp_debug_print_resp(rsp);
2832
2833	status = OCSP_response_status(rsp);
2834	if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
2835		wpa_printf(MSG_INFO, "OpenSSL: OCSP responder error %d (%s)",
2836			   status, OCSP_response_status_str(status));
2837		return 0;
2838	}
2839
2840	basic = OCSP_response_get1_basic(rsp);
2841	if (!basic) {
2842		wpa_printf(MSG_INFO, "OpenSSL: Could not find BasicOCSPResponse");
2843		return 0;
2844	}
2845
2846	status = OCSP_basic_verify(basic, NULL, SSL_CTX_get_cert_store(s->ctx),
2847				   0);
2848	if (status <= 0) {
2849		tls_show_errors(MSG_INFO, __func__,
2850				"OpenSSL: OCSP response failed verification");
2851		OCSP_BASICRESP_free(basic);
2852		OCSP_RESPONSE_free(rsp);
2853		return 0;
2854	}
2855
2856	wpa_printf(MSG_DEBUG, "OpenSSL: OCSP response verification succeeded");
2857
2858	if (!conn->peer_cert || !conn->peer_issuer) {
2859		wpa_printf(MSG_DEBUG, "OpenSSL: Peer certificate or issue certificate not available for OCSP status check");
2860		OCSP_BASICRESP_free(basic);
2861		OCSP_RESPONSE_free(rsp);
2862		return 0;
2863	}
2864
2865	id = OCSP_cert_to_id(NULL, conn->peer_cert, conn->peer_issuer);
2866	if (!id) {
2867		wpa_printf(MSG_DEBUG, "OpenSSL: Could not create OCSP certificate identifier");
2868		OCSP_BASICRESP_free(basic);
2869		OCSP_RESPONSE_free(rsp);
2870		return 0;
2871	}
2872
2873	if (!OCSP_resp_find_status(basic, id, &status, &reason, &produced_at,
2874				   &this_update, &next_update)) {
2875		wpa_printf(MSG_INFO, "OpenSSL: Could not find current server certificate from OCSP response%s",
2876			   (conn->flags & TLS_CONN_REQUIRE_OCSP) ? "" :
2877			   " (OCSP not required)");
2878		OCSP_BASICRESP_free(basic);
2879		OCSP_RESPONSE_free(rsp);
2880		return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
2881	}
2882
2883	if (!OCSP_check_validity(this_update, next_update, 5 * 60, -1)) {
2884		tls_show_errors(MSG_INFO, __func__,
2885				"OpenSSL: OCSP status times invalid");
2886		OCSP_BASICRESP_free(basic);
2887		OCSP_RESPONSE_free(rsp);
2888		return 0;
2889	}
2890
2891	OCSP_BASICRESP_free(basic);
2892	OCSP_RESPONSE_free(rsp);
2893
2894	wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status for server certificate: %s",
2895		   OCSP_cert_status_str(status));
2896
2897	if (status == V_OCSP_CERTSTATUS_GOOD)
2898		return 1;
2899	if (status == V_OCSP_CERTSTATUS_REVOKED)
2900		return 0;
2901	if (conn->flags & TLS_CONN_REQUIRE_OCSP) {
2902		wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP required");
2903		return 0;
2904	}
2905		wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP was not required, so allow connection to continue");
2906	return 1;
2907}
2908
2909
2910static int ocsp_status_cb(SSL *s, void *arg)
2911{
2912	char *tmp;
2913	char *resp;
2914	size_t len;
2915
2916	if (tls_global->ocsp_stapling_response == NULL) {
2917		wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - no response configured");
2918		return SSL_TLSEXT_ERR_OK;
2919	}
2920
2921	resp = os_readfile(tls_global->ocsp_stapling_response, &len);
2922	if (resp == NULL) {
2923		wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - could not read response file");
2924		/* TODO: Build OCSPResponse with responseStatus = internalError
2925		 */
2926		return SSL_TLSEXT_ERR_OK;
2927	}
2928	wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - send cached response");
2929	tmp = OPENSSL_malloc(len);
2930	if (tmp == NULL) {
2931		os_free(resp);
2932		return SSL_TLSEXT_ERR_ALERT_FATAL;
2933	}
2934
2935	os_memcpy(tmp, resp, len);
2936	os_free(resp);
2937	SSL_set_tlsext_status_ocsp_resp(s, tmp, len);
2938
2939	return SSL_TLSEXT_ERR_OK;
2940}
2941
2942#endif /* HAVE_OCSP */
2943
2944
2945int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
2946			      const struct tls_connection_params *params)
2947{
2948	int ret;
2949	unsigned long err;
2950	SSL_CTX *ssl_ctx = tls_ctx;
2951
2952	if (conn == NULL)
2953		return -1;
2954
2955	while ((err = ERR_get_error())) {
2956		wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
2957			   __func__, ERR_error_string(err, NULL));
2958	}
2959
2960	if (params->engine) {
2961		wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
2962		ret = tls_engine_init(conn, params->engine_id, params->pin,
2963				      params->key_id, params->cert_id,
2964				      params->ca_cert_id);
2965		if (ret)
2966			return ret;
2967	}
2968	if (tls_connection_set_subject_match(conn,
2969					     params->subject_match,
2970					     params->altsubject_match))
2971		return -1;
2972
2973	if (params->engine && params->ca_cert_id) {
2974		if (tls_connection_engine_ca_cert(tls_ctx, conn,
2975						  params->ca_cert_id))
2976			return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2977	} else if (tls_connection_ca_cert(tls_ctx, conn, params->ca_cert,
2978					  params->ca_cert_blob,
2979					  params->ca_cert_blob_len,
2980					  params->ca_path))
2981		return -1;
2982
2983	if (params->engine && params->cert_id) {
2984		if (tls_connection_engine_client_cert(conn, params->cert_id))
2985			return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2986	} else if (tls_connection_client_cert(conn, params->client_cert,
2987					      params->client_cert_blob,
2988					      params->client_cert_blob_len))
2989		return -1;
2990
2991	if (params->engine && params->key_id) {
2992		wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
2993		if (tls_connection_engine_private_key(conn))
2994			return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2995	} else if (tls_connection_private_key(tls_ctx, conn,
2996					      params->private_key,
2997					      params->private_key_passwd,
2998					      params->private_key_blob,
2999					      params->private_key_blob_len)) {
3000		wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
3001			   params->private_key);
3002		return -1;
3003	}
3004
3005	if (tls_connection_dh(conn, params->dh_file)) {
3006		wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
3007			   params->dh_file);
3008		return -1;
3009	}
3010
3011#ifdef SSL_OP_NO_TICKET
3012	if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
3013		SSL_set_options(conn->ssl, SSL_OP_NO_TICKET);
3014#ifdef SSL_clear_options
3015	else
3016		SSL_clear_options(conn->ssl, SSL_OP_NO_TICKET);
3017#endif /* SSL_clear_options */
3018#endif /*  SSL_OP_NO_TICKET */
3019
3020#ifdef HAVE_OCSP
3021	if (params->flags & TLS_CONN_REQUEST_OCSP) {
3022		SSL_set_tlsext_status_type(conn->ssl, TLSEXT_STATUSTYPE_ocsp);
3023		SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
3024		SSL_CTX_set_tlsext_status_arg(ssl_ctx, conn);
3025	}
3026#endif /* HAVE_OCSP */
3027
3028	conn->flags = params->flags;
3029
3030	tls_get_errors(tls_ctx);
3031
3032	return 0;
3033}
3034
3035
3036int tls_global_set_params(void *tls_ctx,
3037			  const struct tls_connection_params *params)
3038{
3039	SSL_CTX *ssl_ctx = tls_ctx;
3040	unsigned long err;
3041
3042	while ((err = ERR_get_error())) {
3043		wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
3044			   __func__, ERR_error_string(err, NULL));
3045	}
3046
3047	if (tls_global_ca_cert(ssl_ctx, params->ca_cert))
3048		return -1;
3049
3050	if (tls_global_client_cert(ssl_ctx, params->client_cert))
3051		return -1;
3052
3053	if (tls_global_private_key(ssl_ctx, params->private_key,
3054				   params->private_key_passwd))
3055		return -1;
3056
3057	if (tls_global_dh(ssl_ctx, params->dh_file)) {
3058		wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
3059			   params->dh_file);
3060		return -1;
3061	}
3062
3063#ifdef SSL_OP_NO_TICKET
3064	if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
3065		SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
3066#ifdef SSL_CTX_clear_options
3067	else
3068		SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TICKET);
3069#endif /* SSL_clear_options */
3070#endif /*  SSL_OP_NO_TICKET */
3071
3072#ifdef HAVE_OCSP
3073	SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_status_cb);
3074	SSL_CTX_set_tlsext_status_arg(ssl_ctx, ssl_ctx);
3075	os_free(tls_global->ocsp_stapling_response);
3076	if (params->ocsp_stapling_response)
3077		tls_global->ocsp_stapling_response =
3078			os_strdup(params->ocsp_stapling_response);
3079	else
3080		tls_global->ocsp_stapling_response = NULL;
3081#endif /* HAVE_OCSP */
3082
3083	return 0;
3084}
3085
3086
3087int tls_connection_get_keyblock_size(void *tls_ctx,
3088				     struct tls_connection *conn)
3089{
3090	const EVP_CIPHER *c;
3091	const EVP_MD *h;
3092	int md_size;
3093
3094	if (conn == NULL || conn->ssl == NULL ||
3095	    conn->ssl->enc_read_ctx == NULL ||
3096	    conn->ssl->enc_read_ctx->cipher == NULL ||
3097	    conn->ssl->read_hash == NULL)
3098		return -1;
3099
3100	c = conn->ssl->enc_read_ctx->cipher;
3101#if OPENSSL_VERSION_NUMBER >= 0x00909000L
3102	h = EVP_MD_CTX_md(conn->ssl->read_hash);
3103#else
3104	h = conn->ssl->read_hash;
3105#endif
3106	if (h)
3107		md_size = EVP_MD_size(h);
3108#if OPENSSL_VERSION_NUMBER >= 0x10000000L
3109	else if (conn->ssl->s3)
3110		md_size = conn->ssl->s3->tmp.new_mac_secret_size;
3111#endif
3112	else
3113		return -1;
3114
3115	wpa_printf(MSG_DEBUG, "OpenSSL: keyblock size: key_len=%d MD_size=%d "
3116		   "IV_len=%d", EVP_CIPHER_key_length(c), md_size,
3117		   EVP_CIPHER_iv_length(c));
3118	return 2 * (EVP_CIPHER_key_length(c) +
3119		    md_size +
3120		    EVP_CIPHER_iv_length(c));
3121}
3122
3123
3124unsigned int tls_capabilities(void *tls_ctx)
3125{
3126	return 0;
3127}
3128
3129
3130#if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3131/* Pre-shared secred requires a patch to openssl, so this function is
3132 * commented out unless explicitly needed for EAP-FAST in order to be able to
3133 * build this file with unmodified openssl. */
3134
3135static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
3136			   STACK_OF(SSL_CIPHER) *peer_ciphers,
3137			   SSL_CIPHER **cipher, void *arg)
3138{
3139	struct tls_connection *conn = arg;
3140	int ret;
3141
3142	if (conn == NULL || conn->session_ticket_cb == NULL)
3143		return 0;
3144
3145	ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
3146				      conn->session_ticket,
3147				      conn->session_ticket_len,
3148				      s->s3->client_random,
3149				      s->s3->server_random, secret);
3150	os_free(conn->session_ticket);
3151	conn->session_ticket = NULL;
3152
3153	if (ret <= 0)
3154		return 0;
3155
3156	*secret_len = SSL_MAX_MASTER_KEY_LENGTH;
3157	return 1;
3158}
3159
3160
3161#ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
3162static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
3163				     int len, void *arg)
3164{
3165	struct tls_connection *conn = arg;
3166
3167	if (conn == NULL || conn->session_ticket_cb == NULL)
3168		return 0;
3169
3170	wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
3171
3172	os_free(conn->session_ticket);
3173	conn->session_ticket = NULL;
3174
3175	wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
3176		    "extension", data, len);
3177
3178	conn->session_ticket = os_malloc(len);
3179	if (conn->session_ticket == NULL)
3180		return 0;
3181
3182	os_memcpy(conn->session_ticket, data, len);
3183	conn->session_ticket_len = len;
3184
3185	return 1;
3186}
3187#else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
3188#ifdef SSL_OP_NO_TICKET
3189static void tls_hello_ext_cb(SSL *s, int client_server, int type,
3190			     unsigned char *data, int len, void *arg)
3191{
3192	struct tls_connection *conn = arg;
3193
3194	if (conn == NULL || conn->session_ticket_cb == NULL)
3195		return;
3196
3197	wpa_printf(MSG_DEBUG, "OpenSSL: %s: type=%d length=%d", __func__,
3198		   type, len);
3199
3200	if (type == TLSEXT_TYPE_session_ticket && !client_server) {
3201		os_free(conn->session_ticket);
3202		conn->session_ticket = NULL;
3203
3204		wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
3205			    "extension", data, len);
3206		conn->session_ticket = os_malloc(len);
3207		if (conn->session_ticket == NULL)
3208			return;
3209
3210		os_memcpy(conn->session_ticket, data, len);
3211		conn->session_ticket_len = len;
3212	}
3213}
3214#else /* SSL_OP_NO_TICKET */
3215static int tls_hello_ext_cb(SSL *s, TLS_EXTENSION *ext, void *arg)
3216{
3217	struct tls_connection *conn = arg;
3218
3219	if (conn == NULL || conn->session_ticket_cb == NULL)
3220		return 0;
3221
3222	wpa_printf(MSG_DEBUG, "OpenSSL: %s: type=%d length=%d", __func__,
3223		   ext->type, ext->length);
3224
3225	os_free(conn->session_ticket);
3226	conn->session_ticket = NULL;
3227
3228	if (ext->type == 35) {
3229		wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
3230			    "extension", ext->data, ext->length);
3231		conn->session_ticket = os_malloc(ext->length);
3232		if (conn->session_ticket == NULL)
3233			return SSL_AD_INTERNAL_ERROR;
3234
3235		os_memcpy(conn->session_ticket, ext->data, ext->length);
3236		conn->session_ticket_len = ext->length;
3237	}
3238
3239	return 0;
3240}
3241#endif /* SSL_OP_NO_TICKET */
3242#endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
3243#endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3244
3245
3246int tls_connection_set_session_ticket_cb(void *tls_ctx,
3247					 struct tls_connection *conn,
3248					 tls_session_ticket_cb cb,
3249					 void *ctx)
3250{
3251#if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3252	conn->session_ticket_cb = cb;
3253	conn->session_ticket_cb_ctx = ctx;
3254
3255	if (cb) {
3256		if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
3257					      conn) != 1)
3258			return -1;
3259#ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
3260		SSL_set_session_ticket_ext_cb(conn->ssl,
3261					      tls_session_ticket_ext_cb, conn);
3262#else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
3263#ifdef SSL_OP_NO_TICKET
3264		SSL_set_tlsext_debug_callback(conn->ssl, tls_hello_ext_cb);
3265		SSL_set_tlsext_debug_arg(conn->ssl, conn);
3266#else /* SSL_OP_NO_TICKET */
3267		if (SSL_set_hello_extension_cb(conn->ssl, tls_hello_ext_cb,
3268					       conn) != 1)
3269			return -1;
3270#endif /* SSL_OP_NO_TICKET */
3271#endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
3272	} else {
3273		if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
3274			return -1;
3275#ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
3276		SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
3277#else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
3278#ifdef SSL_OP_NO_TICKET
3279		SSL_set_tlsext_debug_callback(conn->ssl, NULL);
3280		SSL_set_tlsext_debug_arg(conn->ssl, conn);
3281#else /* SSL_OP_NO_TICKET */
3282		if (SSL_set_hello_extension_cb(conn->ssl, NULL, NULL) != 1)
3283			return -1;
3284#endif /* SSL_OP_NO_TICKET */
3285#endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
3286	}
3287
3288	return 0;
3289#else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3290	return -1;
3291#endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3292}
3293