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