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