1/*
2 * SSL/TLS interface functions for OpenSSL
3 * Copyright (c) 2004-2013, 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#include "common.h"
28#include "crypto.h"
29#include "sha1.h"
30#include "tls.h"
31
32#if OPENSSL_VERSION_NUMBER < 0x10000000L
33/* ERR_remove_thread_state replaces ERR_remove_state and the latter is
34 * deprecated. However, OpenSSL 0.9.8 doesn't include
35 * ERR_remove_thread_state. */
36#define ERR_remove_thread_state(tid) ERR_remove_state(0)
37#endif
38
39#if defined(OPENSSL_IS_BORINGSSL)
40/* stack_index_t is the return type of OpenSSL's sk_XXX_num() functions. */
41typedef size_t stack_index_t;
42#else
43typedef int stack_index_t;
44#endif
45
46#ifdef SSL_set_tlsext_status_type
47#ifndef OPENSSL_NO_TLSEXT
48#define HAVE_OCSP
49#include <openssl/ocsp.h>
50#endif /* OPENSSL_NO_TLSEXT */
51#endif /* SSL_set_tlsext_status_type */
52
53#ifdef ANDROID
54#include <openssl/pem.h>
55#include <keystore/keystore_get.h>
56
57static BIO * BIO_from_keystore(const char *key)
58{
59	BIO *bio = NULL;
60	uint8_t *value = NULL;
61	int length = keystore_get(key, strlen(key), &value);
62	if (length != -1 && (bio = BIO_new(BIO_s_mem())) != NULL)
63		BIO_write(bio, value, length);
64	free(value);
65	return bio;
66}
67
68#endif /* ANDROID */
69
70static int tls_openssl_ref_count = 0;
71
72struct tls_context {
73	void (*event_cb)(void *ctx, enum tls_event ev,
74			 union tls_event_data *data);
75	void *cb_ctx;
76	int cert_in_cb;
77	char *ocsp_stapling_response;
78};
79
80static struct tls_context *tls_global = NULL;
81
82
83struct tls_connection {
84	struct tls_context *context;
85	SSL_CTX *ssl_ctx;
86	SSL *ssl;
87	BIO *ssl_in, *ssl_out;
88#if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
89	ENGINE *engine;        /* functional reference to the engine */
90	EVP_PKEY *private_key; /* the private key if using engine */
91#endif /* OPENSSL_NO_ENGINE */
92	char *subject_match, *altsubject_match, *suffix_match, *domain_match;
93	int read_alerts, write_alerts, failed;
94
95	tls_session_ticket_cb session_ticket_cb;
96	void *session_ticket_cb_ctx;
97
98	/* SessionTicket received from OpenSSL hello_extension_cb (server) */
99	u8 *session_ticket;
100	size_t session_ticket_len;
101
102	unsigned int ca_cert_verify:1;
103	unsigned int cert_probe:1;
104	unsigned int server_cert_only:1;
105	unsigned int invalid_hb_used:1;
106
107	u8 srv_cert_hash[32];
108
109	unsigned int flags;
110
111	X509 *peer_cert;
112	X509 *peer_issuer;
113	X509 *peer_issuer_issuer;
114};
115
116
117static struct tls_context * tls_context_new(const struct tls_config *conf)
118{
119	struct tls_context *context = os_zalloc(sizeof(*context));
120	if (context == NULL)
121		return NULL;
122	if (conf) {
123		context->event_cb = conf->event_cb;
124		context->cb_ctx = conf->cb_ctx;
125		context->cert_in_cb = conf->cert_in_cb;
126	}
127	return context;
128}
129
130
131#ifdef CONFIG_NO_STDOUT_DEBUG
132
133static void _tls_show_errors(void)
134{
135	unsigned long err;
136
137	while ((err = ERR_get_error())) {
138		/* Just ignore the errors, since stdout is disabled */
139	}
140}
141#define tls_show_errors(l, f, t) _tls_show_errors()
142
143#else /* CONFIG_NO_STDOUT_DEBUG */
144
145static void tls_show_errors(int level, const char *func, const char *txt)
146{
147	unsigned long err;
148
149	wpa_printf(level, "OpenSSL: %s - %s %s",
150		   func, txt, ERR_error_string(ERR_get_error(), NULL));
151
152	while ((err = ERR_get_error())) {
153		wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
154			   ERR_error_string(err, NULL));
155	}
156}
157
158#endif /* CONFIG_NO_STDOUT_DEBUG */
159
160
161#ifdef CONFIG_NATIVE_WINDOWS
162
163/* Windows CryptoAPI and access to certificate stores */
164#include <wincrypt.h>
165
166#ifdef __MINGW32_VERSION
167/*
168 * MinGW does not yet include all the needed definitions for CryptoAPI, so
169 * define here whatever extra is needed.
170 */
171#define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
172#define CERT_STORE_READONLY_FLAG 0x00008000
173#define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
174
175#endif /* __MINGW32_VERSION */
176
177
178struct cryptoapi_rsa_data {
179	const CERT_CONTEXT *cert;
180	HCRYPTPROV crypt_prov;
181	DWORD key_spec;
182	BOOL free_crypt_prov;
183};
184
185
186static void cryptoapi_error(const char *msg)
187{
188	wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
189		   msg, (unsigned int) GetLastError());
190}
191
192
193static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
194				 unsigned char *to, RSA *rsa, int padding)
195{
196	wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
197	return 0;
198}
199
200
201static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
202				 unsigned char *to, RSA *rsa, int padding)
203{
204	wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
205	return 0;
206}
207
208
209static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
210				  unsigned char *to, RSA *rsa, int padding)
211{
212	struct cryptoapi_rsa_data *priv =
213		(struct cryptoapi_rsa_data *) rsa->meth->app_data;
214	HCRYPTHASH hash;
215	DWORD hash_size, len, i;
216	unsigned char *buf = NULL;
217	int ret = 0;
218
219	if (priv == NULL) {
220		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
221		       ERR_R_PASSED_NULL_PARAMETER);
222		return 0;
223	}
224
225	if (padding != RSA_PKCS1_PADDING) {
226		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
227		       RSA_R_UNKNOWN_PADDING_TYPE);
228		return 0;
229	}
230
231	if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
232		wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
233			   __func__);
234		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
235		       RSA_R_INVALID_MESSAGE_LENGTH);
236		return 0;
237	}
238
239	if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
240	{
241		cryptoapi_error("CryptCreateHash failed");
242		return 0;
243	}
244
245	len = sizeof(hash_size);
246	if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
247			       0)) {
248		cryptoapi_error("CryptGetHashParam failed");
249		goto err;
250	}
251
252	if ((int) hash_size != flen) {
253		wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
254			   (unsigned) hash_size, flen);
255		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
256		       RSA_R_INVALID_MESSAGE_LENGTH);
257		goto err;
258	}
259	if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
260		cryptoapi_error("CryptSetHashParam failed");
261		goto err;
262	}
263
264	len = RSA_size(rsa);
265	buf = os_malloc(len);
266	if (buf == NULL) {
267		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
268		goto err;
269	}
270
271	if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
272		cryptoapi_error("CryptSignHash failed");
273		goto err;
274	}
275
276	for (i = 0; i < len; i++)
277		to[i] = buf[len - i - 1];
278	ret = len;
279
280err:
281	os_free(buf);
282	CryptDestroyHash(hash);
283
284	return ret;
285}
286
287
288static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
289				  unsigned char *to, RSA *rsa, int padding)
290{
291	wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
292	return 0;
293}
294
295
296static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
297{
298	if (priv == NULL)
299		return;
300	if (priv->crypt_prov && priv->free_crypt_prov)
301		CryptReleaseContext(priv->crypt_prov, 0);
302	if (priv->cert)
303		CertFreeCertificateContext(priv->cert);
304	os_free(priv);
305}
306
307
308static int cryptoapi_finish(RSA *rsa)
309{
310	cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
311	os_free((void *) rsa->meth);
312	rsa->meth = NULL;
313	return 1;
314}
315
316
317static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
318{
319	HCERTSTORE cs;
320	const CERT_CONTEXT *ret = NULL;
321
322	cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
323			   store | CERT_STORE_OPEN_EXISTING_FLAG |
324			   CERT_STORE_READONLY_FLAG, L"MY");
325	if (cs == NULL) {
326		cryptoapi_error("Failed to open 'My system store'");
327		return NULL;
328	}
329
330	if (strncmp(name, "cert://", 7) == 0) {
331		unsigned short wbuf[255];
332		MultiByteToWideChar(CP_ACP, 0, name + 7, -1, wbuf, 255);
333		ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
334						 PKCS_7_ASN_ENCODING,
335						 0, CERT_FIND_SUBJECT_STR,
336						 wbuf, NULL);
337	} else if (strncmp(name, "hash://", 7) == 0) {
338		CRYPT_HASH_BLOB blob;
339		int len;
340		const char *hash = name + 7;
341		unsigned char *buf;
342
343		len = os_strlen(hash) / 2;
344		buf = os_malloc(len);
345		if (buf && hexstr2bin(hash, buf, len) == 0) {
346			blob.cbData = len;
347			blob.pbData = buf;
348			ret = CertFindCertificateInStore(cs,
349							 X509_ASN_ENCODING |
350							 PKCS_7_ASN_ENCODING,
351							 0, CERT_FIND_HASH,
352							 &blob, NULL);
353		}
354		os_free(buf);
355	}
356
357	CertCloseStore(cs, 0);
358
359	return ret;
360}
361
362
363static int tls_cryptoapi_cert(SSL *ssl, const char *name)
364{
365	X509 *cert = NULL;
366	RSA *rsa = NULL, *pub_rsa;
367	struct cryptoapi_rsa_data *priv;
368	RSA_METHOD *rsa_meth;
369
370	if (name == NULL ||
371	    (strncmp(name, "cert://", 7) != 0 &&
372	     strncmp(name, "hash://", 7) != 0))
373		return -1;
374
375	priv = os_zalloc(sizeof(*priv));
376	rsa_meth = os_zalloc(sizeof(*rsa_meth));
377	if (priv == NULL || rsa_meth == NULL) {
378		wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
379			   "for CryptoAPI RSA method");
380		os_free(priv);
381		os_free(rsa_meth);
382		return -1;
383	}
384
385	priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
386	if (priv->cert == NULL) {
387		priv->cert = cryptoapi_find_cert(
388			name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
389	}
390	if (priv->cert == NULL) {
391		wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
392			   "'%s'", name);
393		goto err;
394	}
395
396	cert = d2i_X509(NULL,
397			(const unsigned char **) &priv->cert->pbCertEncoded,
398			priv->cert->cbCertEncoded);
399	if (cert == NULL) {
400		wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
401			   "encoding");
402		goto err;
403	}
404
405	if (!CryptAcquireCertificatePrivateKey(priv->cert,
406					       CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
407					       NULL, &priv->crypt_prov,
408					       &priv->key_spec,
409					       &priv->free_crypt_prov)) {
410		cryptoapi_error("Failed to acquire a private key for the "
411				"certificate");
412		goto err;
413	}
414
415	rsa_meth->name = "Microsoft CryptoAPI RSA Method";
416	rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
417	rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
418	rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
419	rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
420	rsa_meth->finish = cryptoapi_finish;
421	rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
422	rsa_meth->app_data = (char *) priv;
423
424	rsa = RSA_new();
425	if (rsa == NULL) {
426		SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
427		       ERR_R_MALLOC_FAILURE);
428		goto err;
429	}
430
431	if (!SSL_use_certificate(ssl, cert)) {
432		RSA_free(rsa);
433		rsa = NULL;
434		goto err;
435	}
436	pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
437	X509_free(cert);
438	cert = NULL;
439
440	rsa->n = BN_dup(pub_rsa->n);
441	rsa->e = BN_dup(pub_rsa->e);
442	if (!RSA_set_method(rsa, rsa_meth))
443		goto err;
444
445	if (!SSL_use_RSAPrivateKey(ssl, rsa))
446		goto err;
447	RSA_free(rsa);
448
449	return 0;
450
451err:
452	if (cert)
453		X509_free(cert);
454	if (rsa)
455		RSA_free(rsa);
456	else {
457		os_free(rsa_meth);
458		cryptoapi_free_data(priv);
459	}
460	return -1;
461}
462
463
464static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
465{
466	HCERTSTORE cs;
467	PCCERT_CONTEXT ctx = NULL;
468	X509 *cert;
469	char buf[128];
470	const char *store;
471#ifdef UNICODE
472	WCHAR *wstore;
473#endif /* UNICODE */
474
475	if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
476		return -1;
477
478	store = name + 13;
479#ifdef UNICODE
480	wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
481	if (wstore == NULL)
482		return -1;
483	wsprintf(wstore, L"%S", store);
484	cs = CertOpenSystemStore(0, wstore);
485	os_free(wstore);
486#else /* UNICODE */
487	cs = CertOpenSystemStore(0, store);
488#endif /* UNICODE */
489	if (cs == NULL) {
490		wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
491			   "'%s': error=%d", __func__, store,
492			   (int) GetLastError());
493		return -1;
494	}
495
496	while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
497		cert = d2i_X509(NULL,
498				(const unsigned char **) &ctx->pbCertEncoded,
499				ctx->cbCertEncoded);
500		if (cert == NULL) {
501			wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
502				   "X509 DER encoding for CA cert");
503			continue;
504		}
505
506		X509_NAME_oneline(X509_get_subject_name(cert), buf,
507				  sizeof(buf));
508		wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
509			   "system certificate store: subject='%s'", buf);
510
511		if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
512			tls_show_errors(MSG_WARNING, __func__,
513					"Failed to add ca_cert to OpenSSL "
514					"certificate store");
515		}
516
517		X509_free(cert);
518	}
519
520	if (!CertCloseStore(cs, 0)) {
521		wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
522			   "'%s': error=%d", __func__, name + 13,
523			   (int) GetLastError());
524	}
525
526	return 0;
527}
528
529
530#else /* CONFIG_NATIVE_WINDOWS */
531
532static int tls_cryptoapi_cert(SSL *ssl, const char *name)
533{
534	return -1;
535}
536
537#endif /* CONFIG_NATIVE_WINDOWS */
538
539
540static void ssl_info_cb(const SSL *ssl, int where, int ret)
541{
542	const char *str;
543	int w;
544
545	wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
546	w = where & ~SSL_ST_MASK;
547	if (w & SSL_ST_CONNECT)
548		str = "SSL_connect";
549	else if (w & SSL_ST_ACCEPT)
550		str = "SSL_accept";
551	else
552		str = "undefined";
553
554	if (where & SSL_CB_LOOP) {
555		wpa_printf(MSG_DEBUG, "SSL: %s:%s",
556			   str, SSL_state_string_long(ssl));
557	} else if (where & SSL_CB_ALERT) {
558		struct tls_connection *conn = SSL_get_app_data((SSL *) ssl);
559		wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
560			   where & SSL_CB_READ ?
561			   "read (remote end reported an error)" :
562			   "write (local SSL3 detected an error)",
563			   SSL_alert_type_string_long(ret),
564			   SSL_alert_desc_string_long(ret));
565		if ((ret >> 8) == SSL3_AL_FATAL) {
566			if (where & SSL_CB_READ)
567				conn->read_alerts++;
568			else
569				conn->write_alerts++;
570		}
571		if (conn->context->event_cb != NULL) {
572			union tls_event_data ev;
573			struct tls_context *context = conn->context;
574			os_memset(&ev, 0, sizeof(ev));
575			ev.alert.is_local = !(where & SSL_CB_READ);
576			ev.alert.type = SSL_alert_type_string_long(ret);
577			ev.alert.description = SSL_alert_desc_string_long(ret);
578			context->event_cb(context->cb_ctx, TLS_ALERT, &ev);
579		}
580	} else if (where & SSL_CB_EXIT && ret <= 0) {
581		wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
582			   str, ret == 0 ? "failed" : "error",
583			   SSL_state_string_long(ssl));
584	}
585}
586
587
588#ifndef OPENSSL_NO_ENGINE
589/**
590 * tls_engine_load_dynamic_generic - load any openssl engine
591 * @pre: an array of commands and values that load an engine initialized
592 *       in the engine specific function
593 * @post: an array of commands and values that initialize an already loaded
594 *        engine (or %NULL if not required)
595 * @id: the engine id of the engine to load (only required if post is not %NULL
596 *
597 * This function is a generic function that loads any openssl engine.
598 *
599 * Returns: 0 on success, -1 on failure
600 */
601static int tls_engine_load_dynamic_generic(const char *pre[],
602					   const char *post[], const char *id)
603{
604	ENGINE *engine;
605	const char *dynamic_id = "dynamic";
606
607	engine = ENGINE_by_id(id);
608	if (engine) {
609		ENGINE_free(engine);
610		wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
611			   "available", id);
612		return 0;
613	}
614	ERR_clear_error();
615
616	engine = ENGINE_by_id(dynamic_id);
617	if (engine == NULL) {
618		wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
619			   dynamic_id,
620			   ERR_error_string(ERR_get_error(), NULL));
621		return -1;
622	}
623
624	/* Perform the pre commands. This will load the engine. */
625	while (pre && pre[0]) {
626		wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
627		if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
628			wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
629				   "%s %s [%s]", pre[0], pre[1],
630				   ERR_error_string(ERR_get_error(), NULL));
631			ENGINE_free(engine);
632			return -1;
633		}
634		pre += 2;
635	}
636
637	/*
638	 * Free the reference to the "dynamic" engine. The loaded engine can
639	 * now be looked up using ENGINE_by_id().
640	 */
641	ENGINE_free(engine);
642
643	engine = ENGINE_by_id(id);
644	if (engine == NULL) {
645		wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
646			   id, ERR_error_string(ERR_get_error(), NULL));
647		return -1;
648	}
649
650	while (post && post[0]) {
651		wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
652		if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
653			wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
654				" %s %s [%s]", post[0], post[1],
655				   ERR_error_string(ERR_get_error(), NULL));
656			ENGINE_remove(engine);
657			ENGINE_free(engine);
658			return -1;
659		}
660		post += 2;
661	}
662	ENGINE_free(engine);
663
664	return 0;
665}
666
667
668/**
669 * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
670 * @pkcs11_so_path: pksc11_so_path from the configuration
671 * @pcks11_module_path: pkcs11_module_path from the configuration
672 */
673static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
674					  const char *pkcs11_module_path)
675{
676	char *engine_id = "pkcs11";
677	const char *pre_cmd[] = {
678		"SO_PATH", NULL /* pkcs11_so_path */,
679		"ID", NULL /* engine_id */,
680		"LIST_ADD", "1",
681		/* "NO_VCHECK", "1", */
682		"LOAD", NULL,
683		NULL, NULL
684	};
685	const char *post_cmd[] = {
686		"MODULE_PATH", NULL /* pkcs11_module_path */,
687		NULL, NULL
688	};
689
690	if (!pkcs11_so_path)
691		return 0;
692
693	pre_cmd[1] = pkcs11_so_path;
694	pre_cmd[3] = engine_id;
695	if (pkcs11_module_path)
696		post_cmd[1] = pkcs11_module_path;
697	else
698		post_cmd[0] = NULL;
699
700	wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
701		   pkcs11_so_path);
702
703	return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
704}
705
706
707/**
708 * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
709 * @opensc_so_path: opensc_so_path from the configuration
710 */
711static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
712{
713	char *engine_id = "opensc";
714	const char *pre_cmd[] = {
715		"SO_PATH", NULL /* opensc_so_path */,
716		"ID", NULL /* engine_id */,
717		"LIST_ADD", "1",
718		"LOAD", NULL,
719		NULL, NULL
720	};
721
722	if (!opensc_so_path)
723		return 0;
724
725	pre_cmd[1] = opensc_so_path;
726	pre_cmd[3] = engine_id;
727
728	wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
729		   opensc_so_path);
730
731	return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
732}
733#endif /* OPENSSL_NO_ENGINE */
734
735
736void * tls_init(const struct tls_config *conf)
737{
738	SSL_CTX *ssl;
739	struct tls_context *context;
740	const char *ciphers;
741
742	if (tls_openssl_ref_count == 0) {
743		tls_global = context = tls_context_new(conf);
744		if (context == NULL)
745			return NULL;
746#ifdef CONFIG_FIPS
747#ifdef OPENSSL_FIPS
748		if (conf && conf->fips_mode) {
749			if (!FIPS_mode_set(1)) {
750				wpa_printf(MSG_ERROR, "Failed to enable FIPS "
751					   "mode");
752				ERR_load_crypto_strings();
753				ERR_print_errors_fp(stderr);
754				os_free(tls_global);
755				tls_global = NULL;
756				return NULL;
757			} else
758				wpa_printf(MSG_INFO, "Running in FIPS mode");
759		}
760#else /* OPENSSL_FIPS */
761		if (conf && conf->fips_mode) {
762			wpa_printf(MSG_ERROR, "FIPS mode requested, but not "
763				   "supported");
764			os_free(tls_global);
765			tls_global = NULL;
766			return NULL;
767		}
768#endif /* OPENSSL_FIPS */
769#endif /* CONFIG_FIPS */
770		SSL_load_error_strings();
771		SSL_library_init();
772#ifndef OPENSSL_NO_SHA256
773		EVP_add_digest(EVP_sha256());
774#endif /* OPENSSL_NO_SHA256 */
775		/* TODO: if /dev/urandom is available, PRNG is seeded
776		 * automatically. If this is not the case, random data should
777		 * be added here. */
778
779#ifdef PKCS12_FUNCS
780#ifndef OPENSSL_NO_RC2
781		/*
782		 * 40-bit RC2 is commonly used in PKCS#12 files, so enable it.
783		 * This is enabled by PKCS12_PBE_add() in OpenSSL 0.9.8
784		 * versions, but it looks like OpenSSL 1.0.0 does not do that
785		 * anymore.
786		 */
787		EVP_add_cipher(EVP_rc2_40_cbc());
788#endif /* OPENSSL_NO_RC2 */
789		PKCS12_PBE_add();
790#endif  /* PKCS12_FUNCS */
791	} else {
792		context = tls_context_new(conf);
793		if (context == NULL)
794			return NULL;
795	}
796	tls_openssl_ref_count++;
797
798	ssl = SSL_CTX_new(SSLv23_method());
799	if (ssl == NULL) {
800		tls_openssl_ref_count--;
801		if (context != tls_global)
802			os_free(context);
803		if (tls_openssl_ref_count == 0) {
804			os_free(tls_global);
805			tls_global = NULL;
806		}
807		return NULL;
808	}
809
810	SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv2);
811	SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv3);
812
813	SSL_CTX_set_info_callback(ssl, ssl_info_cb);
814	SSL_CTX_set_app_data(ssl, context);
815
816#ifndef OPENSSL_NO_ENGINE
817	wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
818	ERR_load_ENGINE_strings();
819	ENGINE_load_dynamic();
820
821	if (conf &&
822	    (conf->opensc_engine_path || conf->pkcs11_engine_path ||
823	     conf->pkcs11_module_path)) {
824		if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
825		    tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
826						   conf->pkcs11_module_path)) {
827			tls_deinit(ssl);
828			return NULL;
829		}
830	}
831#endif /* OPENSSL_NO_ENGINE */
832
833	if (conf && conf->openssl_ciphers)
834		ciphers = conf->openssl_ciphers;
835	else
836		ciphers = "DEFAULT:!EXP:!LOW";
837	if (SSL_CTX_set_cipher_list(ssl, ciphers) != 1) {
838		wpa_printf(MSG_ERROR,
839			   "OpenSSL: Failed to set cipher string '%s'",
840			   ciphers);
841		tls_deinit(ssl);
842		return NULL;
843	}
844
845	return ssl;
846}
847
848
849void tls_deinit(void *ssl_ctx)
850{
851	SSL_CTX *ssl = ssl_ctx;
852	struct tls_context *context = SSL_CTX_get_app_data(ssl);
853	if (context != tls_global)
854		os_free(context);
855	SSL_CTX_free(ssl);
856
857	tls_openssl_ref_count--;
858	if (tls_openssl_ref_count == 0) {
859#ifndef OPENSSL_NO_ENGINE
860		ENGINE_cleanup();
861#endif /* OPENSSL_NO_ENGINE */
862		CRYPTO_cleanup_all_ex_data();
863		ERR_remove_thread_state(NULL);
864		ERR_free_strings();
865		EVP_cleanup();
866		os_free(tls_global->ocsp_stapling_response);
867		tls_global->ocsp_stapling_response = NULL;
868		os_free(tls_global);
869		tls_global = NULL;
870	}
871}
872
873#ifdef ANDROID
874/* EVP_PKEY_from_keystore comes from system/security/keystore-engine. */
875EVP_PKEY* EVP_PKEY_from_keystore(const char* key_id);
876#endif
877
878#ifndef OPENSSL_NO_ENGINE
879
880/* Cryptoki return values */
881#define CKR_PIN_INCORRECT 0x000000a0
882#define CKR_PIN_INVALID 0x000000a1
883#define CKR_PIN_LEN_RANGE 0x000000a2
884
885/* libp11 */
886#define ERR_LIB_PKCS11	ERR_LIB_USER
887
888static int tls_is_pin_error(unsigned int err)
889{
890	return ERR_GET_LIB(err) == ERR_LIB_PKCS11 &&
891		(ERR_GET_REASON(err) == CKR_PIN_INCORRECT ||
892		 ERR_GET_REASON(err) == CKR_PIN_INVALID ||
893		 ERR_GET_REASON(err) == CKR_PIN_LEN_RANGE);
894}
895
896#endif /* OPENSSL_NO_ENGINE */
897
898
899static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
900			   const char *pin, const char *key_id,
901			   const char *cert_id, const char *ca_cert_id)
902{
903#if defined(ANDROID) && defined(OPENSSL_IS_BORINGSSL)
904#if !defined(OPENSSL_NO_ENGINE)
905#error "This code depends on OPENSSL_NO_ENGINE being defined by BoringSSL."
906#endif
907
908	conn->engine = NULL;
909	conn->private_key = EVP_PKEY_from_keystore(key_id);
910	if (!conn->private_key) {
911		wpa_printf(MSG_ERROR,
912			   "ENGINE: cannot load private key with id '%s' [%s]",
913			   key_id,
914			   ERR_error_string(ERR_get_error(), NULL));
915		return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
916	}
917#endif
918
919#ifndef OPENSSL_NO_ENGINE
920	int ret = -1;
921	if (engine_id == NULL) {
922		wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
923		return -1;
924	}
925
926	ERR_clear_error();
927#ifdef ANDROID
928	ENGINE_load_dynamic();
929#endif
930	conn->engine = ENGINE_by_id(engine_id);
931	if (!conn->engine) {
932		wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
933			   engine_id, ERR_error_string(ERR_get_error(), NULL));
934		goto err;
935	}
936	if (ENGINE_init(conn->engine) != 1) {
937		wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
938			   "(engine: %s) [%s]", engine_id,
939			   ERR_error_string(ERR_get_error(), NULL));
940		goto err;
941	}
942	wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
943
944#ifndef ANDROID
945	if (pin && ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
946		wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
947			   ERR_error_string(ERR_get_error(), NULL));
948		goto err;
949	}
950#endif
951	if (key_id) {
952		/*
953		 * Ensure that the ENGINE does not attempt to use the OpenSSL
954		 * UI system to obtain a PIN, if we didn't provide one.
955		 */
956		struct {
957			const void *password;
958			const char *prompt_info;
959		} key_cb = { "", NULL };
960
961		/* load private key first in-case PIN is required for cert */
962		conn->private_key = ENGINE_load_private_key(conn->engine,
963							    key_id, NULL,
964							    &key_cb);
965		if (!conn->private_key) {
966			unsigned long err = ERR_get_error();
967
968			wpa_printf(MSG_ERROR,
969				   "ENGINE: cannot load private key with id '%s' [%s]",
970				   key_id,
971				   ERR_error_string(err, NULL));
972			if (tls_is_pin_error(err))
973				ret = TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
974			else
975				ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
976			goto err;
977		}
978	}
979
980	/* handle a certificate and/or CA certificate */
981	if (cert_id || ca_cert_id) {
982		const char *cmd_name = "LOAD_CERT_CTRL";
983
984		/* test if the engine supports a LOAD_CERT_CTRL */
985		if (!ENGINE_ctrl(conn->engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
986				 0, (void *)cmd_name, NULL)) {
987			wpa_printf(MSG_ERROR, "ENGINE: engine does not support"
988				   " loading certificates");
989			ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
990			goto err;
991		}
992	}
993
994	return 0;
995
996err:
997	if (conn->engine) {
998		ENGINE_free(conn->engine);
999		conn->engine = NULL;
1000	}
1001
1002	if (conn->private_key) {
1003		EVP_PKEY_free(conn->private_key);
1004		conn->private_key = NULL;
1005	}
1006
1007	return ret;
1008#else /* OPENSSL_NO_ENGINE */
1009	return 0;
1010#endif /* OPENSSL_NO_ENGINE */
1011}
1012
1013
1014static void tls_engine_deinit(struct tls_connection *conn)
1015{
1016#if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
1017	wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
1018	if (conn->private_key) {
1019		EVP_PKEY_free(conn->private_key);
1020		conn->private_key = NULL;
1021	}
1022	if (conn->engine) {
1023#if !defined(OPENSSL_IS_BORINGSSL)
1024		ENGINE_finish(conn->engine);
1025#endif
1026		conn->engine = NULL;
1027	}
1028#endif /* OPENSSL_NO_ENGINE */
1029}
1030
1031
1032int tls_get_errors(void *ssl_ctx)
1033{
1034	int count = 0;
1035	unsigned long err;
1036
1037	while ((err = ERR_get_error())) {
1038		wpa_printf(MSG_INFO, "TLS - SSL error: %s",
1039			   ERR_error_string(err, NULL));
1040		count++;
1041	}
1042
1043	return count;
1044}
1045
1046
1047static void tls_msg_cb(int write_p, int version, int content_type,
1048		       const void *buf, size_t len, SSL *ssl, void *arg)
1049{
1050	struct tls_connection *conn = arg;
1051	const u8 *pos = buf;
1052
1053	wpa_printf(MSG_DEBUG, "OpenSSL: %s ver=0x%x content_type=%d",
1054		   write_p ? "TX" : "RX", version, content_type);
1055	wpa_hexdump_key(MSG_MSGDUMP, "OpenSSL: Message", buf, len);
1056	if (content_type == 24 && len >= 3 && pos[0] == 1) {
1057		size_t payload_len = WPA_GET_BE16(pos + 1);
1058		if (payload_len + 3 > len) {
1059			wpa_printf(MSG_ERROR, "OpenSSL: Heartbeat attack detected");
1060			conn->invalid_hb_used = 1;
1061		}
1062	}
1063}
1064
1065
1066struct tls_connection * tls_connection_init(void *ssl_ctx)
1067{
1068	SSL_CTX *ssl = ssl_ctx;
1069	struct tls_connection *conn;
1070	long options;
1071	struct tls_context *context = SSL_CTX_get_app_data(ssl);
1072
1073	conn = os_zalloc(sizeof(*conn));
1074	if (conn == NULL)
1075		return NULL;
1076	conn->ssl_ctx = ssl_ctx;
1077	conn->ssl = SSL_new(ssl);
1078	if (conn->ssl == NULL) {
1079		tls_show_errors(MSG_INFO, __func__,
1080				"Failed to initialize new SSL connection");
1081		os_free(conn);
1082		return NULL;
1083	}
1084
1085	conn->context = context;
1086	SSL_set_app_data(conn->ssl, conn);
1087	SSL_set_msg_callback(conn->ssl, tls_msg_cb);
1088	SSL_set_msg_callback_arg(conn->ssl, conn);
1089	options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
1090		SSL_OP_SINGLE_DH_USE;
1091#ifdef SSL_OP_NO_COMPRESSION
1092	options |= SSL_OP_NO_COMPRESSION;
1093#endif /* SSL_OP_NO_COMPRESSION */
1094	SSL_set_options(conn->ssl, options);
1095
1096	conn->ssl_in = BIO_new(BIO_s_mem());
1097	if (!conn->ssl_in) {
1098		tls_show_errors(MSG_INFO, __func__,
1099				"Failed to create a new BIO for ssl_in");
1100		SSL_free(conn->ssl);
1101		os_free(conn);
1102		return NULL;
1103	}
1104
1105	conn->ssl_out = BIO_new(BIO_s_mem());
1106	if (!conn->ssl_out) {
1107		tls_show_errors(MSG_INFO, __func__,
1108				"Failed to create a new BIO for ssl_out");
1109		SSL_free(conn->ssl);
1110		BIO_free(conn->ssl_in);
1111		os_free(conn);
1112		return NULL;
1113	}
1114
1115	SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
1116
1117	return conn;
1118}
1119
1120
1121void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
1122{
1123	if (conn == NULL)
1124		return;
1125	SSL_free(conn->ssl);
1126	tls_engine_deinit(conn);
1127	os_free(conn->subject_match);
1128	os_free(conn->altsubject_match);
1129	os_free(conn->suffix_match);
1130	os_free(conn->domain_match);
1131	os_free(conn->session_ticket);
1132	os_free(conn);
1133}
1134
1135
1136int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
1137{
1138	return conn ? SSL_is_init_finished(conn->ssl) : 0;
1139}
1140
1141
1142int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
1143{
1144	if (conn == NULL)
1145		return -1;
1146
1147	/* Shutdown previous TLS connection without notifying the peer
1148	 * because the connection was already terminated in practice
1149	 * and "close notify" shutdown alert would confuse AS. */
1150	SSL_set_quiet_shutdown(conn->ssl, 1);
1151	SSL_shutdown(conn->ssl);
1152	return SSL_clear(conn->ssl) == 1 ? 0 : -1;
1153}
1154
1155
1156static int tls_match_altsubject_component(X509 *cert, int type,
1157					  const char *value, size_t len)
1158{
1159	GENERAL_NAME *gen;
1160	void *ext;
1161	int found = 0;
1162	stack_index_t i;
1163
1164	ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
1165
1166	for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
1167		gen = sk_GENERAL_NAME_value(ext, i);
1168		if (gen->type != type)
1169			continue;
1170		if (os_strlen((char *) gen->d.ia5->data) == len &&
1171		    os_memcmp(value, gen->d.ia5->data, len) == 0)
1172			found++;
1173	}
1174
1175	return found;
1176}
1177
1178
1179static int tls_match_altsubject(X509 *cert, const char *match)
1180{
1181	int type;
1182	const char *pos, *end;
1183	size_t len;
1184
1185	pos = match;
1186	do {
1187		if (os_strncmp(pos, "EMAIL:", 6) == 0) {
1188			type = GEN_EMAIL;
1189			pos += 6;
1190		} else if (os_strncmp(pos, "DNS:", 4) == 0) {
1191			type = GEN_DNS;
1192			pos += 4;
1193		} else if (os_strncmp(pos, "URI:", 4) == 0) {
1194			type = GEN_URI;
1195			pos += 4;
1196		} else {
1197			wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
1198				   "match '%s'", pos);
1199			return 0;
1200		}
1201		end = os_strchr(pos, ';');
1202		while (end) {
1203			if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
1204			    os_strncmp(end + 1, "DNS:", 4) == 0 ||
1205			    os_strncmp(end + 1, "URI:", 4) == 0)
1206				break;
1207			end = os_strchr(end + 1, ';');
1208		}
1209		if (end)
1210			len = end - pos;
1211		else
1212			len = os_strlen(pos);
1213		if (tls_match_altsubject_component(cert, type, pos, len) > 0)
1214			return 1;
1215		pos = end + 1;
1216	} while (end);
1217
1218	return 0;
1219}
1220
1221
1222#ifndef CONFIG_NATIVE_WINDOWS
1223static int domain_suffix_match(const u8 *val, size_t len, const char *match,
1224			       int full)
1225{
1226	size_t i, match_len;
1227
1228	/* Check for embedded nuls that could mess up suffix matching */
1229	for (i = 0; i < len; i++) {
1230		if (val[i] == '\0') {
1231			wpa_printf(MSG_DEBUG, "TLS: Embedded null in a string - reject");
1232			return 0;
1233		}
1234	}
1235
1236	match_len = os_strlen(match);
1237	if (match_len > len || (full && match_len != len))
1238		return 0;
1239
1240	if (os_strncasecmp((const char *) val + len - match_len, match,
1241			   match_len) != 0)
1242		return 0; /* no match */
1243
1244	if (match_len == len)
1245		return 1; /* exact match */
1246
1247	if (val[len - match_len - 1] == '.')
1248		return 1; /* full label match completes suffix match */
1249
1250	wpa_printf(MSG_DEBUG, "TLS: Reject due to incomplete label match");
1251	return 0;
1252}
1253#endif /* CONFIG_NATIVE_WINDOWS */
1254
1255
1256static int tls_match_suffix(X509 *cert, const char *match, int full)
1257{
1258#ifdef CONFIG_NATIVE_WINDOWS
1259	/* wincrypt.h has conflicting X509_NAME definition */
1260	return -1;
1261#else /* CONFIG_NATIVE_WINDOWS */
1262	GENERAL_NAME *gen;
1263	void *ext;
1264	int i;
1265	stack_index_t j;
1266	int dns_name = 0;
1267	X509_NAME *name;
1268
1269	wpa_printf(MSG_DEBUG, "TLS: Match domain against %s%s",
1270		   full ? "": "suffix ", match);
1271
1272	ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
1273
1274	for (j = 0; ext && j < sk_GENERAL_NAME_num(ext); j++) {
1275		gen = sk_GENERAL_NAME_value(ext, j);
1276		if (gen->type != GEN_DNS)
1277			continue;
1278		dns_name++;
1279		wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate dNSName",
1280				  gen->d.dNSName->data,
1281				  gen->d.dNSName->length);
1282		if (domain_suffix_match(gen->d.dNSName->data,
1283					gen->d.dNSName->length, match, full) ==
1284		    1) {
1285			wpa_printf(MSG_DEBUG, "TLS: %s in dNSName found",
1286				   full ? "Match" : "Suffix match");
1287			return 1;
1288		}
1289	}
1290
1291	if (dns_name) {
1292		wpa_printf(MSG_DEBUG, "TLS: None of the dNSName(s) matched");
1293		return 0;
1294	}
1295
1296	name = X509_get_subject_name(cert);
1297	i = -1;
1298	for (;;) {
1299		X509_NAME_ENTRY *e;
1300		ASN1_STRING *cn;
1301
1302		i = X509_NAME_get_index_by_NID(name, NID_commonName, i);
1303		if (i == -1)
1304			break;
1305		e = X509_NAME_get_entry(name, i);
1306		if (e == NULL)
1307			continue;
1308		cn = X509_NAME_ENTRY_get_data(e);
1309		if (cn == NULL)
1310			continue;
1311		wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate commonName",
1312				  cn->data, cn->length);
1313		if (domain_suffix_match(cn->data, cn->length, match, full) == 1)
1314		{
1315			wpa_printf(MSG_DEBUG, "TLS: %s in commonName found",
1316				   full ? "Match" : "Suffix match");
1317			return 1;
1318		}
1319	}
1320
1321	wpa_printf(MSG_DEBUG, "TLS: No CommonName %smatch found",
1322		   full ? "": "suffix ");
1323	return 0;
1324#endif /* CONFIG_NATIVE_WINDOWS */
1325}
1326
1327
1328static enum tls_fail_reason openssl_tls_fail_reason(int err)
1329{
1330	switch (err) {
1331	case X509_V_ERR_CERT_REVOKED:
1332		return TLS_FAIL_REVOKED;
1333	case X509_V_ERR_CERT_NOT_YET_VALID:
1334	case X509_V_ERR_CRL_NOT_YET_VALID:
1335		return TLS_FAIL_NOT_YET_VALID;
1336	case X509_V_ERR_CERT_HAS_EXPIRED:
1337	case X509_V_ERR_CRL_HAS_EXPIRED:
1338		return TLS_FAIL_EXPIRED;
1339	case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1340	case X509_V_ERR_UNABLE_TO_GET_CRL:
1341	case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
1342	case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1343	case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1344	case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1345	case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1346	case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1347	case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1348	case X509_V_ERR_INVALID_CA:
1349		return TLS_FAIL_UNTRUSTED;
1350	case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1351	case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1352	case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1353	case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1354	case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1355	case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1356	case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1357	case X509_V_ERR_CERT_UNTRUSTED:
1358	case X509_V_ERR_CERT_REJECTED:
1359		return TLS_FAIL_BAD_CERTIFICATE;
1360	default:
1361		return TLS_FAIL_UNSPECIFIED;
1362	}
1363}
1364
1365
1366static struct wpabuf * get_x509_cert(X509 *cert)
1367{
1368	struct wpabuf *buf;
1369	u8 *tmp;
1370
1371	int cert_len = i2d_X509(cert, NULL);
1372	if (cert_len <= 0)
1373		return NULL;
1374
1375	buf = wpabuf_alloc(cert_len);
1376	if (buf == NULL)
1377		return NULL;
1378
1379	tmp = wpabuf_put(buf, cert_len);
1380	i2d_X509(cert, &tmp);
1381	return buf;
1382}
1383
1384
1385static void openssl_tls_fail_event(struct tls_connection *conn,
1386				   X509 *err_cert, int err, int depth,
1387				   const char *subject, const char *err_str,
1388				   enum tls_fail_reason reason)
1389{
1390	union tls_event_data ev;
1391	struct wpabuf *cert = NULL;
1392	struct tls_context *context = conn->context;
1393
1394	if (context->event_cb == NULL)
1395		return;
1396
1397	cert = get_x509_cert(err_cert);
1398	os_memset(&ev, 0, sizeof(ev));
1399	ev.cert_fail.reason = reason != TLS_FAIL_UNSPECIFIED ?
1400		reason : openssl_tls_fail_reason(err);
1401	ev.cert_fail.depth = depth;
1402	ev.cert_fail.subject = subject;
1403	ev.cert_fail.reason_txt = err_str;
1404	ev.cert_fail.cert = cert;
1405	context->event_cb(context->cb_ctx, TLS_CERT_CHAIN_FAILURE, &ev);
1406	wpabuf_free(cert);
1407}
1408
1409
1410static void openssl_tls_cert_event(struct tls_connection *conn,
1411				   X509 *err_cert, int depth,
1412				   const char *subject)
1413{
1414	struct wpabuf *cert = NULL;
1415	union tls_event_data ev;
1416	struct tls_context *context = conn->context;
1417	char *altsubject[TLS_MAX_ALT_SUBJECT];
1418	int alt, num_altsubject = 0;
1419	GENERAL_NAME *gen;
1420	void *ext;
1421	stack_index_t i;
1422#ifdef CONFIG_SHA256
1423	u8 hash[32];
1424#endif /* CONFIG_SHA256 */
1425
1426	if (context->event_cb == NULL)
1427		return;
1428
1429	os_memset(&ev, 0, sizeof(ev));
1430	if (conn->cert_probe || context->cert_in_cb) {
1431		cert = get_x509_cert(err_cert);
1432		ev.peer_cert.cert = cert;
1433	}
1434#ifdef CONFIG_SHA256
1435	if (cert) {
1436		const u8 *addr[1];
1437		size_t len[1];
1438		addr[0] = wpabuf_head(cert);
1439		len[0] = wpabuf_len(cert);
1440		if (sha256_vector(1, addr, len, hash) == 0) {
1441			ev.peer_cert.hash = hash;
1442			ev.peer_cert.hash_len = sizeof(hash);
1443		}
1444	}
1445#endif /* CONFIG_SHA256 */
1446	ev.peer_cert.depth = depth;
1447	ev.peer_cert.subject = subject;
1448
1449	ext = X509_get_ext_d2i(err_cert, NID_subject_alt_name, NULL, NULL);
1450	for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
1451		char *pos;
1452
1453		if (num_altsubject == TLS_MAX_ALT_SUBJECT)
1454			break;
1455		gen = sk_GENERAL_NAME_value(ext, i);
1456		if (gen->type != GEN_EMAIL &&
1457		    gen->type != GEN_DNS &&
1458		    gen->type != GEN_URI)
1459			continue;
1460
1461		pos = os_malloc(10 + gen->d.ia5->length + 1);
1462		if (pos == NULL)
1463			break;
1464		altsubject[num_altsubject++] = pos;
1465
1466		switch (gen->type) {
1467		case GEN_EMAIL:
1468			os_memcpy(pos, "EMAIL:", 6);
1469			pos += 6;
1470			break;
1471		case GEN_DNS:
1472			os_memcpy(pos, "DNS:", 4);
1473			pos += 4;
1474			break;
1475		case GEN_URI:
1476			os_memcpy(pos, "URI:", 4);
1477			pos += 4;
1478			break;
1479		}
1480
1481		os_memcpy(pos, gen->d.ia5->data, gen->d.ia5->length);
1482		pos += gen->d.ia5->length;
1483		*pos = '\0';
1484	}
1485
1486	for (alt = 0; alt < num_altsubject; alt++)
1487		ev.peer_cert.altsubject[alt] = altsubject[alt];
1488	ev.peer_cert.num_altsubject = num_altsubject;
1489
1490	context->event_cb(context->cb_ctx, TLS_PEER_CERTIFICATE, &ev);
1491	wpabuf_free(cert);
1492	for (alt = 0; alt < num_altsubject; alt++)
1493		os_free(altsubject[alt]);
1494}
1495
1496
1497static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
1498{
1499	char buf[256];
1500	X509 *err_cert;
1501	int err, depth;
1502	SSL *ssl;
1503	struct tls_connection *conn;
1504	struct tls_context *context;
1505	char *match, *altmatch, *suffix_match, *domain_match;
1506	const char *err_str;
1507
1508	err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
1509	if (!err_cert)
1510		return 0;
1511
1512	err = X509_STORE_CTX_get_error(x509_ctx);
1513	depth = X509_STORE_CTX_get_error_depth(x509_ctx);
1514	ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1515					 SSL_get_ex_data_X509_STORE_CTX_idx());
1516	X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
1517
1518	conn = SSL_get_app_data(ssl);
1519	if (conn == NULL)
1520		return 0;
1521
1522	if (depth == 0)
1523		conn->peer_cert = err_cert;
1524	else if (depth == 1)
1525		conn->peer_issuer = err_cert;
1526	else if (depth == 2)
1527		conn->peer_issuer_issuer = err_cert;
1528
1529	context = conn->context;
1530	match = conn->subject_match;
1531	altmatch = conn->altsubject_match;
1532	suffix_match = conn->suffix_match;
1533	domain_match = conn->domain_match;
1534
1535	if (!preverify_ok && !conn->ca_cert_verify)
1536		preverify_ok = 1;
1537	if (!preverify_ok && depth > 0 && conn->server_cert_only)
1538		preverify_ok = 1;
1539	if (!preverify_ok && (conn->flags & TLS_CONN_DISABLE_TIME_CHECKS) &&
1540	    (err == X509_V_ERR_CERT_HAS_EXPIRED ||
1541	     err == X509_V_ERR_CERT_NOT_YET_VALID)) {
1542		wpa_printf(MSG_DEBUG, "OpenSSL: Ignore certificate validity "
1543			   "time mismatch");
1544		preverify_ok = 1;
1545	}
1546
1547	err_str = X509_verify_cert_error_string(err);
1548
1549#ifdef CONFIG_SHA256
1550	/*
1551	 * Do not require preverify_ok so we can explicity allow otherwise
1552	 * invalid pinned server certificates.
1553	 */
1554	if (depth == 0 && conn->server_cert_only) {
1555		struct wpabuf *cert;
1556		cert = get_x509_cert(err_cert);
1557		if (!cert) {
1558			wpa_printf(MSG_DEBUG, "OpenSSL: Could not fetch "
1559				   "server certificate data");
1560			preverify_ok = 0;
1561		} else {
1562			u8 hash[32];
1563			const u8 *addr[1];
1564			size_t len[1];
1565			addr[0] = wpabuf_head(cert);
1566			len[0] = wpabuf_len(cert);
1567			if (sha256_vector(1, addr, len, hash) < 0 ||
1568			    os_memcmp(conn->srv_cert_hash, hash, 32) != 0) {
1569				err_str = "Server certificate mismatch";
1570				err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
1571				preverify_ok = 0;
1572			} else if (!preverify_ok) {
1573				/*
1574				 * Certificate matches pinned certificate, allow
1575				 * regardless of other problems.
1576				 */
1577				wpa_printf(MSG_DEBUG,
1578					   "OpenSSL: Ignore validation issues for a pinned server certificate");
1579				preverify_ok = 1;
1580			}
1581			wpabuf_free(cert);
1582		}
1583	}
1584#endif /* CONFIG_SHA256 */
1585
1586	if (!preverify_ok) {
1587		wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
1588			   " error %d (%s) depth %d for '%s'", err, err_str,
1589			   depth, buf);
1590		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1591				       err_str, TLS_FAIL_UNSPECIFIED);
1592		return preverify_ok;
1593	}
1594
1595	wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - preverify_ok=%d "
1596		   "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
1597		   preverify_ok, err, err_str,
1598		   conn->ca_cert_verify, depth, buf);
1599	if (depth == 0 && match && os_strstr(buf, match) == NULL) {
1600		wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
1601			   "match with '%s'", buf, match);
1602		preverify_ok = 0;
1603		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1604				       "Subject mismatch",
1605				       TLS_FAIL_SUBJECT_MISMATCH);
1606	} else if (depth == 0 && altmatch &&
1607		   !tls_match_altsubject(err_cert, altmatch)) {
1608		wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
1609			   "'%s' not found", altmatch);
1610		preverify_ok = 0;
1611		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1612				       "AltSubject mismatch",
1613				       TLS_FAIL_ALTSUBJECT_MISMATCH);
1614	} else if (depth == 0 && suffix_match &&
1615		   !tls_match_suffix(err_cert, suffix_match, 0)) {
1616		wpa_printf(MSG_WARNING, "TLS: Domain suffix match '%s' not found",
1617			   suffix_match);
1618		preverify_ok = 0;
1619		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1620				       "Domain suffix mismatch",
1621				       TLS_FAIL_DOMAIN_SUFFIX_MISMATCH);
1622	} else if (depth == 0 && domain_match &&
1623		   !tls_match_suffix(err_cert, domain_match, 1)) {
1624		wpa_printf(MSG_WARNING, "TLS: Domain match '%s' not found",
1625			   domain_match);
1626		preverify_ok = 0;
1627		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1628				       "Domain mismatch",
1629				       TLS_FAIL_DOMAIN_MISMATCH);
1630	} else
1631		openssl_tls_cert_event(conn, err_cert, depth, buf);
1632
1633	if (conn->cert_probe && preverify_ok && depth == 0) {
1634		wpa_printf(MSG_DEBUG, "OpenSSL: Reject server certificate "
1635			   "on probe-only run");
1636		preverify_ok = 0;
1637		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1638				       "Server certificate chain probe",
1639				       TLS_FAIL_SERVER_CHAIN_PROBE);
1640	}
1641
1642	if (preverify_ok && context->event_cb != NULL)
1643		context->event_cb(context->cb_ctx,
1644				  TLS_CERT_CHAIN_SUCCESS, NULL);
1645
1646	return preverify_ok;
1647}
1648
1649
1650#ifndef OPENSSL_NO_STDIO
1651static int tls_load_ca_der(void *_ssl_ctx, const char *ca_cert)
1652{
1653	SSL_CTX *ssl_ctx = _ssl_ctx;
1654	X509_LOOKUP *lookup;
1655	int ret = 0;
1656
1657	lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(ssl_ctx),
1658				       X509_LOOKUP_file());
1659	if (lookup == NULL) {
1660		tls_show_errors(MSG_WARNING, __func__,
1661				"Failed add lookup for X509 store");
1662		return -1;
1663	}
1664
1665	if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
1666		unsigned long err = ERR_peek_error();
1667		tls_show_errors(MSG_WARNING, __func__,
1668				"Failed load CA in DER format");
1669		if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1670		    ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1671			wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1672				   "cert already in hash table error",
1673				   __func__);
1674		} else
1675			ret = -1;
1676	}
1677
1678	return ret;
1679}
1680#endif /* OPENSSL_NO_STDIO */
1681
1682
1683static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
1684				  const char *ca_cert, const u8 *ca_cert_blob,
1685				  size_t ca_cert_blob_len, const char *ca_path)
1686{
1687	SSL_CTX *ssl_ctx = _ssl_ctx;
1688	X509_STORE *store;
1689
1690	/*
1691	 * Remove previously configured trusted CA certificates before adding
1692	 * new ones.
1693	 */
1694	store = X509_STORE_new();
1695	if (store == NULL) {
1696		wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1697			   "certificate store", __func__);
1698		return -1;
1699	}
1700	SSL_CTX_set_cert_store(ssl_ctx, store);
1701
1702	SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1703	conn->ca_cert_verify = 1;
1704
1705	if (ca_cert && os_strncmp(ca_cert, "probe://", 8) == 0) {
1706		wpa_printf(MSG_DEBUG, "OpenSSL: Probe for server certificate "
1707			   "chain");
1708		conn->cert_probe = 1;
1709		conn->ca_cert_verify = 0;
1710		return 0;
1711	}
1712
1713	if (ca_cert && os_strncmp(ca_cert, "hash://", 7) == 0) {
1714#ifdef CONFIG_SHA256
1715		const char *pos = ca_cert + 7;
1716		if (os_strncmp(pos, "server/sha256/", 14) != 0) {
1717			wpa_printf(MSG_DEBUG, "OpenSSL: Unsupported ca_cert "
1718				   "hash value '%s'", ca_cert);
1719			return -1;
1720		}
1721		pos += 14;
1722		if (os_strlen(pos) != 32 * 2) {
1723			wpa_printf(MSG_DEBUG, "OpenSSL: Unexpected SHA256 "
1724				   "hash length in ca_cert '%s'", ca_cert);
1725			return -1;
1726		}
1727		if (hexstr2bin(pos, conn->srv_cert_hash, 32) < 0) {
1728			wpa_printf(MSG_DEBUG, "OpenSSL: Invalid SHA256 hash "
1729				   "value in ca_cert '%s'", ca_cert);
1730			return -1;
1731		}
1732		conn->server_cert_only = 1;
1733		wpa_printf(MSG_DEBUG, "OpenSSL: Checking only server "
1734			   "certificate match");
1735		return 0;
1736#else /* CONFIG_SHA256 */
1737		wpa_printf(MSG_INFO, "No SHA256 included in the build - "
1738			   "cannot validate server certificate hash");
1739		return -1;
1740#endif /* CONFIG_SHA256 */
1741	}
1742
1743	if (ca_cert_blob) {
1744		X509 *cert = d2i_X509(NULL,
1745				      (const unsigned char **) &ca_cert_blob,
1746				      ca_cert_blob_len);
1747		if (cert == NULL) {
1748			tls_show_errors(MSG_WARNING, __func__,
1749					"Failed to parse ca_cert_blob");
1750			return -1;
1751		}
1752
1753		if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx),
1754					 cert)) {
1755			unsigned long err = ERR_peek_error();
1756			tls_show_errors(MSG_WARNING, __func__,
1757					"Failed to add ca_cert_blob to "
1758					"certificate store");
1759			if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1760			    ERR_GET_REASON(err) ==
1761			    X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1762				wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1763					   "cert already in hash table error",
1764					   __func__);
1765			} else {
1766				X509_free(cert);
1767				return -1;
1768			}
1769		}
1770		X509_free(cert);
1771		wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
1772			   "to certificate store", __func__);
1773		return 0;
1774	}
1775
1776#ifdef ANDROID
1777	if (ca_cert && os_strncmp("keystore://", ca_cert, 11) == 0) {
1778		BIO *bio = BIO_from_keystore(&ca_cert[11]);
1779		STACK_OF(X509_INFO) *stack = NULL;
1780		stack_index_t i;
1781
1782		if (bio) {
1783			stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
1784			BIO_free(bio);
1785		}
1786		if (!stack)
1787			return -1;
1788
1789		for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
1790			X509_INFO *info = sk_X509_INFO_value(stack, i);
1791			if (info->x509) {
1792				X509_STORE_add_cert(ssl_ctx->cert_store,
1793						    info->x509);
1794			}
1795			if (info->crl) {
1796				X509_STORE_add_crl(ssl_ctx->cert_store,
1797						   info->crl);
1798			}
1799		}
1800		sk_X509_INFO_pop_free(stack, X509_INFO_free);
1801		SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1802		return 0;
1803	}
1804#endif /* ANDROID */
1805
1806#ifdef CONFIG_NATIVE_WINDOWS
1807	if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
1808	    0) {
1809		wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
1810			   "system certificate store");
1811		return 0;
1812	}
1813#endif /* CONFIG_NATIVE_WINDOWS */
1814
1815	if (ca_cert || ca_path) {
1816#ifndef OPENSSL_NO_STDIO
1817		if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
1818		    1) {
1819			tls_show_errors(MSG_WARNING, __func__,
1820					"Failed to load root certificates");
1821			if (ca_cert &&
1822			    tls_load_ca_der(ssl_ctx, ca_cert) == 0) {
1823				wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
1824					   "DER format CA certificate",
1825					   __func__);
1826			} else
1827				return -1;
1828		} else {
1829			wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1830				   "certificate(s) loaded");
1831			tls_get_errors(ssl_ctx);
1832		}
1833#else /* OPENSSL_NO_STDIO */
1834		wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1835			   __func__);
1836		return -1;
1837#endif /* OPENSSL_NO_STDIO */
1838	} else {
1839		/* No ca_cert configured - do not try to verify server
1840		 * certificate */
1841		conn->ca_cert_verify = 0;
1842	}
1843
1844	return 0;
1845}
1846
1847
1848static int tls_global_ca_cert(SSL_CTX *ssl_ctx, const char *ca_cert)
1849{
1850	if (ca_cert) {
1851		if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
1852		{
1853			tls_show_errors(MSG_WARNING, __func__,
1854					"Failed to load root certificates");
1855			return -1;
1856		}
1857
1858		wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1859			   "certificate(s) loaded");
1860
1861#ifndef OPENSSL_NO_STDIO
1862		/* Add the same CAs to the client certificate requests */
1863		SSL_CTX_set_client_CA_list(ssl_ctx,
1864					   SSL_load_client_CA_file(ca_cert));
1865#endif /* OPENSSL_NO_STDIO */
1866	}
1867
1868	return 0;
1869}
1870
1871
1872int tls_global_set_verify(void *ssl_ctx, int check_crl)
1873{
1874	int flags;
1875
1876	if (check_crl) {
1877		X509_STORE *cs = SSL_CTX_get_cert_store(ssl_ctx);
1878		if (cs == NULL) {
1879			tls_show_errors(MSG_INFO, __func__, "Failed to get "
1880					"certificate store when enabling "
1881					"check_crl");
1882			return -1;
1883		}
1884		flags = X509_V_FLAG_CRL_CHECK;
1885		if (check_crl == 2)
1886			flags |= X509_V_FLAG_CRL_CHECK_ALL;
1887		X509_STORE_set_flags(cs, flags);
1888	}
1889	return 0;
1890}
1891
1892
1893static int tls_connection_set_subject_match(struct tls_connection *conn,
1894					    const char *subject_match,
1895					    const char *altsubject_match,
1896					    const char *suffix_match,
1897					    const char *domain_match)
1898{
1899	os_free(conn->subject_match);
1900	conn->subject_match = NULL;
1901	if (subject_match) {
1902		conn->subject_match = os_strdup(subject_match);
1903		if (conn->subject_match == NULL)
1904			return -1;
1905	}
1906
1907	os_free(conn->altsubject_match);
1908	conn->altsubject_match = NULL;
1909	if (altsubject_match) {
1910		conn->altsubject_match = os_strdup(altsubject_match);
1911		if (conn->altsubject_match == NULL)
1912			return -1;
1913	}
1914
1915	os_free(conn->suffix_match);
1916	conn->suffix_match = NULL;
1917	if (suffix_match) {
1918		conn->suffix_match = os_strdup(suffix_match);
1919		if (conn->suffix_match == NULL)
1920			return -1;
1921	}
1922
1923	os_free(conn->domain_match);
1924	conn->domain_match = NULL;
1925	if (domain_match) {
1926		conn->domain_match = os_strdup(domain_match);
1927		if (conn->domain_match == NULL)
1928			return -1;
1929	}
1930
1931	return 0;
1932}
1933
1934
1935int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
1936			      int verify_peer)
1937{
1938	static int counter = 0;
1939
1940	if (conn == NULL)
1941		return -1;
1942
1943	if (verify_peer) {
1944		conn->ca_cert_verify = 1;
1945		SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
1946			       SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1947			       SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
1948	} else {
1949		conn->ca_cert_verify = 0;
1950		SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1951	}
1952
1953	SSL_set_accept_state(conn->ssl);
1954
1955	/*
1956	 * Set session id context in order to avoid fatal errors when client
1957	 * tries to resume a session. However, set the context to a unique
1958	 * value in order to effectively disable session resumption for now
1959	 * since not all areas of the server code are ready for it (e.g.,
1960	 * EAP-TTLS needs special handling for Phase 2 after abbreviated TLS
1961	 * handshake).
1962	 */
1963	counter++;
1964	SSL_set_session_id_context(conn->ssl,
1965				   (const unsigned char *) &counter,
1966				   sizeof(counter));
1967
1968	return 0;
1969}
1970
1971
1972static int tls_connection_client_cert(struct tls_connection *conn,
1973				      const char *client_cert,
1974				      const u8 *client_cert_blob,
1975				      size_t client_cert_blob_len)
1976{
1977	if (client_cert == NULL && client_cert_blob == NULL)
1978		return 0;
1979
1980	if (client_cert_blob &&
1981	    SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
1982				     client_cert_blob_len) == 1) {
1983		wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
1984			   "OK");
1985		return 0;
1986	} else if (client_cert_blob) {
1987		tls_show_errors(MSG_DEBUG, __func__,
1988				"SSL_use_certificate_ASN1 failed");
1989	}
1990
1991	if (client_cert == NULL)
1992		return -1;
1993
1994#ifdef ANDROID
1995	if (os_strncmp("keystore://", client_cert, 11) == 0) {
1996		BIO *bio = BIO_from_keystore(&client_cert[11]);
1997		X509 *x509 = NULL;
1998		int ret = -1;
1999		if (bio) {
2000			x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
2001			BIO_free(bio);
2002		}
2003		if (x509) {
2004			if (SSL_use_certificate(conn->ssl, x509) == 1)
2005				ret = 0;
2006			X509_free(x509);
2007		}
2008		return ret;
2009	}
2010#endif /* ANDROID */
2011
2012#ifndef OPENSSL_NO_STDIO
2013	if (SSL_use_certificate_file(conn->ssl, client_cert,
2014				     SSL_FILETYPE_ASN1) == 1) {
2015		wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
2016			   " --> OK");
2017		return 0;
2018	}
2019
2020	if (SSL_use_certificate_file(conn->ssl, client_cert,
2021				     SSL_FILETYPE_PEM) == 1) {
2022		ERR_clear_error();
2023		wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
2024			   " --> OK");
2025		return 0;
2026	}
2027
2028	tls_show_errors(MSG_DEBUG, __func__,
2029			"SSL_use_certificate_file failed");
2030#else /* OPENSSL_NO_STDIO */
2031	wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
2032#endif /* OPENSSL_NO_STDIO */
2033
2034	return -1;
2035}
2036
2037
2038static int tls_global_client_cert(SSL_CTX *ssl_ctx, const char *client_cert)
2039{
2040#ifndef OPENSSL_NO_STDIO
2041	if (client_cert == NULL)
2042		return 0;
2043
2044	if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
2045					 SSL_FILETYPE_ASN1) != 1 &&
2046	    SSL_CTX_use_certificate_chain_file(ssl_ctx, client_cert) != 1 &&
2047	    SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
2048					 SSL_FILETYPE_PEM) != 1) {
2049		tls_show_errors(MSG_INFO, __func__,
2050				"Failed to load client certificate");
2051		return -1;
2052	}
2053	return 0;
2054#else /* OPENSSL_NO_STDIO */
2055	if (client_cert == NULL)
2056		return 0;
2057	wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
2058	return -1;
2059#endif /* OPENSSL_NO_STDIO */
2060}
2061
2062
2063static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
2064{
2065	if (password == NULL) {
2066		return 0;
2067	}
2068	os_strlcpy(buf, (char *) password, size);
2069	return os_strlen(buf);
2070}
2071
2072
2073#ifdef PKCS12_FUNCS
2074static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
2075			    const char *passwd)
2076{
2077	EVP_PKEY *pkey;
2078	X509 *cert;
2079	STACK_OF(X509) *certs;
2080	int res = 0;
2081	char buf[256];
2082
2083	pkey = NULL;
2084	cert = NULL;
2085	certs = NULL;
2086	if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
2087		tls_show_errors(MSG_DEBUG, __func__,
2088				"Failed to parse PKCS12 file");
2089		PKCS12_free(p12);
2090		return -1;
2091	}
2092	wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
2093
2094	if (cert) {
2095		X509_NAME_oneline(X509_get_subject_name(cert), buf,
2096				  sizeof(buf));
2097		wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
2098			   "subject='%s'", buf);
2099		if (ssl) {
2100			if (SSL_use_certificate(ssl, cert) != 1)
2101				res = -1;
2102		} else {
2103			if (SSL_CTX_use_certificate(ssl_ctx, cert) != 1)
2104				res = -1;
2105		}
2106		X509_free(cert);
2107	}
2108
2109	if (pkey) {
2110		wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
2111		if (ssl) {
2112			if (SSL_use_PrivateKey(ssl, pkey) != 1)
2113				res = -1;
2114		} else {
2115			if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1)
2116				res = -1;
2117		}
2118		EVP_PKEY_free(pkey);
2119	}
2120
2121	if (certs) {
2122		while ((cert = sk_X509_pop(certs)) != NULL) {
2123			X509_NAME_oneline(X509_get_subject_name(cert), buf,
2124					  sizeof(buf));
2125			wpa_printf(MSG_DEBUG, "TLS: additional certificate"
2126				   " from PKCS12: subject='%s'", buf);
2127			/*
2128			 * There is no SSL equivalent for the chain cert - so
2129			 * always add it to the context...
2130			 */
2131			if (SSL_CTX_add_extra_chain_cert(ssl_ctx, cert) != 1) {
2132				res = -1;
2133				break;
2134			}
2135		}
2136		sk_X509_free(certs);
2137	}
2138
2139	PKCS12_free(p12);
2140
2141	if (res < 0)
2142		tls_get_errors(ssl_ctx);
2143
2144	return res;
2145}
2146#endif  /* PKCS12_FUNCS */
2147
2148
2149static int tls_read_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, const char *private_key,
2150			   const char *passwd)
2151{
2152#ifdef PKCS12_FUNCS
2153	FILE *f;
2154	PKCS12 *p12;
2155
2156	f = fopen(private_key, "rb");
2157	if (f == NULL)
2158		return -1;
2159
2160	p12 = d2i_PKCS12_fp(f, NULL);
2161	fclose(f);
2162
2163	if (p12 == NULL) {
2164		tls_show_errors(MSG_INFO, __func__,
2165				"Failed to use PKCS#12 file");
2166		return -1;
2167	}
2168
2169	return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
2170
2171#else /* PKCS12_FUNCS */
2172	wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
2173		   "p12/pfx files");
2174	return -1;
2175#endif  /* PKCS12_FUNCS */
2176}
2177
2178
2179static int tls_read_pkcs12_blob(SSL_CTX *ssl_ctx, SSL *ssl,
2180				const u8 *blob, size_t len, const char *passwd)
2181{
2182#ifdef PKCS12_FUNCS
2183	PKCS12 *p12;
2184
2185	p12 = d2i_PKCS12(NULL, (const unsigned char **) &blob, len);
2186	if (p12 == NULL) {
2187		tls_show_errors(MSG_INFO, __func__,
2188				"Failed to use PKCS#12 blob");
2189		return -1;
2190	}
2191
2192	return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
2193
2194#else /* PKCS12_FUNCS */
2195	wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
2196		   "p12/pfx blobs");
2197	return -1;
2198#endif  /* PKCS12_FUNCS */
2199}
2200
2201
2202#ifndef OPENSSL_NO_ENGINE
2203static int tls_engine_get_cert(struct tls_connection *conn,
2204			       const char *cert_id,
2205			       X509 **cert)
2206{
2207	/* this runs after the private key is loaded so no PIN is required */
2208	struct {
2209		const char *cert_id;
2210		X509 *cert;
2211	} params;
2212	params.cert_id = cert_id;
2213	params.cert = NULL;
2214
2215	if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
2216			     0, &params, NULL, 1)) {
2217		unsigned long err = ERR_get_error();
2218
2219		wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
2220			   " '%s' [%s]", cert_id,
2221			   ERR_error_string(err, NULL));
2222		if (tls_is_pin_error(err))
2223			return TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
2224		return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
2225	}
2226	if (!params.cert) {
2227		wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
2228			   " '%s'", cert_id);
2229		return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
2230	}
2231	*cert = params.cert;
2232	return 0;
2233}
2234#endif /* OPENSSL_NO_ENGINE */
2235
2236
2237static int tls_connection_engine_client_cert(struct tls_connection *conn,
2238					     const char *cert_id)
2239{
2240#ifndef OPENSSL_NO_ENGINE
2241	X509 *cert;
2242
2243	if (tls_engine_get_cert(conn, cert_id, &cert))
2244		return -1;
2245
2246	if (!SSL_use_certificate(conn->ssl, cert)) {
2247		tls_show_errors(MSG_ERROR, __func__,
2248				"SSL_use_certificate failed");
2249                X509_free(cert);
2250		return -1;
2251	}
2252	X509_free(cert);
2253	wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
2254		   "OK");
2255	return 0;
2256
2257#else /* OPENSSL_NO_ENGINE */
2258	return -1;
2259#endif /* OPENSSL_NO_ENGINE */
2260}
2261
2262
2263static int tls_connection_engine_ca_cert(void *_ssl_ctx,
2264					 struct tls_connection *conn,
2265					 const char *ca_cert_id)
2266{
2267#ifndef OPENSSL_NO_ENGINE
2268	X509 *cert;
2269	SSL_CTX *ssl_ctx = _ssl_ctx;
2270	X509_STORE *store;
2271
2272	if (tls_engine_get_cert(conn, ca_cert_id, &cert))
2273		return -1;
2274
2275	/* start off the same as tls_connection_ca_cert */
2276	store = X509_STORE_new();
2277	if (store == NULL) {
2278		wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
2279			   "certificate store", __func__);
2280		X509_free(cert);
2281		return -1;
2282	}
2283	SSL_CTX_set_cert_store(ssl_ctx, store);
2284	if (!X509_STORE_add_cert(store, cert)) {
2285		unsigned long err = ERR_peek_error();
2286		tls_show_errors(MSG_WARNING, __func__,
2287				"Failed to add CA certificate from engine "
2288				"to certificate store");
2289		if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
2290		    ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
2291			wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
2292				   " already in hash table error",
2293				   __func__);
2294		} else {
2295			X509_free(cert);
2296			return -1;
2297		}
2298	}
2299	X509_free(cert);
2300	wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
2301		   "to certificate store", __func__);
2302	SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
2303	conn->ca_cert_verify = 1;
2304
2305	return 0;
2306
2307#else /* OPENSSL_NO_ENGINE */
2308	return -1;
2309#endif /* OPENSSL_NO_ENGINE */
2310}
2311
2312
2313static int tls_connection_engine_private_key(struct tls_connection *conn)
2314{
2315#if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
2316	if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
2317		tls_show_errors(MSG_ERROR, __func__,
2318				"ENGINE: cannot use private key for TLS");
2319		return -1;
2320	}
2321	if (!SSL_check_private_key(conn->ssl)) {
2322		tls_show_errors(MSG_INFO, __func__,
2323				"Private key failed verification");
2324		return -1;
2325	}
2326	return 0;
2327#else /* OPENSSL_NO_ENGINE */
2328	wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
2329		   "engine support was not compiled in");
2330	return -1;
2331#endif /* OPENSSL_NO_ENGINE */
2332}
2333
2334
2335static int tls_connection_private_key(void *_ssl_ctx,
2336				      struct tls_connection *conn,
2337				      const char *private_key,
2338				      const char *private_key_passwd,
2339				      const u8 *private_key_blob,
2340				      size_t private_key_blob_len)
2341{
2342	SSL_CTX *ssl_ctx = _ssl_ctx;
2343	char *passwd;
2344	int ok;
2345
2346	if (private_key == NULL && private_key_blob == NULL)
2347		return 0;
2348
2349	if (private_key_passwd) {
2350		passwd = os_strdup(private_key_passwd);
2351		if (passwd == NULL)
2352			return -1;
2353	} else
2354		passwd = NULL;
2355
2356	SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2357	SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2358
2359	ok = 0;
2360	while (private_key_blob) {
2361		if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
2362					    (u8 *) private_key_blob,
2363					    private_key_blob_len) == 1) {
2364			wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
2365				   "ASN1(EVP_PKEY_RSA) --> OK");
2366			ok = 1;
2367			break;
2368		}
2369
2370		if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
2371					    (u8 *) private_key_blob,
2372					    private_key_blob_len) == 1) {
2373			wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
2374				   "ASN1(EVP_PKEY_DSA) --> OK");
2375			ok = 1;
2376			break;
2377		}
2378
2379		if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
2380					       (u8 *) private_key_blob,
2381					       private_key_blob_len) == 1) {
2382			wpa_printf(MSG_DEBUG, "OpenSSL: "
2383				   "SSL_use_RSAPrivateKey_ASN1 --> OK");
2384			ok = 1;
2385			break;
2386		}
2387
2388		if (tls_read_pkcs12_blob(ssl_ctx, conn->ssl, private_key_blob,
2389					 private_key_blob_len, passwd) == 0) {
2390			wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
2391				   "OK");
2392			ok = 1;
2393			break;
2394		}
2395
2396		break;
2397	}
2398
2399	while (!ok && private_key) {
2400#ifndef OPENSSL_NO_STDIO
2401		if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2402					    SSL_FILETYPE_ASN1) == 1) {
2403			wpa_printf(MSG_DEBUG, "OpenSSL: "
2404				   "SSL_use_PrivateKey_File (DER) --> OK");
2405			ok = 1;
2406			break;
2407		}
2408
2409		if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2410					    SSL_FILETYPE_PEM) == 1) {
2411			wpa_printf(MSG_DEBUG, "OpenSSL: "
2412				   "SSL_use_PrivateKey_File (PEM) --> OK");
2413			ok = 1;
2414			break;
2415		}
2416#else /* OPENSSL_NO_STDIO */
2417		wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
2418			   __func__);
2419#endif /* OPENSSL_NO_STDIO */
2420
2421		if (tls_read_pkcs12(ssl_ctx, conn->ssl, private_key, passwd)
2422		    == 0) {
2423			wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
2424				   "--> OK");
2425			ok = 1;
2426			break;
2427		}
2428
2429		if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
2430			wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
2431				   "access certificate store --> OK");
2432			ok = 1;
2433			break;
2434		}
2435
2436		break;
2437	}
2438
2439	if (!ok) {
2440		tls_show_errors(MSG_INFO, __func__,
2441				"Failed to load private key");
2442		os_free(passwd);
2443		return -1;
2444	}
2445	ERR_clear_error();
2446	SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2447	os_free(passwd);
2448
2449	if (!SSL_check_private_key(conn->ssl)) {
2450		tls_show_errors(MSG_INFO, __func__, "Private key failed "
2451				"verification");
2452		return -1;
2453	}
2454
2455	wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
2456	return 0;
2457}
2458
2459
2460static int tls_global_private_key(SSL_CTX *ssl_ctx, const char *private_key,
2461				  const char *private_key_passwd)
2462{
2463	char *passwd;
2464
2465	if (private_key == NULL)
2466		return 0;
2467
2468	if (private_key_passwd) {
2469		passwd = os_strdup(private_key_passwd);
2470		if (passwd == NULL)
2471			return -1;
2472	} else
2473		passwd = NULL;
2474
2475	SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2476	SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2477	if (
2478#ifndef OPENSSL_NO_STDIO
2479	    SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2480					SSL_FILETYPE_ASN1) != 1 &&
2481	    SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2482					SSL_FILETYPE_PEM) != 1 &&
2483#endif /* OPENSSL_NO_STDIO */
2484	    tls_read_pkcs12(ssl_ctx, NULL, private_key, passwd)) {
2485		tls_show_errors(MSG_INFO, __func__,
2486				"Failed to load private key");
2487		os_free(passwd);
2488		ERR_clear_error();
2489		return -1;
2490	}
2491	os_free(passwd);
2492	ERR_clear_error();
2493	SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2494
2495	if (!SSL_CTX_check_private_key(ssl_ctx)) {
2496		tls_show_errors(MSG_INFO, __func__,
2497				"Private key failed verification");
2498		return -1;
2499	}
2500
2501	return 0;
2502}
2503
2504
2505static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
2506{
2507#ifdef OPENSSL_NO_DH
2508	if (dh_file == NULL)
2509		return 0;
2510	wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2511		   "dh_file specified");
2512	return -1;
2513#else /* OPENSSL_NO_DH */
2514	DH *dh;
2515	BIO *bio;
2516
2517	/* TODO: add support for dh_blob */
2518	if (dh_file == NULL)
2519		return 0;
2520	if (conn == NULL)
2521		return -1;
2522
2523	bio = BIO_new_file(dh_file, "r");
2524	if (bio == NULL) {
2525		wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2526			   dh_file, ERR_error_string(ERR_get_error(), NULL));
2527		return -1;
2528	}
2529	dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2530	BIO_free(bio);
2531#ifndef OPENSSL_NO_DSA
2532	while (dh == NULL) {
2533		DSA *dsa;
2534		wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2535			   " trying to parse as DSA params", dh_file,
2536			   ERR_error_string(ERR_get_error(), NULL));
2537		bio = BIO_new_file(dh_file, "r");
2538		if (bio == NULL)
2539			break;
2540		dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2541		BIO_free(bio);
2542		if (!dsa) {
2543			wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2544				   "'%s': %s", dh_file,
2545				   ERR_error_string(ERR_get_error(), NULL));
2546			break;
2547		}
2548
2549		wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2550		dh = DSA_dup_DH(dsa);
2551		DSA_free(dsa);
2552		if (dh == NULL) {
2553			wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2554				   "params into DH params");
2555			break;
2556		}
2557		break;
2558	}
2559#endif /* !OPENSSL_NO_DSA */
2560	if (dh == NULL) {
2561		wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2562			   "'%s'", dh_file);
2563		return -1;
2564	}
2565
2566	if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
2567		wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2568			   "%s", dh_file,
2569			   ERR_error_string(ERR_get_error(), NULL));
2570		DH_free(dh);
2571		return -1;
2572	}
2573	DH_free(dh);
2574	return 0;
2575#endif /* OPENSSL_NO_DH */
2576}
2577
2578
2579static int tls_global_dh(SSL_CTX *ssl_ctx, const char *dh_file)
2580{
2581#ifdef OPENSSL_NO_DH
2582	if (dh_file == NULL)
2583		return 0;
2584	wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2585		   "dh_file specified");
2586	return -1;
2587#else /* OPENSSL_NO_DH */
2588	DH *dh;
2589	BIO *bio;
2590
2591	/* TODO: add support for dh_blob */
2592	if (dh_file == NULL)
2593		return 0;
2594	if (ssl_ctx == NULL)
2595		return -1;
2596
2597	bio = BIO_new_file(dh_file, "r");
2598	if (bio == NULL) {
2599		wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2600			   dh_file, ERR_error_string(ERR_get_error(), NULL));
2601		return -1;
2602	}
2603	dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2604	BIO_free(bio);
2605#ifndef OPENSSL_NO_DSA
2606	while (dh == NULL) {
2607		DSA *dsa;
2608		wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2609			   " trying to parse as DSA params", dh_file,
2610			   ERR_error_string(ERR_get_error(), NULL));
2611		bio = BIO_new_file(dh_file, "r");
2612		if (bio == NULL)
2613			break;
2614		dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2615		BIO_free(bio);
2616		if (!dsa) {
2617			wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2618				   "'%s': %s", dh_file,
2619				   ERR_error_string(ERR_get_error(), NULL));
2620			break;
2621		}
2622
2623		wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2624		dh = DSA_dup_DH(dsa);
2625		DSA_free(dsa);
2626		if (dh == NULL) {
2627			wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2628				   "params into DH params");
2629			break;
2630		}
2631		break;
2632	}
2633#endif /* !OPENSSL_NO_DSA */
2634	if (dh == NULL) {
2635		wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2636			   "'%s'", dh_file);
2637		return -1;
2638	}
2639
2640	if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
2641		wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2642			   "%s", dh_file,
2643			   ERR_error_string(ERR_get_error(), NULL));
2644		DH_free(dh);
2645		return -1;
2646	}
2647	DH_free(dh);
2648	return 0;
2649#endif /* OPENSSL_NO_DH */
2650}
2651
2652
2653int tls_connection_get_keys(void *ssl_ctx, struct tls_connection *conn,
2654			    struct tls_keys *keys)
2655{
2656#ifdef CONFIG_FIPS
2657	wpa_printf(MSG_ERROR, "OpenSSL: TLS keys cannot be exported in FIPS "
2658		   "mode");
2659	return -1;
2660#else /* CONFIG_FIPS */
2661	SSL *ssl;
2662
2663	if (conn == NULL || keys == NULL)
2664		return -1;
2665	ssl = conn->ssl;
2666	if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
2667		return -1;
2668
2669	os_memset(keys, 0, sizeof(*keys));
2670	keys->client_random = ssl->s3->client_random;
2671	keys->client_random_len = SSL3_RANDOM_SIZE;
2672	keys->server_random = ssl->s3->server_random;
2673	keys->server_random_len = SSL3_RANDOM_SIZE;
2674
2675	return 0;
2676#endif /* CONFIG_FIPS */
2677}
2678
2679
2680static int openssl_get_keyblock_size(SSL *ssl)
2681{
2682	const EVP_CIPHER *c;
2683	const EVP_MD *h;
2684	int md_size;
2685
2686	if (ssl->enc_read_ctx == NULL || ssl->enc_read_ctx->cipher == NULL ||
2687	    ssl->read_hash == NULL)
2688		return -1;
2689
2690	c = ssl->enc_read_ctx->cipher;
2691#if OPENSSL_VERSION_NUMBER >= 0x00909000L
2692	h = EVP_MD_CTX_md(ssl->read_hash);
2693#else
2694	h = ssl->read_hash;
2695#endif
2696	if (h)
2697		md_size = EVP_MD_size(h);
2698#if OPENSSL_VERSION_NUMBER >= 0x10000000L
2699	else if (ssl->s3)
2700		md_size = ssl->s3->tmp.new_mac_secret_size;
2701#endif
2702	else
2703		return -1;
2704
2705	wpa_printf(MSG_DEBUG, "OpenSSL: keyblock size: key_len=%d MD_size=%d "
2706		   "IV_len=%d", EVP_CIPHER_key_length(c), md_size,
2707		   EVP_CIPHER_iv_length(c));
2708	return 2 * (EVP_CIPHER_key_length(c) +
2709		    md_size +
2710		    EVP_CIPHER_iv_length(c));
2711}
2712
2713
2714static int openssl_tls_prf(void *tls_ctx, struct tls_connection *conn,
2715			   const char *label, int server_random_first,
2716			   int skip_keyblock, u8 *out, size_t out_len)
2717{
2718#ifdef CONFIG_FIPS
2719	wpa_printf(MSG_ERROR, "OpenSSL: TLS keys cannot be exported in FIPS "
2720		   "mode");
2721	return -1;
2722#else /* CONFIG_FIPS */
2723	SSL *ssl;
2724	u8 *rnd;
2725	int ret = -1;
2726	int skip = 0;
2727	u8 *tmp_out = NULL;
2728	u8 *_out = out;
2729
2730	/*
2731	 * TLS library did not support key generation, so get the needed TLS
2732	 * session parameters and use an internal implementation of TLS PRF to
2733	 * derive the key.
2734	 */
2735
2736	if (conn == NULL)
2737		return -1;
2738	ssl = conn->ssl;
2739	if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL ||
2740	    ssl->session->master_key_length <= 0)
2741		return -1;
2742
2743	if (skip_keyblock) {
2744		skip = openssl_get_keyblock_size(ssl);
2745		if (skip < 0)
2746			return -1;
2747		tmp_out = os_malloc(skip + out_len);
2748		if (!tmp_out)
2749			return -1;
2750		_out = tmp_out;
2751	}
2752
2753	rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
2754	if (!rnd) {
2755		os_free(tmp_out);
2756		return -1;
2757	}
2758
2759	if (server_random_first) {
2760		os_memcpy(rnd, ssl->s3->server_random, SSL3_RANDOM_SIZE);
2761		os_memcpy(rnd + SSL3_RANDOM_SIZE, ssl->s3->client_random,
2762			SSL3_RANDOM_SIZE);
2763	} else {
2764		os_memcpy(rnd, ssl->s3->client_random, SSL3_RANDOM_SIZE);
2765		os_memcpy(rnd + SSL3_RANDOM_SIZE, ssl->s3->server_random,
2766			SSL3_RANDOM_SIZE);
2767	}
2768
2769	/* TODO: TLSv1.2 may need another PRF. This could use something closer
2770	 * to SSL_export_keying_material() design. */
2771	if (tls_prf_sha1_md5(ssl->session->master_key,
2772			     ssl->session->master_key_length,
2773			     label, rnd, 2 * SSL3_RANDOM_SIZE,
2774			     _out, skip + out_len) == 0)
2775		ret = 0;
2776	os_free(rnd);
2777	if (ret == 0 && skip_keyblock)
2778		os_memcpy(out, _out + skip, out_len);
2779	bin_clear_free(tmp_out, skip);
2780
2781	return ret;
2782#endif /* CONFIG_FIPS */
2783}
2784
2785
2786int tls_connection_prf(void *tls_ctx, struct tls_connection *conn,
2787		       const char *label, int server_random_first,
2788		       int skip_keyblock, u8 *out, size_t out_len)
2789{
2790#if OPENSSL_VERSION_NUMBER >= 0x10001000L
2791	SSL *ssl;
2792	if (conn == NULL)
2793		return -1;
2794	if (server_random_first || skip_keyblock)
2795		return openssl_tls_prf(tls_ctx, conn, label,
2796				       server_random_first, skip_keyblock,
2797				       out, out_len);
2798	ssl = conn->ssl;
2799	if (SSL_export_keying_material(ssl, out, out_len, label,
2800				       os_strlen(label), NULL, 0, 0) == 1) {
2801		wpa_printf(MSG_DEBUG, "OpenSSL: Using internal PRF");
2802		return 0;
2803	}
2804#endif
2805	return openssl_tls_prf(tls_ctx, conn, label, server_random_first,
2806			       skip_keyblock, out, out_len);
2807}
2808
2809
2810static struct wpabuf *
2811openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data,
2812		  int server)
2813{
2814	int res;
2815	struct wpabuf *out_data;
2816
2817	/*
2818	 * Give TLS handshake data from the server (if available) to OpenSSL
2819	 * for processing.
2820	 */
2821	if (in_data &&
2822	    BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
2823	    < 0) {
2824		tls_show_errors(MSG_INFO, __func__,
2825				"Handshake failed - BIO_write");
2826		return NULL;
2827	}
2828
2829	/* Initiate TLS handshake or continue the existing handshake */
2830	if (server)
2831		res = SSL_accept(conn->ssl);
2832	else
2833		res = SSL_connect(conn->ssl);
2834	if (res != 1) {
2835		int err = SSL_get_error(conn->ssl, res);
2836		if (err == SSL_ERROR_WANT_READ)
2837			wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
2838				   "more data");
2839		else if (err == SSL_ERROR_WANT_WRITE)
2840			wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
2841				   "write");
2842		else {
2843			tls_show_errors(MSG_INFO, __func__, "SSL_connect");
2844			conn->failed++;
2845		}
2846	}
2847
2848	/* Get the TLS handshake data to be sent to the server */
2849	res = BIO_ctrl_pending(conn->ssl_out);
2850	wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
2851	out_data = wpabuf_alloc(res);
2852	if (out_data == NULL) {
2853		wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
2854			   "handshake output (%d bytes)", res);
2855		if (BIO_reset(conn->ssl_out) < 0) {
2856			tls_show_errors(MSG_INFO, __func__,
2857					"BIO_reset failed");
2858		}
2859		return NULL;
2860	}
2861	res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
2862				      res);
2863	if (res < 0) {
2864		tls_show_errors(MSG_INFO, __func__,
2865				"Handshake failed - BIO_read");
2866		if (BIO_reset(conn->ssl_out) < 0) {
2867			tls_show_errors(MSG_INFO, __func__,
2868					"BIO_reset failed");
2869		}
2870		wpabuf_free(out_data);
2871		return NULL;
2872	}
2873	wpabuf_put(out_data, res);
2874
2875	return out_data;
2876}
2877
2878
2879static struct wpabuf *
2880openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
2881{
2882	struct wpabuf *appl_data;
2883	int res;
2884
2885	appl_data = wpabuf_alloc(max_len + 100);
2886	if (appl_data == NULL)
2887		return NULL;
2888
2889	res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
2890		       wpabuf_size(appl_data));
2891	if (res < 0) {
2892		int err = SSL_get_error(conn->ssl, res);
2893		if (err == SSL_ERROR_WANT_READ ||
2894		    err == SSL_ERROR_WANT_WRITE) {
2895			wpa_printf(MSG_DEBUG, "SSL: No Application Data "
2896				   "included");
2897		} else {
2898			tls_show_errors(MSG_INFO, __func__,
2899					"Failed to read possible "
2900					"Application Data");
2901		}
2902		wpabuf_free(appl_data);
2903		return NULL;
2904	}
2905
2906	wpabuf_put(appl_data, res);
2907	wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
2908			    "message", appl_data);
2909
2910	return appl_data;
2911}
2912
2913
2914static struct wpabuf *
2915openssl_connection_handshake(struct tls_connection *conn,
2916			     const struct wpabuf *in_data,
2917			     struct wpabuf **appl_data, int server)
2918{
2919	struct wpabuf *out_data;
2920
2921	if (appl_data)
2922		*appl_data = NULL;
2923
2924	out_data = openssl_handshake(conn, in_data, server);
2925	if (out_data == NULL)
2926		return NULL;
2927	if (conn->invalid_hb_used) {
2928		wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
2929		wpabuf_free(out_data);
2930		return NULL;
2931	}
2932
2933	if (SSL_is_init_finished(conn->ssl) && appl_data && in_data)
2934		*appl_data = openssl_get_appl_data(conn, wpabuf_len(in_data));
2935
2936	if (conn->invalid_hb_used) {
2937		wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
2938		if (appl_data) {
2939			wpabuf_free(*appl_data);
2940			*appl_data = NULL;
2941		}
2942		wpabuf_free(out_data);
2943		return NULL;
2944	}
2945
2946	return out_data;
2947}
2948
2949
2950struct wpabuf *
2951tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
2952			 const struct wpabuf *in_data,
2953			 struct wpabuf **appl_data)
2954{
2955	return openssl_connection_handshake(conn, in_data, appl_data, 0);
2956}
2957
2958
2959struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
2960						struct tls_connection *conn,
2961						const struct wpabuf *in_data,
2962						struct wpabuf **appl_data)
2963{
2964	return openssl_connection_handshake(conn, in_data, appl_data, 1);
2965}
2966
2967
2968struct wpabuf * tls_connection_encrypt(void *tls_ctx,
2969				       struct tls_connection *conn,
2970				       const struct wpabuf *in_data)
2971{
2972	int res;
2973	struct wpabuf *buf;
2974
2975	if (conn == NULL)
2976		return NULL;
2977
2978	/* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
2979	if ((res = BIO_reset(conn->ssl_in)) < 0 ||
2980	    (res = BIO_reset(conn->ssl_out)) < 0) {
2981		tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2982		return NULL;
2983	}
2984	res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
2985	if (res < 0) {
2986		tls_show_errors(MSG_INFO, __func__,
2987				"Encryption failed - SSL_write");
2988		return NULL;
2989	}
2990
2991	/* Read encrypted data to be sent to the server */
2992	buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
2993	if (buf == NULL)
2994		return NULL;
2995	res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
2996	if (res < 0) {
2997		tls_show_errors(MSG_INFO, __func__,
2998				"Encryption failed - BIO_read");
2999		wpabuf_free(buf);
3000		return NULL;
3001	}
3002	wpabuf_put(buf, res);
3003
3004	return buf;
3005}
3006
3007
3008struct wpabuf * tls_connection_decrypt(void *tls_ctx,
3009				       struct tls_connection *conn,
3010				       const struct wpabuf *in_data)
3011{
3012	int res;
3013	struct wpabuf *buf;
3014
3015	/* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
3016	res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
3017			wpabuf_len(in_data));
3018	if (res < 0) {
3019		tls_show_errors(MSG_INFO, __func__,
3020				"Decryption failed - BIO_write");
3021		return NULL;
3022	}
3023	if (BIO_reset(conn->ssl_out) < 0) {
3024		tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
3025		return NULL;
3026	}
3027
3028	/* Read decrypted data for further processing */
3029	/*
3030	 * Even though we try to disable TLS compression, it is possible that
3031	 * this cannot be done with all TLS libraries. Add extra buffer space
3032	 * to handle the possibility of the decrypted data being longer than
3033	 * input data.
3034	 */
3035	buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
3036	if (buf == NULL)
3037		return NULL;
3038	res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
3039	if (res < 0) {
3040		tls_show_errors(MSG_INFO, __func__,
3041				"Decryption failed - SSL_read");
3042		wpabuf_free(buf);
3043		return NULL;
3044	}
3045	wpabuf_put(buf, res);
3046
3047	if (conn->invalid_hb_used) {
3048		wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
3049		wpabuf_free(buf);
3050		return NULL;
3051	}
3052
3053	return buf;
3054}
3055
3056
3057int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
3058{
3059#if OPENSSL_VERSION_NUMBER >= 0x10001000L
3060	return conn ? SSL_cache_hit(conn->ssl) : 0;
3061#else
3062	return conn ? conn->ssl->hit : 0;
3063#endif
3064}
3065
3066
3067int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
3068				   u8 *ciphers)
3069{
3070	char buf[100], *pos, *end;
3071	u8 *c;
3072	int ret;
3073
3074	if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
3075		return -1;
3076
3077	buf[0] = '\0';
3078	pos = buf;
3079	end = pos + sizeof(buf);
3080
3081	c = ciphers;
3082	while (*c != TLS_CIPHER_NONE) {
3083		const char *suite;
3084
3085		switch (*c) {
3086		case TLS_CIPHER_RC4_SHA:
3087			suite = "RC4-SHA";
3088			break;
3089		case TLS_CIPHER_AES128_SHA:
3090			suite = "AES128-SHA";
3091			break;
3092		case TLS_CIPHER_RSA_DHE_AES128_SHA:
3093			suite = "DHE-RSA-AES128-SHA";
3094			break;
3095		case TLS_CIPHER_ANON_DH_AES128_SHA:
3096			suite = "ADH-AES128-SHA";
3097			break;
3098		default:
3099			wpa_printf(MSG_DEBUG, "TLS: Unsupported "
3100				   "cipher selection: %d", *c);
3101			return -1;
3102		}
3103		ret = os_snprintf(pos, end - pos, ":%s", suite);
3104		if (os_snprintf_error(end - pos, ret))
3105			break;
3106		pos += ret;
3107
3108		c++;
3109	}
3110
3111	wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
3112
3113	if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
3114		tls_show_errors(MSG_INFO, __func__,
3115				"Cipher suite configuration failed");
3116		return -1;
3117	}
3118
3119	return 0;
3120}
3121
3122
3123int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
3124		   char *buf, size_t buflen)
3125{
3126	const char *name;
3127	if (conn == NULL || conn->ssl == NULL)
3128		return -1;
3129
3130	name = SSL_get_cipher(conn->ssl);
3131	if (name == NULL)
3132		return -1;
3133
3134	os_strlcpy(buf, name, buflen);
3135	return 0;
3136}
3137
3138
3139int tls_connection_enable_workaround(void *ssl_ctx,
3140				     struct tls_connection *conn)
3141{
3142	SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
3143
3144	return 0;
3145}
3146
3147
3148#if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3149/* ClientHello TLS extensions require a patch to openssl, so this function is
3150 * commented out unless explicitly needed for EAP-FAST in order to be able to
3151 * build this file with unmodified openssl. */
3152int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
3153				    int ext_type, const u8 *data,
3154				    size_t data_len)
3155{
3156	if (conn == NULL || conn->ssl == NULL || ext_type != 35)
3157		return -1;
3158
3159	if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
3160				       data_len) != 1)
3161		return -1;
3162
3163	return 0;
3164}
3165#endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3166
3167
3168int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
3169{
3170	if (conn == NULL)
3171		return -1;
3172	return conn->failed;
3173}
3174
3175
3176int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
3177{
3178	if (conn == NULL)
3179		return -1;
3180	return conn->read_alerts;
3181}
3182
3183
3184int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
3185{
3186	if (conn == NULL)
3187		return -1;
3188	return conn->write_alerts;
3189}
3190
3191
3192#ifdef HAVE_OCSP
3193
3194static void ocsp_debug_print_resp(OCSP_RESPONSE *rsp)
3195{
3196#ifndef CONFIG_NO_STDOUT_DEBUG
3197	BIO *out;
3198	size_t rlen;
3199	char *txt;
3200	int res;
3201
3202	if (wpa_debug_level > MSG_DEBUG)
3203		return;
3204
3205	out = BIO_new(BIO_s_mem());
3206	if (!out)
3207		return;
3208
3209	OCSP_RESPONSE_print(out, rsp, 0);
3210	rlen = BIO_ctrl_pending(out);
3211	txt = os_malloc(rlen + 1);
3212	if (!txt) {
3213		BIO_free(out);
3214		return;
3215	}
3216
3217	res = BIO_read(out, txt, rlen);
3218	if (res > 0) {
3219		txt[res] = '\0';
3220		wpa_printf(MSG_DEBUG, "OpenSSL: OCSP Response\n%s", txt);
3221	}
3222	os_free(txt);
3223	BIO_free(out);
3224#endif /* CONFIG_NO_STDOUT_DEBUG */
3225}
3226
3227
3228static void debug_print_cert(X509 *cert, const char *title)
3229{
3230#ifndef CONFIG_NO_STDOUT_DEBUG
3231	BIO *out;
3232	size_t rlen;
3233	char *txt;
3234	int res;
3235
3236	if (wpa_debug_level > MSG_DEBUG)
3237		return;
3238
3239	out = BIO_new(BIO_s_mem());
3240	if (!out)
3241		return;
3242
3243	X509_print(out, cert);
3244	rlen = BIO_ctrl_pending(out);
3245	txt = os_malloc(rlen + 1);
3246	if (!txt) {
3247		BIO_free(out);
3248		return;
3249	}
3250
3251	res = BIO_read(out, txt, rlen);
3252	if (res > 0) {
3253		txt[res] = '\0';
3254		wpa_printf(MSG_DEBUG, "OpenSSL: %s\n%s", title, txt);
3255	}
3256	os_free(txt);
3257
3258	BIO_free(out);
3259#endif /* CONFIG_NO_STDOUT_DEBUG */
3260}
3261
3262
3263static int ocsp_resp_cb(SSL *s, void *arg)
3264{
3265	struct tls_connection *conn = arg;
3266	const unsigned char *p;
3267	int len, status, reason;
3268	OCSP_RESPONSE *rsp;
3269	OCSP_BASICRESP *basic;
3270	OCSP_CERTID *id;
3271	ASN1_GENERALIZEDTIME *produced_at, *this_update, *next_update;
3272	X509_STORE *store;
3273	STACK_OF(X509) *certs = NULL;
3274
3275	len = SSL_get_tlsext_status_ocsp_resp(s, &p);
3276	if (!p) {
3277		wpa_printf(MSG_DEBUG, "OpenSSL: No OCSP response received");
3278		return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
3279	}
3280
3281	wpa_hexdump(MSG_DEBUG, "OpenSSL: OCSP response", p, len);
3282
3283	rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
3284	if (!rsp) {
3285		wpa_printf(MSG_INFO, "OpenSSL: Failed to parse OCSP response");
3286		return 0;
3287	}
3288
3289	ocsp_debug_print_resp(rsp);
3290
3291	status = OCSP_response_status(rsp);
3292	if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
3293		wpa_printf(MSG_INFO, "OpenSSL: OCSP responder error %d (%s)",
3294			   status, OCSP_response_status_str(status));
3295		return 0;
3296	}
3297
3298	basic = OCSP_response_get1_basic(rsp);
3299	if (!basic) {
3300		wpa_printf(MSG_INFO, "OpenSSL: Could not find BasicOCSPResponse");
3301		return 0;
3302	}
3303
3304	store = SSL_CTX_get_cert_store(conn->ssl_ctx);
3305	if (conn->peer_issuer) {
3306		debug_print_cert(conn->peer_issuer, "Add OCSP issuer");
3307
3308		if (X509_STORE_add_cert(store, conn->peer_issuer) != 1) {
3309			tls_show_errors(MSG_INFO, __func__,
3310					"OpenSSL: Could not add issuer to certificate store");
3311		}
3312		certs = sk_X509_new_null();
3313		if (certs) {
3314			X509 *cert;
3315			cert = X509_dup(conn->peer_issuer);
3316			if (cert && !sk_X509_push(certs, cert)) {
3317				tls_show_errors(
3318					MSG_INFO, __func__,
3319					"OpenSSL: Could not add issuer to OCSP responder trust store");
3320				X509_free(cert);
3321				sk_X509_free(certs);
3322				certs = NULL;
3323			}
3324			if (certs && conn->peer_issuer_issuer) {
3325				cert = X509_dup(conn->peer_issuer_issuer);
3326				if (cert && !sk_X509_push(certs, cert)) {
3327					tls_show_errors(
3328						MSG_INFO, __func__,
3329						"OpenSSL: Could not add issuer's issuer to OCSP responder trust store");
3330					X509_free(cert);
3331				}
3332			}
3333		}
3334	}
3335
3336	status = OCSP_basic_verify(basic, certs, store, OCSP_TRUSTOTHER);
3337	sk_X509_pop_free(certs, X509_free);
3338	if (status <= 0) {
3339		tls_show_errors(MSG_INFO, __func__,
3340				"OpenSSL: OCSP response failed verification");
3341		OCSP_BASICRESP_free(basic);
3342		OCSP_RESPONSE_free(rsp);
3343		return 0;
3344	}
3345
3346	wpa_printf(MSG_DEBUG, "OpenSSL: OCSP response verification succeeded");
3347
3348	if (!conn->peer_cert) {
3349		wpa_printf(MSG_DEBUG, "OpenSSL: Peer certificate not available for OCSP status check");
3350		OCSP_BASICRESP_free(basic);
3351		OCSP_RESPONSE_free(rsp);
3352		return 0;
3353	}
3354
3355	if (!conn->peer_issuer) {
3356		wpa_printf(MSG_DEBUG, "OpenSSL: Peer issuer certificate not available for OCSP status check");
3357		OCSP_BASICRESP_free(basic);
3358		OCSP_RESPONSE_free(rsp);
3359		return 0;
3360	}
3361
3362	id = OCSP_cert_to_id(NULL, conn->peer_cert, conn->peer_issuer);
3363	if (!id) {
3364		wpa_printf(MSG_DEBUG, "OpenSSL: Could not create OCSP certificate identifier");
3365		OCSP_BASICRESP_free(basic);
3366		OCSP_RESPONSE_free(rsp);
3367		return 0;
3368	}
3369
3370	if (!OCSP_resp_find_status(basic, id, &status, &reason, &produced_at,
3371				   &this_update, &next_update)) {
3372		wpa_printf(MSG_INFO, "OpenSSL: Could not find current server certificate from OCSP response%s",
3373			   (conn->flags & TLS_CONN_REQUIRE_OCSP) ? "" :
3374			   " (OCSP not required)");
3375		OCSP_BASICRESP_free(basic);
3376		OCSP_RESPONSE_free(rsp);
3377		return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
3378	}
3379
3380	if (!OCSP_check_validity(this_update, next_update, 5 * 60, -1)) {
3381		tls_show_errors(MSG_INFO, __func__,
3382				"OpenSSL: OCSP status times invalid");
3383		OCSP_BASICRESP_free(basic);
3384		OCSP_RESPONSE_free(rsp);
3385		return 0;
3386	}
3387
3388	OCSP_BASICRESP_free(basic);
3389	OCSP_RESPONSE_free(rsp);
3390
3391	wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status for server certificate: %s",
3392		   OCSP_cert_status_str(status));
3393
3394	if (status == V_OCSP_CERTSTATUS_GOOD)
3395		return 1;
3396	if (status == V_OCSP_CERTSTATUS_REVOKED)
3397		return 0;
3398	if (conn->flags & TLS_CONN_REQUIRE_OCSP) {
3399		wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP required");
3400		return 0;
3401	}
3402	wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP was not required, so allow connection to continue");
3403	return 1;
3404}
3405
3406
3407static int ocsp_status_cb(SSL *s, void *arg)
3408{
3409	char *tmp;
3410	char *resp;
3411	size_t len;
3412
3413	if (tls_global->ocsp_stapling_response == NULL) {
3414		wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - no response configured");
3415		return SSL_TLSEXT_ERR_OK;
3416	}
3417
3418	resp = os_readfile(tls_global->ocsp_stapling_response, &len);
3419	if (resp == NULL) {
3420		wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - could not read response file");
3421		/* TODO: Build OCSPResponse with responseStatus = internalError
3422		 */
3423		return SSL_TLSEXT_ERR_OK;
3424	}
3425	wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - send cached response");
3426	tmp = OPENSSL_malloc(len);
3427	if (tmp == NULL) {
3428		os_free(resp);
3429		return SSL_TLSEXT_ERR_ALERT_FATAL;
3430	}
3431
3432	os_memcpy(tmp, resp, len);
3433	os_free(resp);
3434	SSL_set_tlsext_status_ocsp_resp(s, tmp, len);
3435
3436	return SSL_TLSEXT_ERR_OK;
3437}
3438
3439#endif /* HAVE_OCSP */
3440
3441
3442int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
3443			      const struct tls_connection_params *params)
3444{
3445	int ret;
3446	unsigned long err;
3447	int can_pkcs11 = 0;
3448	const char *key_id = params->key_id;
3449	const char *cert_id = params->cert_id;
3450	const char *ca_cert_id = params->ca_cert_id;
3451	const char *engine_id = params->engine ? params->engine_id : NULL;
3452
3453	if (conn == NULL)
3454		return -1;
3455
3456	/*
3457	 * If the engine isn't explicitly configured, and any of the
3458	 * cert/key fields are actually PKCS#11 URIs, then automatically
3459	 * use the PKCS#11 ENGINE.
3460	 */
3461	if (!engine_id || os_strcmp(engine_id, "pkcs11") == 0)
3462		can_pkcs11 = 1;
3463
3464	if (!key_id && params->private_key && can_pkcs11 &&
3465	    os_strncmp(params->private_key, "pkcs11:", 7) == 0) {
3466		can_pkcs11 = 2;
3467		key_id = params->private_key;
3468	}
3469
3470	if (!cert_id && params->client_cert && can_pkcs11 &&
3471	    os_strncmp(params->client_cert, "pkcs11:", 7) == 0) {
3472		can_pkcs11 = 2;
3473		cert_id = params->client_cert;
3474	}
3475
3476	if (!ca_cert_id && params->ca_cert && can_pkcs11 &&
3477	    os_strncmp(params->ca_cert, "pkcs11:", 7) == 0) {
3478		can_pkcs11 = 2;
3479		ca_cert_id = params->ca_cert;
3480	}
3481
3482	/* If we need to automatically enable the PKCS#11 ENGINE, do so. */
3483	if (can_pkcs11 == 2 && !engine_id)
3484		engine_id = "pkcs11";
3485
3486	if (params->flags & TLS_CONN_EAP_FAST) {
3487		wpa_printf(MSG_DEBUG,
3488			   "OpenSSL: Use TLSv1_method() for EAP-FAST");
3489		if (SSL_set_ssl_method(conn->ssl, TLSv1_method()) != 1) {
3490			tls_show_errors(MSG_INFO, __func__,
3491					"Failed to set TLSv1_method() for EAP-FAST");
3492			return -1;
3493		}
3494	}
3495
3496	while ((err = ERR_get_error())) {
3497		wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
3498			   __func__, ERR_error_string(err, NULL));
3499	}
3500
3501	if (engine_id) {
3502		wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
3503		ret = tls_engine_init(conn, engine_id, params->pin,
3504				      key_id, cert_id, ca_cert_id);
3505		if (ret)
3506			return ret;
3507	}
3508	if (tls_connection_set_subject_match(conn,
3509					     params->subject_match,
3510					     params->altsubject_match,
3511					     params->suffix_match,
3512					     params->domain_match))
3513		return -1;
3514
3515	if (engine_id && ca_cert_id) {
3516		if (tls_connection_engine_ca_cert(tls_ctx, conn,
3517						  ca_cert_id))
3518			return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3519	} else if (tls_connection_ca_cert(tls_ctx, conn, params->ca_cert,
3520					  params->ca_cert_blob,
3521					  params->ca_cert_blob_len,
3522					  params->ca_path))
3523		return -1;
3524
3525	if (engine_id && cert_id) {
3526		if (tls_connection_engine_client_cert(conn, cert_id))
3527			return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3528	} else if (tls_connection_client_cert(conn, params->client_cert,
3529					      params->client_cert_blob,
3530					      params->client_cert_blob_len))
3531		return -1;
3532
3533	if (engine_id && key_id) {
3534		wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
3535		if (tls_connection_engine_private_key(conn))
3536			return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3537	} else if (tls_connection_private_key(tls_ctx, conn,
3538					      params->private_key,
3539					      params->private_key_passwd,
3540					      params->private_key_blob,
3541					      params->private_key_blob_len)) {
3542		wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
3543			   params->private_key);
3544		return -1;
3545	}
3546
3547	if (tls_connection_dh(conn, params->dh_file)) {
3548		wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
3549			   params->dh_file);
3550		return -1;
3551	}
3552
3553	if (params->openssl_ciphers &&
3554	    SSL_set_cipher_list(conn->ssl, params->openssl_ciphers) != 1) {
3555		wpa_printf(MSG_INFO,
3556			   "OpenSSL: Failed to set cipher string '%s'",
3557			   params->openssl_ciphers);
3558		return -1;
3559	}
3560
3561#ifdef SSL_OP_NO_TICKET
3562	if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
3563		SSL_set_options(conn->ssl, SSL_OP_NO_TICKET);
3564#ifdef SSL_clear_options
3565	else
3566		SSL_clear_options(conn->ssl, SSL_OP_NO_TICKET);
3567#endif /* SSL_clear_options */
3568#endif /*  SSL_OP_NO_TICKET */
3569
3570#ifdef SSL_OP_NO_TLSv1_1
3571	if (params->flags & TLS_CONN_DISABLE_TLSv1_1)
3572		SSL_set_options(conn->ssl, SSL_OP_NO_TLSv1_1);
3573	else
3574		SSL_clear_options(conn->ssl, SSL_OP_NO_TLSv1_1);
3575#endif /* SSL_OP_NO_TLSv1_1 */
3576#ifdef SSL_OP_NO_TLSv1_2
3577	if (params->flags & TLS_CONN_DISABLE_TLSv1_2)
3578		SSL_set_options(conn->ssl, SSL_OP_NO_TLSv1_2);
3579	else
3580		SSL_clear_options(conn->ssl, SSL_OP_NO_TLSv1_2);
3581#endif /* SSL_OP_NO_TLSv1_2 */
3582
3583#ifdef HAVE_OCSP
3584	if (params->flags & TLS_CONN_REQUEST_OCSP) {
3585		SSL_CTX *ssl_ctx = tls_ctx;
3586		SSL_set_tlsext_status_type(conn->ssl, TLSEXT_STATUSTYPE_ocsp);
3587		SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
3588		SSL_CTX_set_tlsext_status_arg(ssl_ctx, conn);
3589	}
3590#endif /* HAVE_OCSP */
3591
3592	conn->flags = params->flags;
3593
3594	tls_get_errors(tls_ctx);
3595
3596	return 0;
3597}
3598
3599
3600int tls_global_set_params(void *tls_ctx,
3601			  const struct tls_connection_params *params)
3602{
3603	SSL_CTX *ssl_ctx = tls_ctx;
3604	unsigned long err;
3605
3606	while ((err = ERR_get_error())) {
3607		wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
3608			   __func__, ERR_error_string(err, NULL));
3609	}
3610
3611	if (tls_global_ca_cert(ssl_ctx, params->ca_cert))
3612		return -1;
3613
3614	if (tls_global_client_cert(ssl_ctx, params->client_cert))
3615		return -1;
3616
3617	if (tls_global_private_key(ssl_ctx, params->private_key,
3618				   params->private_key_passwd))
3619		return -1;
3620
3621	if (tls_global_dh(ssl_ctx, params->dh_file)) {
3622		wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
3623			   params->dh_file);
3624		return -1;
3625	}
3626
3627	if (params->openssl_ciphers &&
3628	    SSL_CTX_set_cipher_list(ssl_ctx, params->openssl_ciphers) != 1) {
3629		wpa_printf(MSG_INFO,
3630			   "OpenSSL: Failed to set cipher string '%s'",
3631			   params->openssl_ciphers);
3632		return -1;
3633	}
3634
3635#ifdef SSL_OP_NO_TICKET
3636	if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
3637		SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
3638#ifdef SSL_CTX_clear_options
3639	else
3640		SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TICKET);
3641#endif /* SSL_clear_options */
3642#endif /*  SSL_OP_NO_TICKET */
3643
3644#ifdef HAVE_OCSP
3645	SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_status_cb);
3646	SSL_CTX_set_tlsext_status_arg(ssl_ctx, ssl_ctx);
3647	os_free(tls_global->ocsp_stapling_response);
3648	if (params->ocsp_stapling_response)
3649		tls_global->ocsp_stapling_response =
3650			os_strdup(params->ocsp_stapling_response);
3651	else
3652		tls_global->ocsp_stapling_response = NULL;
3653#endif /* HAVE_OCSP */
3654
3655	return 0;
3656}
3657
3658
3659unsigned int tls_capabilities(void *tls_ctx)
3660{
3661	return 0;
3662}
3663
3664
3665#if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3666/* Pre-shared secred requires a patch to openssl, so this function is
3667 * commented out unless explicitly needed for EAP-FAST in order to be able to
3668 * build this file with unmodified openssl. */
3669
3670#ifdef OPENSSL_IS_BORINGSSL
3671static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
3672			   STACK_OF(SSL_CIPHER) *peer_ciphers,
3673			   const SSL_CIPHER **cipher, void *arg)
3674#else /* OPENSSL_IS_BORINGSSL */
3675static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
3676			   STACK_OF(SSL_CIPHER) *peer_ciphers,
3677			   SSL_CIPHER **cipher, void *arg)
3678#endif /* OPENSSL_IS_BORINGSSL */
3679{
3680	struct tls_connection *conn = arg;
3681	int ret;
3682
3683	if (conn == NULL || conn->session_ticket_cb == NULL)
3684		return 0;
3685
3686	ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
3687				      conn->session_ticket,
3688				      conn->session_ticket_len,
3689				      s->s3->client_random,
3690				      s->s3->server_random, secret);
3691	os_free(conn->session_ticket);
3692	conn->session_ticket = NULL;
3693
3694	if (ret <= 0)
3695		return 0;
3696
3697	*secret_len = SSL_MAX_MASTER_KEY_LENGTH;
3698	return 1;
3699}
3700
3701
3702static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
3703				     int len, void *arg)
3704{
3705	struct tls_connection *conn = arg;
3706
3707	if (conn == NULL || conn->session_ticket_cb == NULL)
3708		return 0;
3709
3710	wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
3711
3712	os_free(conn->session_ticket);
3713	conn->session_ticket = NULL;
3714
3715	wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
3716		    "extension", data, len);
3717
3718	conn->session_ticket = os_malloc(len);
3719	if (conn->session_ticket == NULL)
3720		return 0;
3721
3722	os_memcpy(conn->session_ticket, data, len);
3723	conn->session_ticket_len = len;
3724
3725	return 1;
3726}
3727#endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3728
3729
3730int tls_connection_set_session_ticket_cb(void *tls_ctx,
3731					 struct tls_connection *conn,
3732					 tls_session_ticket_cb cb,
3733					 void *ctx)
3734{
3735#if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3736	conn->session_ticket_cb = cb;
3737	conn->session_ticket_cb_ctx = ctx;
3738
3739	if (cb) {
3740		if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
3741					      conn) != 1)
3742			return -1;
3743		SSL_set_session_ticket_ext_cb(conn->ssl,
3744					      tls_session_ticket_ext_cb, conn);
3745	} else {
3746		if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
3747			return -1;
3748		SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
3749	}
3750
3751	return 0;
3752#else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3753	return -1;
3754#endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3755}
3756
3757
3758int tls_get_library_version(char *buf, size_t buf_len)
3759{
3760	return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
3761			   OPENSSL_VERSION_TEXT,
3762			   SSLeay_version(SSLEAY_VERSION));
3763}
3764