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