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