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