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