• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * SSL/TLS interface functions for OpenSSL
3  * Copyright (c) 2004-2015, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  */
8 
9 #include "includes.h"
10 
11 #ifndef CONFIG_SMARTCARD
12 #ifndef OPENSSL_NO_ENGINE
13 #ifndef ANDROID
14 #define OPENSSL_NO_ENGINE
15 #endif
16 #endif
17 #endif
18 
19 #include <openssl/ssl.h>
20 #include <openssl/err.h>
21 #include <openssl/opensslv.h>
22 #include <openssl/pkcs12.h>
23 #include <openssl/x509v3.h>
24 #ifndef OPENSSL_NO_ENGINE
25 #include <openssl/engine.h>
26 #endif /* OPENSSL_NO_ENGINE */
27 #ifndef OPENSSL_NO_DSA
28 #include <openssl/dsa.h>
29 #endif
30 #ifndef OPENSSL_NO_DH
31 #include <openssl/dh.h>
32 #endif
33 
34 #include "common.h"
35 #include "crypto.h"
36 #include "sha1.h"
37 #include "sha256.h"
38 #include "tls.h"
39 #include "tls_openssl.h"
40 
41 #if !defined(CONFIG_FIPS) &&                             \
42     (defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) ||   \
43      defined(EAP_SERVER_FAST))
44 #define OPENSSL_NEED_EAP_FAST_PRF
45 #endif
46 
47 #if defined(OPENSSL_IS_BORINGSSL)
48 /* stack_index_t is the return type of OpenSSL's sk_XXX_num() functions. */
49 typedef size_t stack_index_t;
50 #else
51 typedef int stack_index_t;
52 #endif
53 
54 #ifdef SSL_set_tlsext_status_type
55 #ifndef OPENSSL_NO_TLSEXT
56 #define HAVE_OCSP
57 #include <openssl/ocsp.h>
58 #endif /* OPENSSL_NO_TLSEXT */
59 #endif /* SSL_set_tlsext_status_type */
60 
61 #if (OPENSSL_VERSION_NUMBER < 0x10100000L || \
62      (defined(LIBRESSL_VERSION_NUMBER) && \
63       LIBRESSL_VERSION_NUMBER < 0x20700000L)) && \
64     !defined(BORINGSSL_API_VERSION)
65 /*
66  * SSL_get_client_random() and SSL_get_server_random() were added in OpenSSL
67  * 1.1.0 and newer BoringSSL revisions. Provide compatibility wrappers for
68  * older versions.
69  */
70 
SSL_get_client_random(const SSL * ssl,unsigned char * out,size_t outlen)71 static size_t SSL_get_client_random(const SSL *ssl, unsigned char *out,
72 				    size_t outlen)
73 {
74 	if (!ssl->s3 || outlen < SSL3_RANDOM_SIZE)
75 		return 0;
76 	os_memcpy(out, ssl->s3->client_random, SSL3_RANDOM_SIZE);
77 	return SSL3_RANDOM_SIZE;
78 }
79 
80 
SSL_get_server_random(const SSL * ssl,unsigned char * out,size_t outlen)81 static size_t SSL_get_server_random(const SSL *ssl, unsigned char *out,
82 				    size_t outlen)
83 {
84 	if (!ssl->s3 || outlen < SSL3_RANDOM_SIZE)
85 		return 0;
86 	os_memcpy(out, ssl->s3->server_random, SSL3_RANDOM_SIZE);
87 	return SSL3_RANDOM_SIZE;
88 }
89 
90 
91 #ifdef OPENSSL_NEED_EAP_FAST_PRF
SSL_SESSION_get_master_key(const SSL_SESSION * session,unsigned char * out,size_t outlen)92 static size_t SSL_SESSION_get_master_key(const SSL_SESSION *session,
93 					 unsigned char *out, size_t outlen)
94 {
95 	if (!session || session->master_key_length < 0 ||
96 	    (size_t) session->master_key_length > outlen)
97 		return 0;
98 	if ((size_t) session->master_key_length < outlen)
99 		outlen = session->master_key_length;
100 	os_memcpy(out, session->master_key, outlen);
101 	return outlen;
102 }
103 #endif /* OPENSSL_NEED_EAP_FAST_PRF */
104 
105 #endif
106 
107 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
108 	(defined(LIBRESSL_VERSION_NUMBER) && \
109 	 LIBRESSL_VERSION_NUMBER < 0x20700000L)
110 #ifdef CONFIG_SUITEB
RSA_bits(const RSA * r)111 static int RSA_bits(const RSA *r)
112 {
113 	return BN_num_bits(r->n);
114 }
115 #endif /* CONFIG_SUITEB */
116 
117 
ASN1_STRING_get0_data(const ASN1_STRING * x)118 static const unsigned char * ASN1_STRING_get0_data(const ASN1_STRING *x)
119 {
120 	return ASN1_STRING_data((ASN1_STRING *) x);
121 }
122 #endif
123 
124 #ifdef ANDROID
125 #include <openssl/pem.h>
126 #include <keystore/keystore_get.h>
127 
128 #include <log/log.h>
129 #include <log/log_event_list.h>
130 
131 #define CERT_VALIDATION_FAILURE 210033
132 
log_cert_validation_failure(const char * reason)133 static void log_cert_validation_failure(const char *reason)
134 {
135 	android_log_context ctx = create_android_logger(CERT_VALIDATION_FAILURE);
136 	android_log_write_string8(ctx, reason);
137 	android_log_write_list(ctx, LOG_ID_SECURITY);
138 	android_log_destroy(&ctx);
139 }
140 
141 
BIO_from_keystore(const char * key)142 static BIO * BIO_from_keystore(const char *key)
143 {
144 	BIO *bio = NULL;
145 	uint8_t *value = NULL;
146 	int length = keystore_get(key, strlen(key), &value);
147 	if (length != -1 && (bio = BIO_new(BIO_s_mem())) != NULL)
148 		BIO_write(bio, value, length);
149 	free(value);
150 	return bio;
151 }
152 
153 
tls_add_ca_from_keystore(X509_STORE * ctx,const char * key_alias)154 static int tls_add_ca_from_keystore(X509_STORE *ctx, const char *key_alias)
155 {
156 	BIO *bio = BIO_from_keystore(key_alias);
157 	STACK_OF(X509_INFO) *stack = NULL;
158 	stack_index_t i;
159 
160 	if (bio) {
161 		stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
162 		BIO_free(bio);
163 	}
164 
165 	if (!stack) {
166 		wpa_printf(MSG_WARNING, "TLS: Failed to parse certificate: %s",
167 			   key_alias);
168 		return -1;
169 	}
170 
171 	for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
172 		X509_INFO *info = sk_X509_INFO_value(stack, i);
173 
174 		if (info->x509)
175 			X509_STORE_add_cert(ctx, info->x509);
176 		if (info->crl)
177 			X509_STORE_add_crl(ctx, info->crl);
178 	}
179 
180 	sk_X509_INFO_pop_free(stack, X509_INFO_free);
181 
182 	return 0;
183 }
184 
185 
tls_add_ca_from_keystore_encoded(X509_STORE * ctx,const char * encoded_key_alias)186 static int tls_add_ca_from_keystore_encoded(X509_STORE *ctx,
187 					    const char *encoded_key_alias)
188 {
189 	int rc = -1;
190 	int len = os_strlen(encoded_key_alias);
191 	unsigned char *decoded_alias;
192 
193 	if (len & 1) {
194 		wpa_printf(MSG_WARNING, "Invalid hex-encoded alias: %s",
195 			   encoded_key_alias);
196 		return rc;
197 	}
198 
199 	decoded_alias = os_malloc(len / 2 + 1);
200 	if (decoded_alias) {
201 		if (!hexstr2bin(encoded_key_alias, decoded_alias, len / 2)) {
202 			decoded_alias[len / 2] = '\0';
203 			rc = tls_add_ca_from_keystore(
204 				ctx, (const char *) decoded_alias);
205 		}
206 		os_free(decoded_alias);
207 	}
208 
209 	return rc;
210 }
211 
212 #endif /* ANDROID */
213 
214 static int tls_openssl_ref_count = 0;
215 static int tls_ex_idx_session = -1;
216 
217 struct tls_context {
218 	void (*event_cb)(void *ctx, enum tls_event ev,
219 			 union tls_event_data *data);
220 	void *cb_ctx;
221 	int cert_in_cb;
222 	char *ocsp_stapling_response;
223 };
224 
225 static struct tls_context *tls_global = NULL;
226 
227 
228 struct tls_data {
229 	SSL_CTX *ssl;
230 	unsigned int tls_session_lifetime;
231 	int check_crl;
232 	int check_crl_strict;
233 	char *ca_cert;
234 	unsigned int crl_reload_interval;
235 	struct os_reltime crl_last_reload;
236 	char *check_cert_subject;
237 };
238 
239 struct tls_connection {
240 	struct tls_context *context;
241 	struct tls_data *data;
242 	SSL_CTX *ssl_ctx;
243 	SSL *ssl;
244 	BIO *ssl_in, *ssl_out;
245 #if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
246 	ENGINE *engine;        /* functional reference to the engine */
247 	EVP_PKEY *private_key; /* the private key if using engine */
248 #endif /* OPENSSL_NO_ENGINE */
249 	char *subject_match, *altsubject_match, *suffix_match, *domain_match;
250 	char *check_cert_subject;
251 	int read_alerts, write_alerts, failed;
252 
253 	tls_session_ticket_cb session_ticket_cb;
254 	void *session_ticket_cb_ctx;
255 
256 	/* SessionTicket received from OpenSSL hello_extension_cb (server) */
257 	u8 *session_ticket;
258 	size_t session_ticket_len;
259 
260 	unsigned int ca_cert_verify:1;
261 	unsigned int cert_probe:1;
262 	unsigned int server_cert_only:1;
263 	unsigned int invalid_hb_used:1;
264 	unsigned int success_data:1;
265 	unsigned int client_hello_generated:1;
266 	unsigned int server:1;
267 
268 	u8 srv_cert_hash[32];
269 
270 	unsigned int flags;
271 
272 	X509 *peer_cert;
273 	X509 *peer_issuer;
274 	X509 *peer_issuer_issuer;
275 
276 	unsigned char client_random[SSL3_RANDOM_SIZE];
277 	unsigned char server_random[SSL3_RANDOM_SIZE];
278 
279 	u16 cipher_suite;
280 	int server_dh_prime_len;
281 };
282 
283 
tls_context_new(const struct tls_config * conf)284 static struct tls_context * tls_context_new(const struct tls_config *conf)
285 {
286 	struct tls_context *context = os_zalloc(sizeof(*context));
287 	if (context == NULL)
288 		return NULL;
289 	if (conf) {
290 		context->event_cb = conf->event_cb;
291 		context->cb_ctx = conf->cb_ctx;
292 		context->cert_in_cb = conf->cert_in_cb;
293 	}
294 	return context;
295 }
296 
297 
298 #ifdef CONFIG_NO_STDOUT_DEBUG
299 
_tls_show_errors(void)300 static void _tls_show_errors(void)
301 {
302 	unsigned long err;
303 
304 	while ((err = ERR_get_error())) {
305 		/* Just ignore the errors, since stdout is disabled */
306 	}
307 }
308 #define tls_show_errors(l, f, t) _tls_show_errors()
309 
310 #else /* CONFIG_NO_STDOUT_DEBUG */
311 
tls_show_errors(int level,const char * func,const char * txt)312 static void tls_show_errors(int level, const char *func, const char *txt)
313 {
314 	unsigned long err;
315 
316 	wpa_printf(level, "OpenSSL: %s - %s %s",
317 		   func, txt, ERR_error_string(ERR_get_error(), NULL));
318 
319 	while ((err = ERR_get_error())) {
320 		wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
321 			   ERR_error_string(err, NULL));
322 	}
323 }
324 
325 #endif /* CONFIG_NO_STDOUT_DEBUG */
326 
327 
tls_crl_cert_reload(const char * ca_cert,int check_crl)328 static X509_STORE * tls_crl_cert_reload(const char *ca_cert, int check_crl)
329 {
330 	int flags;
331 	X509_STORE *store;
332 
333 	store = X509_STORE_new();
334 	if (!store) {
335 		wpa_printf(MSG_DEBUG,
336 			   "OpenSSL: %s - failed to allocate new certificate store",
337 			   __func__);
338 		return NULL;
339 	}
340 
341 	if (ca_cert && X509_STORE_load_locations(store, ca_cert, NULL) != 1) {
342 		tls_show_errors(MSG_WARNING, __func__,
343 				"Failed to load root certificates");
344 		X509_STORE_free(store);
345 		return NULL;
346 	}
347 
348 	flags = check_crl ? X509_V_FLAG_CRL_CHECK : 0;
349 	if (check_crl == 2)
350 		flags |= X509_V_FLAG_CRL_CHECK_ALL;
351 
352 	X509_STORE_set_flags(store, flags);
353 
354 	return store;
355 }
356 
357 
358 #ifdef CONFIG_NATIVE_WINDOWS
359 
360 /* Windows CryptoAPI and access to certificate stores */
361 #include <wincrypt.h>
362 
363 #ifdef __MINGW32_VERSION
364 /*
365  * MinGW does not yet include all the needed definitions for CryptoAPI, so
366  * define here whatever extra is needed.
367  */
368 #define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
369 #define CERT_STORE_READONLY_FLAG 0x00008000
370 #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
371 
372 #endif /* __MINGW32_VERSION */
373 
374 
375 struct cryptoapi_rsa_data {
376 	const CERT_CONTEXT *cert;
377 	HCRYPTPROV crypt_prov;
378 	DWORD key_spec;
379 	BOOL free_crypt_prov;
380 };
381 
382 
cryptoapi_error(const char * msg)383 static void cryptoapi_error(const char *msg)
384 {
385 	wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
386 		   msg, (unsigned int) GetLastError());
387 }
388 
389 
cryptoapi_rsa_pub_enc(int flen,const unsigned char * from,unsigned char * to,RSA * rsa,int padding)390 static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
391 				 unsigned char *to, RSA *rsa, int padding)
392 {
393 	wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
394 	return 0;
395 }
396 
397 
cryptoapi_rsa_pub_dec(int flen,const unsigned char * from,unsigned char * to,RSA * rsa,int padding)398 static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
399 				 unsigned char *to, RSA *rsa, int padding)
400 {
401 	wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
402 	return 0;
403 }
404 
405 
cryptoapi_rsa_priv_enc(int flen,const unsigned char * from,unsigned char * to,RSA * rsa,int padding)406 static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
407 				  unsigned char *to, RSA *rsa, int padding)
408 {
409 	struct cryptoapi_rsa_data *priv =
410 		(struct cryptoapi_rsa_data *) rsa->meth->app_data;
411 	HCRYPTHASH hash;
412 	DWORD hash_size, len, i;
413 	unsigned char *buf = NULL;
414 	int ret = 0;
415 
416 	if (priv == NULL) {
417 		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
418 		       ERR_R_PASSED_NULL_PARAMETER);
419 		return 0;
420 	}
421 
422 	if (padding != RSA_PKCS1_PADDING) {
423 		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
424 		       RSA_R_UNKNOWN_PADDING_TYPE);
425 		return 0;
426 	}
427 
428 	if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
429 		wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
430 			   __func__);
431 		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
432 		       RSA_R_INVALID_MESSAGE_LENGTH);
433 		return 0;
434 	}
435 
436 	if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
437 	{
438 		cryptoapi_error("CryptCreateHash failed");
439 		return 0;
440 	}
441 
442 	len = sizeof(hash_size);
443 	if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
444 			       0)) {
445 		cryptoapi_error("CryptGetHashParam failed");
446 		goto err;
447 	}
448 
449 	if ((int) hash_size != flen) {
450 		wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
451 			   (unsigned) hash_size, flen);
452 		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
453 		       RSA_R_INVALID_MESSAGE_LENGTH);
454 		goto err;
455 	}
456 	if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
457 		cryptoapi_error("CryptSetHashParam failed");
458 		goto err;
459 	}
460 
461 	len = RSA_size(rsa);
462 	buf = os_malloc(len);
463 	if (buf == NULL) {
464 		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
465 		goto err;
466 	}
467 
468 	if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
469 		cryptoapi_error("CryptSignHash failed");
470 		goto err;
471 	}
472 
473 	for (i = 0; i < len; i++)
474 		to[i] = buf[len - i - 1];
475 	ret = len;
476 
477 err:
478 	os_free(buf);
479 	CryptDestroyHash(hash);
480 
481 	return ret;
482 }
483 
484 
cryptoapi_rsa_priv_dec(int flen,const unsigned char * from,unsigned char * to,RSA * rsa,int padding)485 static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
486 				  unsigned char *to, RSA *rsa, int padding)
487 {
488 	wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
489 	return 0;
490 }
491 
492 
cryptoapi_free_data(struct cryptoapi_rsa_data * priv)493 static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
494 {
495 	if (priv == NULL)
496 		return;
497 	if (priv->crypt_prov && priv->free_crypt_prov)
498 		CryptReleaseContext(priv->crypt_prov, 0);
499 	if (priv->cert)
500 		CertFreeCertificateContext(priv->cert);
501 	os_free(priv);
502 }
503 
504 
cryptoapi_finish(RSA * rsa)505 static int cryptoapi_finish(RSA *rsa)
506 {
507 	cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
508 	os_free((void *) rsa->meth);
509 	rsa->meth = NULL;
510 	return 1;
511 }
512 
513 
cryptoapi_find_cert(const char * name,DWORD store)514 static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
515 {
516 	HCERTSTORE cs;
517 	const CERT_CONTEXT *ret = NULL;
518 
519 	cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
520 			   store | CERT_STORE_OPEN_EXISTING_FLAG |
521 			   CERT_STORE_READONLY_FLAG, L"MY");
522 	if (cs == NULL) {
523 		cryptoapi_error("Failed to open 'My system store'");
524 		return NULL;
525 	}
526 
527 	if (strncmp(name, "cert://", 7) == 0) {
528 		unsigned short wbuf[255];
529 		MultiByteToWideChar(CP_ACP, 0, name + 7, -1, wbuf, 255);
530 		ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
531 						 PKCS_7_ASN_ENCODING,
532 						 0, CERT_FIND_SUBJECT_STR,
533 						 wbuf, NULL);
534 	} else if (strncmp(name, "hash://", 7) == 0) {
535 		CRYPT_HASH_BLOB blob;
536 		int len;
537 		const char *hash = name + 7;
538 		unsigned char *buf;
539 
540 		len = os_strlen(hash) / 2;
541 		buf = os_malloc(len);
542 		if (buf && hexstr2bin(hash, buf, len) == 0) {
543 			blob.cbData = len;
544 			blob.pbData = buf;
545 			ret = CertFindCertificateInStore(cs,
546 							 X509_ASN_ENCODING |
547 							 PKCS_7_ASN_ENCODING,
548 							 0, CERT_FIND_HASH,
549 							 &blob, NULL);
550 		}
551 		os_free(buf);
552 	}
553 
554 	CertCloseStore(cs, 0);
555 
556 	return ret;
557 }
558 
559 
tls_cryptoapi_cert(SSL * ssl,const char * name)560 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
561 {
562 	X509 *cert = NULL;
563 	RSA *rsa = NULL, *pub_rsa;
564 	struct cryptoapi_rsa_data *priv;
565 	RSA_METHOD *rsa_meth;
566 
567 	if (name == NULL ||
568 	    (strncmp(name, "cert://", 7) != 0 &&
569 	     strncmp(name, "hash://", 7) != 0))
570 		return -1;
571 
572 	priv = os_zalloc(sizeof(*priv));
573 	rsa_meth = os_zalloc(sizeof(*rsa_meth));
574 	if (priv == NULL || rsa_meth == NULL) {
575 		wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
576 			   "for CryptoAPI RSA method");
577 		os_free(priv);
578 		os_free(rsa_meth);
579 		return -1;
580 	}
581 
582 	priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
583 	if (priv->cert == NULL) {
584 		priv->cert = cryptoapi_find_cert(
585 			name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
586 	}
587 	if (priv->cert == NULL) {
588 		wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
589 			   "'%s'", name);
590 		goto err;
591 	}
592 
593 	cert = d2i_X509(NULL,
594 			(const unsigned char **) &priv->cert->pbCertEncoded,
595 			priv->cert->cbCertEncoded);
596 	if (cert == NULL) {
597 		wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
598 			   "encoding");
599 		goto err;
600 	}
601 
602 	if (!CryptAcquireCertificatePrivateKey(priv->cert,
603 					       CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
604 					       NULL, &priv->crypt_prov,
605 					       &priv->key_spec,
606 					       &priv->free_crypt_prov)) {
607 		cryptoapi_error("Failed to acquire a private key for the "
608 				"certificate");
609 		goto err;
610 	}
611 
612 	rsa_meth->name = "Microsoft CryptoAPI RSA Method";
613 	rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
614 	rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
615 	rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
616 	rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
617 	rsa_meth->finish = cryptoapi_finish;
618 	rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
619 	rsa_meth->app_data = (char *) priv;
620 
621 	rsa = RSA_new();
622 	if (rsa == NULL) {
623 		SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
624 		       ERR_R_MALLOC_FAILURE);
625 		goto err;
626 	}
627 
628 	if (!SSL_use_certificate(ssl, cert)) {
629 		RSA_free(rsa);
630 		rsa = NULL;
631 		goto err;
632 	}
633 	pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
634 	X509_free(cert);
635 	cert = NULL;
636 
637 	rsa->n = BN_dup(pub_rsa->n);
638 	rsa->e = BN_dup(pub_rsa->e);
639 	if (!RSA_set_method(rsa, rsa_meth))
640 		goto err;
641 
642 	if (!SSL_use_RSAPrivateKey(ssl, rsa))
643 		goto err;
644 	RSA_free(rsa);
645 
646 	return 0;
647 
648 err:
649 	if (cert)
650 		X509_free(cert);
651 	if (rsa)
652 		RSA_free(rsa);
653 	else {
654 		os_free(rsa_meth);
655 		cryptoapi_free_data(priv);
656 	}
657 	return -1;
658 }
659 
660 
tls_cryptoapi_ca_cert(SSL_CTX * ssl_ctx,SSL * ssl,const char * name)661 static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
662 {
663 	HCERTSTORE cs;
664 	PCCERT_CONTEXT ctx = NULL;
665 	X509 *cert;
666 	char buf[128];
667 	const char *store;
668 #ifdef UNICODE
669 	WCHAR *wstore;
670 #endif /* UNICODE */
671 
672 	if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
673 		return -1;
674 
675 	store = name + 13;
676 #ifdef UNICODE
677 	wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
678 	if (wstore == NULL)
679 		return -1;
680 	wsprintf(wstore, L"%S", store);
681 	cs = CertOpenSystemStore(0, wstore);
682 	os_free(wstore);
683 #else /* UNICODE */
684 	cs = CertOpenSystemStore(0, store);
685 #endif /* UNICODE */
686 	if (cs == NULL) {
687 		wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
688 			   "'%s': error=%d", __func__, store,
689 			   (int) GetLastError());
690 		return -1;
691 	}
692 
693 	while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
694 		cert = d2i_X509(NULL,
695 				(const unsigned char **) &ctx->pbCertEncoded,
696 				ctx->cbCertEncoded);
697 		if (cert == NULL) {
698 			wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
699 				   "X509 DER encoding for CA cert");
700 			continue;
701 		}
702 
703 		X509_NAME_oneline(X509_get_subject_name(cert), buf,
704 				  sizeof(buf));
705 		wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
706 			   "system certificate store: subject='%s'", buf);
707 
708 		if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx),
709 					 cert)) {
710 			tls_show_errors(MSG_WARNING, __func__,
711 					"Failed to add ca_cert to OpenSSL "
712 					"certificate store");
713 		}
714 
715 		X509_free(cert);
716 	}
717 
718 	if (!CertCloseStore(cs, 0)) {
719 		wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
720 			   "'%s': error=%d", __func__, name + 13,
721 			   (int) GetLastError());
722 	}
723 
724 	return 0;
725 }
726 
727 
728 #else /* CONFIG_NATIVE_WINDOWS */
729 
tls_cryptoapi_cert(SSL * ssl,const char * name)730 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
731 {
732 	return -1;
733 }
734 
735 #endif /* CONFIG_NATIVE_WINDOWS */
736 
737 
ssl_info_cb(const SSL * ssl,int where,int ret)738 static void ssl_info_cb(const SSL *ssl, int where, int ret)
739 {
740 	const char *str;
741 	int w;
742 
743 	wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
744 	w = where & ~SSL_ST_MASK;
745 	if (w & SSL_ST_CONNECT)
746 		str = "SSL_connect";
747 	else if (w & SSL_ST_ACCEPT)
748 		str = "SSL_accept";
749 	else
750 		str = "undefined";
751 
752 	if (where & SSL_CB_LOOP) {
753 		wpa_printf(MSG_DEBUG, "SSL: %s:%s",
754 			   str, SSL_state_string_long(ssl));
755 	} else if (where & SSL_CB_ALERT) {
756 		struct tls_connection *conn = SSL_get_app_data((SSL *) ssl);
757 		wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
758 			   where & SSL_CB_READ ?
759 			   "read (remote end reported an error)" :
760 			   "write (local SSL3 detected an error)",
761 			   SSL_alert_type_string_long(ret),
762 			   SSL_alert_desc_string_long(ret));
763 		if ((ret >> 8) == SSL3_AL_FATAL) {
764 			if (where & SSL_CB_READ)
765 				conn->read_alerts++;
766 			else
767 				conn->write_alerts++;
768 		}
769 		if (conn->context->event_cb != NULL) {
770 			union tls_event_data ev;
771 			struct tls_context *context = conn->context;
772 			os_memset(&ev, 0, sizeof(ev));
773 			ev.alert.is_local = !(where & SSL_CB_READ);
774 			ev.alert.type = SSL_alert_type_string_long(ret);
775 			ev.alert.description = SSL_alert_desc_string_long(ret);
776 			context->event_cb(context->cb_ctx, TLS_ALERT, &ev);
777 		}
778 	} else if (where & SSL_CB_EXIT && ret <= 0) {
779 		wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
780 			   str, ret == 0 ? "failed" : "error",
781 			   SSL_state_string_long(ssl));
782 	}
783 }
784 
785 
786 #ifndef OPENSSL_NO_ENGINE
787 /**
788  * tls_engine_load_dynamic_generic - load any openssl engine
789  * @pre: an array of commands and values that load an engine initialized
790  *       in the engine specific function
791  * @post: an array of commands and values that initialize an already loaded
792  *        engine (or %NULL if not required)
793  * @id: the engine id of the engine to load (only required if post is not %NULL
794  *
795  * This function is a generic function that loads any openssl engine.
796  *
797  * Returns: 0 on success, -1 on failure
798  */
tls_engine_load_dynamic_generic(const char * pre[],const char * post[],const char * id)799 static int tls_engine_load_dynamic_generic(const char *pre[],
800 					   const char *post[], const char *id)
801 {
802 	ENGINE *engine;
803 	const char *dynamic_id = "dynamic";
804 
805 	engine = ENGINE_by_id(id);
806 	if (engine) {
807 		wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
808 			   "available", id);
809 		/*
810 		 * If it was auto-loaded by ENGINE_by_id() we might still
811 		 * need to tell it which PKCS#11 module to use in legacy
812 		 * (non-p11-kit) environments. Do so now; even if it was
813 		 * properly initialised before, setting it again will be
814 		 * harmless.
815 		 */
816 		goto found;
817 	}
818 	ERR_clear_error();
819 
820 	engine = ENGINE_by_id(dynamic_id);
821 	if (engine == NULL) {
822 		wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
823 			   dynamic_id,
824 			   ERR_error_string(ERR_get_error(), NULL));
825 		return -1;
826 	}
827 
828 	/* Perform the pre commands. This will load the engine. */
829 	while (pre && pre[0]) {
830 		wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
831 		if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
832 			wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
833 				   "%s %s [%s]", pre[0], pre[1],
834 				   ERR_error_string(ERR_get_error(), NULL));
835 			ENGINE_free(engine);
836 			return -1;
837 		}
838 		pre += 2;
839 	}
840 
841 	/*
842 	 * Free the reference to the "dynamic" engine. The loaded engine can
843 	 * now be looked up using ENGINE_by_id().
844 	 */
845 	ENGINE_free(engine);
846 
847 	engine = ENGINE_by_id(id);
848 	if (engine == NULL) {
849 		wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
850 			   id, ERR_error_string(ERR_get_error(), NULL));
851 		return -1;
852 	}
853  found:
854 	while (post && post[0]) {
855 		wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
856 		if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
857 			wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
858 				" %s %s [%s]", post[0], post[1],
859 				   ERR_error_string(ERR_get_error(), NULL));
860 			ENGINE_remove(engine);
861 			ENGINE_free(engine);
862 			return -1;
863 		}
864 		post += 2;
865 	}
866 	ENGINE_free(engine);
867 
868 	return 0;
869 }
870 
871 
872 /**
873  * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
874  * @pkcs11_so_path: pksc11_so_path from the configuration
875  * @pcks11_module_path: pkcs11_module_path from the configuration
876  */
tls_engine_load_dynamic_pkcs11(const char * pkcs11_so_path,const char * pkcs11_module_path)877 static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
878 					  const char *pkcs11_module_path)
879 {
880 	char *engine_id = "pkcs11";
881 	const char *pre_cmd[] = {
882 		"SO_PATH", NULL /* pkcs11_so_path */,
883 		"ID", NULL /* engine_id */,
884 		"LIST_ADD", "1",
885 		/* "NO_VCHECK", "1", */
886 		"LOAD", NULL,
887 		NULL, NULL
888 	};
889 	const char *post_cmd[] = {
890 		"MODULE_PATH", NULL /* pkcs11_module_path */,
891 		NULL, NULL
892 	};
893 
894 	if (!pkcs11_so_path)
895 		return 0;
896 
897 	pre_cmd[1] = pkcs11_so_path;
898 	pre_cmd[3] = engine_id;
899 	if (pkcs11_module_path)
900 		post_cmd[1] = pkcs11_module_path;
901 	else
902 		post_cmd[0] = NULL;
903 
904 	wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
905 		   pkcs11_so_path);
906 
907 	return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
908 }
909 
910 
911 /**
912  * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
913  * @opensc_so_path: opensc_so_path from the configuration
914  */
tls_engine_load_dynamic_opensc(const char * opensc_so_path)915 static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
916 {
917 	char *engine_id = "opensc";
918 	const char *pre_cmd[] = {
919 		"SO_PATH", NULL /* opensc_so_path */,
920 		"ID", NULL /* engine_id */,
921 		"LIST_ADD", "1",
922 		"LOAD", NULL,
923 		NULL, NULL
924 	};
925 
926 	if (!opensc_so_path)
927 		return 0;
928 
929 	pre_cmd[1] = opensc_so_path;
930 	pre_cmd[3] = engine_id;
931 
932 	wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
933 		   opensc_so_path);
934 
935 	return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
936 }
937 #endif /* OPENSSL_NO_ENGINE */
938 
939 
remove_session_cb(SSL_CTX * ctx,SSL_SESSION * sess)940 static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *sess)
941 {
942 	struct wpabuf *buf;
943 
944 	if (tls_ex_idx_session < 0)
945 		return;
946 	buf = SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
947 	if (!buf)
948 		return;
949 	wpa_printf(MSG_DEBUG,
950 		   "OpenSSL: Free application session data %p (sess %p)",
951 		   buf, sess);
952 	wpabuf_free(buf);
953 
954 	SSL_SESSION_set_ex_data(sess, tls_ex_idx_session, NULL);
955 }
956 
957 
tls_init(const struct tls_config * conf)958 void * tls_init(const struct tls_config *conf)
959 {
960 	struct tls_data *data;
961 	SSL_CTX *ssl;
962 	struct tls_context *context;
963 	const char *ciphers;
964 
965 	if (tls_openssl_ref_count == 0) {
966 		tls_global = context = tls_context_new(conf);
967 		if (context == NULL)
968 			return NULL;
969 #ifdef CONFIG_FIPS
970 #ifdef OPENSSL_FIPS
971 		if (conf && conf->fips_mode) {
972 			static int fips_enabled = 0;
973 
974 			if (!fips_enabled && !FIPS_mode_set(1)) {
975 				wpa_printf(MSG_ERROR, "Failed to enable FIPS "
976 					   "mode");
977 				ERR_load_crypto_strings();
978 				ERR_print_errors_fp(stderr);
979 				os_free(tls_global);
980 				tls_global = NULL;
981 				return NULL;
982 			} else {
983 				wpa_printf(MSG_INFO, "Running in FIPS mode");
984 				fips_enabled = 1;
985 			}
986 		}
987 #else /* OPENSSL_FIPS */
988 		if (conf && conf->fips_mode) {
989 			wpa_printf(MSG_ERROR, "FIPS mode requested, but not "
990 				   "supported");
991 			os_free(tls_global);
992 			tls_global = NULL;
993 			return NULL;
994 		}
995 #endif /* OPENSSL_FIPS */
996 #endif /* CONFIG_FIPS */
997 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
998 	(defined(LIBRESSL_VERSION_NUMBER) && \
999 	 LIBRESSL_VERSION_NUMBER < 0x20700000L)
1000 		SSL_load_error_strings();
1001 		SSL_library_init();
1002 #ifndef OPENSSL_NO_SHA256
1003 		EVP_add_digest(EVP_sha256());
1004 #endif /* OPENSSL_NO_SHA256 */
1005 		/* TODO: if /dev/urandom is available, PRNG is seeded
1006 		 * automatically. If this is not the case, random data should
1007 		 * be added here. */
1008 
1009 #ifdef PKCS12_FUNCS
1010 #ifndef OPENSSL_NO_RC2
1011 		/*
1012 		 * 40-bit RC2 is commonly used in PKCS#12 files, so enable it.
1013 		 * This is enabled by PKCS12_PBE_add() in OpenSSL 0.9.8
1014 		 * versions, but it looks like OpenSSL 1.0.0 does not do that
1015 		 * anymore.
1016 		 */
1017 		EVP_add_cipher(EVP_rc2_40_cbc());
1018 #endif /* OPENSSL_NO_RC2 */
1019 		PKCS12_PBE_add();
1020 #endif  /* PKCS12_FUNCS */
1021 #endif /* < 1.1.0 */
1022 	} else {
1023 		context = tls_context_new(conf);
1024 		if (context == NULL)
1025 			return NULL;
1026 	}
1027 	tls_openssl_ref_count++;
1028 
1029 	data = os_zalloc(sizeof(*data));
1030 	if (data)
1031 		ssl = SSL_CTX_new(SSLv23_method());
1032 	else
1033 		ssl = NULL;
1034 	if (ssl == NULL) {
1035 		tls_openssl_ref_count--;
1036 		if (context != tls_global)
1037 			os_free(context);
1038 		if (tls_openssl_ref_count == 0) {
1039 			os_free(tls_global);
1040 			tls_global = NULL;
1041 		}
1042 		os_free(data);
1043 		return NULL;
1044 	}
1045 	data->ssl = ssl;
1046 	if (conf) {
1047 		data->tls_session_lifetime = conf->tls_session_lifetime;
1048 		data->crl_reload_interval = conf->crl_reload_interval;
1049 	}
1050 
1051 	SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv2);
1052 	SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv3);
1053 
1054 #ifdef SSL_MODE_NO_AUTO_CHAIN
1055 	/* Number of deployed use cases assume the default OpenSSL behavior of
1056 	 * auto chaining the local certificate is in use. BoringSSL removed this
1057 	 * functionality by default, so we need to restore it here to avoid
1058 	 * breaking existing use cases. */
1059 	SSL_CTX_clear_mode(ssl, SSL_MODE_NO_AUTO_CHAIN);
1060 #endif /* SSL_MODE_NO_AUTO_CHAIN */
1061 
1062 	SSL_CTX_set_info_callback(ssl, ssl_info_cb);
1063 	SSL_CTX_set_app_data(ssl, context);
1064 	if (data->tls_session_lifetime > 0) {
1065 		SSL_CTX_set_quiet_shutdown(ssl, 1);
1066 		/*
1067 		 * Set default context here. In practice, this will be replaced
1068 		 * by the per-EAP method context in tls_connection_set_verify().
1069 		 */
1070 		SSL_CTX_set_session_id_context(ssl, (u8 *) "hostapd", 7);
1071 		SSL_CTX_set_session_cache_mode(ssl, SSL_SESS_CACHE_SERVER);
1072 		SSL_CTX_set_timeout(ssl, data->tls_session_lifetime);
1073 		SSL_CTX_sess_set_remove_cb(ssl, remove_session_cb);
1074 	} else {
1075 		SSL_CTX_set_session_cache_mode(ssl, SSL_SESS_CACHE_OFF);
1076 	}
1077 
1078 	if (tls_ex_idx_session < 0) {
1079 		tls_ex_idx_session = SSL_SESSION_get_ex_new_index(
1080 			0, NULL, NULL, NULL, NULL);
1081 		if (tls_ex_idx_session < 0) {
1082 			tls_deinit(data);
1083 			return NULL;
1084 		}
1085 	}
1086 
1087 #ifndef OPENSSL_NO_ENGINE
1088 	wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
1089 #if OPENSSL_VERSION_NUMBER < 0x10100000L
1090 	ERR_load_ENGINE_strings();
1091 	ENGINE_load_dynamic();
1092 #endif /* OPENSSL_VERSION_NUMBER */
1093 
1094 	if (conf &&
1095 	    (conf->opensc_engine_path || conf->pkcs11_engine_path ||
1096 	     conf->pkcs11_module_path)) {
1097 		if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
1098 		    tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
1099 						   conf->pkcs11_module_path)) {
1100 			tls_deinit(data);
1101 			return NULL;
1102 		}
1103 	}
1104 #endif /* OPENSSL_NO_ENGINE */
1105 
1106 	if (conf && conf->openssl_ciphers)
1107 		ciphers = conf->openssl_ciphers;
1108 	else
1109 		ciphers = TLS_DEFAULT_CIPHERS;
1110 	if (SSL_CTX_set_cipher_list(ssl, ciphers) != 1) {
1111 		wpa_printf(MSG_ERROR,
1112 			   "OpenSSL: Failed to set cipher string '%s'",
1113 			   ciphers);
1114 		tls_deinit(data);
1115 		return NULL;
1116 	}
1117 
1118 	return data;
1119 }
1120 
1121 
tls_deinit(void * ssl_ctx)1122 void tls_deinit(void *ssl_ctx)
1123 {
1124 	struct tls_data *data = ssl_ctx;
1125 	SSL_CTX *ssl = data->ssl;
1126 	struct tls_context *context = SSL_CTX_get_app_data(ssl);
1127 	if (context != tls_global)
1128 		os_free(context);
1129 	if (data->tls_session_lifetime > 0)
1130 		SSL_CTX_flush_sessions(ssl, 0);
1131 	os_free(data->ca_cert);
1132 	SSL_CTX_free(ssl);
1133 
1134 	tls_openssl_ref_count--;
1135 	if (tls_openssl_ref_count == 0) {
1136 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
1137 	(defined(LIBRESSL_VERSION_NUMBER) && \
1138 	 LIBRESSL_VERSION_NUMBER < 0x20700000L)
1139 #ifndef OPENSSL_NO_ENGINE
1140 		ENGINE_cleanup();
1141 #endif /* OPENSSL_NO_ENGINE */
1142 		CRYPTO_cleanup_all_ex_data();
1143 		ERR_remove_thread_state(NULL);
1144 		ERR_free_strings();
1145 		EVP_cleanup();
1146 #endif /* < 1.1.0 */
1147 		os_free(tls_global->ocsp_stapling_response);
1148 		tls_global->ocsp_stapling_response = NULL;
1149 		os_free(tls_global);
1150 		tls_global = NULL;
1151 	}
1152 
1153 	os_free(data->check_cert_subject);
1154 	os_free(data);
1155 }
1156 
1157 
1158 #ifndef OPENSSL_NO_ENGINE
1159 
1160 /* Cryptoki return values */
1161 #define CKR_PIN_INCORRECT 0x000000a0
1162 #define CKR_PIN_INVALID 0x000000a1
1163 #define CKR_PIN_LEN_RANGE 0x000000a2
1164 
1165 /* libp11 */
1166 #define ERR_LIB_PKCS11	ERR_LIB_USER
1167 
tls_is_pin_error(unsigned int err)1168 static int tls_is_pin_error(unsigned int err)
1169 {
1170 	return ERR_GET_LIB(err) == ERR_LIB_PKCS11 &&
1171 		(ERR_GET_REASON(err) == CKR_PIN_INCORRECT ||
1172 		 ERR_GET_REASON(err) == CKR_PIN_INVALID ||
1173 		 ERR_GET_REASON(err) == CKR_PIN_LEN_RANGE);
1174 }
1175 
1176 #endif /* OPENSSL_NO_ENGINE */
1177 
1178 
1179 #ifdef ANDROID
1180 /* EVP_PKEY_from_keystore comes from system/security/keystore-engine. */
1181 EVP_PKEY * EVP_PKEY_from_keystore(const char *key_id);
1182 #endif /* ANDROID */
1183 
tls_engine_init(struct tls_connection * conn,const char * engine_id,const char * pin,const char * key_id,const char * cert_id,const char * ca_cert_id)1184 static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
1185 			   const char *pin, const char *key_id,
1186 			   const char *cert_id, const char *ca_cert_id)
1187 {
1188 #if defined(ANDROID) && defined(OPENSSL_IS_BORINGSSL)
1189 #if !defined(OPENSSL_NO_ENGINE)
1190 #error "This code depends on OPENSSL_NO_ENGINE being defined by BoringSSL."
1191 #endif
1192 	if (!key_id)
1193 		return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1194 	conn->engine = NULL;
1195 	conn->private_key = EVP_PKEY_from_keystore(key_id);
1196 	if (!conn->private_key) {
1197 		wpa_printf(MSG_ERROR,
1198 			   "ENGINE: cannot load private key with id '%s' [%s]",
1199 			   key_id,
1200 			   ERR_error_string(ERR_get_error(), NULL));
1201 		return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1202 	}
1203 #endif /* ANDROID && OPENSSL_IS_BORINGSSL */
1204 
1205 #ifndef OPENSSL_NO_ENGINE
1206 	int ret = -1;
1207 	if (engine_id == NULL) {
1208 		wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
1209 		return -1;
1210 	}
1211 
1212 	ERR_clear_error();
1213 #ifdef ANDROID
1214 	ENGINE_load_dynamic();
1215 #endif
1216 	conn->engine = ENGINE_by_id(engine_id);
1217 	if (!conn->engine) {
1218 		wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
1219 			   engine_id, ERR_error_string(ERR_get_error(), NULL));
1220 		goto err;
1221 	}
1222 	if (ENGINE_init(conn->engine) != 1) {
1223 		wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
1224 			   "(engine: %s) [%s]", engine_id,
1225 			   ERR_error_string(ERR_get_error(), NULL));
1226 		goto err;
1227 	}
1228 	wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
1229 
1230 #ifndef ANDROID
1231 	if (pin && ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
1232 		wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
1233 			   ERR_error_string(ERR_get_error(), NULL));
1234 		goto err;
1235 	}
1236 #endif
1237 	if (key_id) {
1238 		/*
1239 		 * Ensure that the ENGINE does not attempt to use the OpenSSL
1240 		 * UI system to obtain a PIN, if we didn't provide one.
1241 		 */
1242 		struct {
1243 			const void *password;
1244 			const char *prompt_info;
1245 		} key_cb = { "", NULL };
1246 
1247 		/* load private key first in-case PIN is required for cert */
1248 		conn->private_key = ENGINE_load_private_key(conn->engine,
1249 							    key_id, NULL,
1250 							    &key_cb);
1251 		if (!conn->private_key) {
1252 			unsigned long err = ERR_get_error();
1253 
1254 			wpa_printf(MSG_ERROR,
1255 				   "ENGINE: cannot load private key with id '%s' [%s]",
1256 				   key_id,
1257 				   ERR_error_string(err, NULL));
1258 			if (tls_is_pin_error(err))
1259 				ret = TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
1260 			else
1261 				ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1262 			goto err;
1263 		}
1264 	}
1265 
1266 	/* handle a certificate and/or CA certificate */
1267 	if (cert_id || ca_cert_id) {
1268 		const char *cmd_name = "LOAD_CERT_CTRL";
1269 
1270 		/* test if the engine supports a LOAD_CERT_CTRL */
1271 		if (!ENGINE_ctrl(conn->engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
1272 				 0, (void *)cmd_name, NULL)) {
1273 			wpa_printf(MSG_ERROR, "ENGINE: engine does not support"
1274 				   " loading certificates");
1275 			ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1276 			goto err;
1277 		}
1278 	}
1279 
1280 	return 0;
1281 
1282 err:
1283 	if (conn->engine) {
1284 		ENGINE_free(conn->engine);
1285 		conn->engine = NULL;
1286 	}
1287 
1288 	if (conn->private_key) {
1289 		EVP_PKEY_free(conn->private_key);
1290 		conn->private_key = NULL;
1291 	}
1292 
1293 	return ret;
1294 #else /* OPENSSL_NO_ENGINE */
1295 	return 0;
1296 #endif /* OPENSSL_NO_ENGINE */
1297 }
1298 
1299 
tls_engine_deinit(struct tls_connection * conn)1300 static void tls_engine_deinit(struct tls_connection *conn)
1301 {
1302 #if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
1303 	wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
1304 	if (conn->private_key) {
1305 		EVP_PKEY_free(conn->private_key);
1306 		conn->private_key = NULL;
1307 	}
1308 	if (conn->engine) {
1309 #if !defined(OPENSSL_IS_BORINGSSL)
1310 		ENGINE_finish(conn->engine);
1311 #endif /* !OPENSSL_IS_BORINGSSL */
1312 		conn->engine = NULL;
1313 	}
1314 #endif /* ANDROID || !OPENSSL_NO_ENGINE */
1315 }
1316 
1317 
tls_get_errors(void * ssl_ctx)1318 int tls_get_errors(void *ssl_ctx)
1319 {
1320 	int count = 0;
1321 	unsigned long err;
1322 
1323 	while ((err = ERR_get_error())) {
1324 		wpa_printf(MSG_INFO, "TLS - SSL error: %s",
1325 			   ERR_error_string(err, NULL));
1326 		count++;
1327 	}
1328 
1329 	return count;
1330 }
1331 
1332 
openssl_content_type(int content_type)1333 static const char * openssl_content_type(int content_type)
1334 {
1335 	switch (content_type) {
1336 	case 20:
1337 		return "change cipher spec";
1338 	case 21:
1339 		return "alert";
1340 	case 22:
1341 		return "handshake";
1342 	case 23:
1343 		return "application data";
1344 	case 24:
1345 		return "heartbeat";
1346 	case 256:
1347 		return "TLS header info"; /* pseudo content type */
1348 	default:
1349 		return "?";
1350 	}
1351 }
1352 
1353 
openssl_handshake_type(int content_type,const u8 * buf,size_t len)1354 static const char * openssl_handshake_type(int content_type, const u8 *buf,
1355 					   size_t len)
1356 {
1357 	if (content_type != 22 || !buf || len == 0)
1358 		return "";
1359 	switch (buf[0]) {
1360 	case 0:
1361 		return "hello request";
1362 	case 1:
1363 		return "client hello";
1364 	case 2:
1365 		return "server hello";
1366 	case 3:
1367 		return "hello verify request";
1368 	case 4:
1369 		return "new session ticket";
1370 	case 5:
1371 		return "end of early data";
1372 	case 6:
1373 		return "hello retry request";
1374 	case 8:
1375 		return "encrypted extensions";
1376 	case 11:
1377 		return "certificate";
1378 	case 12:
1379 		return "server key exchange";
1380 	case 13:
1381 		return "certificate request";
1382 	case 14:
1383 		return "server hello done";
1384 	case 15:
1385 		return "certificate verify";
1386 	case 16:
1387 		return "client key exchange";
1388 	case 20:
1389 		return "finished";
1390 	case 21:
1391 		return "certificate url";
1392 	case 22:
1393 		return "certificate status";
1394 	case 23:
1395 		return "supplemental data";
1396 	case 24:
1397 		return "key update";
1398 	case 254:
1399 		return "message hash";
1400 	default:
1401 		return "?";
1402 	}
1403 }
1404 
1405 
1406 #ifdef CONFIG_SUITEB
1407 
check_server_hello(struct tls_connection * conn,const u8 * pos,const u8 * end)1408 static void check_server_hello(struct tls_connection *conn,
1409 			       const u8 *pos, const u8 *end)
1410 {
1411 	size_t payload_len, id_len;
1412 
1413 	/*
1414 	 * Parse ServerHello to get the selected cipher suite since OpenSSL does
1415 	 * not make it cleanly available during handshake and we need to know
1416 	 * whether DHE was selected.
1417 	 */
1418 
1419 	if (end - pos < 3)
1420 		return;
1421 	payload_len = WPA_GET_BE24(pos);
1422 	pos += 3;
1423 
1424 	if ((size_t) (end - pos) < payload_len)
1425 		return;
1426 	end = pos + payload_len;
1427 
1428 	/* Skip Version and Random */
1429 	if (end - pos < 2 + SSL3_RANDOM_SIZE)
1430 		return;
1431 	pos += 2 + SSL3_RANDOM_SIZE;
1432 
1433 	/* Skip Session ID */
1434 	if (end - pos < 1)
1435 		return;
1436 	id_len = *pos++;
1437 	if ((size_t) (end - pos) < id_len)
1438 		return;
1439 	pos += id_len;
1440 
1441 	if (end - pos < 2)
1442 		return;
1443 	conn->cipher_suite = WPA_GET_BE16(pos);
1444 	wpa_printf(MSG_DEBUG, "OpenSSL: Server selected cipher suite 0x%x",
1445 		   conn->cipher_suite);
1446 }
1447 
1448 
check_server_key_exchange(SSL * ssl,struct tls_connection * conn,const u8 * pos,const u8 * end)1449 static void check_server_key_exchange(SSL *ssl, struct tls_connection *conn,
1450 				      const u8 *pos, const u8 *end)
1451 {
1452 	size_t payload_len;
1453 	u16 dh_len;
1454 	BIGNUM *p;
1455 	int bits;
1456 
1457 	if (!(conn->flags & TLS_CONN_SUITEB))
1458 		return;
1459 
1460 	/* DHE is enabled only with DHE-RSA-AES256-GCM-SHA384 */
1461 	if (conn->cipher_suite != 0x9f)
1462 		return;
1463 
1464 	if (end - pos < 3)
1465 		return;
1466 	payload_len = WPA_GET_BE24(pos);
1467 	pos += 3;
1468 
1469 	if ((size_t) (end - pos) < payload_len)
1470 		return;
1471 	end = pos + payload_len;
1472 
1473 	if (end - pos < 2)
1474 		return;
1475 	dh_len = WPA_GET_BE16(pos);
1476 	pos += 2;
1477 
1478 	if ((size_t) (end - pos) < dh_len)
1479 		return;
1480 	p = BN_bin2bn(pos, dh_len, NULL);
1481 	if (!p)
1482 		return;
1483 
1484 	bits = BN_num_bits(p);
1485 	BN_free(p);
1486 
1487 	conn->server_dh_prime_len = bits;
1488 	wpa_printf(MSG_DEBUG, "OpenSSL: Server DH prime length: %d bits",
1489 		   conn->server_dh_prime_len);
1490 }
1491 
1492 #endif /* CONFIG_SUITEB */
1493 
1494 
tls_msg_cb(int write_p,int version,int content_type,const void * buf,size_t len,SSL * ssl,void * arg)1495 static void tls_msg_cb(int write_p, int version, int content_type,
1496 		       const void *buf, size_t len, SSL *ssl, void *arg)
1497 {
1498 	struct tls_connection *conn = arg;
1499 	const u8 *pos = buf;
1500 
1501 	if (write_p == 2) {
1502 		wpa_printf(MSG_DEBUG,
1503 			   "OpenSSL: session ver=0x%x content_type=%d",
1504 			   version, content_type);
1505 		wpa_hexdump_key(MSG_MSGDUMP, "OpenSSL: Data", buf, len);
1506 		return;
1507 	}
1508 
1509 	wpa_printf(MSG_DEBUG, "OpenSSL: %s ver=0x%x content_type=%d (%s/%s)",
1510 		   write_p ? "TX" : "RX", version, content_type,
1511 		   openssl_content_type(content_type),
1512 		   openssl_handshake_type(content_type, buf, len));
1513 	wpa_hexdump_key(MSG_MSGDUMP, "OpenSSL: Message", buf, len);
1514 	if (content_type == 24 && len >= 3 && pos[0] == 1) {
1515 		size_t payload_len = WPA_GET_BE16(pos + 1);
1516 		if (payload_len + 3 > len) {
1517 			wpa_printf(MSG_ERROR, "OpenSSL: Heartbeat attack detected");
1518 			conn->invalid_hb_used = 1;
1519 		}
1520 	}
1521 
1522 #ifdef CONFIG_SUITEB
1523 	/*
1524 	 * Need to parse these handshake messages to be able to check DH prime
1525 	 * length since OpenSSL does not expose the new cipher suite and DH
1526 	 * parameters during handshake (e.g., for cert_cb() callback).
1527 	 */
1528 	if (content_type == 22 && pos && len > 0 && pos[0] == 2)
1529 		check_server_hello(conn, pos + 1, pos + len);
1530 	if (content_type == 22 && pos && len > 0 && pos[0] == 12)
1531 		check_server_key_exchange(ssl, conn, pos + 1, pos + len);
1532 #endif /* CONFIG_SUITEB */
1533 }
1534 
1535 
tls_connection_init(void * ssl_ctx)1536 struct tls_connection * tls_connection_init(void *ssl_ctx)
1537 {
1538 	struct tls_data *data = ssl_ctx;
1539 	SSL_CTX *ssl = data->ssl;
1540 	struct tls_connection *conn;
1541 	long options;
1542 	X509_STORE *new_cert_store;
1543 	struct os_reltime now;
1544 	struct tls_context *context = SSL_CTX_get_app_data(ssl);
1545 
1546 	/* Replace X509 store if it is time to update CRL. */
1547 	if (data->crl_reload_interval > 0 && os_get_reltime(&now) == 0 &&
1548 	    os_reltime_expired(&now, &data->crl_last_reload,
1549 			       data->crl_reload_interval)) {
1550 		wpa_printf(MSG_INFO,
1551 			   "OpenSSL: Flushing X509 store with ca_cert file");
1552 		new_cert_store = tls_crl_cert_reload(data->ca_cert,
1553 						     data->check_crl);
1554 		if (!new_cert_store) {
1555 			wpa_printf(MSG_ERROR,
1556 				   "OpenSSL: Error replacing X509 store with ca_cert file");
1557 		} else {
1558 			/* Replace old store */
1559 			SSL_CTX_set_cert_store(ssl, new_cert_store);
1560 			data->crl_last_reload = now;
1561 		}
1562 	}
1563 
1564 	conn = os_zalloc(sizeof(*conn));
1565 	if (conn == NULL)
1566 		return NULL;
1567 	conn->data = data;
1568 	conn->ssl_ctx = ssl;
1569 	conn->ssl = SSL_new(ssl);
1570 	if (conn->ssl == NULL) {
1571 		tls_show_errors(MSG_INFO, __func__,
1572 				"Failed to initialize new SSL connection");
1573 		os_free(conn);
1574 		return NULL;
1575 	}
1576 
1577 	conn->context = context;
1578 	SSL_set_app_data(conn->ssl, conn);
1579 	SSL_set_msg_callback(conn->ssl, tls_msg_cb);
1580 	SSL_set_msg_callback_arg(conn->ssl, conn);
1581 	options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
1582 		SSL_OP_SINGLE_DH_USE;
1583 #ifdef SSL_OP_NO_COMPRESSION
1584 	options |= SSL_OP_NO_COMPRESSION;
1585 #endif /* SSL_OP_NO_COMPRESSION */
1586 	SSL_set_options(conn->ssl, options);
1587 
1588 	conn->ssl_in = BIO_new(BIO_s_mem());
1589 	if (!conn->ssl_in) {
1590 		tls_show_errors(MSG_INFO, __func__,
1591 				"Failed to create a new BIO for ssl_in");
1592 		SSL_free(conn->ssl);
1593 		os_free(conn);
1594 		return NULL;
1595 	}
1596 
1597 	conn->ssl_out = BIO_new(BIO_s_mem());
1598 	if (!conn->ssl_out) {
1599 		tls_show_errors(MSG_INFO, __func__,
1600 				"Failed to create a new BIO for ssl_out");
1601 		SSL_free(conn->ssl);
1602 		BIO_free(conn->ssl_in);
1603 		os_free(conn);
1604 		return NULL;
1605 	}
1606 
1607 	SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
1608 
1609 	return conn;
1610 }
1611 
1612 
tls_connection_deinit(void * ssl_ctx,struct tls_connection * conn)1613 void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
1614 {
1615 	if (conn == NULL)
1616 		return;
1617 	if (conn->success_data) {
1618 		/*
1619 		 * Make sure ssl_clear_bad_session() does not remove this
1620 		 * session.
1621 		 */
1622 		SSL_set_quiet_shutdown(conn->ssl, 1);
1623 		SSL_shutdown(conn->ssl);
1624 	}
1625 	SSL_free(conn->ssl);
1626 	tls_engine_deinit(conn);
1627 	os_free(conn->subject_match);
1628 	os_free(conn->altsubject_match);
1629 	os_free(conn->suffix_match);
1630 	os_free(conn->domain_match);
1631 	os_free(conn->check_cert_subject);
1632 	os_free(conn->session_ticket);
1633 	os_free(conn);
1634 }
1635 
1636 
tls_connection_established(void * ssl_ctx,struct tls_connection * conn)1637 int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
1638 {
1639 	return conn ? SSL_is_init_finished(conn->ssl) : 0;
1640 }
1641 
1642 
tls_connection_peer_serial_num(void * tls_ctx,struct tls_connection * conn)1643 char * tls_connection_peer_serial_num(void *tls_ctx,
1644 				      struct tls_connection *conn)
1645 {
1646 	ASN1_INTEGER *ser;
1647 	char *serial_num;
1648 	size_t len;
1649 
1650 	if (!conn->peer_cert)
1651 		return NULL;
1652 
1653 	ser = X509_get_serialNumber(conn->peer_cert);
1654 	if (!ser)
1655 		return NULL;
1656 
1657 	len = ASN1_STRING_length(ser) * 2 + 1;
1658 	serial_num = os_malloc(len);
1659 	if (!serial_num)
1660 		return NULL;
1661 	wpa_snprintf_hex_uppercase(serial_num, len,
1662 				   ASN1_STRING_get0_data(ser),
1663 				   ASN1_STRING_length(ser));
1664 	return serial_num;
1665 }
1666 
1667 
tls_connection_shutdown(void * ssl_ctx,struct tls_connection * conn)1668 int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
1669 {
1670 	if (conn == NULL)
1671 		return -1;
1672 
1673 	/* Shutdown previous TLS connection without notifying the peer
1674 	 * because the connection was already terminated in practice
1675 	 * and "close notify" shutdown alert would confuse AS. */
1676 	SSL_set_quiet_shutdown(conn->ssl, 1);
1677 	SSL_shutdown(conn->ssl);
1678 	return SSL_clear(conn->ssl) == 1 ? 0 : -1;
1679 }
1680 
1681 
tls_match_altsubject_component(X509 * cert,int type,const char * value,size_t len)1682 static int tls_match_altsubject_component(X509 *cert, int type,
1683 					  const char *value, size_t len)
1684 {
1685 	GENERAL_NAME *gen;
1686 	void *ext;
1687 	int found = 0;
1688 	stack_index_t i;
1689 
1690 	ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
1691 
1692 	for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
1693 		gen = sk_GENERAL_NAME_value(ext, i);
1694 		if (gen->type != type)
1695 			continue;
1696 		if (os_strlen((char *) gen->d.ia5->data) == len &&
1697 		    os_memcmp(value, gen->d.ia5->data, len) == 0)
1698 			found++;
1699 	}
1700 
1701 	sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
1702 
1703 	return found;
1704 }
1705 
1706 
tls_match_altsubject(X509 * cert,const char * match)1707 static int tls_match_altsubject(X509 *cert, const char *match)
1708 {
1709 	int type;
1710 	const char *pos, *end;
1711 	size_t len;
1712 
1713 	pos = match;
1714 	do {
1715 		if (os_strncmp(pos, "EMAIL:", 6) == 0) {
1716 			type = GEN_EMAIL;
1717 			pos += 6;
1718 		} else if (os_strncmp(pos, "DNS:", 4) == 0) {
1719 			type = GEN_DNS;
1720 			pos += 4;
1721 		} else if (os_strncmp(pos, "URI:", 4) == 0) {
1722 			type = GEN_URI;
1723 			pos += 4;
1724 		} else {
1725 			wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
1726 				   "match '%s'", pos);
1727 			return 0;
1728 		}
1729 		end = os_strchr(pos, ';');
1730 		while (end) {
1731 			if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
1732 			    os_strncmp(end + 1, "DNS:", 4) == 0 ||
1733 			    os_strncmp(end + 1, "URI:", 4) == 0)
1734 				break;
1735 			end = os_strchr(end + 1, ';');
1736 		}
1737 		if (end)
1738 			len = end - pos;
1739 		else
1740 			len = os_strlen(pos);
1741 		if (tls_match_altsubject_component(cert, type, pos, len) > 0)
1742 			return 1;
1743 		pos = end + 1;
1744 	} while (end);
1745 
1746 	return 0;
1747 }
1748 
1749 
1750 #ifndef CONFIG_NATIVE_WINDOWS
domain_suffix_match(const u8 * val,size_t len,const char * match,size_t match_len,int full)1751 static int domain_suffix_match(const u8 *val, size_t len, const char *match,
1752 			       size_t match_len, int full)
1753 {
1754 	size_t i;
1755 
1756 	/* Check for embedded nuls that could mess up suffix matching */
1757 	for (i = 0; i < len; i++) {
1758 		if (val[i] == '\0') {
1759 			wpa_printf(MSG_DEBUG, "TLS: Embedded null in a string - reject");
1760 			return 0;
1761 		}
1762 	}
1763 
1764 	if (match_len > len || (full && match_len != len))
1765 		return 0;
1766 
1767 	if (os_strncasecmp((const char *) val + len - match_len, match,
1768 			   match_len) != 0)
1769 		return 0; /* no match */
1770 
1771 	if (match_len == len)
1772 		return 1; /* exact match */
1773 
1774 	if (val[len - match_len - 1] == '.')
1775 		return 1; /* full label match completes suffix match */
1776 
1777 	wpa_printf(MSG_DEBUG, "TLS: Reject due to incomplete label match");
1778 	return 0;
1779 }
1780 #endif /* CONFIG_NATIVE_WINDOWS */
1781 
1782 
1783 struct tls_dn_field_order_cnt {
1784 	u8 cn;
1785 	u8 c;
1786 	u8 l;
1787 	u8 st;
1788 	u8 o;
1789 	u8 ou;
1790 	u8 email;
1791 };
1792 
1793 
get_dn_field_index(const struct tls_dn_field_order_cnt * dn_cnt,int nid)1794 static int get_dn_field_index(const struct tls_dn_field_order_cnt *dn_cnt,
1795 			      int nid)
1796 {
1797 	switch (nid) {
1798 	case NID_commonName:
1799 		return dn_cnt->cn;
1800 	case NID_countryName:
1801 		return dn_cnt->c;
1802 	case NID_localityName:
1803 		return dn_cnt->l;
1804 	case NID_stateOrProvinceName:
1805 		return dn_cnt->st;
1806 	case NID_organizationName:
1807 		return dn_cnt->o;
1808 	case NID_organizationalUnitName:
1809 		return dn_cnt->ou;
1810 	case NID_pkcs9_emailAddress:
1811 		return dn_cnt->email;
1812 	default:
1813 		wpa_printf(MSG_ERROR,
1814 			   "TLS: Unknown NID '%d' in check_cert_subject",
1815 			   nid);
1816 		return -1;
1817 	}
1818 }
1819 
1820 
1821 /**
1822  * match_dn_field - Match configuration DN field against Certificate DN field
1823  * @cert: Certificate
1824  * @nid: NID of DN field
1825  * @field: Field name
1826  * @value DN field value which is passed from configuration
1827  *	e.g., if configuration have C=US and this argument will point to US.
1828  * @dn_cnt: DN matching context
1829  * Returns: 1 on success and 0 on failure
1830  */
match_dn_field(const X509 * cert,int nid,const char * field,const char * value,const struct tls_dn_field_order_cnt * dn_cnt)1831 static int match_dn_field(const X509 *cert, int nid, const char *field,
1832 			  const char *value,
1833 			  const struct tls_dn_field_order_cnt *dn_cnt)
1834 {
1835 	int i, ret = 0, len, config_dn_field_index, match_index = 0;
1836 	X509_NAME *name;
1837 
1838 	len = os_strlen(value);
1839 	name = X509_get_subject_name((X509 *) cert);
1840 
1841 	/* Assign incremented cnt for every field of DN to check DN field in
1842 	 * right order */
1843 	config_dn_field_index = get_dn_field_index(dn_cnt, nid);
1844 	if (config_dn_field_index < 0)
1845 		return 0;
1846 
1847 	/* Fetch value based on NID */
1848 	for (i = -1; (i = X509_NAME_get_index_by_NID(name, nid, i)) > -1;) {
1849 		X509_NAME_ENTRY *e;
1850 		ASN1_STRING *cn;
1851 
1852 		e = X509_NAME_get_entry(name, i);
1853 		if (!e)
1854 			continue;
1855 
1856 		cn = X509_NAME_ENTRY_get_data(e);
1857 		if (!cn)
1858 			continue;
1859 
1860 		match_index++;
1861 
1862 		/* check for more than one DN field with same name */
1863 		if (match_index != config_dn_field_index)
1864 			continue;
1865 
1866 		/* Check wildcard at the right end side */
1867 		/* E.g., if OU=develop* mentioned in configuration, allow 'OU'
1868 		 * of the subject in the client certificate to start with
1869 		 * 'develop' */
1870 		if (len > 0 && value[len - 1] == '*') {
1871 			/* Compare actual certificate DN field value with
1872 			 * configuration DN field value up to the specified
1873 			 * length. */
1874 			ret = ASN1_STRING_length(cn) >= len - 1 &&
1875 				os_memcmp(ASN1_STRING_get0_data(cn), value,
1876 					  len - 1) == 0;
1877 		} else {
1878 			/* Compare actual certificate DN field value with
1879 			 * configuration DN field value */
1880 			ret = ASN1_STRING_length(cn) == len &&
1881 				os_memcmp(ASN1_STRING_get0_data(cn), value,
1882 					  len) == 0;
1883 		}
1884 		if (!ret) {
1885 			wpa_printf(MSG_ERROR,
1886 				   "OpenSSL: Failed to match %s '%s' with certificate DN field value '%s'",
1887 				   field, value, ASN1_STRING_get0_data(cn));
1888 		}
1889 		break;
1890 	}
1891 
1892 	return ret;
1893 }
1894 
1895 
1896 /**
1897  * get_value_from_field - Get value from DN field
1898  * @cert: Certificate
1899  * @field_str: DN field string which is passed from configuration file (e.g.,
1900  *	 C=US)
1901  * @dn_cnt: DN matching context
1902  * Returns: 1 on success and 0 on failure
1903  */
get_value_from_field(const X509 * cert,char * field_str,struct tls_dn_field_order_cnt * dn_cnt)1904 static int get_value_from_field(const X509 *cert, char *field_str,
1905 				struct tls_dn_field_order_cnt *dn_cnt)
1906 {
1907 	int nid;
1908 	char *context = NULL, *name, *value;
1909 
1910 	if (os_strcmp(field_str, "*") == 0)
1911 		return 1; /* wildcard matches everything */
1912 
1913 	name = str_token(field_str, "=", &context);
1914 	if (!name)
1915 		return 0;
1916 
1917 	/* Compare all configured DN fields and assign nid based on that to
1918 	 * fetch correct value from certificate subject */
1919 	if (os_strcmp(name, "CN") == 0) {
1920 		nid = NID_commonName;
1921 		dn_cnt->cn++;
1922 	} else if(os_strcmp(name, "C") == 0) {
1923 		nid = NID_countryName;
1924 		dn_cnt->c++;
1925 	} else if (os_strcmp(name, "L") == 0) {
1926 		nid = NID_localityName;
1927 		dn_cnt->l++;
1928 	} else if (os_strcmp(name, "ST") == 0) {
1929 		nid = NID_stateOrProvinceName;
1930 		dn_cnt->st++;
1931 	} else if (os_strcmp(name, "O") == 0) {
1932 		nid = NID_organizationName;
1933 		dn_cnt->o++;
1934 	} else if (os_strcmp(name, "OU") == 0) {
1935 		nid = NID_organizationalUnitName;
1936 		dn_cnt->ou++;
1937 	} else if (os_strcmp(name, "emailAddress") == 0) {
1938 		nid = NID_pkcs9_emailAddress;
1939 		dn_cnt->email++;
1940 	} else {
1941 		wpa_printf(MSG_ERROR,
1942 			"TLS: Unknown field '%s' in check_cert_subject", name);
1943 		return 0;
1944 	}
1945 
1946 	value = str_token(field_str, "=", &context);
1947 	if (!value) {
1948 		wpa_printf(MSG_ERROR,
1949 			   "TLS: Distinguished Name field '%s' value is not defined in check_cert_subject",
1950 			   name);
1951 		return 0;
1952 	}
1953 
1954 	return match_dn_field(cert, nid, name, value, dn_cnt);
1955 }
1956 
1957 
1958 /**
1959  * tls_match_dn_field - Match subject DN field with check_cert_subject
1960  * @cert: Certificate
1961  * @match: check_cert_subject string
1962  * Returns: Return 1 on success and 0 on failure
1963 */
tls_match_dn_field(X509 * cert,const char * match)1964 static int tls_match_dn_field(X509 *cert, const char *match)
1965 {
1966 	const char *token, *last = NULL;
1967 	char field[256];
1968 	struct tls_dn_field_order_cnt dn_cnt;
1969 
1970 	os_memset(&dn_cnt, 0, sizeof(dn_cnt));
1971 
1972 	/* Maximum length of each DN field is 255 characters */
1973 
1974 	/* Process each '/' delimited field */
1975 	while ((token = cstr_token(match, "/", &last))) {
1976 		if (last - token >= (int) sizeof(field)) {
1977 			wpa_printf(MSG_ERROR,
1978 				   "OpenSSL: Too long DN matching field value in '%s'",
1979 				   match);
1980 			return 0;
1981 		}
1982 		os_memcpy(field, token, last - token);
1983 		field[last - token] = '\0';
1984 
1985 		if (!get_value_from_field(cert, field, &dn_cnt)) {
1986 			wpa_printf(MSG_DEBUG, "OpenSSL: No match for DN '%s'",
1987 				   field);
1988 			return 0;
1989 		}
1990 	}
1991 
1992 	return 1;
1993 }
1994 
1995 
1996 #ifndef CONFIG_NATIVE_WINDOWS
tls_match_suffix_helper(X509 * cert,const char * match,size_t match_len,int full)1997 static int tls_match_suffix_helper(X509 *cert, const char *match,
1998 				   size_t match_len, int full)
1999 {
2000 	GENERAL_NAME *gen;
2001 	void *ext;
2002 	int i;
2003 	stack_index_t j;
2004 	int dns_name = 0;
2005 	X509_NAME *name;
2006 
2007 	wpa_printf(MSG_DEBUG, "TLS: Match domain against %s%s",
2008 		   full ? "": "suffix ", match);
2009 
2010 	ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
2011 
2012 	for (j = 0; ext && j < sk_GENERAL_NAME_num(ext); j++) {
2013 		gen = sk_GENERAL_NAME_value(ext, j);
2014 		if (gen->type != GEN_DNS)
2015 			continue;
2016 		dns_name++;
2017 		wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate dNSName",
2018 				  gen->d.dNSName->data,
2019 				  gen->d.dNSName->length);
2020 		if (domain_suffix_match(gen->d.dNSName->data,
2021 					gen->d.dNSName->length,
2022 					match, match_len, full) == 1) {
2023 			wpa_printf(MSG_DEBUG, "TLS: %s in dNSName found",
2024 				   full ? "Match" : "Suffix match");
2025 			sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
2026 			return 1;
2027 		}
2028 	}
2029 	sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
2030 
2031 	if (dns_name) {
2032 		wpa_printf(MSG_DEBUG, "TLS: None of the dNSName(s) matched");
2033 		return 0;
2034 	}
2035 
2036 	name = X509_get_subject_name(cert);
2037 	i = -1;
2038 	for (;;) {
2039 		X509_NAME_ENTRY *e;
2040 		ASN1_STRING *cn;
2041 
2042 		i = X509_NAME_get_index_by_NID(name, NID_commonName, i);
2043 		if (i == -1)
2044 			break;
2045 		e = X509_NAME_get_entry(name, i);
2046 		if (e == NULL)
2047 			continue;
2048 		cn = X509_NAME_ENTRY_get_data(e);
2049 		if (cn == NULL)
2050 			continue;
2051 		wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate commonName",
2052 				  cn->data, cn->length);
2053 		if (domain_suffix_match(cn->data, cn->length,
2054 					match, match_len, full) == 1) {
2055 			wpa_printf(MSG_DEBUG, "TLS: %s in commonName found",
2056 				   full ? "Match" : "Suffix match");
2057 			return 1;
2058 		}
2059 	}
2060 
2061 	wpa_printf(MSG_DEBUG, "TLS: No CommonName %smatch found",
2062 		   full ? "": "suffix ");
2063 	return 0;
2064 }
2065 #endif /* CONFIG_NATIVE_WINDOWS */
2066 
2067 
tls_match_suffix(X509 * cert,const char * match,int full)2068 static int tls_match_suffix(X509 *cert, const char *match, int full)
2069 {
2070 #ifdef CONFIG_NATIVE_WINDOWS
2071 	/* wincrypt.h has conflicting X509_NAME definition */
2072 	return -1;
2073 #else /* CONFIG_NATIVE_WINDOWS */
2074 	const char *token, *last = NULL;
2075 
2076 	/* Process each match alternative separately until a match is found */
2077 	while ((token = cstr_token(match, ";", &last))) {
2078 		if (tls_match_suffix_helper(cert, token, last - token, full))
2079 			return 1;
2080 	}
2081 
2082 	return 0;
2083 #endif /* CONFIG_NATIVE_WINDOWS */
2084 }
2085 
2086 
openssl_tls_fail_reason(int err)2087 static enum tls_fail_reason openssl_tls_fail_reason(int err)
2088 {
2089 	switch (err) {
2090 	case X509_V_ERR_CERT_REVOKED:
2091 		return TLS_FAIL_REVOKED;
2092 	case X509_V_ERR_CERT_NOT_YET_VALID:
2093 	case X509_V_ERR_CRL_NOT_YET_VALID:
2094 		return TLS_FAIL_NOT_YET_VALID;
2095 	case X509_V_ERR_CERT_HAS_EXPIRED:
2096 	case X509_V_ERR_CRL_HAS_EXPIRED:
2097 		return TLS_FAIL_EXPIRED;
2098 	case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
2099 	case X509_V_ERR_UNABLE_TO_GET_CRL:
2100 	case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
2101 	case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
2102 	case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
2103 	case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
2104 	case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
2105 	case X509_V_ERR_CERT_CHAIN_TOO_LONG:
2106 	case X509_V_ERR_PATH_LENGTH_EXCEEDED:
2107 	case X509_V_ERR_INVALID_CA:
2108 		return TLS_FAIL_UNTRUSTED;
2109 	case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
2110 	case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
2111 	case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
2112 	case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
2113 	case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
2114 	case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
2115 	case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
2116 	case X509_V_ERR_CERT_UNTRUSTED:
2117 	case X509_V_ERR_CERT_REJECTED:
2118 		return TLS_FAIL_BAD_CERTIFICATE;
2119 	default:
2120 		return TLS_FAIL_UNSPECIFIED;
2121 	}
2122 }
2123 
2124 
get_x509_cert(X509 * cert)2125 static struct wpabuf * get_x509_cert(X509 *cert)
2126 {
2127 	struct wpabuf *buf;
2128 	u8 *tmp;
2129 
2130 	int cert_len = i2d_X509(cert, NULL);
2131 	if (cert_len <= 0)
2132 		return NULL;
2133 
2134 	buf = wpabuf_alloc(cert_len);
2135 	if (buf == NULL)
2136 		return NULL;
2137 
2138 	tmp = wpabuf_put(buf, cert_len);
2139 	i2d_X509(cert, &tmp);
2140 	return buf;
2141 }
2142 
2143 
openssl_tls_fail_event(struct tls_connection * conn,X509 * err_cert,int err,int depth,const char * subject,const char * err_str,enum tls_fail_reason reason)2144 static void openssl_tls_fail_event(struct tls_connection *conn,
2145 				   X509 *err_cert, int err, int depth,
2146 				   const char *subject, const char *err_str,
2147 				   enum tls_fail_reason reason)
2148 {
2149 	union tls_event_data ev;
2150 	struct wpabuf *cert = NULL;
2151 	struct tls_context *context = conn->context;
2152 
2153 #ifdef ANDROID
2154 	log_cert_validation_failure(err_str);
2155 #endif
2156 
2157 	if (context->event_cb == NULL)
2158 		return;
2159 
2160 	cert = get_x509_cert(err_cert);
2161 	os_memset(&ev, 0, sizeof(ev));
2162 	ev.cert_fail.reason = reason != TLS_FAIL_UNSPECIFIED ?
2163 		reason : openssl_tls_fail_reason(err);
2164 	ev.cert_fail.depth = depth;
2165 	ev.cert_fail.subject = subject;
2166 	ev.cert_fail.reason_txt = err_str;
2167 	ev.cert_fail.cert = cert;
2168 	context->event_cb(context->cb_ctx, TLS_CERT_CHAIN_FAILURE, &ev);
2169 	wpabuf_free(cert);
2170 }
2171 
2172 
openssl_tls_cert_event(struct tls_connection * conn,X509 * err_cert,int depth,const char * subject)2173 static void openssl_tls_cert_event(struct tls_connection *conn,
2174 				   X509 *err_cert, int depth,
2175 				   const char *subject)
2176 {
2177 	struct wpabuf *cert = NULL;
2178 	union tls_event_data ev;
2179 	struct tls_context *context = conn->context;
2180 	char *altsubject[TLS_MAX_ALT_SUBJECT];
2181 	int alt, num_altsubject = 0;
2182 	GENERAL_NAME *gen;
2183 	void *ext;
2184 	stack_index_t i;
2185 	ASN1_INTEGER *ser;
2186 	char serial_num[128];
2187 #ifdef CONFIG_SHA256
2188 	u8 hash[32];
2189 #endif /* CONFIG_SHA256 */
2190 
2191 	if (context->event_cb == NULL)
2192 		return;
2193 
2194 	os_memset(&ev, 0, sizeof(ev));
2195 	if (conn->cert_probe || (conn->flags & TLS_CONN_EXT_CERT_CHECK) ||
2196 	    context->cert_in_cb) {
2197 		cert = get_x509_cert(err_cert);
2198 		ev.peer_cert.cert = cert;
2199 	}
2200 #ifdef CONFIG_SHA256
2201 	if (cert) {
2202 		const u8 *addr[1];
2203 		size_t len[1];
2204 		addr[0] = wpabuf_head(cert);
2205 		len[0] = wpabuf_len(cert);
2206 		if (sha256_vector(1, addr, len, hash) == 0) {
2207 			ev.peer_cert.hash = hash;
2208 			ev.peer_cert.hash_len = sizeof(hash);
2209 		}
2210 	}
2211 #endif /* CONFIG_SHA256 */
2212 	ev.peer_cert.depth = depth;
2213 	ev.peer_cert.subject = subject;
2214 
2215 	ser = X509_get_serialNumber(err_cert);
2216 	if (ser) {
2217 		wpa_snprintf_hex_uppercase(serial_num, sizeof(serial_num),
2218 					   ASN1_STRING_get0_data(ser),
2219 					   ASN1_STRING_length(ser));
2220 		ev.peer_cert.serial_num = serial_num;
2221 	}
2222 
2223 	ext = X509_get_ext_d2i(err_cert, NID_subject_alt_name, NULL, NULL);
2224 	for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
2225 		char *pos;
2226 
2227 		if (num_altsubject == TLS_MAX_ALT_SUBJECT)
2228 			break;
2229 		gen = sk_GENERAL_NAME_value(ext, i);
2230 		if (gen->type != GEN_EMAIL &&
2231 		    gen->type != GEN_DNS &&
2232 		    gen->type != GEN_URI)
2233 			continue;
2234 
2235 		pos = os_malloc(10 + gen->d.ia5->length + 1);
2236 		if (pos == NULL)
2237 			break;
2238 		altsubject[num_altsubject++] = pos;
2239 
2240 		switch (gen->type) {
2241 		case GEN_EMAIL:
2242 			os_memcpy(pos, "EMAIL:", 6);
2243 			pos += 6;
2244 			break;
2245 		case GEN_DNS:
2246 			os_memcpy(pos, "DNS:", 4);
2247 			pos += 4;
2248 			break;
2249 		case GEN_URI:
2250 			os_memcpy(pos, "URI:", 4);
2251 			pos += 4;
2252 			break;
2253 		}
2254 
2255 		os_memcpy(pos, gen->d.ia5->data, gen->d.ia5->length);
2256 		pos += gen->d.ia5->length;
2257 		*pos = '\0';
2258 	}
2259 	sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
2260 
2261 	for (alt = 0; alt < num_altsubject; alt++)
2262 		ev.peer_cert.altsubject[alt] = altsubject[alt];
2263 	ev.peer_cert.num_altsubject = num_altsubject;
2264 
2265 	context->event_cb(context->cb_ctx, TLS_PEER_CERTIFICATE, &ev);
2266 	wpabuf_free(cert);
2267 	for (alt = 0; alt < num_altsubject; alt++)
2268 		os_free(altsubject[alt]);
2269 }
2270 
2271 
tls_verify_cb(int preverify_ok,X509_STORE_CTX * x509_ctx)2272 static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
2273 {
2274 	char buf[256];
2275 	X509 *err_cert;
2276 	int err, depth;
2277 	SSL *ssl;
2278 	struct tls_connection *conn;
2279 	struct tls_context *context;
2280 	char *match, *altmatch, *suffix_match, *domain_match;
2281 	const char *check_cert_subject;
2282 	const char *err_str;
2283 
2284 	err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
2285 	if (!err_cert)
2286 		return 0;
2287 
2288 	err = X509_STORE_CTX_get_error(x509_ctx);
2289 	depth = X509_STORE_CTX_get_error_depth(x509_ctx);
2290 	ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
2291 					 SSL_get_ex_data_X509_STORE_CTX_idx());
2292 	X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
2293 
2294 	conn = SSL_get_app_data(ssl);
2295 	if (conn == NULL)
2296 		return 0;
2297 
2298 	if (depth == 0)
2299 		conn->peer_cert = err_cert;
2300 	else if (depth == 1)
2301 		conn->peer_issuer = err_cert;
2302 	else if (depth == 2)
2303 		conn->peer_issuer_issuer = err_cert;
2304 
2305 	context = conn->context;
2306 	match = conn->subject_match;
2307 	altmatch = conn->altsubject_match;
2308 	suffix_match = conn->suffix_match;
2309 	domain_match = conn->domain_match;
2310 
2311 	if (!preverify_ok && !conn->ca_cert_verify)
2312 		preverify_ok = 1;
2313 	if (!preverify_ok && depth > 0 && conn->server_cert_only)
2314 		preverify_ok = 1;
2315 	if (!preverify_ok && (conn->flags & TLS_CONN_DISABLE_TIME_CHECKS) &&
2316 	    (err == X509_V_ERR_CERT_HAS_EXPIRED ||
2317 	     err == X509_V_ERR_CERT_NOT_YET_VALID)) {
2318 		wpa_printf(MSG_DEBUG, "OpenSSL: Ignore certificate validity "
2319 			   "time mismatch");
2320 		preverify_ok = 1;
2321 	}
2322 	if (!preverify_ok && !conn->data->check_crl_strict &&
2323 	    (err == X509_V_ERR_CRL_HAS_EXPIRED ||
2324 	     err == X509_V_ERR_CRL_NOT_YET_VALID)) {
2325 		wpa_printf(MSG_DEBUG,
2326 			   "OpenSSL: Ignore certificate validity CRL time mismatch");
2327 		preverify_ok = 1;
2328 	}
2329 
2330 	err_str = X509_verify_cert_error_string(err);
2331 
2332 #ifdef CONFIG_SHA256
2333 	/*
2334 	 * Do not require preverify_ok so we can explicity allow otherwise
2335 	 * invalid pinned server certificates.
2336 	 */
2337 	if (depth == 0 && conn->server_cert_only) {
2338 		struct wpabuf *cert;
2339 		cert = get_x509_cert(err_cert);
2340 		if (!cert) {
2341 			wpa_printf(MSG_DEBUG, "OpenSSL: Could not fetch "
2342 				   "server certificate data");
2343 			preverify_ok = 0;
2344 		} else {
2345 			u8 hash[32];
2346 			const u8 *addr[1];
2347 			size_t len[1];
2348 			addr[0] = wpabuf_head(cert);
2349 			len[0] = wpabuf_len(cert);
2350 			if (sha256_vector(1, addr, len, hash) < 0 ||
2351 			    os_memcmp(conn->srv_cert_hash, hash, 32) != 0) {
2352 				err_str = "Server certificate mismatch";
2353 				err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
2354 				preverify_ok = 0;
2355 			} else if (!preverify_ok) {
2356 				/*
2357 				 * Certificate matches pinned certificate, allow
2358 				 * regardless of other problems.
2359 				 */
2360 				wpa_printf(MSG_DEBUG,
2361 					   "OpenSSL: Ignore validation issues for a pinned server certificate");
2362 				preverify_ok = 1;
2363 			}
2364 			wpabuf_free(cert);
2365 		}
2366 	}
2367 #endif /* CONFIG_SHA256 */
2368 
2369 	if (!preverify_ok) {
2370 		wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
2371 			   " error %d (%s) depth %d for '%s'", err, err_str,
2372 			   depth, buf);
2373 		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2374 				       err_str, TLS_FAIL_UNSPECIFIED);
2375 		return preverify_ok;
2376 	}
2377 
2378 	wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - preverify_ok=%d "
2379 		   "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
2380 		   preverify_ok, err, err_str,
2381 		   conn->ca_cert_verify, depth, buf);
2382 	check_cert_subject = conn->check_cert_subject;
2383 	if (!check_cert_subject)
2384 		check_cert_subject = conn->data->check_cert_subject;
2385 	if (check_cert_subject) {
2386 		if (depth == 0 &&
2387 		    !tls_match_dn_field(err_cert, check_cert_subject)) {
2388 			preverify_ok = 0;
2389 			openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2390 					       "Distinguished Name",
2391 					       TLS_FAIL_DN_MISMATCH);
2392 		}
2393 	}
2394 	if (depth == 0 && match && os_strstr(buf, match) == NULL) {
2395 		wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
2396 			   "match with '%s'", buf, match);
2397 		preverify_ok = 0;
2398 		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2399 				       "Subject mismatch",
2400 				       TLS_FAIL_SUBJECT_MISMATCH);
2401 	} else if (depth == 0 && altmatch &&
2402 		   !tls_match_altsubject(err_cert, altmatch)) {
2403 		wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
2404 			   "'%s' not found", altmatch);
2405 		preverify_ok = 0;
2406 		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2407 				       "AltSubject mismatch",
2408 				       TLS_FAIL_ALTSUBJECT_MISMATCH);
2409 	} else if (depth == 0 && suffix_match &&
2410 		   !tls_match_suffix(err_cert, suffix_match, 0)) {
2411 		wpa_printf(MSG_WARNING, "TLS: Domain suffix match '%s' not found",
2412 			   suffix_match);
2413 		preverify_ok = 0;
2414 		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2415 				       "Domain suffix mismatch",
2416 				       TLS_FAIL_DOMAIN_SUFFIX_MISMATCH);
2417 	} else if (depth == 0 && domain_match &&
2418 		   !tls_match_suffix(err_cert, domain_match, 1)) {
2419 		wpa_printf(MSG_WARNING, "TLS: Domain match '%s' not found",
2420 			   domain_match);
2421 		preverify_ok = 0;
2422 		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2423 				       "Domain mismatch",
2424 				       TLS_FAIL_DOMAIN_MISMATCH);
2425 	} else
2426 		openssl_tls_cert_event(conn, err_cert, depth, buf);
2427 
2428 	if (conn->cert_probe && preverify_ok && depth == 0) {
2429 		wpa_printf(MSG_DEBUG, "OpenSSL: Reject server certificate "
2430 			   "on probe-only run");
2431 		preverify_ok = 0;
2432 		openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2433 				       "Server certificate chain probe",
2434 				       TLS_FAIL_SERVER_CHAIN_PROBE);
2435 	}
2436 
2437 #ifdef CONFIG_SUITEB
2438 	if (conn->flags & TLS_CONN_SUITEB) {
2439 		EVP_PKEY *pk;
2440 		RSA *rsa;
2441 		int len = -1;
2442 
2443 		pk = X509_get_pubkey(err_cert);
2444 		if (pk) {
2445 			rsa = EVP_PKEY_get1_RSA(pk);
2446 			if (rsa) {
2447 				len = RSA_bits(rsa);
2448 				RSA_free(rsa);
2449 			}
2450 			EVP_PKEY_free(pk);
2451 		}
2452 
2453 		if (len >= 0) {
2454 			wpa_printf(MSG_DEBUG,
2455 				   "OpenSSL: RSA modulus size: %d bits", len);
2456 			if (len < 3072) {
2457 				preverify_ok = 0;
2458 				openssl_tls_fail_event(
2459 					conn, err_cert, err,
2460 					depth, buf,
2461 					"Insufficient RSA modulus size",
2462 					TLS_FAIL_INSUFFICIENT_KEY_LEN);
2463 			}
2464 		}
2465 	}
2466 #endif /* CONFIG_SUITEB */
2467 
2468 #ifdef OPENSSL_IS_BORINGSSL
2469 	if (depth == 0 && (conn->flags & TLS_CONN_REQUEST_OCSP) &&
2470 	    preverify_ok) {
2471 		enum ocsp_result res;
2472 
2473 		res = check_ocsp_resp(conn->ssl_ctx, conn->ssl, err_cert,
2474 				      conn->peer_issuer,
2475 				      conn->peer_issuer_issuer);
2476 		if (res == OCSP_REVOKED) {
2477 			preverify_ok = 0;
2478 			openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2479 					       "certificate revoked",
2480 					       TLS_FAIL_REVOKED);
2481 			if (err == X509_V_OK)
2482 				X509_STORE_CTX_set_error(
2483 					x509_ctx, X509_V_ERR_CERT_REVOKED);
2484 		} else if (res != OCSP_GOOD &&
2485 			   (conn->flags & TLS_CONN_REQUIRE_OCSP)) {
2486 			preverify_ok = 0;
2487 			openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2488 					       "bad certificate status response",
2489 					       TLS_FAIL_UNSPECIFIED);
2490 		}
2491 	}
2492 #endif /* OPENSSL_IS_BORINGSSL */
2493 
2494 	if (depth == 0 && preverify_ok && context->event_cb != NULL)
2495 		context->event_cb(context->cb_ctx,
2496 				  TLS_CERT_CHAIN_SUCCESS, NULL);
2497 
2498 	return preverify_ok;
2499 }
2500 
2501 
2502 #ifndef OPENSSL_NO_STDIO
tls_load_ca_der(struct tls_data * data,const char * ca_cert)2503 static int tls_load_ca_der(struct tls_data *data, const char *ca_cert)
2504 {
2505 	SSL_CTX *ssl_ctx = data->ssl;
2506 	X509_LOOKUP *lookup;
2507 	int ret = 0;
2508 
2509 	lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(ssl_ctx),
2510 				       X509_LOOKUP_file());
2511 	if (lookup == NULL) {
2512 		tls_show_errors(MSG_WARNING, __func__,
2513 				"Failed add lookup for X509 store");
2514 		return -1;
2515 	}
2516 
2517 	if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
2518 		unsigned long err = ERR_peek_error();
2519 		tls_show_errors(MSG_WARNING, __func__,
2520 				"Failed load CA in DER format");
2521 		if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
2522 		    ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
2523 			wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
2524 				   "cert already in hash table error",
2525 				   __func__);
2526 		} else
2527 			ret = -1;
2528 	}
2529 
2530 	return ret;
2531 }
2532 #endif /* OPENSSL_NO_STDIO */
2533 
2534 
tls_connection_ca_cert(struct tls_data * data,struct tls_connection * conn,const char * ca_cert,const u8 * ca_cert_blob,size_t ca_cert_blob_len,const char * ca_path)2535 static int tls_connection_ca_cert(struct tls_data *data,
2536 				  struct tls_connection *conn,
2537 				  const char *ca_cert, const u8 *ca_cert_blob,
2538 				  size_t ca_cert_blob_len, const char *ca_path)
2539 {
2540 	SSL_CTX *ssl_ctx = data->ssl;
2541 	X509_STORE *store;
2542 
2543 	/*
2544 	 * Remove previously configured trusted CA certificates before adding
2545 	 * new ones.
2546 	 */
2547 	store = X509_STORE_new();
2548 	if (store == NULL) {
2549 		wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
2550 			   "certificate store", __func__);
2551 		return -1;
2552 	}
2553 	SSL_CTX_set_cert_store(ssl_ctx, store);
2554 
2555 	SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
2556 	conn->ca_cert_verify = 1;
2557 
2558 	if (ca_cert && os_strncmp(ca_cert, "probe://", 8) == 0) {
2559 		wpa_printf(MSG_DEBUG, "OpenSSL: Probe for server certificate "
2560 			   "chain");
2561 		conn->cert_probe = 1;
2562 		conn->ca_cert_verify = 0;
2563 		return 0;
2564 	}
2565 
2566 	if (ca_cert && os_strncmp(ca_cert, "hash://", 7) == 0) {
2567 #ifdef CONFIG_SHA256
2568 		const char *pos = ca_cert + 7;
2569 		if (os_strncmp(pos, "server/sha256/", 14) != 0) {
2570 			wpa_printf(MSG_DEBUG, "OpenSSL: Unsupported ca_cert "
2571 				   "hash value '%s'", ca_cert);
2572 			return -1;
2573 		}
2574 		pos += 14;
2575 		if (os_strlen(pos) != 32 * 2) {
2576 			wpa_printf(MSG_DEBUG, "OpenSSL: Unexpected SHA256 "
2577 				   "hash length in ca_cert '%s'", ca_cert);
2578 			return -1;
2579 		}
2580 		if (hexstr2bin(pos, conn->srv_cert_hash, 32) < 0) {
2581 			wpa_printf(MSG_DEBUG, "OpenSSL: Invalid SHA256 hash "
2582 				   "value in ca_cert '%s'", ca_cert);
2583 			return -1;
2584 		}
2585 		conn->server_cert_only = 1;
2586 		wpa_printf(MSG_DEBUG, "OpenSSL: Checking only server "
2587 			   "certificate match");
2588 		return 0;
2589 #else /* CONFIG_SHA256 */
2590 		wpa_printf(MSG_INFO, "No SHA256 included in the build - "
2591 			   "cannot validate server certificate hash");
2592 		return -1;
2593 #endif /* CONFIG_SHA256 */
2594 	}
2595 
2596 	if (ca_cert_blob) {
2597 		X509 *cert = d2i_X509(NULL,
2598 				      (const unsigned char **) &ca_cert_blob,
2599 				      ca_cert_blob_len);
2600 		if (cert == NULL) {
2601 			tls_show_errors(MSG_WARNING, __func__,
2602 					"Failed to parse ca_cert_blob");
2603 			return -1;
2604 		}
2605 
2606 		if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx),
2607 					 cert)) {
2608 			unsigned long err = ERR_peek_error();
2609 			tls_show_errors(MSG_WARNING, __func__,
2610 					"Failed to add ca_cert_blob to "
2611 					"certificate store");
2612 			if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
2613 			    ERR_GET_REASON(err) ==
2614 			    X509_R_CERT_ALREADY_IN_HASH_TABLE) {
2615 				wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
2616 					   "cert already in hash table error",
2617 					   __func__);
2618 			} else {
2619 				X509_free(cert);
2620 				return -1;
2621 			}
2622 		}
2623 		X509_free(cert);
2624 		wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
2625 			   "to certificate store", __func__);
2626 		return 0;
2627 	}
2628 
2629 #ifdef ANDROID
2630 	/* Single alias */
2631 	if (ca_cert && os_strncmp("keystore://", ca_cert, 11) == 0) {
2632 		if (tls_add_ca_from_keystore(SSL_CTX_get_cert_store(ssl_ctx),
2633 					     &ca_cert[11]) < 0)
2634 			return -1;
2635 		SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
2636 		return 0;
2637 	}
2638 
2639 	/* Multiple aliases separated by space */
2640 	if (ca_cert && os_strncmp("keystores://", ca_cert, 12) == 0) {
2641 		char *aliases = os_strdup(&ca_cert[12]);
2642 		const char *delim = " ";
2643 		int rc = 0;
2644 		char *savedptr;
2645 		char *alias;
2646 
2647 		if (!aliases)
2648 			return -1;
2649 		alias = strtok_r(aliases, delim, &savedptr);
2650 		for (; alias; alias = strtok_r(NULL, delim, &savedptr)) {
2651 			if (tls_add_ca_from_keystore_encoded(
2652 				    SSL_CTX_get_cert_store(ssl_ctx), alias)) {
2653 				wpa_printf(MSG_WARNING,
2654 					   "OpenSSL: %s - Failed to add ca_cert %s from keystore",
2655 					   __func__, alias);
2656 				rc = -1;
2657 				break;
2658 			}
2659 		}
2660 		os_free(aliases);
2661 		if (rc)
2662 			return rc;
2663 
2664 		SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
2665 		return 0;
2666 	}
2667 #endif /* ANDROID */
2668 
2669 #ifdef CONFIG_NATIVE_WINDOWS
2670 	if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
2671 	    0) {
2672 		wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
2673 			   "system certificate store");
2674 		return 0;
2675 	}
2676 #endif /* CONFIG_NATIVE_WINDOWS */
2677 
2678 	if (ca_cert || ca_path) {
2679 #ifndef OPENSSL_NO_STDIO
2680 		if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
2681 		    1) {
2682 			tls_show_errors(MSG_WARNING, __func__,
2683 					"Failed to load root certificates");
2684 			if (ca_cert &&
2685 			    tls_load_ca_der(data, ca_cert) == 0) {
2686 				wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
2687 					   "DER format CA certificate",
2688 					   __func__);
2689 			} else
2690 				return -1;
2691 		} else {
2692 			wpa_printf(MSG_DEBUG, "TLS: Trusted root "
2693 				   "certificate(s) loaded");
2694 			tls_get_errors(data);
2695 		}
2696 #else /* OPENSSL_NO_STDIO */
2697 		wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
2698 			   __func__);
2699 		return -1;
2700 #endif /* OPENSSL_NO_STDIO */
2701 	} else {
2702 		/* No ca_cert configured - do not try to verify server
2703 		 * certificate */
2704 		conn->ca_cert_verify = 0;
2705 	}
2706 
2707 	return 0;
2708 }
2709 
2710 
tls_global_ca_cert(struct tls_data * data,const char * ca_cert)2711 static int tls_global_ca_cert(struct tls_data *data, const char *ca_cert)
2712 {
2713 	SSL_CTX *ssl_ctx = data->ssl;
2714 
2715 	if (ca_cert) {
2716 		if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
2717 		{
2718 			tls_show_errors(MSG_WARNING, __func__,
2719 					"Failed to load root certificates");
2720 			return -1;
2721 		}
2722 
2723 		wpa_printf(MSG_DEBUG, "TLS: Trusted root "
2724 			   "certificate(s) loaded");
2725 
2726 #ifndef OPENSSL_NO_STDIO
2727 		/* Add the same CAs to the client certificate requests */
2728 		SSL_CTX_set_client_CA_list(ssl_ctx,
2729 					   SSL_load_client_CA_file(ca_cert));
2730 #endif /* OPENSSL_NO_STDIO */
2731 
2732 		os_free(data->ca_cert);
2733 		data->ca_cert = os_strdup(ca_cert);
2734 	}
2735 
2736 	return 0;
2737 }
2738 
2739 
tls_global_set_verify(void * ssl_ctx,int check_crl,int strict)2740 int tls_global_set_verify(void *ssl_ctx, int check_crl, int strict)
2741 {
2742 	int flags;
2743 
2744 	if (check_crl) {
2745 		struct tls_data *data = ssl_ctx;
2746 		X509_STORE *cs = SSL_CTX_get_cert_store(data->ssl);
2747 		if (cs == NULL) {
2748 			tls_show_errors(MSG_INFO, __func__, "Failed to get "
2749 					"certificate store when enabling "
2750 					"check_crl");
2751 			return -1;
2752 		}
2753 		flags = X509_V_FLAG_CRL_CHECK;
2754 		if (check_crl == 2)
2755 			flags |= X509_V_FLAG_CRL_CHECK_ALL;
2756 		X509_STORE_set_flags(cs, flags);
2757 
2758 		data->check_crl = check_crl;
2759 		data->check_crl_strict = strict;
2760 		os_get_reltime(&data->crl_last_reload);
2761 	}
2762 	return 0;
2763 }
2764 
2765 
tls_connection_set_subject_match(struct tls_connection * conn,const char * subject_match,const char * altsubject_match,const char * suffix_match,const char * domain_match,const char * check_cert_subject)2766 static int tls_connection_set_subject_match(struct tls_connection *conn,
2767 					    const char *subject_match,
2768 					    const char *altsubject_match,
2769 					    const char *suffix_match,
2770 					    const char *domain_match,
2771 					    const char *check_cert_subject)
2772 {
2773 	os_free(conn->subject_match);
2774 	conn->subject_match = NULL;
2775 	if (subject_match) {
2776 		conn->subject_match = os_strdup(subject_match);
2777 		if (conn->subject_match == NULL)
2778 			return -1;
2779 	}
2780 
2781 	os_free(conn->altsubject_match);
2782 	conn->altsubject_match = NULL;
2783 	if (altsubject_match) {
2784 		conn->altsubject_match = os_strdup(altsubject_match);
2785 		if (conn->altsubject_match == NULL)
2786 			return -1;
2787 	}
2788 
2789 	os_free(conn->suffix_match);
2790 	conn->suffix_match = NULL;
2791 	if (suffix_match) {
2792 		conn->suffix_match = os_strdup(suffix_match);
2793 		if (conn->suffix_match == NULL)
2794 			return -1;
2795 	}
2796 
2797 	os_free(conn->domain_match);
2798 	conn->domain_match = NULL;
2799 	if (domain_match) {
2800 		conn->domain_match = os_strdup(domain_match);
2801 		if (conn->domain_match == NULL)
2802 			return -1;
2803 	}
2804 
2805 	os_free(conn->check_cert_subject);
2806 	conn->check_cert_subject = NULL;
2807 	if (check_cert_subject) {
2808 		conn->check_cert_subject = os_strdup(check_cert_subject);
2809 		if (!conn->check_cert_subject)
2810 			return -1;
2811 	}
2812 
2813 	return 0;
2814 }
2815 
2816 
2817 #ifdef CONFIG_SUITEB
2818 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
suiteb_cert_cb(SSL * ssl,void * arg)2819 static int suiteb_cert_cb(SSL *ssl, void *arg)
2820 {
2821 	struct tls_connection *conn = arg;
2822 
2823 	/*
2824 	 * This cert_cb() is not really the best location for doing a
2825 	 * constraint check for the ServerKeyExchange message, but this seems to
2826 	 * be the only place where the current OpenSSL sequence can be
2827 	 * terminated cleanly with an TLS alert going out to the server.
2828 	 */
2829 
2830 	if (!(conn->flags & TLS_CONN_SUITEB))
2831 		return 1;
2832 
2833 	/* DHE is enabled only with DHE-RSA-AES256-GCM-SHA384 */
2834 	if (conn->cipher_suite != 0x9f)
2835 		return 1;
2836 
2837 	if (conn->server_dh_prime_len >= 3072)
2838 		return 1;
2839 
2840 	wpa_printf(MSG_DEBUG,
2841 		   "OpenSSL: Server DH prime length (%d bits) not sufficient for Suite B RSA - reject handshake",
2842 		   conn->server_dh_prime_len);
2843 	return 0;
2844 }
2845 #endif /* OPENSSL_VERSION_NUMBER */
2846 #endif /* CONFIG_SUITEB */
2847 
2848 
tls_set_conn_flags(struct tls_connection * conn,unsigned int flags,const char * openssl_ciphers)2849 static int tls_set_conn_flags(struct tls_connection *conn, unsigned int flags,
2850 			      const char *openssl_ciphers)
2851 {
2852 	SSL *ssl = conn->ssl;
2853 
2854 #ifdef SSL_OP_NO_TICKET
2855 	if (flags & TLS_CONN_DISABLE_SESSION_TICKET)
2856 		SSL_set_options(ssl, SSL_OP_NO_TICKET);
2857 	else
2858 		SSL_clear_options(ssl, SSL_OP_NO_TICKET);
2859 #endif /* SSL_OP_NO_TICKET */
2860 
2861 #ifdef SSL_OP_NO_TLSv1
2862 	if (flags & TLS_CONN_DISABLE_TLSv1_0)
2863 		SSL_set_options(ssl, SSL_OP_NO_TLSv1);
2864 	else
2865 		SSL_clear_options(ssl, SSL_OP_NO_TLSv1);
2866 #endif /* SSL_OP_NO_TLSv1 */
2867 #ifdef SSL_OP_NO_TLSv1_1
2868 	if (flags & TLS_CONN_DISABLE_TLSv1_1)
2869 		SSL_set_options(ssl, SSL_OP_NO_TLSv1_1);
2870 	else
2871 		SSL_clear_options(ssl, SSL_OP_NO_TLSv1_1);
2872 #endif /* SSL_OP_NO_TLSv1_1 */
2873 #ifdef SSL_OP_NO_TLSv1_2
2874 	if (flags & TLS_CONN_DISABLE_TLSv1_2)
2875 		SSL_set_options(ssl, SSL_OP_NO_TLSv1_2);
2876 	else
2877 		SSL_clear_options(ssl, SSL_OP_NO_TLSv1_2);
2878 #endif /* SSL_OP_NO_TLSv1_2 */
2879 #ifdef SSL_OP_NO_TLSv1_3
2880 	if (flags & TLS_CONN_DISABLE_TLSv1_3)
2881 		SSL_set_options(ssl, SSL_OP_NO_TLSv1_3);
2882 	else
2883 		SSL_clear_options(ssl, SSL_OP_NO_TLSv1_3);
2884 #endif /* SSL_OP_NO_TLSv1_3 */
2885 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
2886 	if (flags & (TLS_CONN_ENABLE_TLSv1_0 |
2887 		     TLS_CONN_ENABLE_TLSv1_1 |
2888 		     TLS_CONN_ENABLE_TLSv1_2)) {
2889 		int version = 0;
2890 
2891 		/* Explicit request to enable TLS versions even if needing to
2892 		 * override systemwide policies. */
2893 		if (flags & TLS_CONN_ENABLE_TLSv1_0) {
2894 			version = TLS1_VERSION;
2895 		} else if (flags & TLS_CONN_ENABLE_TLSv1_1) {
2896 			if (!(flags & TLS_CONN_DISABLE_TLSv1_0))
2897 				version = TLS1_1_VERSION;
2898 		} else if (flags & TLS_CONN_ENABLE_TLSv1_2) {
2899 			if (!(flags & (TLS_CONN_DISABLE_TLSv1_0 |
2900 				       TLS_CONN_DISABLE_TLSv1_1)))
2901 				version = TLS1_2_VERSION;
2902 		}
2903 		if (!version) {
2904 			wpa_printf(MSG_DEBUG,
2905 				   "OpenSSL: Invalid TLS version configuration");
2906 			return -1;
2907 		}
2908 
2909 		if (SSL_set_min_proto_version(ssl, version) != 1) {
2910 			wpa_printf(MSG_DEBUG,
2911 				   "OpenSSL: Failed to set minimum TLS version");
2912 			return -1;
2913 		}
2914 	}
2915 #endif /* >= 1.1.0 */
2916 
2917 #ifdef CONFIG_SUITEB
2918 #ifdef OPENSSL_IS_BORINGSSL
2919 	/* Start with defaults from BoringSSL */
2920 	SSL_CTX_set_verify_algorithm_prefs(conn->ssl_ctx, NULL, 0);
2921 #endif /* OPENSSL_IS_BORINGSSL */
2922 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
2923 	if (flags & TLS_CONN_SUITEB_NO_ECDH) {
2924 		const char *ciphers = "DHE-RSA-AES256-GCM-SHA384";
2925 
2926 		if (openssl_ciphers) {
2927 			wpa_printf(MSG_DEBUG,
2928 				   "OpenSSL: Override ciphers for Suite B (no ECDH): %s",
2929 				   openssl_ciphers);
2930 			ciphers = openssl_ciphers;
2931 		}
2932 		if (SSL_set_cipher_list(ssl, ciphers) != 1) {
2933 			wpa_printf(MSG_INFO,
2934 				   "OpenSSL: Failed to set Suite B ciphers");
2935 			return -1;
2936 		}
2937 	} else if (flags & TLS_CONN_SUITEB) {
2938 		EC_KEY *ecdh;
2939 		const char *ciphers =
2940 			"ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384";
2941 		int nid[1] = { NID_secp384r1 };
2942 
2943 		if (openssl_ciphers) {
2944 			wpa_printf(MSG_DEBUG,
2945 				   "OpenSSL: Override ciphers for Suite B: %s",
2946 				   openssl_ciphers);
2947 			ciphers = openssl_ciphers;
2948 		}
2949 		if (SSL_set_cipher_list(ssl, ciphers) != 1) {
2950 			wpa_printf(MSG_INFO,
2951 				   "OpenSSL: Failed to set Suite B ciphers");
2952 			return -1;
2953 		}
2954 
2955 		if (SSL_set1_curves(ssl, nid, 1) != 1) {
2956 			wpa_printf(MSG_INFO,
2957 				   "OpenSSL: Failed to set Suite B curves");
2958 			return -1;
2959 		}
2960 
2961 		ecdh = EC_KEY_new_by_curve_name(NID_secp384r1);
2962 		if (!ecdh || SSL_set_tmp_ecdh(ssl, ecdh) != 1) {
2963 			EC_KEY_free(ecdh);
2964 			wpa_printf(MSG_INFO,
2965 				   "OpenSSL: Failed to set ECDH parameter");
2966 			return -1;
2967 		}
2968 		EC_KEY_free(ecdh);
2969 	}
2970 	if (flags & (TLS_CONN_SUITEB | TLS_CONN_SUITEB_NO_ECDH)) {
2971 #ifdef OPENSSL_IS_BORINGSSL
2972 		uint16_t sigalgs[1] = { SSL_SIGN_RSA_PKCS1_SHA384 };
2973 
2974 		if (SSL_CTX_set_verify_algorithm_prefs(conn->ssl_ctx, sigalgs,
2975 						       1) != 1) {
2976 			wpa_printf(MSG_INFO,
2977 				   "OpenSSL: Failed to set Suite B sigalgs");
2978 			return -1;
2979 		}
2980 #else /* OPENSSL_IS_BORINGSSL */
2981 		/* ECDSA+SHA384 if need to add EC support here */
2982 		if (SSL_set1_sigalgs_list(ssl, "RSA+SHA384") != 1) {
2983 			wpa_printf(MSG_INFO,
2984 				   "OpenSSL: Failed to set Suite B sigalgs");
2985 			return -1;
2986 		}
2987 #endif /* OPENSSL_IS_BORINGSSL */
2988 
2989 		SSL_set_options(ssl, SSL_OP_NO_TLSv1);
2990 		SSL_set_options(ssl, SSL_OP_NO_TLSv1_1);
2991 		SSL_set_cert_cb(ssl, suiteb_cert_cb, conn);
2992 	}
2993 #else /* OPENSSL_VERSION_NUMBER < 0x10002000L */
2994 	if (flags & (TLS_CONN_SUITEB | TLS_CONN_SUITEB_NO_ECDH)) {
2995 		wpa_printf(MSG_ERROR,
2996 			   "OpenSSL: Suite B RSA case not supported with this OpenSSL version");
2997 		return -1;
2998 	}
2999 #endif /* OPENSSL_VERSION_NUMBER */
3000 
3001 #ifdef OPENSSL_IS_BORINGSSL
3002 	if (openssl_ciphers && os_strcmp(openssl_ciphers, "SUITEB192") == 0) {
3003 		uint16_t sigalgs[1] = { SSL_SIGN_ECDSA_SECP384R1_SHA384 };
3004 		int nid[1] = { NID_secp384r1 };
3005 
3006 		if (SSL_set1_curves(ssl, nid, 1) != 1) {
3007 			wpa_printf(MSG_INFO,
3008 				   "OpenSSL: Failed to set Suite B curves");
3009 			return -1;
3010 		}
3011 
3012 		if (SSL_CTX_set_verify_algorithm_prefs(conn->ssl_ctx, sigalgs,
3013 						       1) != 1) {
3014 			wpa_printf(MSG_INFO,
3015 				   "OpenSSL: Failed to set Suite B sigalgs");
3016 			return -1;
3017 		}
3018 	}
3019 #else /* OPENSSL_IS_BORINGSSL */
3020 	if (!(flags & (TLS_CONN_SUITEB | TLS_CONN_SUITEB_NO_ECDH)) &&
3021 	    openssl_ciphers && SSL_set_cipher_list(ssl, openssl_ciphers) != 1) {
3022 		wpa_printf(MSG_INFO,
3023 			   "OpenSSL: Failed to set openssl_ciphers '%s'",
3024 			   openssl_ciphers);
3025 		return -1;
3026 	}
3027 #endif /* OPENSSL_IS_BORINGSSL */
3028 #else /* CONFIG_SUITEB */
3029 	if (openssl_ciphers && SSL_set_cipher_list(ssl, openssl_ciphers) != 1) {
3030 		wpa_printf(MSG_INFO,
3031 			   "OpenSSL: Failed to set openssl_ciphers '%s'",
3032 			   openssl_ciphers);
3033 		return -1;
3034 	}
3035 #endif /* CONFIG_SUITEB */
3036 
3037 	return 0;
3038 }
3039 
3040 
tls_connection_set_verify(void * ssl_ctx,struct tls_connection * conn,int verify_peer,unsigned int flags,const u8 * session_ctx,size_t session_ctx_len)3041 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
3042 			      int verify_peer, unsigned int flags,
3043 			      const u8 *session_ctx, size_t session_ctx_len)
3044 {
3045 	static int counter = 0;
3046 	struct tls_data *data = ssl_ctx;
3047 
3048 	if (conn == NULL)
3049 		return -1;
3050 
3051 	if (verify_peer) {
3052 		conn->ca_cert_verify = 1;
3053 		SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
3054 			       SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
3055 			       SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
3056 	} else {
3057 		conn->ca_cert_verify = 0;
3058 		SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
3059 	}
3060 
3061 	if (tls_set_conn_flags(conn, flags, NULL) < 0)
3062 		return -1;
3063 	conn->flags = flags;
3064 
3065 	SSL_set_accept_state(conn->ssl);
3066 
3067 	if (data->tls_session_lifetime == 0) {
3068 		/*
3069 		 * Set session id context to a unique value to make sure
3070 		 * session resumption cannot be used either through session
3071 		 * caching or TLS ticket extension.
3072 		 */
3073 		counter++;
3074 		SSL_set_session_id_context(conn->ssl,
3075 					   (const unsigned char *) &counter,
3076 					   sizeof(counter));
3077 	} else if (session_ctx) {
3078 		SSL_set_session_id_context(conn->ssl, session_ctx,
3079 					   session_ctx_len);
3080 	}
3081 
3082 	return 0;
3083 }
3084 
3085 
tls_connection_client_cert(struct tls_connection * conn,const char * client_cert,const u8 * client_cert_blob,size_t client_cert_blob_len)3086 static int tls_connection_client_cert(struct tls_connection *conn,
3087 				      const char *client_cert,
3088 				      const u8 *client_cert_blob,
3089 				      size_t client_cert_blob_len)
3090 {
3091 	if (client_cert == NULL && client_cert_blob == NULL)
3092 		return 0;
3093 
3094 #ifdef PKCS12_FUNCS
3095 #if OPENSSL_VERSION_NUMBER < 0x10002000L || defined(LIBRESSL_VERSION_NUMBER)
3096 	/*
3097 	 * Clear previously set extra chain certificates, if any, from PKCS#12
3098 	 * processing in tls_parse_pkcs12() to allow OpenSSL to build a new
3099 	 * chain properly.
3100 	 */
3101 	SSL_CTX_clear_extra_chain_certs(conn->ssl_ctx);
3102 #endif /* OPENSSL_VERSION_NUMBER < 0x10002000L */
3103 #endif /* PKCS12_FUNCS */
3104 
3105 	if (client_cert_blob &&
3106 	    SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
3107 				     client_cert_blob_len) == 1) {
3108 		wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
3109 			   "OK");
3110 		return 0;
3111 	} else if (client_cert_blob) {
3112 		tls_show_errors(MSG_DEBUG, __func__,
3113 				"SSL_use_certificate_ASN1 failed");
3114 	}
3115 
3116 	if (client_cert == NULL)
3117 		return -1;
3118 
3119 #ifdef ANDROID
3120 	if (os_strncmp("keystore://", client_cert, 11) == 0) {
3121 		BIO *bio = BIO_from_keystore(&client_cert[11]);
3122 		X509 *x509 = NULL;
3123 		int ret = -1;
3124 		if (bio) {
3125 			x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
3126 		}
3127 		if (x509) {
3128 			if (SSL_use_certificate(conn->ssl, x509) == 1)
3129 				ret = 0;
3130 			X509_free(x509);
3131 		}
3132 
3133 		/* Read additional certificates into the chain. */
3134 		while (bio) {
3135 			x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
3136 			if (x509) {
3137 				/* Takes ownership of x509 */
3138 				SSL_add0_chain_cert(conn->ssl, x509);
3139 			} else {
3140 				BIO_free(bio);
3141 				bio = NULL;
3142 			}
3143 		}
3144 		return ret;
3145 	}
3146 #endif /* ANDROID */
3147 
3148 #ifndef OPENSSL_NO_STDIO
3149 	if (SSL_use_certificate_file(conn->ssl, client_cert,
3150 				     SSL_FILETYPE_ASN1) == 1) {
3151 		wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
3152 			   " --> OK");
3153 		return 0;
3154 	}
3155 
3156 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
3157 	!defined(LIBRESSL_VERSION_NUMBER) && !defined(OPENSSL_IS_BORINGSSL)
3158 	if (SSL_use_certificate_chain_file(conn->ssl, client_cert) == 1) {
3159 		ERR_clear_error();
3160 		wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_chain_file"
3161 			   " --> OK");
3162 		return 0;
3163 	}
3164 #else
3165 	if (SSL_use_certificate_file(conn->ssl, client_cert,
3166 				     SSL_FILETYPE_PEM) == 1) {
3167 		ERR_clear_error();
3168 		wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
3169 			   " --> OK");
3170 		return 0;
3171 	}
3172 #endif
3173 
3174 	tls_show_errors(MSG_DEBUG, __func__,
3175 			"SSL_use_certificate_file failed");
3176 #else /* OPENSSL_NO_STDIO */
3177 	wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
3178 #endif /* OPENSSL_NO_STDIO */
3179 
3180 	return -1;
3181 }
3182 
3183 
tls_global_client_cert(struct tls_data * data,const char * client_cert)3184 static int tls_global_client_cert(struct tls_data *data,
3185 				  const char *client_cert)
3186 {
3187 #ifndef OPENSSL_NO_STDIO
3188 	SSL_CTX *ssl_ctx = data->ssl;
3189 
3190 	if (client_cert == NULL)
3191 		return 0;
3192 
3193 	if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
3194 					 SSL_FILETYPE_ASN1) != 1 &&
3195 	    SSL_CTX_use_certificate_chain_file(ssl_ctx, client_cert) != 1 &&
3196 	    SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
3197 					 SSL_FILETYPE_PEM) != 1) {
3198 		tls_show_errors(MSG_INFO, __func__,
3199 				"Failed to load client certificate");
3200 		return -1;
3201 	}
3202 	return 0;
3203 #else /* OPENSSL_NO_STDIO */
3204 	if (client_cert == NULL)
3205 		return 0;
3206 	wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
3207 	return -1;
3208 #endif /* OPENSSL_NO_STDIO */
3209 }
3210 
3211 
3212 #ifdef PKCS12_FUNCS
tls_parse_pkcs12(struct tls_data * data,SSL * ssl,PKCS12 * p12,const char * passwd)3213 static int tls_parse_pkcs12(struct tls_data *data, SSL *ssl, PKCS12 *p12,
3214 			    const char *passwd)
3215 {
3216 	EVP_PKEY *pkey;
3217 	X509 *cert;
3218 	STACK_OF(X509) *certs;
3219 	int res = 0;
3220 	char buf[256];
3221 
3222 	pkey = NULL;
3223 	cert = NULL;
3224 	certs = NULL;
3225 	if (!passwd)
3226 		passwd = "";
3227 	if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
3228 		tls_show_errors(MSG_DEBUG, __func__,
3229 				"Failed to parse PKCS12 file");
3230 		PKCS12_free(p12);
3231 		return -1;
3232 	}
3233 	wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
3234 
3235 	if (cert) {
3236 		X509_NAME_oneline(X509_get_subject_name(cert), buf,
3237 				  sizeof(buf));
3238 		wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
3239 			   "subject='%s'", buf);
3240 		if (ssl) {
3241 			if (SSL_use_certificate(ssl, cert) != 1)
3242 				res = -1;
3243 		} else {
3244 			if (SSL_CTX_use_certificate(data->ssl, cert) != 1)
3245 				res = -1;
3246 		}
3247 		X509_free(cert);
3248 	}
3249 
3250 	if (pkey) {
3251 		wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
3252 		if (ssl) {
3253 			if (SSL_use_PrivateKey(ssl, pkey) != 1)
3254 				res = -1;
3255 		} else {
3256 			if (SSL_CTX_use_PrivateKey(data->ssl, pkey) != 1)
3257 				res = -1;
3258 		}
3259 		EVP_PKEY_free(pkey);
3260 	}
3261 
3262 	if (certs) {
3263 #if OPENSSL_VERSION_NUMBER >= 0x10002000L && !defined(LIBRESSL_VERSION_NUMBER)
3264 		if (ssl)
3265 			SSL_clear_chain_certs(ssl);
3266 		else
3267 			SSL_CTX_clear_chain_certs(data->ssl);
3268 		while ((cert = sk_X509_pop(certs)) != NULL) {
3269 			X509_NAME_oneline(X509_get_subject_name(cert), buf,
3270 					  sizeof(buf));
3271 			wpa_printf(MSG_DEBUG, "TLS: additional certificate"
3272 				   " from PKCS12: subject='%s'", buf);
3273 			if ((ssl && SSL_add1_chain_cert(ssl, cert) != 1) ||
3274 			    (!ssl && SSL_CTX_add1_chain_cert(data->ssl,
3275 							     cert) != 1)) {
3276 				tls_show_errors(MSG_DEBUG, __func__,
3277 						"Failed to add additional certificate");
3278 				res = -1;
3279 				X509_free(cert);
3280 				break;
3281 			}
3282 			X509_free(cert);
3283 		}
3284 		if (!res) {
3285 			/* Try to continue anyway */
3286 		}
3287 		sk_X509_pop_free(certs, X509_free);
3288 #ifndef OPENSSL_IS_BORINGSSL
3289 		if (ssl)
3290 			res = SSL_build_cert_chain(
3291 				ssl,
3292 				SSL_BUILD_CHAIN_FLAG_CHECK |
3293 				SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR);
3294 		else
3295 			res = SSL_CTX_build_cert_chain(
3296 				data->ssl,
3297 				SSL_BUILD_CHAIN_FLAG_CHECK |
3298 				SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR);
3299 		if (!res) {
3300 			tls_show_errors(MSG_DEBUG, __func__,
3301 					"Failed to build certificate chain");
3302 		} else if (res == 2) {
3303 			wpa_printf(MSG_DEBUG,
3304 				   "TLS: Ignore certificate chain verification error when building chain with PKCS#12 extra certificates");
3305 		}
3306 #endif /* OPENSSL_IS_BORINGSSL */
3307 		/*
3308 		 * Try to continue regardless of result since it is possible for
3309 		 * the extra certificates not to be required.
3310 		 */
3311 		res = 0;
3312 #else /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
3313 		SSL_CTX_clear_extra_chain_certs(data->ssl);
3314 		while ((cert = sk_X509_pop(certs)) != NULL) {
3315 			X509_NAME_oneline(X509_get_subject_name(cert), buf,
3316 					  sizeof(buf));
3317 			wpa_printf(MSG_DEBUG, "TLS: additional certificate"
3318 				   " from PKCS12: subject='%s'", buf);
3319 			/*
3320 			 * There is no SSL equivalent for the chain cert - so
3321 			 * always add it to the context...
3322 			 */
3323 			if (SSL_CTX_add_extra_chain_cert(data->ssl, cert) != 1)
3324 			{
3325 				X509_free(cert);
3326 				res = -1;
3327 				break;
3328 			}
3329 		}
3330 		sk_X509_pop_free(certs, X509_free);
3331 #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
3332 	}
3333 
3334 	PKCS12_free(p12);
3335 
3336 	if (res < 0)
3337 		tls_get_errors(data);
3338 
3339 	return res;
3340 }
3341 #endif  /* PKCS12_FUNCS */
3342 
3343 
tls_read_pkcs12(struct tls_data * data,SSL * ssl,const char * private_key,const char * passwd)3344 static int tls_read_pkcs12(struct tls_data *data, SSL *ssl,
3345 			   const char *private_key, const char *passwd)
3346 {
3347 #ifdef PKCS12_FUNCS
3348 	FILE *f;
3349 	PKCS12 *p12;
3350 
3351 	f = fopen(private_key, "rb");
3352 	if (f == NULL)
3353 		return -1;
3354 
3355 	p12 = d2i_PKCS12_fp(f, NULL);
3356 	fclose(f);
3357 
3358 	if (p12 == NULL) {
3359 		tls_show_errors(MSG_INFO, __func__,
3360 				"Failed to use PKCS#12 file");
3361 		return -1;
3362 	}
3363 
3364 	return tls_parse_pkcs12(data, ssl, p12, passwd);
3365 
3366 #else /* PKCS12_FUNCS */
3367 	wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
3368 		   "p12/pfx files");
3369 	return -1;
3370 #endif  /* PKCS12_FUNCS */
3371 }
3372 
3373 
tls_read_pkcs12_blob(struct tls_data * data,SSL * ssl,const u8 * blob,size_t len,const char * passwd)3374 static int tls_read_pkcs12_blob(struct tls_data *data, SSL *ssl,
3375 				const u8 *blob, size_t len, const char *passwd)
3376 {
3377 #ifdef PKCS12_FUNCS
3378 	PKCS12 *p12;
3379 
3380 	p12 = d2i_PKCS12(NULL, (const unsigned char **) &blob, len);
3381 	if (p12 == NULL) {
3382 		tls_show_errors(MSG_INFO, __func__,
3383 				"Failed to use PKCS#12 blob");
3384 		return -1;
3385 	}
3386 
3387 	return tls_parse_pkcs12(data, ssl, p12, passwd);
3388 
3389 #else /* PKCS12_FUNCS */
3390 	wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
3391 		   "p12/pfx blobs");
3392 	return -1;
3393 #endif  /* PKCS12_FUNCS */
3394 }
3395 
3396 
3397 #ifndef OPENSSL_NO_ENGINE
tls_engine_get_cert(struct tls_connection * conn,const char * cert_id,X509 ** cert)3398 static int tls_engine_get_cert(struct tls_connection *conn,
3399 			       const char *cert_id,
3400 			       X509 **cert)
3401 {
3402 	/* this runs after the private key is loaded so no PIN is required */
3403 	struct {
3404 		const char *cert_id;
3405 		X509 *cert;
3406 	} params;
3407 	params.cert_id = cert_id;
3408 	params.cert = NULL;
3409 
3410 	if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
3411 			     0, &params, NULL, 1)) {
3412 		unsigned long err = ERR_get_error();
3413 
3414 		wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
3415 			   " '%s' [%s]", cert_id,
3416 			   ERR_error_string(err, NULL));
3417 		if (tls_is_pin_error(err))
3418 			return TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
3419 		return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
3420 	}
3421 	if (!params.cert) {
3422 		wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
3423 			   " '%s'", cert_id);
3424 		return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
3425 	}
3426 	*cert = params.cert;
3427 	return 0;
3428 }
3429 #endif /* OPENSSL_NO_ENGINE */
3430 
3431 
tls_connection_engine_client_cert(struct tls_connection * conn,const char * cert_id)3432 static int tls_connection_engine_client_cert(struct tls_connection *conn,
3433 					     const char *cert_id)
3434 {
3435 #ifndef OPENSSL_NO_ENGINE
3436 	X509 *cert;
3437 
3438 	if (tls_engine_get_cert(conn, cert_id, &cert))
3439 		return -1;
3440 
3441 	if (!SSL_use_certificate(conn->ssl, cert)) {
3442 		tls_show_errors(MSG_ERROR, __func__,
3443 				"SSL_use_certificate failed");
3444                 X509_free(cert);
3445 		return -1;
3446 	}
3447 	X509_free(cert);
3448 	wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
3449 		   "OK");
3450 	return 0;
3451 
3452 #else /* OPENSSL_NO_ENGINE */
3453 	return -1;
3454 #endif /* OPENSSL_NO_ENGINE */
3455 }
3456 
3457 
tls_connection_engine_ca_cert(struct tls_data * data,struct tls_connection * conn,const char * ca_cert_id)3458 static int tls_connection_engine_ca_cert(struct tls_data *data,
3459 					 struct tls_connection *conn,
3460 					 const char *ca_cert_id)
3461 {
3462 #ifndef OPENSSL_NO_ENGINE
3463 	X509 *cert;
3464 	SSL_CTX *ssl_ctx = data->ssl;
3465 	X509_STORE *store;
3466 
3467 	if (tls_engine_get_cert(conn, ca_cert_id, &cert))
3468 		return -1;
3469 
3470 	/* start off the same as tls_connection_ca_cert */
3471 	store = X509_STORE_new();
3472 	if (store == NULL) {
3473 		wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
3474 			   "certificate store", __func__);
3475 		X509_free(cert);
3476 		return -1;
3477 	}
3478 	SSL_CTX_set_cert_store(ssl_ctx, store);
3479 	if (!X509_STORE_add_cert(store, cert)) {
3480 		unsigned long err = ERR_peek_error();
3481 		tls_show_errors(MSG_WARNING, __func__,
3482 				"Failed to add CA certificate from engine "
3483 				"to certificate store");
3484 		if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
3485 		    ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
3486 			wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
3487 				   " already in hash table error",
3488 				   __func__);
3489 		} else {
3490 			X509_free(cert);
3491 			return -1;
3492 		}
3493 	}
3494 	X509_free(cert);
3495 	wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
3496 		   "to certificate store", __func__);
3497 	SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
3498 	conn->ca_cert_verify = 1;
3499 
3500 	return 0;
3501 
3502 #else /* OPENSSL_NO_ENGINE */
3503 	return -1;
3504 #endif /* OPENSSL_NO_ENGINE */
3505 }
3506 
3507 
tls_connection_engine_private_key(struct tls_connection * conn)3508 static int tls_connection_engine_private_key(struct tls_connection *conn)
3509 {
3510 #if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
3511 	if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
3512 		tls_show_errors(MSG_ERROR, __func__,
3513 				"ENGINE: cannot use private key for TLS");
3514 		return -1;
3515 	}
3516 	if (!SSL_check_private_key(conn->ssl)) {
3517 		tls_show_errors(MSG_INFO, __func__,
3518 				"Private key failed verification");
3519 		return -1;
3520 	}
3521 	return 0;
3522 #else /* OPENSSL_NO_ENGINE */
3523 	wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
3524 		   "engine support was not compiled in");
3525 	return -1;
3526 #endif /* OPENSSL_NO_ENGINE */
3527 }
3528 
3529 
3530 #ifndef OPENSSL_NO_STDIO
tls_passwd_cb(char * buf,int size,int rwflag,void * password)3531 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
3532 {
3533 	if (!password)
3534 		return 0;
3535 	os_strlcpy(buf, (const char *) password, size);
3536 	return os_strlen(buf);
3537 }
3538 #endif /* OPENSSL_NO_STDIO */
3539 
3540 
tls_use_private_key_file(struct tls_data * data,SSL * ssl,const char * private_key,const char * private_key_passwd)3541 static int tls_use_private_key_file(struct tls_data *data, SSL *ssl,
3542 				    const char *private_key,
3543 				    const char *private_key_passwd)
3544 {
3545 #ifndef OPENSSL_NO_STDIO
3546 	BIO *bio;
3547 	EVP_PKEY *pkey;
3548 	int ret;
3549 
3550 	/* First try ASN.1 (DER). */
3551 	bio = BIO_new_file(private_key, "r");
3552 	if (!bio)
3553 		return -1;
3554 	pkey = d2i_PrivateKey_bio(bio, NULL);
3555 	BIO_free(bio);
3556 
3557 	if (pkey) {
3558 		wpa_printf(MSG_DEBUG, "OpenSSL: %s (DER) --> loaded", __func__);
3559 	} else {
3560 		/* Try PEM with the provided password. */
3561 		bio = BIO_new_file(private_key, "r");
3562 		if (!bio)
3563 			return -1;
3564 		pkey = PEM_read_bio_PrivateKey(bio, NULL, tls_passwd_cb,
3565 					       (void *) private_key_passwd);
3566 		BIO_free(bio);
3567 		if (!pkey)
3568 			return -1;
3569 		wpa_printf(MSG_DEBUG, "OpenSSL: %s (PEM) --> loaded", __func__);
3570 		/* Clear errors from the previous failed load. */
3571 		ERR_clear_error();
3572 	}
3573 
3574 	if (ssl)
3575 		ret = SSL_use_PrivateKey(ssl, pkey);
3576 	else
3577 		ret = SSL_CTX_use_PrivateKey(data->ssl, pkey);
3578 
3579 	EVP_PKEY_free(pkey);
3580 	return ret == 1 ? 0 : -1;
3581 #else /* OPENSSL_NO_STDIO */
3582 	wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
3583 	return -1;
3584 #endif /* OPENSSL_NO_STDIO */
3585 }
3586 
3587 
tls_connection_private_key(struct tls_data * data,struct tls_connection * conn,const char * private_key,const char * private_key_passwd,const u8 * private_key_blob,size_t private_key_blob_len)3588 static int tls_connection_private_key(struct tls_data *data,
3589 				      struct tls_connection *conn,
3590 				      const char *private_key,
3591 				      const char *private_key_passwd,
3592 				      const u8 *private_key_blob,
3593 				      size_t private_key_blob_len)
3594 {
3595 	int ok;
3596 
3597 	if (private_key == NULL && private_key_blob == NULL)
3598 		return 0;
3599 
3600 	ok = 0;
3601 	while (private_key_blob) {
3602 		if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
3603 					    (u8 *) private_key_blob,
3604 					    private_key_blob_len) == 1) {
3605 			wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
3606 				   "ASN1(EVP_PKEY_RSA) --> OK");
3607 			ok = 1;
3608 			break;
3609 		}
3610 
3611 		if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
3612 					    (u8 *) private_key_blob,
3613 					    private_key_blob_len) == 1) {
3614 			wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
3615 				   "ASN1(EVP_PKEY_DSA) --> OK");
3616 			ok = 1;
3617 			break;
3618 		}
3619 
3620 		if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
3621 					       (u8 *) private_key_blob,
3622 					       private_key_blob_len) == 1) {
3623 			wpa_printf(MSG_DEBUG, "OpenSSL: "
3624 				   "SSL_use_RSAPrivateKey_ASN1 --> OK");
3625 			ok = 1;
3626 			break;
3627 		}
3628 
3629 		if (tls_read_pkcs12_blob(data, conn->ssl, private_key_blob,
3630 					 private_key_blob_len,
3631 					 private_key_passwd) == 0) {
3632 			wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
3633 				   "OK");
3634 			ok = 1;
3635 			break;
3636 		}
3637 
3638 		break;
3639 	}
3640 
3641 	while (!ok && private_key) {
3642 		if (tls_use_private_key_file(data, conn->ssl, private_key,
3643 					     private_key_passwd) == 0) {
3644 			ok = 1;
3645 			break;
3646 		}
3647 
3648 		if (tls_read_pkcs12(data, conn->ssl, private_key,
3649 				    private_key_passwd) == 0) {
3650 			wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
3651 				   "--> OK");
3652 			ok = 1;
3653 			break;
3654 		}
3655 
3656 		if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
3657 			wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
3658 				   "access certificate store --> OK");
3659 			ok = 1;
3660 			break;
3661 		}
3662 
3663 		break;
3664 	}
3665 
3666 	if (!ok) {
3667 		tls_show_errors(MSG_INFO, __func__,
3668 				"Failed to load private key");
3669 		return -1;
3670 	}
3671 	ERR_clear_error();
3672 
3673 	if (!SSL_check_private_key(conn->ssl)) {
3674 		tls_show_errors(MSG_INFO, __func__, "Private key failed "
3675 				"verification");
3676 		return -1;
3677 	}
3678 
3679 	wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
3680 	return 0;
3681 }
3682 
3683 
tls_global_private_key(struct tls_data * data,const char * private_key,const char * private_key_passwd)3684 static int tls_global_private_key(struct tls_data *data,
3685 				  const char *private_key,
3686 				  const char *private_key_passwd)
3687 {
3688 	SSL_CTX *ssl_ctx = data->ssl;
3689 
3690 	if (private_key == NULL)
3691 		return 0;
3692 
3693 	if (tls_use_private_key_file(data, NULL, private_key,
3694 				     private_key_passwd) &&
3695 	    tls_read_pkcs12(data, NULL, private_key, private_key_passwd)) {
3696 		tls_show_errors(MSG_INFO, __func__,
3697 				"Failed to load private key");
3698 		ERR_clear_error();
3699 		return -1;
3700 	}
3701 	ERR_clear_error();
3702 
3703 	if (!SSL_CTX_check_private_key(ssl_ctx)) {
3704 		tls_show_errors(MSG_INFO, __func__,
3705 				"Private key failed verification");
3706 		return -1;
3707 	}
3708 
3709 	return 0;
3710 }
3711 
3712 
tls_connection_dh(struct tls_connection * conn,const char * dh_file)3713 static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
3714 {
3715 #ifdef OPENSSL_NO_DH
3716 	if (dh_file == NULL)
3717 		return 0;
3718 	wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
3719 		   "dh_file specified");
3720 	return -1;
3721 #else /* OPENSSL_NO_DH */
3722 	DH *dh;
3723 	BIO *bio;
3724 
3725 	/* TODO: add support for dh_blob */
3726 	if (dh_file == NULL)
3727 		return 0;
3728 	if (conn == NULL)
3729 		return -1;
3730 
3731 	bio = BIO_new_file(dh_file, "r");
3732 	if (bio == NULL) {
3733 		wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
3734 			   dh_file, ERR_error_string(ERR_get_error(), NULL));
3735 		return -1;
3736 	}
3737 	dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3738 	BIO_free(bio);
3739 #ifndef OPENSSL_NO_DSA
3740 	while (dh == NULL) {
3741 		DSA *dsa;
3742 		wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
3743 			   " trying to parse as DSA params", dh_file,
3744 			   ERR_error_string(ERR_get_error(), NULL));
3745 		bio = BIO_new_file(dh_file, "r");
3746 		if (bio == NULL)
3747 			break;
3748 		dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
3749 		BIO_free(bio);
3750 		if (!dsa) {
3751 			wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
3752 				   "'%s': %s", dh_file,
3753 				   ERR_error_string(ERR_get_error(), NULL));
3754 			break;
3755 		}
3756 
3757 		wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
3758 		dh = DSA_dup_DH(dsa);
3759 		DSA_free(dsa);
3760 		if (dh == NULL) {
3761 			wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
3762 				   "params into DH params");
3763 			break;
3764 		}
3765 		break;
3766 	}
3767 #endif /* !OPENSSL_NO_DSA */
3768 	if (dh == NULL) {
3769 		wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
3770 			   "'%s'", dh_file);
3771 		return -1;
3772 	}
3773 
3774 	if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
3775 		wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
3776 			   "%s", dh_file,
3777 			   ERR_error_string(ERR_get_error(), NULL));
3778 		DH_free(dh);
3779 		return -1;
3780 	}
3781 	DH_free(dh);
3782 	return 0;
3783 #endif /* OPENSSL_NO_DH */
3784 }
3785 
3786 
tls_global_dh(struct tls_data * data,const char * dh_file)3787 static int tls_global_dh(struct tls_data *data, const char *dh_file)
3788 {
3789 #ifdef OPENSSL_NO_DH
3790 	if (dh_file == NULL)
3791 		return 0;
3792 	wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
3793 		   "dh_file specified");
3794 	return -1;
3795 #else /* OPENSSL_NO_DH */
3796 	SSL_CTX *ssl_ctx = data->ssl;
3797 	DH *dh;
3798 	BIO *bio;
3799 
3800 	/* TODO: add support for dh_blob */
3801 	if (dh_file == NULL)
3802 		return 0;
3803 	if (ssl_ctx == NULL)
3804 		return -1;
3805 
3806 	bio = BIO_new_file(dh_file, "r");
3807 	if (bio == NULL) {
3808 		wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
3809 			   dh_file, ERR_error_string(ERR_get_error(), NULL));
3810 		return -1;
3811 	}
3812 	dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3813 	BIO_free(bio);
3814 #ifndef OPENSSL_NO_DSA
3815 	while (dh == NULL) {
3816 		DSA *dsa;
3817 		wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
3818 			   " trying to parse as DSA params", dh_file,
3819 			   ERR_error_string(ERR_get_error(), NULL));
3820 		bio = BIO_new_file(dh_file, "r");
3821 		if (bio == NULL)
3822 			break;
3823 		dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
3824 		BIO_free(bio);
3825 		if (!dsa) {
3826 			wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
3827 				   "'%s': %s", dh_file,
3828 				   ERR_error_string(ERR_get_error(), NULL));
3829 			break;
3830 		}
3831 
3832 		wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
3833 		dh = DSA_dup_DH(dsa);
3834 		DSA_free(dsa);
3835 		if (dh == NULL) {
3836 			wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
3837 				   "params into DH params");
3838 			break;
3839 		}
3840 		break;
3841 	}
3842 #endif /* !OPENSSL_NO_DSA */
3843 	if (dh == NULL) {
3844 		wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
3845 			   "'%s'", dh_file);
3846 		return -1;
3847 	}
3848 
3849 	if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
3850 		wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
3851 			   "%s", dh_file,
3852 			   ERR_error_string(ERR_get_error(), NULL));
3853 		DH_free(dh);
3854 		return -1;
3855 	}
3856 	DH_free(dh);
3857 	return 0;
3858 #endif /* OPENSSL_NO_DH */
3859 }
3860 
3861 
tls_connection_get_random(void * ssl_ctx,struct tls_connection * conn,struct tls_random * keys)3862 int tls_connection_get_random(void *ssl_ctx, struct tls_connection *conn,
3863 			      struct tls_random *keys)
3864 {
3865 	SSL *ssl;
3866 
3867 	if (conn == NULL || keys == NULL)
3868 		return -1;
3869 	ssl = conn->ssl;
3870 	if (ssl == NULL)
3871 		return -1;
3872 
3873 	os_memset(keys, 0, sizeof(*keys));
3874 	keys->client_random = conn->client_random;
3875 	keys->client_random_len = SSL_get_client_random(
3876 		ssl, conn->client_random, sizeof(conn->client_random));
3877 	keys->server_random = conn->server_random;
3878 	keys->server_random_len = SSL_get_server_random(
3879 		ssl, conn->server_random, sizeof(conn->server_random));
3880 
3881 	return 0;
3882 }
3883 
3884 
3885 #ifdef OPENSSL_NEED_EAP_FAST_PRF
openssl_get_keyblock_size(SSL * ssl)3886 static int openssl_get_keyblock_size(SSL *ssl)
3887 {
3888 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
3889 	(defined(LIBRESSL_VERSION_NUMBER) && \
3890 	 LIBRESSL_VERSION_NUMBER < 0x20700000L)
3891 	const EVP_CIPHER *c;
3892 	const EVP_MD *h;
3893 	int md_size;
3894 
3895 	if (ssl->enc_read_ctx == NULL || ssl->enc_read_ctx->cipher == NULL ||
3896 	    ssl->read_hash == NULL)
3897 		return -1;
3898 
3899 	c = ssl->enc_read_ctx->cipher;
3900 	h = EVP_MD_CTX_md(ssl->read_hash);
3901 	if (h)
3902 		md_size = EVP_MD_size(h);
3903 	else if (ssl->s3)
3904 		md_size = ssl->s3->tmp.new_mac_secret_size;
3905 	else
3906 		return -1;
3907 
3908 	wpa_printf(MSG_DEBUG, "OpenSSL: keyblock size: key_len=%d MD_size=%d "
3909 		   "IV_len=%d", EVP_CIPHER_key_length(c), md_size,
3910 		   EVP_CIPHER_iv_length(c));
3911 	return 2 * (EVP_CIPHER_key_length(c) +
3912 		    md_size +
3913 		    EVP_CIPHER_iv_length(c));
3914 #else
3915 	const SSL_CIPHER *ssl_cipher;
3916 	int cipher, digest;
3917 	const EVP_CIPHER *c;
3918 	const EVP_MD *h;
3919 
3920 	ssl_cipher = SSL_get_current_cipher(ssl);
3921 	if (!ssl_cipher)
3922 		return -1;
3923 	cipher = SSL_CIPHER_get_cipher_nid(ssl_cipher);
3924 	digest = SSL_CIPHER_get_digest_nid(ssl_cipher);
3925 	wpa_printf(MSG_DEBUG, "OpenSSL: cipher nid %d digest nid %d",
3926 		   cipher, digest);
3927 	if (cipher < 0 || digest < 0)
3928 		return -1;
3929 	c = EVP_get_cipherbynid(cipher);
3930 	h = EVP_get_digestbynid(digest);
3931 	if (!c || !h)
3932 		return -1;
3933 
3934 	wpa_printf(MSG_DEBUG,
3935 		   "OpenSSL: keyblock size: key_len=%d MD_size=%d IV_len=%d",
3936 		   EVP_CIPHER_key_length(c), EVP_MD_size(h),
3937 		   EVP_CIPHER_iv_length(c));
3938 	return 2 * (EVP_CIPHER_key_length(c) + EVP_MD_size(h) +
3939 		    EVP_CIPHER_iv_length(c));
3940 #endif
3941 }
3942 #endif /* OPENSSL_NEED_EAP_FAST_PRF */
3943 
3944 
tls_connection_export_key(void * tls_ctx,struct tls_connection * conn,const char * label,const u8 * context,size_t context_len,u8 * out,size_t out_len)3945 int tls_connection_export_key(void *tls_ctx, struct tls_connection *conn,
3946 			      const char *label, const u8 *context,
3947 			      size_t context_len, u8 *out, size_t out_len)
3948 {
3949 	if (!conn ||
3950 	    SSL_export_keying_material(conn->ssl, out, out_len, label,
3951 				       os_strlen(label), context, context_len,
3952 				       context != NULL) != 1)
3953 		return -1;
3954 	return 0;
3955 }
3956 
3957 
tls_connection_get_eap_fast_key(void * tls_ctx,struct tls_connection * conn,u8 * out,size_t out_len)3958 int tls_connection_get_eap_fast_key(void *tls_ctx, struct tls_connection *conn,
3959 				    u8 *out, size_t out_len)
3960 {
3961 #ifdef OPENSSL_NEED_EAP_FAST_PRF
3962 	SSL *ssl;
3963 	SSL_SESSION *sess;
3964 	u8 *rnd;
3965 	int ret = -1;
3966 	int skip = 0;
3967 	u8 *tmp_out = NULL;
3968 	u8 *_out = out;
3969 	unsigned char client_random[SSL3_RANDOM_SIZE];
3970 	unsigned char server_random[SSL3_RANDOM_SIZE];
3971 	unsigned char master_key[64];
3972 	size_t master_key_len;
3973 	const char *ver;
3974 
3975 	/*
3976 	 * TLS library did not support EAP-FAST key generation, so get the
3977 	 * needed TLS session parameters and use an internal implementation of
3978 	 * TLS PRF to derive the key.
3979 	 */
3980 
3981 	if (conn == NULL)
3982 		return -1;
3983 	ssl = conn->ssl;
3984 	if (ssl == NULL)
3985 		return -1;
3986 	ver = SSL_get_version(ssl);
3987 	sess = SSL_get_session(ssl);
3988 	if (!ver || !sess)
3989 		return -1;
3990 
3991 	skip = openssl_get_keyblock_size(ssl);
3992 	if (skip < 0)
3993 		return -1;
3994 	tmp_out = os_malloc(skip + out_len);
3995 	if (!tmp_out)
3996 		return -1;
3997 	_out = tmp_out;
3998 
3999 	rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
4000 	if (!rnd) {
4001 		os_free(tmp_out);
4002 		return -1;
4003 	}
4004 
4005 	SSL_get_client_random(ssl, client_random, sizeof(client_random));
4006 	SSL_get_server_random(ssl, server_random, sizeof(server_random));
4007 	master_key_len = SSL_SESSION_get_master_key(sess, master_key,
4008 						    sizeof(master_key));
4009 
4010 	os_memcpy(rnd, server_random, SSL3_RANDOM_SIZE);
4011 	os_memcpy(rnd + SSL3_RANDOM_SIZE, client_random, SSL3_RANDOM_SIZE);
4012 
4013 	if (os_strcmp(ver, "TLSv1.2") == 0) {
4014 		tls_prf_sha256(master_key, master_key_len,
4015 			       "key expansion", rnd, 2 * SSL3_RANDOM_SIZE,
4016 			       _out, skip + out_len);
4017 		ret = 0;
4018 	} else if (tls_prf_sha1_md5(master_key, master_key_len,
4019 				    "key expansion", rnd, 2 * SSL3_RANDOM_SIZE,
4020 				    _out, skip + out_len) == 0) {
4021 		ret = 0;
4022 	}
4023 	os_memset(master_key, 0, sizeof(master_key));
4024 	os_free(rnd);
4025 	if (ret == 0)
4026 		os_memcpy(out, _out + skip, out_len);
4027 	bin_clear_free(tmp_out, skip);
4028 
4029 	return ret;
4030 #else /* OPENSSL_NEED_EAP_FAST_PRF */
4031 	wpa_printf(MSG_ERROR,
4032 		   "OpenSSL: EAP-FAST keys cannot be exported in FIPS mode");
4033 	return -1;
4034 #endif /* OPENSSL_NEED_EAP_FAST_PRF */
4035 }
4036 
4037 
4038 static struct wpabuf *
openssl_handshake(struct tls_connection * conn,const struct wpabuf * in_data)4039 openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data)
4040 {
4041 	int res;
4042 	struct wpabuf *out_data;
4043 
4044 	/*
4045 	 * Give TLS handshake data from the server (if available) to OpenSSL
4046 	 * for processing.
4047 	 */
4048 	if (in_data && wpabuf_len(in_data) > 0 &&
4049 	    BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
4050 	    < 0) {
4051 		tls_show_errors(MSG_INFO, __func__,
4052 				"Handshake failed - BIO_write");
4053 		return NULL;
4054 	}
4055 
4056 	/* Initiate TLS handshake or continue the existing handshake */
4057 	if (conn->server)
4058 		res = SSL_accept(conn->ssl);
4059 	else
4060 		res = SSL_connect(conn->ssl);
4061 	if (res != 1) {
4062 		int err = SSL_get_error(conn->ssl, res);
4063 		if (err == SSL_ERROR_WANT_READ)
4064 			wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
4065 				   "more data");
4066 		else if (err == SSL_ERROR_WANT_WRITE)
4067 			wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
4068 				   "write");
4069 		else {
4070 			tls_show_errors(MSG_INFO, __func__, "SSL_connect");
4071 			conn->failed++;
4072 			if (!conn->server && !conn->client_hello_generated) {
4073 				/* The server would not understand TLS Alert
4074 				 * before ClientHello, so simply terminate
4075 				 * handshake on this type of error case caused
4076 				 * by a likely internal error like no ciphers
4077 				 * available. */
4078 				wpa_printf(MSG_DEBUG,
4079 					   "OpenSSL: Could not generate ClientHello");
4080 				conn->write_alerts++;
4081 				return NULL;
4082 			}
4083 		}
4084 	}
4085 
4086 	if (!conn->server && !conn->failed)
4087 		conn->client_hello_generated = 1;
4088 
4089 #ifdef CONFIG_SUITEB
4090 	if ((conn->flags & TLS_CONN_SUITEB) && !conn->server &&
4091 	    os_strncmp(SSL_get_cipher(conn->ssl), "DHE-", 4) == 0 &&
4092 	    conn->server_dh_prime_len < 3072) {
4093 		struct tls_context *context = conn->context;
4094 
4095 		/*
4096 		 * This should not be reached since earlier cert_cb should have
4097 		 * terminated the handshake. Keep this check here for extra
4098 		 * protection if anything goes wrong with the more low-level
4099 		 * checks based on having to parse the TLS handshake messages.
4100 		 */
4101 		wpa_printf(MSG_DEBUG,
4102 			   "OpenSSL: Server DH prime length: %d bits",
4103 			   conn->server_dh_prime_len);
4104 
4105 		if (context->event_cb) {
4106 			union tls_event_data ev;
4107 
4108 			os_memset(&ev, 0, sizeof(ev));
4109 			ev.alert.is_local = 1;
4110 			ev.alert.type = "fatal";
4111 			ev.alert.description = "insufficient security";
4112 			context->event_cb(context->cb_ctx, TLS_ALERT, &ev);
4113 		}
4114 		/*
4115 		 * Could send a TLS Alert to the server, but for now, simply
4116 		 * terminate handshake.
4117 		 */
4118 		conn->failed++;
4119 		conn->write_alerts++;
4120 		return NULL;
4121 	}
4122 #endif /* CONFIG_SUITEB */
4123 
4124 	/* Get the TLS handshake data to be sent to the server */
4125 	res = BIO_ctrl_pending(conn->ssl_out);
4126 	wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
4127 	out_data = wpabuf_alloc(res);
4128 	if (out_data == NULL) {
4129 		wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
4130 			   "handshake output (%d bytes)", res);
4131 		if (BIO_reset(conn->ssl_out) < 0) {
4132 			tls_show_errors(MSG_INFO, __func__,
4133 					"BIO_reset failed");
4134 		}
4135 		return NULL;
4136 	}
4137 	res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
4138 				      res);
4139 	if (res < 0) {
4140 		tls_show_errors(MSG_INFO, __func__,
4141 				"Handshake failed - BIO_read");
4142 		if (BIO_reset(conn->ssl_out) < 0) {
4143 			tls_show_errors(MSG_INFO, __func__,
4144 					"BIO_reset failed");
4145 		}
4146 		wpabuf_free(out_data);
4147 		return NULL;
4148 	}
4149 	wpabuf_put(out_data, res);
4150 
4151 	return out_data;
4152 }
4153 
4154 
4155 static struct wpabuf *
openssl_get_appl_data(struct tls_connection * conn,size_t max_len)4156 openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
4157 {
4158 	struct wpabuf *appl_data;
4159 	int res;
4160 
4161 	appl_data = wpabuf_alloc(max_len + 100);
4162 	if (appl_data == NULL)
4163 		return NULL;
4164 
4165 	res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
4166 		       wpabuf_size(appl_data));
4167 	if (res < 0) {
4168 		int err = SSL_get_error(conn->ssl, res);
4169 		if (err == SSL_ERROR_WANT_READ ||
4170 		    err == SSL_ERROR_WANT_WRITE) {
4171 			wpa_printf(MSG_DEBUG, "SSL: No Application Data "
4172 				   "included");
4173 		} else {
4174 			tls_show_errors(MSG_INFO, __func__,
4175 					"Failed to read possible "
4176 					"Application Data");
4177 		}
4178 		wpabuf_free(appl_data);
4179 		return NULL;
4180 	}
4181 
4182 	wpabuf_put(appl_data, res);
4183 	wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
4184 			    "message", appl_data);
4185 
4186 	return appl_data;
4187 }
4188 
4189 
4190 static struct wpabuf *
openssl_connection_handshake(struct tls_connection * conn,const struct wpabuf * in_data,struct wpabuf ** appl_data)4191 openssl_connection_handshake(struct tls_connection *conn,
4192 			     const struct wpabuf *in_data,
4193 			     struct wpabuf **appl_data)
4194 {
4195 	struct wpabuf *out_data;
4196 
4197 	if (appl_data)
4198 		*appl_data = NULL;
4199 
4200 	out_data = openssl_handshake(conn, in_data);
4201 	if (out_data == NULL)
4202 		return NULL;
4203 	if (conn->invalid_hb_used) {
4204 		wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
4205 		wpabuf_free(out_data);
4206 		return NULL;
4207 	}
4208 
4209 	if (SSL_is_init_finished(conn->ssl)) {
4210 		wpa_printf(MSG_DEBUG,
4211 			   "OpenSSL: Handshake finished - resumed=%d",
4212 			   tls_connection_resumed(conn->ssl_ctx, conn));
4213 		if (appl_data && in_data)
4214 			*appl_data = openssl_get_appl_data(conn,
4215 							   wpabuf_len(in_data));
4216 	}
4217 
4218 	if (conn->invalid_hb_used) {
4219 		wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
4220 		if (appl_data) {
4221 			wpabuf_free(*appl_data);
4222 			*appl_data = NULL;
4223 		}
4224 		wpabuf_free(out_data);
4225 		return NULL;
4226 	}
4227 
4228 	return out_data;
4229 }
4230 
4231 
4232 struct wpabuf *
tls_connection_handshake(void * ssl_ctx,struct tls_connection * conn,const struct wpabuf * in_data,struct wpabuf ** appl_data)4233 tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
4234 			 const struct wpabuf *in_data,
4235 			 struct wpabuf **appl_data)
4236 {
4237 	return openssl_connection_handshake(conn, in_data, appl_data);
4238 }
4239 
4240 
tls_connection_server_handshake(void * tls_ctx,struct tls_connection * conn,const struct wpabuf * in_data,struct wpabuf ** appl_data)4241 struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
4242 						struct tls_connection *conn,
4243 						const struct wpabuf *in_data,
4244 						struct wpabuf **appl_data)
4245 {
4246 	conn->server = 1;
4247 	return openssl_connection_handshake(conn, in_data, appl_data);
4248 }
4249 
4250 
tls_connection_encrypt(void * tls_ctx,struct tls_connection * conn,const struct wpabuf * in_data)4251 struct wpabuf * tls_connection_encrypt(void *tls_ctx,
4252 				       struct tls_connection *conn,
4253 				       const struct wpabuf *in_data)
4254 {
4255 	int res;
4256 	struct wpabuf *buf;
4257 
4258 	if (conn == NULL)
4259 		return NULL;
4260 
4261 	/* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
4262 	if ((res = BIO_reset(conn->ssl_in)) < 0 ||
4263 	    (res = BIO_reset(conn->ssl_out)) < 0) {
4264 		tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
4265 		return NULL;
4266 	}
4267 	res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
4268 	if (res < 0) {
4269 		tls_show_errors(MSG_INFO, __func__,
4270 				"Encryption failed - SSL_write");
4271 		return NULL;
4272 	}
4273 
4274 	/* Read encrypted data to be sent to the server */
4275 	buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
4276 	if (buf == NULL)
4277 		return NULL;
4278 	res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
4279 	if (res < 0) {
4280 		tls_show_errors(MSG_INFO, __func__,
4281 				"Encryption failed - BIO_read");
4282 		wpabuf_free(buf);
4283 		return NULL;
4284 	}
4285 	wpabuf_put(buf, res);
4286 
4287 	return buf;
4288 }
4289 
4290 
tls_connection_decrypt(void * tls_ctx,struct tls_connection * conn,const struct wpabuf * in_data)4291 struct wpabuf * tls_connection_decrypt(void *tls_ctx,
4292 				       struct tls_connection *conn,
4293 				       const struct wpabuf *in_data)
4294 {
4295 	int res;
4296 	struct wpabuf *buf;
4297 
4298 	/* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
4299 	res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
4300 			wpabuf_len(in_data));
4301 	if (res < 0) {
4302 		tls_show_errors(MSG_INFO, __func__,
4303 				"Decryption failed - BIO_write");
4304 		return NULL;
4305 	}
4306 	if (BIO_reset(conn->ssl_out) < 0) {
4307 		tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
4308 		return NULL;
4309 	}
4310 
4311 	/* Read decrypted data for further processing */
4312 	/*
4313 	 * Even though we try to disable TLS compression, it is possible that
4314 	 * this cannot be done with all TLS libraries. Add extra buffer space
4315 	 * to handle the possibility of the decrypted data being longer than
4316 	 * input data.
4317 	 */
4318 	buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
4319 	if (buf == NULL)
4320 		return NULL;
4321 	res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
4322 	if (res < 0) {
4323 		tls_show_errors(MSG_INFO, __func__,
4324 				"Decryption failed - SSL_read");
4325 		wpabuf_free(buf);
4326 		return NULL;
4327 	}
4328 	wpabuf_put(buf, res);
4329 
4330 	if (conn->invalid_hb_used) {
4331 		wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
4332 		wpabuf_free(buf);
4333 		return NULL;
4334 	}
4335 
4336 	return buf;
4337 }
4338 
4339 
tls_connection_resumed(void * ssl_ctx,struct tls_connection * conn)4340 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
4341 {
4342 	return conn ? SSL_session_reused(conn->ssl) : 0;
4343 }
4344 
4345 
tls_connection_set_cipher_list(void * tls_ctx,struct tls_connection * conn,u8 * ciphers)4346 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
4347 				   u8 *ciphers)
4348 {
4349 	char buf[500], *pos, *end;
4350 	u8 *c;
4351 	int ret;
4352 
4353 	if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
4354 		return -1;
4355 
4356 	buf[0] = '\0';
4357 	pos = buf;
4358 	end = pos + sizeof(buf);
4359 
4360 	c = ciphers;
4361 	while (*c != TLS_CIPHER_NONE) {
4362 		const char *suite;
4363 
4364 		switch (*c) {
4365 		case TLS_CIPHER_RC4_SHA:
4366 			suite = "RC4-SHA";
4367 			break;
4368 		case TLS_CIPHER_AES128_SHA:
4369 			suite = "AES128-SHA";
4370 			break;
4371 		case TLS_CIPHER_RSA_DHE_AES128_SHA:
4372 			suite = "DHE-RSA-AES128-SHA";
4373 			break;
4374 		case TLS_CIPHER_ANON_DH_AES128_SHA:
4375 			suite = "ADH-AES128-SHA";
4376 			break;
4377 		case TLS_CIPHER_RSA_DHE_AES256_SHA:
4378 			suite = "DHE-RSA-AES256-SHA";
4379 			break;
4380 		case TLS_CIPHER_AES256_SHA:
4381 			suite = "AES256-SHA";
4382 			break;
4383 		default:
4384 			wpa_printf(MSG_DEBUG, "TLS: Unsupported "
4385 				   "cipher selection: %d", *c);
4386 			return -1;
4387 		}
4388 		ret = os_snprintf(pos, end - pos, ":%s", suite);
4389 		if (os_snprintf_error(end - pos, ret))
4390 			break;
4391 		pos += ret;
4392 
4393 		c++;
4394 	}
4395 
4396 	wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
4397 
4398 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
4399 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
4400 	if (os_strstr(buf, ":ADH-")) {
4401 		/*
4402 		 * Need to drop to security level 0 to allow anonymous
4403 		 * cipher suites for EAP-FAST.
4404 		 */
4405 		SSL_set_security_level(conn->ssl, 0);
4406 	} else if (SSL_get_security_level(conn->ssl) == 0) {
4407 		/* Force at least security level 1 */
4408 		SSL_set_security_level(conn->ssl, 1);
4409 	}
4410 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4411 #endif
4412 
4413 	if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
4414 		tls_show_errors(MSG_INFO, __func__,
4415 				"Cipher suite configuration failed");
4416 		return -1;
4417 	}
4418 
4419 	return 0;
4420 }
4421 
4422 
tls_get_version(void * ssl_ctx,struct tls_connection * conn,char * buf,size_t buflen)4423 int tls_get_version(void *ssl_ctx, struct tls_connection *conn,
4424 		    char *buf, size_t buflen)
4425 {
4426 	const char *name;
4427 	if (conn == NULL || conn->ssl == NULL)
4428 		return -1;
4429 
4430 	name = SSL_get_version(conn->ssl);
4431 	if (name == NULL)
4432 		return -1;
4433 
4434 	os_strlcpy(buf, name, buflen);
4435 	return 0;
4436 }
4437 
4438 
tls_get_cipher(void * ssl_ctx,struct tls_connection * conn,char * buf,size_t buflen)4439 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
4440 		   char *buf, size_t buflen)
4441 {
4442 	const char *name;
4443 	if (conn == NULL || conn->ssl == NULL)
4444 		return -1;
4445 
4446 	name = SSL_get_cipher(conn->ssl);
4447 	if (name == NULL)
4448 		return -1;
4449 
4450 	os_strlcpy(buf, name, buflen);
4451 	return 0;
4452 }
4453 
4454 
tls_connection_enable_workaround(void * ssl_ctx,struct tls_connection * conn)4455 int tls_connection_enable_workaround(void *ssl_ctx,
4456 				     struct tls_connection *conn)
4457 {
4458 	SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
4459 
4460 	return 0;
4461 }
4462 
4463 
4464 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
4465 /* ClientHello TLS extensions require a patch to openssl, so this function is
4466  * commented out unless explicitly needed for EAP-FAST in order to be able to
4467  * build this file with unmodified openssl. */
tls_connection_client_hello_ext(void * ssl_ctx,struct tls_connection * conn,int ext_type,const u8 * data,size_t data_len)4468 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
4469 				    int ext_type, const u8 *data,
4470 				    size_t data_len)
4471 {
4472 	if (conn == NULL || conn->ssl == NULL || ext_type != 35)
4473 		return -1;
4474 
4475 	if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
4476 				       data_len) != 1)
4477 		return -1;
4478 
4479 	return 0;
4480 }
4481 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4482 
4483 
tls_connection_get_failed(void * ssl_ctx,struct tls_connection * conn)4484 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
4485 {
4486 	if (conn == NULL)
4487 		return -1;
4488 	return conn->failed;
4489 }
4490 
4491 
tls_connection_get_read_alerts(void * ssl_ctx,struct tls_connection * conn)4492 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
4493 {
4494 	if (conn == NULL)
4495 		return -1;
4496 	return conn->read_alerts;
4497 }
4498 
4499 
tls_connection_get_write_alerts(void * ssl_ctx,struct tls_connection * conn)4500 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
4501 {
4502 	if (conn == NULL)
4503 		return -1;
4504 	return conn->write_alerts;
4505 }
4506 
4507 
4508 #ifdef HAVE_OCSP
4509 
ocsp_debug_print_resp(OCSP_RESPONSE * rsp)4510 static void ocsp_debug_print_resp(OCSP_RESPONSE *rsp)
4511 {
4512 #ifndef CONFIG_NO_STDOUT_DEBUG
4513 	BIO *out;
4514 	size_t rlen;
4515 	char *txt;
4516 	int res;
4517 
4518 	if (wpa_debug_level > MSG_DEBUG)
4519 		return;
4520 
4521 	out = BIO_new(BIO_s_mem());
4522 	if (!out)
4523 		return;
4524 
4525 	OCSP_RESPONSE_print(out, rsp, 0);
4526 	rlen = BIO_ctrl_pending(out);
4527 	txt = os_malloc(rlen + 1);
4528 	if (!txt) {
4529 		BIO_free(out);
4530 		return;
4531 	}
4532 
4533 	res = BIO_read(out, txt, rlen);
4534 	if (res > 0) {
4535 		txt[res] = '\0';
4536 		wpa_printf(MSG_DEBUG, "OpenSSL: OCSP Response\n%s", txt);
4537 	}
4538 	os_free(txt);
4539 	BIO_free(out);
4540 #endif /* CONFIG_NO_STDOUT_DEBUG */
4541 }
4542 
4543 
debug_print_cert(X509 * cert,const char * title)4544 static void debug_print_cert(X509 *cert, const char *title)
4545 {
4546 #ifndef CONFIG_NO_STDOUT_DEBUG
4547 	BIO *out;
4548 	size_t rlen;
4549 	char *txt;
4550 	int res;
4551 
4552 	if (wpa_debug_level > MSG_DEBUG)
4553 		return;
4554 
4555 	out = BIO_new(BIO_s_mem());
4556 	if (!out)
4557 		return;
4558 
4559 	X509_print(out, cert);
4560 	rlen = BIO_ctrl_pending(out);
4561 	txt = os_malloc(rlen + 1);
4562 	if (!txt) {
4563 		BIO_free(out);
4564 		return;
4565 	}
4566 
4567 	res = BIO_read(out, txt, rlen);
4568 	if (res > 0) {
4569 		txt[res] = '\0';
4570 		wpa_printf(MSG_DEBUG, "OpenSSL: %s\n%s", title, txt);
4571 	}
4572 	os_free(txt);
4573 
4574 	BIO_free(out);
4575 #endif /* CONFIG_NO_STDOUT_DEBUG */
4576 }
4577 
4578 
ocsp_resp_cb(SSL * s,void * arg)4579 static int ocsp_resp_cb(SSL *s, void *arg)
4580 {
4581 	struct tls_connection *conn = arg;
4582 	const unsigned char *p;
4583 	int len, status, reason, res;
4584 	OCSP_RESPONSE *rsp;
4585 	OCSP_BASICRESP *basic;
4586 	OCSP_CERTID *id;
4587 	ASN1_GENERALIZEDTIME *produced_at, *this_update, *next_update;
4588 	X509_STORE *store;
4589 	STACK_OF(X509) *certs = NULL;
4590 
4591 	len = SSL_get_tlsext_status_ocsp_resp(s, &p);
4592 	if (!p) {
4593 		wpa_printf(MSG_DEBUG, "OpenSSL: No OCSP response received");
4594 		return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
4595 	}
4596 
4597 	wpa_hexdump(MSG_DEBUG, "OpenSSL: OCSP response", p, len);
4598 
4599 	rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
4600 	if (!rsp) {
4601 		wpa_printf(MSG_INFO, "OpenSSL: Failed to parse OCSP response");
4602 		return 0;
4603 	}
4604 
4605 	ocsp_debug_print_resp(rsp);
4606 
4607 	status = OCSP_response_status(rsp);
4608 	if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
4609 		wpa_printf(MSG_INFO, "OpenSSL: OCSP responder error %d (%s)",
4610 			   status, OCSP_response_status_str(status));
4611 		return 0;
4612 	}
4613 
4614 	basic = OCSP_response_get1_basic(rsp);
4615 	if (!basic) {
4616 		wpa_printf(MSG_INFO, "OpenSSL: Could not find BasicOCSPResponse");
4617 		return 0;
4618 	}
4619 
4620 	store = SSL_CTX_get_cert_store(conn->ssl_ctx);
4621 	if (conn->peer_issuer) {
4622 		debug_print_cert(conn->peer_issuer, "Add OCSP issuer");
4623 
4624 		if (X509_STORE_add_cert(store, conn->peer_issuer) != 1) {
4625 			tls_show_errors(MSG_INFO, __func__,
4626 					"OpenSSL: Could not add issuer to certificate store");
4627 		}
4628 		certs = sk_X509_new_null();
4629 		if (certs) {
4630 			X509 *cert;
4631 			cert = X509_dup(conn->peer_issuer);
4632 			if (cert && !sk_X509_push(certs, cert)) {
4633 				tls_show_errors(
4634 					MSG_INFO, __func__,
4635 					"OpenSSL: Could not add issuer to OCSP responder trust store");
4636 				X509_free(cert);
4637 				sk_X509_free(certs);
4638 				certs = NULL;
4639 			}
4640 			if (certs && conn->peer_issuer_issuer) {
4641 				cert = X509_dup(conn->peer_issuer_issuer);
4642 				if (cert && !sk_X509_push(certs, cert)) {
4643 					tls_show_errors(
4644 						MSG_INFO, __func__,
4645 						"OpenSSL: Could not add issuer's issuer to OCSP responder trust store");
4646 					X509_free(cert);
4647 				}
4648 			}
4649 		}
4650 	}
4651 
4652 	status = OCSP_basic_verify(basic, certs, store, OCSP_TRUSTOTHER);
4653 	sk_X509_pop_free(certs, X509_free);
4654 	if (status <= 0) {
4655 		tls_show_errors(MSG_INFO, __func__,
4656 				"OpenSSL: OCSP response failed verification");
4657 		OCSP_BASICRESP_free(basic);
4658 		OCSP_RESPONSE_free(rsp);
4659 		return 0;
4660 	}
4661 
4662 	wpa_printf(MSG_DEBUG, "OpenSSL: OCSP response verification succeeded");
4663 
4664 	if (!conn->peer_cert) {
4665 		wpa_printf(MSG_DEBUG, "OpenSSL: Peer certificate not available for OCSP status check");
4666 		OCSP_BASICRESP_free(basic);
4667 		OCSP_RESPONSE_free(rsp);
4668 		return 0;
4669 	}
4670 
4671 	if (!conn->peer_issuer) {
4672 		wpa_printf(MSG_DEBUG, "OpenSSL: Peer issuer certificate not available for OCSP status check");
4673 		OCSP_BASICRESP_free(basic);
4674 		OCSP_RESPONSE_free(rsp);
4675 		return 0;
4676 	}
4677 
4678 	id = OCSP_cert_to_id(EVP_sha256(), conn->peer_cert, conn->peer_issuer);
4679 	if (!id) {
4680 		wpa_printf(MSG_DEBUG,
4681 			   "OpenSSL: Could not create OCSP certificate identifier (SHA256)");
4682 		OCSP_BASICRESP_free(basic);
4683 		OCSP_RESPONSE_free(rsp);
4684 		return 0;
4685 	}
4686 
4687 	res = OCSP_resp_find_status(basic, id, &status, &reason, &produced_at,
4688 				    &this_update, &next_update);
4689 	if (!res) {
4690 		id = OCSP_cert_to_id(NULL, conn->peer_cert, conn->peer_issuer);
4691 		if (!id) {
4692 			wpa_printf(MSG_DEBUG,
4693 				   "OpenSSL: Could not create OCSP certificate identifier (SHA1)");
4694 			OCSP_BASICRESP_free(basic);
4695 			OCSP_RESPONSE_free(rsp);
4696 			return 0;
4697 		}
4698 
4699 		res = OCSP_resp_find_status(basic, id, &status, &reason,
4700 					    &produced_at, &this_update,
4701 					    &next_update);
4702 	}
4703 
4704 	if (!res) {
4705 		wpa_printf(MSG_INFO, "OpenSSL: Could not find current server certificate from OCSP response%s",
4706 			   (conn->flags & TLS_CONN_REQUIRE_OCSP) ? "" :
4707 			   " (OCSP not required)");
4708 		OCSP_CERTID_free(id);
4709 		OCSP_BASICRESP_free(basic);
4710 		OCSP_RESPONSE_free(rsp);
4711 		return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
4712 	}
4713 	OCSP_CERTID_free(id);
4714 
4715 	if (!OCSP_check_validity(this_update, next_update, 5 * 60, -1)) {
4716 		tls_show_errors(MSG_INFO, __func__,
4717 				"OpenSSL: OCSP status times invalid");
4718 		OCSP_BASICRESP_free(basic);
4719 		OCSP_RESPONSE_free(rsp);
4720 		return 0;
4721 	}
4722 
4723 	OCSP_BASICRESP_free(basic);
4724 	OCSP_RESPONSE_free(rsp);
4725 
4726 	wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status for server certificate: %s",
4727 		   OCSP_cert_status_str(status));
4728 
4729 	if (status == V_OCSP_CERTSTATUS_GOOD)
4730 		return 1;
4731 	if (status == V_OCSP_CERTSTATUS_REVOKED)
4732 		return 0;
4733 	if (conn->flags & TLS_CONN_REQUIRE_OCSP) {
4734 		wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP required");
4735 		return 0;
4736 	}
4737 	wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP was not required, so allow connection to continue");
4738 	return 1;
4739 }
4740 
4741 
ocsp_status_cb(SSL * s,void * arg)4742 static int ocsp_status_cb(SSL *s, void *arg)
4743 {
4744 	char *tmp;
4745 	char *resp;
4746 	size_t len;
4747 
4748 	if (tls_global->ocsp_stapling_response == NULL) {
4749 		wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - no response configured");
4750 		return SSL_TLSEXT_ERR_OK;
4751 	}
4752 
4753 	resp = os_readfile(tls_global->ocsp_stapling_response, &len);
4754 	if (resp == NULL) {
4755 		wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - could not read response file");
4756 		/* TODO: Build OCSPResponse with responseStatus = internalError
4757 		 */
4758 		return SSL_TLSEXT_ERR_OK;
4759 	}
4760 	wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - send cached response");
4761 	tmp = OPENSSL_malloc(len);
4762 	if (tmp == NULL) {
4763 		os_free(resp);
4764 		return SSL_TLSEXT_ERR_ALERT_FATAL;
4765 	}
4766 
4767 	os_memcpy(tmp, resp, len);
4768 	os_free(resp);
4769 	SSL_set_tlsext_status_ocsp_resp(s, tmp, len);
4770 
4771 	return SSL_TLSEXT_ERR_OK;
4772 }
4773 
4774 #endif /* HAVE_OCSP */
4775 
4776 
tls_connection_set_params(void * tls_ctx,struct tls_connection * conn,const struct tls_connection_params * params)4777 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
4778 			      const struct tls_connection_params *params)
4779 {
4780 	struct tls_data *data = tls_ctx;
4781 	int ret;
4782 	unsigned long err;
4783 	int can_pkcs11 = 0;
4784 	const char *key_id = params->key_id;
4785 	const char *cert_id = params->cert_id;
4786 	const char *ca_cert_id = params->ca_cert_id;
4787 	const char *engine_id = params->engine ? params->engine_id : NULL;
4788 	const char *ciphers;
4789 
4790 	if (conn == NULL)
4791 		return -1;
4792 
4793 	if (params->flags & TLS_CONN_REQUIRE_OCSP_ALL) {
4794 		wpa_printf(MSG_INFO,
4795 			   "OpenSSL: ocsp=3 not supported");
4796 		return -1;
4797 	}
4798 
4799 	/*
4800 	 * If the engine isn't explicitly configured, and any of the
4801 	 * cert/key fields are actually PKCS#11 URIs, then automatically
4802 	 * use the PKCS#11 ENGINE.
4803 	 */
4804 	if (!engine_id || os_strcmp(engine_id, "pkcs11") == 0)
4805 		can_pkcs11 = 1;
4806 
4807 	if (!key_id && params->private_key && can_pkcs11 &&
4808 	    os_strncmp(params->private_key, "pkcs11:", 7) == 0) {
4809 		can_pkcs11 = 2;
4810 		key_id = params->private_key;
4811 	}
4812 
4813 	if (!cert_id && params->client_cert && can_pkcs11 &&
4814 	    os_strncmp(params->client_cert, "pkcs11:", 7) == 0) {
4815 		can_pkcs11 = 2;
4816 		cert_id = params->client_cert;
4817 	}
4818 
4819 	if (!ca_cert_id && params->ca_cert && can_pkcs11 &&
4820 	    os_strncmp(params->ca_cert, "pkcs11:", 7) == 0) {
4821 		can_pkcs11 = 2;
4822 		ca_cert_id = params->ca_cert;
4823 	}
4824 
4825 	/* If we need to automatically enable the PKCS#11 ENGINE, do so. */
4826 	if (can_pkcs11 == 2 && !engine_id)
4827 		engine_id = "pkcs11";
4828 
4829 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
4830 #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
4831 	if (params->flags & TLS_CONN_EAP_FAST) {
4832 		wpa_printf(MSG_DEBUG,
4833 			   "OpenSSL: Use TLSv1_method() for EAP-FAST");
4834 		if (SSL_set_ssl_method(conn->ssl, TLSv1_method()) != 1) {
4835 			tls_show_errors(MSG_INFO, __func__,
4836 					"Failed to set TLSv1_method() for EAP-FAST");
4837 			return -1;
4838 		}
4839 	}
4840 #endif
4841 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
4842 #ifdef SSL_OP_NO_TLSv1_3
4843 	if (params->flags & TLS_CONN_EAP_FAST) {
4844 		/* Need to disable TLS v1.3 at least for now since OpenSSL 1.1.1
4845 		 * refuses to start the handshake with the modified ciphersuite
4846 		 * list (no TLS v1.3 ciphersuites included) for EAP-FAST. */
4847 		wpa_printf(MSG_DEBUG, "OpenSSL: Disable TLSv1.3 for EAP-FAST");
4848 		SSL_set_options(conn->ssl, SSL_OP_NO_TLSv1_3);
4849 	}
4850 #endif /* SSL_OP_NO_TLSv1_3 */
4851 #endif
4852 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4853 
4854 	while ((err = ERR_get_error())) {
4855 		wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
4856 			   __func__, ERR_error_string(err, NULL));
4857 	}
4858 
4859 	if (engine_id) {
4860 		wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
4861 		ret = tls_engine_init(conn, engine_id, params->pin,
4862 				      key_id, cert_id, ca_cert_id);
4863 		if (ret)
4864 			return ret;
4865 	}
4866 	if (tls_connection_set_subject_match(conn,
4867 					     params->subject_match,
4868 					     params->altsubject_match,
4869 					     params->suffix_match,
4870 					     params->domain_match,
4871 					     params->check_cert_subject))
4872 		return -1;
4873 
4874 	if (engine_id && ca_cert_id) {
4875 		if (tls_connection_engine_ca_cert(data, conn, ca_cert_id))
4876 			return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
4877 	} else if (tls_connection_ca_cert(data, conn, params->ca_cert,
4878 					  params->ca_cert_blob,
4879 					  params->ca_cert_blob_len,
4880 					  params->ca_path))
4881 		return -1;
4882 
4883 	if (engine_id && cert_id) {
4884 		if (tls_connection_engine_client_cert(conn, cert_id))
4885 			return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
4886 	} else if (tls_connection_client_cert(conn, params->client_cert,
4887 					      params->client_cert_blob,
4888 					      params->client_cert_blob_len))
4889 		return -1;
4890 
4891 	if (engine_id && key_id) {
4892 		wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
4893 		if (tls_connection_engine_private_key(conn))
4894 			return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
4895 	} else if (tls_connection_private_key(data, conn,
4896 					      params->private_key,
4897 					      params->private_key_passwd,
4898 					      params->private_key_blob,
4899 					      params->private_key_blob_len)) {
4900 		wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
4901 			   params->private_key);
4902 		return -1;
4903 	}
4904 
4905 	if (tls_connection_dh(conn, params->dh_file)) {
4906 		wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
4907 			   params->dh_file);
4908 		return -1;
4909 	}
4910 
4911 	ciphers = params->openssl_ciphers;
4912 #ifdef CONFIG_SUITEB
4913 #ifdef OPENSSL_IS_BORINGSSL
4914 	if (ciphers && os_strcmp(ciphers, "SUITEB192") == 0) {
4915 		/* BoringSSL removed support for SUITEB192, so need to handle
4916 		 * this with hardcoded ciphersuite and additional checks for
4917 		 * other parameters. */
4918 		ciphers = "ECDHE-ECDSA-AES256-GCM-SHA384";
4919 	}
4920 #endif /* OPENSSL_IS_BORINGSSL */
4921 #endif /* CONFIG_SUITEB */
4922 	if (ciphers && SSL_set_cipher_list(conn->ssl, ciphers) != 1) {
4923 		wpa_printf(MSG_INFO,
4924 			   "OpenSSL: Failed to set cipher string '%s'",
4925 			   ciphers);
4926 		return -1;
4927 	}
4928 
4929 	if (!params->openssl_ecdh_curves) {
4930 #ifndef OPENSSL_IS_BORINGSSL
4931 #ifndef OPENSSL_NO_EC
4932 #if (OPENSSL_VERSION_NUMBER >= 0x10002000L) && \
4933 	(OPENSSL_VERSION_NUMBER < 0x10100000L)
4934 		if (SSL_set_ecdh_auto(conn->ssl, 1) != 1) {
4935 			wpa_printf(MSG_INFO,
4936 				   "OpenSSL: Failed to set ECDH curves to auto");
4937 			return -1;
4938 		}
4939 #endif /* >= 1.0.2 && < 1.1.0 */
4940 #endif /* OPENSSL_NO_EC */
4941 #endif /* OPENSSL_IS_BORINGSSL */
4942 	} else if (params->openssl_ecdh_curves[0]) {
4943 #if defined(OPENSSL_IS_BORINGSSL) || (OPENSSL_VERSION_NUMBER < 0x10002000L)
4944 		wpa_printf(MSG_INFO,
4945 			"OpenSSL: ECDH configuration nnot supported");
4946 		return -1;
4947 #else /* OPENSSL_IS_BORINGSSL || < 1.0.2 */
4948 #ifndef OPENSSL_NO_EC
4949 		if (SSL_set1_curves_list(conn->ssl,
4950 					 params->openssl_ecdh_curves) != 1) {
4951 			wpa_printf(MSG_INFO,
4952 				   "OpenSSL: Failed to set ECDH curves '%s'",
4953 				   params->openssl_ecdh_curves);
4954 			return -1;
4955 		}
4956 #else /* OPENSSL_NO_EC */
4957 		wpa_printf(MSG_INFO, "OpenSSL: ECDH not supported");
4958 		return -1;
4959 #endif /* OPENSSL_NO_EC */
4960 #endif /* OPENSSL_IS_BORINGSSL */
4961 	}
4962 
4963 	if (tls_set_conn_flags(conn, params->flags,
4964 			       params->openssl_ciphers) < 0)
4965 		return -1;
4966 
4967 #ifdef OPENSSL_IS_BORINGSSL
4968 	if (params->flags & TLS_CONN_REQUEST_OCSP) {
4969 		SSL_enable_ocsp_stapling(conn->ssl);
4970 	}
4971 #else /* OPENSSL_IS_BORINGSSL */
4972 #ifdef HAVE_OCSP
4973 	if (params->flags & TLS_CONN_REQUEST_OCSP) {
4974 		SSL_CTX *ssl_ctx = data->ssl;
4975 		SSL_set_tlsext_status_type(conn->ssl, TLSEXT_STATUSTYPE_ocsp);
4976 		SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
4977 		SSL_CTX_set_tlsext_status_arg(ssl_ctx, conn);
4978 	}
4979 #else /* HAVE_OCSP */
4980 	if (params->flags & TLS_CONN_REQUIRE_OCSP) {
4981 		wpa_printf(MSG_INFO,
4982 			   "OpenSSL: No OCSP support included - reject configuration");
4983 		return -1;
4984 	}
4985 	if (params->flags & TLS_CONN_REQUEST_OCSP) {
4986 		wpa_printf(MSG_DEBUG,
4987 			   "OpenSSL: No OCSP support included - allow optional OCSP case to continue");
4988 	}
4989 #endif /* HAVE_OCSP */
4990 #endif /* OPENSSL_IS_BORINGSSL */
4991 
4992 	conn->flags = params->flags;
4993 
4994 	tls_get_errors(data);
4995 
4996 	return 0;
4997 }
4998 
4999 
tls_global_set_params(void * tls_ctx,const struct tls_connection_params * params)5000 int tls_global_set_params(void *tls_ctx,
5001 			  const struct tls_connection_params *params)
5002 {
5003 	struct tls_data *data = tls_ctx;
5004 	SSL_CTX *ssl_ctx = data->ssl;
5005 	unsigned long err;
5006 
5007 	while ((err = ERR_get_error())) {
5008 		wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
5009 			   __func__, ERR_error_string(err, NULL));
5010 	}
5011 
5012 	os_free(data->check_cert_subject);
5013 	data->check_cert_subject = NULL;
5014 	if (params->check_cert_subject) {
5015 		data->check_cert_subject =
5016 			os_strdup(params->check_cert_subject);
5017 		if (!data->check_cert_subject)
5018 			return -1;
5019 	}
5020 
5021 	if (tls_global_ca_cert(data, params->ca_cert) ||
5022 	    tls_global_client_cert(data, params->client_cert) ||
5023 	    tls_global_private_key(data, params->private_key,
5024 				   params->private_key_passwd) ||
5025 	    tls_global_dh(data, params->dh_file)) {
5026 		wpa_printf(MSG_INFO, "TLS: Failed to set global parameters");
5027 		return -1;
5028 	}
5029 
5030 	if (params->openssl_ciphers &&
5031 	    SSL_CTX_set_cipher_list(ssl_ctx, params->openssl_ciphers) != 1) {
5032 		wpa_printf(MSG_INFO,
5033 			   "OpenSSL: Failed to set cipher string '%s'",
5034 			   params->openssl_ciphers);
5035 		return -1;
5036 	}
5037 
5038 	if (!params->openssl_ecdh_curves) {
5039 #ifndef OPENSSL_IS_BORINGSSL
5040 #ifndef OPENSSL_NO_EC
5041 #if (OPENSSL_VERSION_NUMBER >= 0x10002000L) && \
5042 	(OPENSSL_VERSION_NUMBER < 0x10100000L)
5043 		if (SSL_CTX_set_ecdh_auto(ssl_ctx, 1) != 1) {
5044 			wpa_printf(MSG_INFO,
5045 				   "OpenSSL: Failed to set ECDH curves to auto");
5046 			return -1;
5047 		}
5048 #endif /* >= 1.0.2 && < 1.1.0 */
5049 #endif /* OPENSSL_NO_EC */
5050 #endif /* OPENSSL_IS_BORINGSSL */
5051 	} else if (params->openssl_ecdh_curves[0]) {
5052 #if defined(OPENSSL_IS_BORINGSSL) || (OPENSSL_VERSION_NUMBER < 0x10002000L)
5053 		wpa_printf(MSG_INFO,
5054 			"OpenSSL: ECDH configuration nnot supported");
5055 		return -1;
5056 #else /* OPENSSL_IS_BORINGSSL || < 1.0.2 */
5057 #ifndef OPENSSL_NO_EC
5058 #if OPENSSL_VERSION_NUMBER < 0x10100000L
5059 		SSL_CTX_set_ecdh_auto(ssl_ctx, 1);
5060 #endif
5061 		if (SSL_CTX_set1_curves_list(ssl_ctx,
5062 					     params->openssl_ecdh_curves) !=
5063 		    1) {
5064 			wpa_printf(MSG_INFO,
5065 				   "OpenSSL: Failed to set ECDH curves '%s'",
5066 				   params->openssl_ecdh_curves);
5067 			return -1;
5068 		}
5069 #else /* OPENSSL_NO_EC */
5070 		wpa_printf(MSG_INFO, "OpenSSL: ECDH not supported");
5071 		return -1;
5072 #endif /* OPENSSL_NO_EC */
5073 #endif /* OPENSSL_IS_BORINGSSL */
5074 	}
5075 
5076 #ifdef SSL_OP_NO_TICKET
5077 	if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
5078 		SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
5079 	else
5080 		SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TICKET);
5081 #endif /*  SSL_OP_NO_TICKET */
5082 
5083 #ifdef HAVE_OCSP
5084 	SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_status_cb);
5085 	SSL_CTX_set_tlsext_status_arg(ssl_ctx, ssl_ctx);
5086 	os_free(tls_global->ocsp_stapling_response);
5087 	if (params->ocsp_stapling_response)
5088 		tls_global->ocsp_stapling_response =
5089 			os_strdup(params->ocsp_stapling_response);
5090 	else
5091 		tls_global->ocsp_stapling_response = NULL;
5092 #endif /* HAVE_OCSP */
5093 
5094 	return 0;
5095 }
5096 
5097 
5098 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
5099 /* Pre-shared secred requires a patch to openssl, so this function is
5100  * commented out unless explicitly needed for EAP-FAST in order to be able to
5101  * build this file with unmodified openssl. */
5102 
5103 #if (defined(OPENSSL_IS_BORINGSSL) || OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
tls_sess_sec_cb(SSL * s,void * secret,int * secret_len,STACK_OF (SSL_CIPHER)* peer_ciphers,const SSL_CIPHER ** cipher,void * arg)5104 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
5105 			   STACK_OF(SSL_CIPHER) *peer_ciphers,
5106 			   const SSL_CIPHER **cipher, void *arg)
5107 #else /* OPENSSL_IS_BORINGSSL */
5108 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
5109 			   STACK_OF(SSL_CIPHER) *peer_ciphers,
5110 			   SSL_CIPHER **cipher, void *arg)
5111 #endif /* OPENSSL_IS_BORINGSSL */
5112 {
5113 	struct tls_connection *conn = arg;
5114 	int ret;
5115 
5116 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
5117 	(defined(LIBRESSL_VERSION_NUMBER) && \
5118 	 LIBRESSL_VERSION_NUMBER < 0x20700000L)
5119 	if (conn == NULL || conn->session_ticket_cb == NULL)
5120 		return 0;
5121 
5122 	ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
5123 				      conn->session_ticket,
5124 				      conn->session_ticket_len,
5125 				      s->s3->client_random,
5126 				      s->s3->server_random, secret);
5127 #else
5128 	unsigned char client_random[SSL3_RANDOM_SIZE];
5129 	unsigned char server_random[SSL3_RANDOM_SIZE];
5130 
5131 	if (conn == NULL || conn->session_ticket_cb == NULL)
5132 		return 0;
5133 
5134 	SSL_get_client_random(s, client_random, sizeof(client_random));
5135 	SSL_get_server_random(s, server_random, sizeof(server_random));
5136 
5137 	ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
5138 				      conn->session_ticket,
5139 				      conn->session_ticket_len,
5140 				      client_random,
5141 				      server_random, secret);
5142 #endif
5143 
5144 	os_free(conn->session_ticket);
5145 	conn->session_ticket = NULL;
5146 
5147 	if (ret <= 0)
5148 		return 0;
5149 
5150 	*secret_len = SSL_MAX_MASTER_KEY_LENGTH;
5151 	return 1;
5152 }
5153 
5154 
tls_session_ticket_ext_cb(SSL * s,const unsigned char * data,int len,void * arg)5155 static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
5156 				     int len, void *arg)
5157 {
5158 	struct tls_connection *conn = arg;
5159 
5160 	if (conn == NULL || conn->session_ticket_cb == NULL)
5161 		return 0;
5162 
5163 	wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
5164 
5165 	os_free(conn->session_ticket);
5166 	conn->session_ticket = NULL;
5167 
5168 	wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
5169 		    "extension", data, len);
5170 
5171 	conn->session_ticket = os_memdup(data, len);
5172 	if (conn->session_ticket == NULL)
5173 		return 0;
5174 
5175 	conn->session_ticket_len = len;
5176 
5177 	return 1;
5178 }
5179 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
5180 
5181 
tls_connection_set_session_ticket_cb(void * tls_ctx,struct tls_connection * conn,tls_session_ticket_cb cb,void * ctx)5182 int tls_connection_set_session_ticket_cb(void *tls_ctx,
5183 					 struct tls_connection *conn,
5184 					 tls_session_ticket_cb cb,
5185 					 void *ctx)
5186 {
5187 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
5188 	conn->session_ticket_cb = cb;
5189 	conn->session_ticket_cb_ctx = ctx;
5190 
5191 	if (cb) {
5192 		if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
5193 					      conn) != 1)
5194 			return -1;
5195 		SSL_set_session_ticket_ext_cb(conn->ssl,
5196 					      tls_session_ticket_ext_cb, conn);
5197 	} else {
5198 		if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
5199 			return -1;
5200 		SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
5201 	}
5202 
5203 	return 0;
5204 #else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
5205 	return -1;
5206 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
5207 }
5208 
5209 
tls_get_library_version(char * buf,size_t buf_len)5210 int tls_get_library_version(char *buf, size_t buf_len)
5211 {
5212 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
5213 	return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
5214 			   OPENSSL_VERSION_TEXT,
5215 			   OpenSSL_version(OPENSSL_VERSION));
5216 #else
5217 	return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
5218 			   OPENSSL_VERSION_TEXT,
5219 			   SSLeay_version(SSLEAY_VERSION));
5220 #endif
5221 }
5222 
5223 
tls_connection_set_success_data(struct tls_connection * conn,struct wpabuf * data)5224 void tls_connection_set_success_data(struct tls_connection *conn,
5225 				     struct wpabuf *data)
5226 {
5227 	SSL_SESSION *sess;
5228 	struct wpabuf *old;
5229 
5230 	if (tls_ex_idx_session < 0)
5231 		goto fail;
5232 	sess = SSL_get_session(conn->ssl);
5233 	if (!sess)
5234 		goto fail;
5235 	old = SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
5236 	if (old) {
5237 		wpa_printf(MSG_DEBUG, "OpenSSL: Replacing old success data %p",
5238 			   old);
5239 		wpabuf_free(old);
5240 	}
5241 	if (SSL_SESSION_set_ex_data(sess, tls_ex_idx_session, data) != 1)
5242 		goto fail;
5243 
5244 	wpa_printf(MSG_DEBUG, "OpenSSL: Stored success data %p", data);
5245 	conn->success_data = 1;
5246 	return;
5247 
5248 fail:
5249 	wpa_printf(MSG_INFO, "OpenSSL: Failed to store success data");
5250 	wpabuf_free(data);
5251 }
5252 
5253 
tls_connection_set_success_data_resumed(struct tls_connection * conn)5254 void tls_connection_set_success_data_resumed(struct tls_connection *conn)
5255 {
5256 	wpa_printf(MSG_DEBUG,
5257 		   "OpenSSL: Success data accepted for resumed session");
5258 	conn->success_data = 1;
5259 }
5260 
5261 
5262 const struct wpabuf *
tls_connection_get_success_data(struct tls_connection * conn)5263 tls_connection_get_success_data(struct tls_connection *conn)
5264 {
5265 	SSL_SESSION *sess;
5266 
5267 	if (tls_ex_idx_session < 0 ||
5268 	    !(sess = SSL_get_session(conn->ssl)))
5269 		return NULL;
5270 	return SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
5271 }
5272 
5273 
tls_connection_remove_session(struct tls_connection * conn)5274 void tls_connection_remove_session(struct tls_connection *conn)
5275 {
5276 	SSL_SESSION *sess;
5277 
5278 	sess = SSL_get_session(conn->ssl);
5279 	if (!sess)
5280 		return;
5281 
5282 	if (SSL_CTX_remove_session(conn->ssl_ctx, sess) != 1)
5283 		wpa_printf(MSG_DEBUG,
5284 			   "OpenSSL: Session was not cached");
5285 	else
5286 		wpa_printf(MSG_DEBUG,
5287 			   "OpenSSL: Removed cached session to disable session resumption");
5288 }
5289