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