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