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