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