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