2 * SSL/TLS interface functions for OpenSSL
3 * Copyright (c) 2004-2015, Jouni Malinen <j@w1.fi>
5 * This software may be distributed under the terms of the BSD license.
6 * See README for more details.
11 #ifndef CONFIG_SMARTCARD
12 #ifndef OPENSSL_NO_ENGINE
14 #define OPENSSL_NO_ENGINE
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>
31 #include <openssl/dh.h>
39 #include "tls_openssl.h"
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
47 #if defined(OPENSSL_IS_BORINGSSL)
48 /* stack_index_t is the return type of OpenSSL's sk_XXX_num() functions. */
49 typedef size_t stack_index_t;
51 typedef int stack_index_t;
54 #ifdef SSL_set_tlsext_status_type
55 #ifndef OPENSSL_NO_TLSEXT
57 #include <openssl/ocsp.h>
58 #endif /* OPENSSL_NO_TLSEXT */
59 #endif /* SSL_set_tlsext_status_type */
61 #if (OPENSSL_VERSION_NUMBER < 0x10100000L || \
62 (defined(LIBRESSL_VERSION_NUMBER) && \
63 LIBRESSL_VERSION_NUMBER < 0x20700000L)) && \
64 !defined(BORINGSSL_API_VERSION)
66 * SSL_get_client_random() and SSL_get_server_random() were added in OpenSSL
67 * 1.1.0 and newer BoringSSL revisions. Provide compatibility wrappers for
71 static size_t SSL_get_client_random(const SSL *ssl, unsigned char *out,
74 if (!ssl->s3 || outlen < SSL3_RANDOM_SIZE)
76 os_memcpy(out, ssl->s3->client_random, SSL3_RANDOM_SIZE);
77 return SSL3_RANDOM_SIZE;
81 static size_t SSL_get_server_random(const SSL *ssl, unsigned char *out,
84 if (!ssl->s3 || outlen < SSL3_RANDOM_SIZE)
86 os_memcpy(out, ssl->s3->server_random, SSL3_RANDOM_SIZE);
87 return SSL3_RANDOM_SIZE;
91 #ifdef OPENSSL_NEED_EAP_FAST_PRF
92 static size_t SSL_SESSION_get_master_key(const SSL_SESSION *session,
93 unsigned char *out, size_t outlen)
95 if (!session || session->master_key_length < 0 ||
96 (size_t) session->master_key_length > outlen)
98 if ((size_t) session->master_key_length < outlen)
99 outlen = session->master_key_length;
100 os_memcpy(out, session->master_key, outlen);
103 #endif /* OPENSSL_NEED_EAP_FAST_PRF */
107 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
108 (defined(LIBRESSL_VERSION_NUMBER) && \
109 LIBRESSL_VERSION_NUMBER < 0x20700000L)
111 static int RSA_bits(const RSA *r)
113 return BN_num_bits(r->n);
115 #endif /* CONFIG_SUITEB */
118 static const unsigned char * ASN1_STRING_get0_data(const ASN1_STRING *x)
120 return ASN1_STRING_data((ASN1_STRING *) x);
125 #include <openssl/pem.h>
126 #include <keystore/keystore_get.h>
128 static BIO * BIO_from_keystore(const char *key)
131 uint8_t *value = NULL;
132 int length = keystore_get(key, strlen(key), &value);
133 if (length != -1 && (bio = BIO_new(BIO_s_mem())) != NULL)
134 BIO_write(bio, value, length);
140 static int tls_add_ca_from_keystore(X509_STORE *ctx, const char *key_alias)
142 BIO *bio = BIO_from_keystore(key_alias);
143 STACK_OF(X509_INFO) *stack = NULL;
147 stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
152 wpa_printf(MSG_WARNING, "TLS: Failed to parse certificate: %s",
157 for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
158 X509_INFO *info = sk_X509_INFO_value(stack, i);
161 X509_STORE_add_cert(ctx, info->x509);
163 X509_STORE_add_crl(ctx, info->crl);
166 sk_X509_INFO_pop_free(stack, X509_INFO_free);
172 static int tls_add_ca_from_keystore_encoded(X509_STORE *ctx,
173 const char *encoded_key_alias)
176 int len = os_strlen(encoded_key_alias);
177 unsigned char *decoded_alias;
180 wpa_printf(MSG_WARNING, "Invalid hex-encoded alias: %s",
185 decoded_alias = os_malloc(len / 2 + 1);
187 if (!hexstr2bin(encoded_key_alias, decoded_alias, len / 2)) {
188 decoded_alias[len / 2] = '\0';
189 rc = tls_add_ca_from_keystore(
190 ctx, (const char *) decoded_alias);
192 os_free(decoded_alias);
200 static int tls_openssl_ref_count = 0;
201 static int tls_ex_idx_session = -1;
204 void (*event_cb)(void *ctx, enum tls_event ev,
205 union tls_event_data *data);
208 char *ocsp_stapling_response;
211 static struct tls_context *tls_global = NULL;
216 unsigned int tls_session_lifetime;
218 int check_crl_strict;
220 unsigned int crl_reload_interval;
221 struct os_reltime crl_last_reload;
222 char *check_cert_subject;
225 struct tls_connection {
226 struct tls_context *context;
227 struct tls_data *data;
230 BIO *ssl_in, *ssl_out;
231 #if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
232 ENGINE *engine; /* functional reference to the engine */
233 EVP_PKEY *private_key; /* the private key if using engine */
234 #endif /* OPENSSL_NO_ENGINE */
235 char *subject_match, *altsubject_match, *suffix_match, *domain_match;
236 char *check_cert_subject;
237 int read_alerts, write_alerts, failed;
239 tls_session_ticket_cb session_ticket_cb;
240 void *session_ticket_cb_ctx;
242 /* SessionTicket received from OpenSSL hello_extension_cb (server) */
244 size_t session_ticket_len;
246 unsigned int ca_cert_verify:1;
247 unsigned int cert_probe:1;
248 unsigned int server_cert_only:1;
249 unsigned int invalid_hb_used:1;
250 unsigned int success_data:1;
251 unsigned int client_hello_generated:1;
252 unsigned int server:1;
254 u8 srv_cert_hash[32];
260 X509 *peer_issuer_issuer;
262 unsigned char client_random[SSL3_RANDOM_SIZE];
263 unsigned char server_random[SSL3_RANDOM_SIZE];
266 int server_dh_prime_len;
270 static struct tls_context * tls_context_new(const struct tls_config *conf)
272 struct tls_context *context = os_zalloc(sizeof(*context));
276 context->event_cb = conf->event_cb;
277 context->cb_ctx = conf->cb_ctx;
278 context->cert_in_cb = conf->cert_in_cb;
284 #ifdef CONFIG_NO_STDOUT_DEBUG
286 static void _tls_show_errors(void)
290 while ((err = ERR_get_error())) {
291 /* Just ignore the errors, since stdout is disabled */
294 #define tls_show_errors(l, f, t) _tls_show_errors()
296 #else /* CONFIG_NO_STDOUT_DEBUG */
298 static void tls_show_errors(int level, const char *func, const char *txt)
302 wpa_printf(level, "OpenSSL: %s - %s %s",
303 func, txt, ERR_error_string(ERR_get_error(), NULL));
305 while ((err = ERR_get_error())) {
306 wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
307 ERR_error_string(err, NULL));
311 #endif /* CONFIG_NO_STDOUT_DEBUG */
314 static X509_STORE * tls_crl_cert_reload(const char *ca_cert, int check_crl)
319 store = X509_STORE_new();
321 wpa_printf(MSG_DEBUG,
322 "OpenSSL: %s - failed to allocate new certificate store",
327 if (ca_cert && X509_STORE_load_locations(store, ca_cert, NULL) != 1) {
328 tls_show_errors(MSG_WARNING, __func__,
329 "Failed to load root certificates");
330 X509_STORE_free(store);
334 flags = check_crl ? X509_V_FLAG_CRL_CHECK : 0;
336 flags |= X509_V_FLAG_CRL_CHECK_ALL;
338 X509_STORE_set_flags(store, flags);
344 #ifdef CONFIG_NATIVE_WINDOWS
346 /* Windows CryptoAPI and access to certificate stores */
347 #include <wincrypt.h>
349 #ifdef __MINGW32_VERSION
351 * MinGW does not yet include all the needed definitions for CryptoAPI, so
352 * define here whatever extra is needed.
354 #define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
355 #define CERT_STORE_READONLY_FLAG 0x00008000
356 #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
358 #endif /* __MINGW32_VERSION */
361 struct cryptoapi_rsa_data {
362 const CERT_CONTEXT *cert;
363 HCRYPTPROV crypt_prov;
365 BOOL free_crypt_prov;
369 static void cryptoapi_error(const char *msg)
371 wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
372 msg, (unsigned int) GetLastError());
376 static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
377 unsigned char *to, RSA *rsa, int padding)
379 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
384 static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
385 unsigned char *to, RSA *rsa, int padding)
387 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
392 static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
393 unsigned char *to, RSA *rsa, int padding)
395 struct cryptoapi_rsa_data *priv =
396 (struct cryptoapi_rsa_data *) rsa->meth->app_data;
398 DWORD hash_size, len, i;
399 unsigned char *buf = NULL;
403 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
404 ERR_R_PASSED_NULL_PARAMETER);
408 if (padding != RSA_PKCS1_PADDING) {
409 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
410 RSA_R_UNKNOWN_PADDING_TYPE);
414 if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
415 wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
417 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
418 RSA_R_INVALID_MESSAGE_LENGTH);
422 if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
424 cryptoapi_error("CryptCreateHash failed");
428 len = sizeof(hash_size);
429 if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
431 cryptoapi_error("CryptGetHashParam failed");
435 if ((int) hash_size != flen) {
436 wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
437 (unsigned) hash_size, flen);
438 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
439 RSA_R_INVALID_MESSAGE_LENGTH);
442 if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
443 cryptoapi_error("CryptSetHashParam failed");
448 buf = os_malloc(len);
450 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
454 if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
455 cryptoapi_error("CryptSignHash failed");
459 for (i = 0; i < len; i++)
460 to[i] = buf[len - i - 1];
465 CryptDestroyHash(hash);
471 static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
472 unsigned char *to, RSA *rsa, int padding)
474 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
479 static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
483 if (priv->crypt_prov && priv->free_crypt_prov)
484 CryptReleaseContext(priv->crypt_prov, 0);
486 CertFreeCertificateContext(priv->cert);
491 static int cryptoapi_finish(RSA *rsa)
493 cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
494 os_free((void *) rsa->meth);
500 static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
503 const CERT_CONTEXT *ret = NULL;
505 cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
506 store | CERT_STORE_OPEN_EXISTING_FLAG |
507 CERT_STORE_READONLY_FLAG, L"MY");
509 cryptoapi_error("Failed to open 'My system store'");
513 if (strncmp(name, "cert://", 7) == 0) {
514 unsigned short wbuf[255];
515 MultiByteToWideChar(CP_ACP, 0, name + 7, -1, wbuf, 255);
516 ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
518 0, CERT_FIND_SUBJECT_STR,
520 } else if (strncmp(name, "hash://", 7) == 0) {
521 CRYPT_HASH_BLOB blob;
523 const char *hash = name + 7;
526 len = os_strlen(hash) / 2;
527 buf = os_malloc(len);
528 if (buf && hexstr2bin(hash, buf, len) == 0) {
531 ret = CertFindCertificateInStore(cs,
540 CertCloseStore(cs, 0);
546 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
549 RSA *rsa = NULL, *pub_rsa;
550 struct cryptoapi_rsa_data *priv;
551 RSA_METHOD *rsa_meth;
554 (strncmp(name, "cert://", 7) != 0 &&
555 strncmp(name, "hash://", 7) != 0))
558 priv = os_zalloc(sizeof(*priv));
559 rsa_meth = os_zalloc(sizeof(*rsa_meth));
560 if (priv == NULL || rsa_meth == NULL) {
561 wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
562 "for CryptoAPI RSA method");
568 priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
569 if (priv->cert == NULL) {
570 priv->cert = cryptoapi_find_cert(
571 name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
573 if (priv->cert == NULL) {
574 wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
579 cert = d2i_X509(NULL,
580 (const unsigned char **) &priv->cert->pbCertEncoded,
581 priv->cert->cbCertEncoded);
583 wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
588 if (!CryptAcquireCertificatePrivateKey(priv->cert,
589 CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
590 NULL, &priv->crypt_prov,
592 &priv->free_crypt_prov)) {
593 cryptoapi_error("Failed to acquire a private key for the "
598 rsa_meth->name = "Microsoft CryptoAPI RSA Method";
599 rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
600 rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
601 rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
602 rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
603 rsa_meth->finish = cryptoapi_finish;
604 rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
605 rsa_meth->app_data = (char *) priv;
609 SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
610 ERR_R_MALLOC_FAILURE);
614 if (!SSL_use_certificate(ssl, cert)) {
619 pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
623 rsa->n = BN_dup(pub_rsa->n);
624 rsa->e = BN_dup(pub_rsa->e);
625 if (!RSA_set_method(rsa, rsa_meth))
628 if (!SSL_use_RSAPrivateKey(ssl, rsa))
641 cryptoapi_free_data(priv);
647 static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
650 PCCERT_CONTEXT ctx = NULL;
658 if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
663 wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
666 wsprintf(wstore, L"%S", store);
667 cs = CertOpenSystemStore(0, wstore);
670 cs = CertOpenSystemStore(0, store);
673 wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
674 "'%s': error=%d", __func__, store,
675 (int) GetLastError());
679 while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
680 cert = d2i_X509(NULL,
681 (const unsigned char **) &ctx->pbCertEncoded,
684 wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
685 "X509 DER encoding for CA cert");
689 X509_NAME_oneline(X509_get_subject_name(cert), buf,
691 wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
692 "system certificate store: subject='%s'", buf);
694 if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx),
696 tls_show_errors(MSG_WARNING, __func__,
697 "Failed to add ca_cert to OpenSSL "
698 "certificate store");
704 if (!CertCloseStore(cs, 0)) {
705 wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
706 "'%s': error=%d", __func__, name + 13,
707 (int) GetLastError());
714 #else /* CONFIG_NATIVE_WINDOWS */
716 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
721 #endif /* CONFIG_NATIVE_WINDOWS */
724 static void ssl_info_cb(const SSL *ssl, int where, int ret)
729 wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
730 w = where & ~SSL_ST_MASK;
731 if (w & SSL_ST_CONNECT)
733 else if (w & SSL_ST_ACCEPT)
738 if (where & SSL_CB_LOOP) {
739 wpa_printf(MSG_DEBUG, "SSL: %s:%s",
740 str, SSL_state_string_long(ssl));
741 } else if (where & SSL_CB_ALERT) {
742 struct tls_connection *conn = SSL_get_app_data((SSL *) ssl);
743 wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
744 where & SSL_CB_READ ?
745 "read (remote end reported an error)" :
746 "write (local SSL3 detected an error)",
747 SSL_alert_type_string_long(ret),
748 SSL_alert_desc_string_long(ret));
749 if ((ret >> 8) == SSL3_AL_FATAL) {
750 if (where & SSL_CB_READ)
753 conn->write_alerts++;
755 if (conn->context->event_cb != NULL) {
756 union tls_event_data ev;
757 struct tls_context *context = conn->context;
758 os_memset(&ev, 0, sizeof(ev));
759 ev.alert.is_local = !(where & SSL_CB_READ);
760 ev.alert.type = SSL_alert_type_string_long(ret);
761 ev.alert.description = SSL_alert_desc_string_long(ret);
762 context->event_cb(context->cb_ctx, TLS_ALERT, &ev);
764 } else if (where & SSL_CB_EXIT && ret <= 0) {
765 wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
766 str, ret == 0 ? "failed" : "error",
767 SSL_state_string_long(ssl));
772 #ifndef OPENSSL_NO_ENGINE
774 * tls_engine_load_dynamic_generic - load any openssl engine
775 * @pre: an array of commands and values that load an engine initialized
776 * in the engine specific function
777 * @post: an array of commands and values that initialize an already loaded
778 * engine (or %NULL if not required)
779 * @id: the engine id of the engine to load (only required if post is not %NULL
781 * This function is a generic function that loads any openssl engine.
783 * Returns: 0 on success, -1 on failure
785 static int tls_engine_load_dynamic_generic(const char *pre[],
786 const char *post[], const char *id)
789 const char *dynamic_id = "dynamic";
791 engine = ENGINE_by_id(id);
793 wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
796 * If it was auto-loaded by ENGINE_by_id() we might still
797 * need to tell it which PKCS#11 module to use in legacy
798 * (non-p11-kit) environments. Do so now; even if it was
799 * properly initialised before, setting it again will be
806 engine = ENGINE_by_id(dynamic_id);
807 if (engine == NULL) {
808 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
810 ERR_error_string(ERR_get_error(), NULL));
814 /* Perform the pre commands. This will load the engine. */
815 while (pre && pre[0]) {
816 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
817 if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
818 wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
819 "%s %s [%s]", pre[0], pre[1],
820 ERR_error_string(ERR_get_error(), NULL));
828 * Free the reference to the "dynamic" engine. The loaded engine can
829 * now be looked up using ENGINE_by_id().
833 engine = ENGINE_by_id(id);
834 if (engine == NULL) {
835 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
836 id, ERR_error_string(ERR_get_error(), NULL));
840 while (post && post[0]) {
841 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
842 if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
843 wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
844 " %s %s [%s]", post[0], post[1],
845 ERR_error_string(ERR_get_error(), NULL));
846 ENGINE_remove(engine);
859 * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
860 * @pkcs11_so_path: pksc11_so_path from the configuration
861 * @pcks11_module_path: pkcs11_module_path from the configuration
863 static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
864 const char *pkcs11_module_path)
866 char *engine_id = "pkcs11";
867 const char *pre_cmd[] = {
868 "SO_PATH", NULL /* pkcs11_so_path */,
869 "ID", NULL /* engine_id */,
871 /* "NO_VCHECK", "1", */
875 const char *post_cmd[] = {
876 "MODULE_PATH", NULL /* pkcs11_module_path */,
883 pre_cmd[1] = pkcs11_so_path;
884 pre_cmd[3] = engine_id;
885 if (pkcs11_module_path)
886 post_cmd[1] = pkcs11_module_path;
890 wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
893 return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
898 * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
899 * @opensc_so_path: opensc_so_path from the configuration
901 static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
903 char *engine_id = "opensc";
904 const char *pre_cmd[] = {
905 "SO_PATH", NULL /* opensc_so_path */,
906 "ID", NULL /* engine_id */,
915 pre_cmd[1] = opensc_so_path;
916 pre_cmd[3] = engine_id;
918 wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
921 return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
923 #endif /* OPENSSL_NO_ENGINE */
926 static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *sess)
930 if (tls_ex_idx_session < 0)
932 buf = SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
935 wpa_printf(MSG_DEBUG,
936 "OpenSSL: Free application session data %p (sess %p)",
940 SSL_SESSION_set_ex_data(sess, tls_ex_idx_session, NULL);
944 void * tls_init(const struct tls_config *conf)
946 struct tls_data *data;
948 struct tls_context *context;
951 if (tls_openssl_ref_count == 0) {
952 tls_global = context = tls_context_new(conf);
957 if (conf && conf->fips_mode) {
958 static int fips_enabled = 0;
960 if (!fips_enabled && !FIPS_mode_set(1)) {
961 wpa_printf(MSG_ERROR, "Failed to enable FIPS "
963 ERR_load_crypto_strings();
964 ERR_print_errors_fp(stderr);
969 wpa_printf(MSG_INFO, "Running in FIPS mode");
973 #else /* OPENSSL_FIPS */
974 if (conf && conf->fips_mode) {
975 wpa_printf(MSG_ERROR, "FIPS mode requested, but not "
981 #endif /* OPENSSL_FIPS */
982 #endif /* CONFIG_FIPS */
983 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
984 (defined(LIBRESSL_VERSION_NUMBER) && \
985 LIBRESSL_VERSION_NUMBER < 0x20700000L)
986 SSL_load_error_strings();
988 #ifndef OPENSSL_NO_SHA256
989 EVP_add_digest(EVP_sha256());
990 #endif /* OPENSSL_NO_SHA256 */
991 /* TODO: if /dev/urandom is available, PRNG is seeded
992 * automatically. If this is not the case, random data should
996 #ifndef OPENSSL_NO_RC2
998 * 40-bit RC2 is commonly used in PKCS#12 files, so enable it.
999 * This is enabled by PKCS12_PBE_add() in OpenSSL 0.9.8
1000 * versions, but it looks like OpenSSL 1.0.0 does not do that
1003 EVP_add_cipher(EVP_rc2_40_cbc());
1004 #endif /* OPENSSL_NO_RC2 */
1006 #endif /* PKCS12_FUNCS */
1007 #endif /* < 1.1.0 */
1009 context = tls_context_new(conf);
1010 if (context == NULL)
1013 tls_openssl_ref_count++;
1015 data = os_zalloc(sizeof(*data));
1017 ssl = SSL_CTX_new(SSLv23_method());
1021 tls_openssl_ref_count--;
1022 if (context != tls_global)
1024 if (tls_openssl_ref_count == 0) {
1025 os_free(tls_global);
1033 data->tls_session_lifetime = conf->tls_session_lifetime;
1034 data->crl_reload_interval = conf->crl_reload_interval;
1037 SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv2);
1038 SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv3);
1040 #ifdef SSL_MODE_NO_AUTO_CHAIN
1041 /* Number of deployed use cases assume the default OpenSSL behavior of
1042 * auto chaining the local certificate is in use. BoringSSL removed this
1043 * functionality by default, so we need to restore it here to avoid
1044 * breaking existing use cases. */
1045 SSL_CTX_clear_mode(ssl, SSL_MODE_NO_AUTO_CHAIN);
1046 #endif /* SSL_MODE_NO_AUTO_CHAIN */
1048 SSL_CTX_set_info_callback(ssl, ssl_info_cb);
1049 SSL_CTX_set_app_data(ssl, context);
1050 if (data->tls_session_lifetime > 0) {
1051 SSL_CTX_set_quiet_shutdown(ssl, 1);
1053 * Set default context here. In practice, this will be replaced
1054 * by the per-EAP method context in tls_connection_set_verify().
1056 SSL_CTX_set_session_id_context(ssl, (u8 *) "hostapd", 7);
1057 SSL_CTX_set_session_cache_mode(ssl, SSL_SESS_CACHE_SERVER);
1058 SSL_CTX_set_timeout(ssl, data->tls_session_lifetime);
1059 SSL_CTX_sess_set_remove_cb(ssl, remove_session_cb);
1061 SSL_CTX_set_session_cache_mode(ssl, SSL_SESS_CACHE_OFF);
1064 if (tls_ex_idx_session < 0) {
1065 tls_ex_idx_session = SSL_SESSION_get_ex_new_index(
1066 0, NULL, NULL, NULL, NULL);
1067 if (tls_ex_idx_session < 0) {
1073 #ifndef OPENSSL_NO_ENGINE
1074 wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
1075 #if OPENSSL_VERSION_NUMBER < 0x10100000L
1076 ERR_load_ENGINE_strings();
1077 ENGINE_load_dynamic();
1078 #endif /* OPENSSL_VERSION_NUMBER */
1081 (conf->opensc_engine_path || conf->pkcs11_engine_path ||
1082 conf->pkcs11_module_path)) {
1083 if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
1084 tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
1085 conf->pkcs11_module_path)) {
1090 #endif /* OPENSSL_NO_ENGINE */
1092 if (conf && conf->openssl_ciphers)
1093 ciphers = conf->openssl_ciphers;
1095 ciphers = TLS_DEFAULT_CIPHERS;
1096 if (SSL_CTX_set_cipher_list(ssl, ciphers) != 1) {
1097 wpa_printf(MSG_ERROR,
1098 "OpenSSL: Failed to set cipher string '%s'",
1108 void tls_deinit(void *ssl_ctx)
1110 struct tls_data *data = ssl_ctx;
1111 SSL_CTX *ssl = data->ssl;
1112 struct tls_context *context = SSL_CTX_get_app_data(ssl);
1113 if (context != tls_global)
1115 if (data->tls_session_lifetime > 0)
1116 SSL_CTX_flush_sessions(ssl, 0);
1117 os_free(data->ca_cert);
1120 tls_openssl_ref_count--;
1121 if (tls_openssl_ref_count == 0) {
1122 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
1123 (defined(LIBRESSL_VERSION_NUMBER) && \
1124 LIBRESSL_VERSION_NUMBER < 0x20700000L)
1125 #ifndef OPENSSL_NO_ENGINE
1127 #endif /* OPENSSL_NO_ENGINE */
1128 CRYPTO_cleanup_all_ex_data();
1129 ERR_remove_thread_state(NULL);
1132 #endif /* < 1.1.0 */
1133 os_free(tls_global->ocsp_stapling_response);
1134 tls_global->ocsp_stapling_response = NULL;
1135 os_free(tls_global);
1139 os_free(data->check_cert_subject);
1144 #ifndef OPENSSL_NO_ENGINE
1146 /* Cryptoki return values */
1147 #define CKR_PIN_INCORRECT 0x000000a0
1148 #define CKR_PIN_INVALID 0x000000a1
1149 #define CKR_PIN_LEN_RANGE 0x000000a2
1152 #define ERR_LIB_PKCS11 ERR_LIB_USER
1154 static int tls_is_pin_error(unsigned int err)
1156 return ERR_GET_LIB(err) == ERR_LIB_PKCS11 &&
1157 (ERR_GET_REASON(err) == CKR_PIN_INCORRECT ||
1158 ERR_GET_REASON(err) == CKR_PIN_INVALID ||
1159 ERR_GET_REASON(err) == CKR_PIN_LEN_RANGE);
1162 #endif /* OPENSSL_NO_ENGINE */
1166 /* EVP_PKEY_from_keystore comes from system/security/keystore-engine. */
1167 EVP_PKEY * EVP_PKEY_from_keystore(const char *key_id);
1168 #endif /* ANDROID */
1170 static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
1171 const char *pin, const char *key_id,
1172 const char *cert_id, const char *ca_cert_id)
1174 #if defined(ANDROID) && defined(OPENSSL_IS_BORINGSSL)
1175 #if !defined(OPENSSL_NO_ENGINE)
1176 #error "This code depends on OPENSSL_NO_ENGINE being defined by BoringSSL."
1179 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1180 conn->engine = NULL;
1181 conn->private_key = EVP_PKEY_from_keystore(key_id);
1182 if (!conn->private_key) {
1183 wpa_printf(MSG_ERROR,
1184 "ENGINE: cannot load private key with id '%s' [%s]",
1186 ERR_error_string(ERR_get_error(), NULL));
1187 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1189 #endif /* ANDROID && OPENSSL_IS_BORINGSSL */
1191 #ifndef OPENSSL_NO_ENGINE
1193 if (engine_id == NULL) {
1194 wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
1200 ENGINE_load_dynamic();
1202 conn->engine = ENGINE_by_id(engine_id);
1203 if (!conn->engine) {
1204 wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
1205 engine_id, ERR_error_string(ERR_get_error(), NULL));
1208 if (ENGINE_init(conn->engine) != 1) {
1209 wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
1210 "(engine: %s) [%s]", engine_id,
1211 ERR_error_string(ERR_get_error(), NULL));
1214 wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
1217 if (pin && ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
1218 wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
1219 ERR_error_string(ERR_get_error(), NULL));
1225 * Ensure that the ENGINE does not attempt to use the OpenSSL
1226 * UI system to obtain a PIN, if we didn't provide one.
1229 const void *password;
1230 const char *prompt_info;
1231 } key_cb = { "", NULL };
1233 /* load private key first in-case PIN is required for cert */
1234 conn->private_key = ENGINE_load_private_key(conn->engine,
1237 if (!conn->private_key) {
1238 unsigned long err = ERR_get_error();
1240 wpa_printf(MSG_ERROR,
1241 "ENGINE: cannot load private key with id '%s' [%s]",
1243 ERR_error_string(err, NULL));
1244 if (tls_is_pin_error(err))
1245 ret = TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
1247 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1252 /* handle a certificate and/or CA certificate */
1253 if (cert_id || ca_cert_id) {
1254 const char *cmd_name = "LOAD_CERT_CTRL";
1256 /* test if the engine supports a LOAD_CERT_CTRL */
1257 if (!ENGINE_ctrl(conn->engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
1258 0, (void *)cmd_name, NULL)) {
1259 wpa_printf(MSG_ERROR, "ENGINE: engine does not support"
1260 " loading certificates");
1261 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1270 ENGINE_free(conn->engine);
1271 conn->engine = NULL;
1274 if (conn->private_key) {
1275 EVP_PKEY_free(conn->private_key);
1276 conn->private_key = NULL;
1280 #else /* OPENSSL_NO_ENGINE */
1282 #endif /* OPENSSL_NO_ENGINE */
1286 static void tls_engine_deinit(struct tls_connection *conn)
1288 #if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
1289 wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
1290 if (conn->private_key) {
1291 EVP_PKEY_free(conn->private_key);
1292 conn->private_key = NULL;
1295 #if !defined(OPENSSL_IS_BORINGSSL)
1296 ENGINE_finish(conn->engine);
1297 #endif /* !OPENSSL_IS_BORINGSSL */
1298 conn->engine = NULL;
1300 #endif /* ANDROID || !OPENSSL_NO_ENGINE */
1304 int tls_get_errors(void *ssl_ctx)
1309 while ((err = ERR_get_error())) {
1310 wpa_printf(MSG_INFO, "TLS - SSL error: %s",
1311 ERR_error_string(err, NULL));
1319 static const char * openssl_content_type(int content_type)
1321 switch (content_type) {
1323 return "change cipher spec";
1329 return "application data";
1333 return "TLS header info"; /* pseudo content type */
1340 static const char * openssl_handshake_type(int content_type, const u8 *buf,
1343 if (content_type != 22 || !buf || len == 0)
1347 return "hello request";
1349 return "client hello";
1351 return "server hello";
1353 return "hello verify request";
1355 return "new session ticket";
1357 return "end of early data";
1359 return "hello retry request";
1361 return "encrypted extensions";
1363 return "certificate";
1365 return "server key exchange";
1367 return "certificate request";
1369 return "server hello done";
1371 return "certificate verify";
1373 return "client key exchange";
1377 return "certificate url";
1379 return "certificate status";
1381 return "supplemental data";
1383 return "key update";
1385 return "message hash";
1392 #ifdef CONFIG_SUITEB
1394 static void check_server_hello(struct tls_connection *conn,
1395 const u8 *pos, const u8 *end)
1397 size_t payload_len, id_len;
1400 * Parse ServerHello to get the selected cipher suite since OpenSSL does
1401 * not make it cleanly available during handshake and we need to know
1402 * whether DHE was selected.
1407 payload_len = WPA_GET_BE24(pos);
1410 if ((size_t) (end - pos) < payload_len)
1412 end = pos + payload_len;
1414 /* Skip Version and Random */
1415 if (end - pos < 2 + SSL3_RANDOM_SIZE)
1417 pos += 2 + SSL3_RANDOM_SIZE;
1419 /* Skip Session ID */
1423 if ((size_t) (end - pos) < id_len)
1429 conn->cipher_suite = WPA_GET_BE16(pos);
1430 wpa_printf(MSG_DEBUG, "OpenSSL: Server selected cipher suite 0x%x",
1431 conn->cipher_suite);
1435 static void check_server_key_exchange(SSL *ssl, struct tls_connection *conn,
1436 const u8 *pos, const u8 *end)
1443 if (!(conn->flags & TLS_CONN_SUITEB))
1446 /* DHE is enabled only with DHE-RSA-AES256-GCM-SHA384 */
1447 if (conn->cipher_suite != 0x9f)
1452 payload_len = WPA_GET_BE24(pos);
1455 if ((size_t) (end - pos) < payload_len)
1457 end = pos + payload_len;
1461 dh_len = WPA_GET_BE16(pos);
1464 if ((size_t) (end - pos) < dh_len)
1466 p = BN_bin2bn(pos, dh_len, NULL);
1470 bits = BN_num_bits(p);
1473 conn->server_dh_prime_len = bits;
1474 wpa_printf(MSG_DEBUG, "OpenSSL: Server DH prime length: %d bits",
1475 conn->server_dh_prime_len);
1478 #endif /* CONFIG_SUITEB */
1481 static void tls_msg_cb(int write_p, int version, int content_type,
1482 const void *buf, size_t len, SSL *ssl, void *arg)
1484 struct tls_connection *conn = arg;
1485 const u8 *pos = buf;
1488 wpa_printf(MSG_DEBUG,
1489 "OpenSSL: session ver=0x%x content_type=%d",
1490 version, content_type);
1491 wpa_hexdump_key(MSG_MSGDUMP, "OpenSSL: Data", buf, len);
1495 wpa_printf(MSG_DEBUG, "OpenSSL: %s ver=0x%x content_type=%d (%s/%s)",
1496 write_p ? "TX" : "RX", version, content_type,
1497 openssl_content_type(content_type),
1498 openssl_handshake_type(content_type, buf, len));
1499 wpa_hexdump_key(MSG_MSGDUMP, "OpenSSL: Message", buf, len);
1500 if (content_type == 24 && len >= 3 && pos[0] == 1) {
1501 size_t payload_len = WPA_GET_BE16(pos + 1);
1502 if (payload_len + 3 > len) {
1503 wpa_printf(MSG_ERROR, "OpenSSL: Heartbeat attack detected");
1504 conn->invalid_hb_used = 1;
1508 #ifdef CONFIG_SUITEB
1510 * Need to parse these handshake messages to be able to check DH prime
1511 * length since OpenSSL does not expose the new cipher suite and DH
1512 * parameters during handshake (e.g., for cert_cb() callback).
1514 if (content_type == 22 && pos && len > 0 && pos[0] == 2)
1515 check_server_hello(conn, pos + 1, pos + len);
1516 if (content_type == 22 && pos && len > 0 && pos[0] == 12)
1517 check_server_key_exchange(ssl, conn, pos + 1, pos + len);
1518 #endif /* CONFIG_SUITEB */
1522 struct tls_connection * tls_connection_init(void *ssl_ctx)
1524 struct tls_data *data = ssl_ctx;
1525 SSL_CTX *ssl = data->ssl;
1526 struct tls_connection *conn;
1528 X509_STORE *new_cert_store;
1529 struct os_reltime now;
1530 struct tls_context *context = SSL_CTX_get_app_data(ssl);
1532 /* Replace X509 store if it is time to update CRL. */
1533 if (data->crl_reload_interval > 0 && os_get_reltime(&now) == 0 &&
1534 os_reltime_expired(&now, &data->crl_last_reload,
1535 data->crl_reload_interval)) {
1536 wpa_printf(MSG_INFO,
1537 "OpenSSL: Flushing X509 store with ca_cert file");
1538 new_cert_store = tls_crl_cert_reload(data->ca_cert,
1540 if (!new_cert_store) {
1541 wpa_printf(MSG_ERROR,
1542 "OpenSSL: Error replacing X509 store with ca_cert file");
1544 /* Replace old store */
1545 SSL_CTX_set_cert_store(ssl, new_cert_store);
1546 data->crl_last_reload = now;
1550 conn = os_zalloc(sizeof(*conn));
1554 conn->ssl_ctx = ssl;
1555 conn->ssl = SSL_new(ssl);
1556 if (conn->ssl == NULL) {
1557 tls_show_errors(MSG_INFO, __func__,
1558 "Failed to initialize new SSL connection");
1563 conn->context = context;
1564 SSL_set_app_data(conn->ssl, conn);
1565 SSL_set_msg_callback(conn->ssl, tls_msg_cb);
1566 SSL_set_msg_callback_arg(conn->ssl, conn);
1567 options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
1568 SSL_OP_SINGLE_DH_USE;
1569 #ifdef SSL_OP_NO_COMPRESSION
1570 options |= SSL_OP_NO_COMPRESSION;
1571 #endif /* SSL_OP_NO_COMPRESSION */
1572 SSL_set_options(conn->ssl, options);
1574 conn->ssl_in = BIO_new(BIO_s_mem());
1575 if (!conn->ssl_in) {
1576 tls_show_errors(MSG_INFO, __func__,
1577 "Failed to create a new BIO for ssl_in");
1578 SSL_free(conn->ssl);
1583 conn->ssl_out = BIO_new(BIO_s_mem());
1584 if (!conn->ssl_out) {
1585 tls_show_errors(MSG_INFO, __func__,
1586 "Failed to create a new BIO for ssl_out");
1587 SSL_free(conn->ssl);
1588 BIO_free(conn->ssl_in);
1593 SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
1599 void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
1603 if (conn->success_data) {
1605 * Make sure ssl_clear_bad_session() does not remove this
1608 SSL_set_quiet_shutdown(conn->ssl, 1);
1609 SSL_shutdown(conn->ssl);
1611 SSL_free(conn->ssl);
1612 tls_engine_deinit(conn);
1613 os_free(conn->subject_match);
1614 os_free(conn->altsubject_match);
1615 os_free(conn->suffix_match);
1616 os_free(conn->domain_match);
1617 os_free(conn->check_cert_subject);
1618 os_free(conn->session_ticket);
1623 int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
1625 return conn ? SSL_is_init_finished(conn->ssl) : 0;
1629 char * tls_connection_peer_serial_num(void *tls_ctx,
1630 struct tls_connection *conn)
1636 if (!conn->peer_cert)
1639 ser = X509_get_serialNumber(conn->peer_cert);
1643 len = ASN1_STRING_length(ser) * 2 + 1;
1644 serial_num = os_malloc(len);
1647 wpa_snprintf_hex_uppercase(serial_num, len,
1648 ASN1_STRING_get0_data(ser),
1649 ASN1_STRING_length(ser));
1654 int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
1659 /* Shutdown previous TLS connection without notifying the peer
1660 * because the connection was already terminated in practice
1661 * and "close notify" shutdown alert would confuse AS. */
1662 SSL_set_quiet_shutdown(conn->ssl, 1);
1663 SSL_shutdown(conn->ssl);
1664 return SSL_clear(conn->ssl) == 1 ? 0 : -1;
1668 static int tls_match_altsubject_component(X509 *cert, int type,
1669 const char *value, size_t len)
1676 ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
1678 for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
1679 gen = sk_GENERAL_NAME_value(ext, i);
1680 if (gen->type != type)
1682 if (os_strlen((char *) gen->d.ia5->data) == len &&
1683 os_memcmp(value, gen->d.ia5->data, len) == 0)
1687 sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
1693 static int tls_match_altsubject(X509 *cert, const char *match)
1696 const char *pos, *end;
1701 if (os_strncmp(pos, "EMAIL:", 6) == 0) {
1704 } else if (os_strncmp(pos, "DNS:", 4) == 0) {
1707 } else if (os_strncmp(pos, "URI:", 4) == 0) {
1711 wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
1715 end = os_strchr(pos, ';');
1717 if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
1718 os_strncmp(end + 1, "DNS:", 4) == 0 ||
1719 os_strncmp(end + 1, "URI:", 4) == 0)
1721 end = os_strchr(end + 1, ';');
1726 len = os_strlen(pos);
1727 if (tls_match_altsubject_component(cert, type, pos, len) > 0)
1736 #ifndef CONFIG_NATIVE_WINDOWS
1737 static int domain_suffix_match(const u8 *val, size_t len, const char *match,
1738 size_t match_len, int full)
1742 /* Check for embedded nuls that could mess up suffix matching */
1743 for (i = 0; i < len; i++) {
1744 if (val[i] == '\0') {
1745 wpa_printf(MSG_DEBUG, "TLS: Embedded null in a string - reject");
1750 if (match_len > len || (full && match_len != len))
1753 if (os_strncasecmp((const char *) val + len - match_len, match,
1755 return 0; /* no match */
1757 if (match_len == len)
1758 return 1; /* exact match */
1760 if (val[len - match_len - 1] == '.')
1761 return 1; /* full label match completes suffix match */
1763 wpa_printf(MSG_DEBUG, "TLS: Reject due to incomplete label match");
1766 #endif /* CONFIG_NATIVE_WINDOWS */
1769 struct tls_dn_field_order_cnt {
1780 static int get_dn_field_index(const struct tls_dn_field_order_cnt *dn_cnt,
1784 case NID_commonName:
1786 case NID_countryName:
1788 case NID_localityName:
1790 case NID_stateOrProvinceName:
1792 case NID_organizationName:
1794 case NID_organizationalUnitName:
1796 case NID_pkcs9_emailAddress:
1797 return dn_cnt->email;
1799 wpa_printf(MSG_ERROR,
1800 "TLS: Unknown NID '%d' in check_cert_subject",
1808 * match_dn_field - Match configuration DN field against Certificate DN field
1809 * @cert: Certificate
1810 * @nid: NID of DN field
1811 * @field: Field name
1812 * @value DN field value which is passed from configuration
1813 * e.g., if configuration have C=US and this argument will point to US.
1814 * @dn_cnt: DN matching context
1815 * Returns: 1 on success and 0 on failure
1817 static int match_dn_field(const X509 *cert, int nid, const char *field,
1819 const struct tls_dn_field_order_cnt *dn_cnt)
1821 int i, ret = 0, len, config_dn_field_index, match_index = 0;
1824 len = os_strlen(value);
1825 name = X509_get_subject_name((X509 *) cert);
1827 /* Assign incremented cnt for every field of DN to check DN field in
1829 config_dn_field_index = get_dn_field_index(dn_cnt, nid);
1830 if (config_dn_field_index < 0)
1833 /* Fetch value based on NID */
1834 for (i = -1; (i = X509_NAME_get_index_by_NID(name, nid, i)) > -1;) {
1838 e = X509_NAME_get_entry(name, i);
1842 cn = X509_NAME_ENTRY_get_data(e);
1848 /* check for more than one DN field with same name */
1849 if (match_index != config_dn_field_index)
1852 /* Check wildcard at the right end side */
1853 /* E.g., if OU=develop* mentioned in configuration, allow 'OU'
1854 * of the subject in the client certificate to start with
1856 if (len > 0 && value[len - 1] == '*') {
1857 /* Compare actual certificate DN field value with
1858 * configuration DN field value up to the specified
1860 ret = ASN1_STRING_length(cn) >= len - 1 &&
1861 os_memcmp(ASN1_STRING_get0_data(cn), value,
1864 /* Compare actual certificate DN field value with
1865 * configuration DN field value */
1866 ret = ASN1_STRING_length(cn) == len &&
1867 os_memcmp(ASN1_STRING_get0_data(cn), value,
1871 wpa_printf(MSG_ERROR,
1872 "OpenSSL: Failed to match %s '%s' with certificate DN field value '%s'",
1873 field, value, ASN1_STRING_get0_data(cn));
1883 * get_value_from_field - Get value from DN field
1884 * @cert: Certificate
1885 * @field_str: DN field string which is passed from configuration file (e.g.,
1887 * @dn_cnt: DN matching context
1888 * Returns: 1 on success and 0 on failure
1890 static int get_value_from_field(const X509 *cert, char *field_str,
1891 struct tls_dn_field_order_cnt *dn_cnt)
1894 char *context = NULL, *name, *value;
1896 if (os_strcmp(field_str, "*") == 0)
1897 return 1; /* wildcard matches everything */
1899 name = str_token(field_str, "=", &context);
1903 /* Compare all configured DN fields and assign nid based on that to
1904 * fetch correct value from certificate subject */
1905 if (os_strcmp(name, "CN") == 0) {
1906 nid = NID_commonName;
1908 } else if(os_strcmp(name, "C") == 0) {
1909 nid = NID_countryName;
1911 } else if (os_strcmp(name, "L") == 0) {
1912 nid = NID_localityName;
1914 } else if (os_strcmp(name, "ST") == 0) {
1915 nid = NID_stateOrProvinceName;
1917 } else if (os_strcmp(name, "O") == 0) {
1918 nid = NID_organizationName;
1920 } else if (os_strcmp(name, "OU") == 0) {
1921 nid = NID_organizationalUnitName;
1923 } else if (os_strcmp(name, "emailAddress") == 0) {
1924 nid = NID_pkcs9_emailAddress;
1927 wpa_printf(MSG_ERROR,
1928 "TLS: Unknown field '%s' in check_cert_subject", name);
1932 value = str_token(field_str, "=", &context);
1934 wpa_printf(MSG_ERROR,
1935 "TLS: Distinguished Name field '%s' value is not defined in check_cert_subject",
1940 return match_dn_field(cert, nid, name, value, dn_cnt);
1945 * tls_match_dn_field - Match subject DN field with check_cert_subject
1946 * @cert: Certificate
1947 * @match: check_cert_subject string
1948 * Returns: Return 1 on success and 0 on failure
1950 static int tls_match_dn_field(X509 *cert, const char *match)
1952 const char *token, *last = NULL;
1954 struct tls_dn_field_order_cnt dn_cnt;
1956 os_memset(&dn_cnt, 0, sizeof(dn_cnt));
1958 /* Maximum length of each DN field is 255 characters */
1960 /* Process each '/' delimited field */
1961 while ((token = cstr_token(match, "/", &last))) {
1962 if (last - token >= (int) sizeof(field)) {
1963 wpa_printf(MSG_ERROR,
1964 "OpenSSL: Too long DN matching field value in '%s'",
1968 os_memcpy(field, token, last - token);
1969 field[last - token] = '\0';
1971 if (!get_value_from_field(cert, field, &dn_cnt)) {
1972 wpa_printf(MSG_DEBUG, "OpenSSL: No match for DN '%s'",
1982 #ifndef CONFIG_NATIVE_WINDOWS
1983 static int tls_match_suffix_helper(X509 *cert, const char *match,
1984 size_t match_len, int full)
1993 wpa_printf(MSG_DEBUG, "TLS: Match domain against %s%s",
1994 full ? "": "suffix ", match);
1996 ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
1998 for (j = 0; ext && j < sk_GENERAL_NAME_num(ext); j++) {
1999 gen = sk_GENERAL_NAME_value(ext, j);
2000 if (gen->type != GEN_DNS)
2003 wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate dNSName",
2004 gen->d.dNSName->data,
2005 gen->d.dNSName->length);
2006 if (domain_suffix_match(gen->d.dNSName->data,
2007 gen->d.dNSName->length,
2008 match, match_len, full) == 1) {
2009 wpa_printf(MSG_DEBUG, "TLS: %s in dNSName found",
2010 full ? "Match" : "Suffix match");
2011 sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
2015 sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
2018 wpa_printf(MSG_DEBUG, "TLS: None of the dNSName(s) matched");
2022 name = X509_get_subject_name(cert);
2028 i = X509_NAME_get_index_by_NID(name, NID_commonName, i);
2031 e = X509_NAME_get_entry(name, i);
2034 cn = X509_NAME_ENTRY_get_data(e);
2037 wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate commonName",
2038 cn->data, cn->length);
2039 if (domain_suffix_match(cn->data, cn->length,
2040 match, match_len, full) == 1) {
2041 wpa_printf(MSG_DEBUG, "TLS: %s in commonName found",
2042 full ? "Match" : "Suffix match");
2047 wpa_printf(MSG_DEBUG, "TLS: No CommonName %smatch found",
2048 full ? "": "suffix ");
2051 #endif /* CONFIG_NATIVE_WINDOWS */
2054 static int tls_match_suffix(X509 *cert, const char *match, int full)
2056 #ifdef CONFIG_NATIVE_WINDOWS
2057 /* wincrypt.h has conflicting X509_NAME definition */
2059 #else /* CONFIG_NATIVE_WINDOWS */
2060 const char *token, *last = NULL;
2062 /* Process each match alternative separately until a match is found */
2063 while ((token = cstr_token(match, ";", &last))) {
2064 if (tls_match_suffix_helper(cert, token, last - token, full))
2069 #endif /* CONFIG_NATIVE_WINDOWS */
2073 static enum tls_fail_reason openssl_tls_fail_reason(int err)
2076 case X509_V_ERR_CERT_REVOKED:
2077 return TLS_FAIL_REVOKED;
2078 case X509_V_ERR_CERT_NOT_YET_VALID:
2079 case X509_V_ERR_CRL_NOT_YET_VALID:
2080 return TLS_FAIL_NOT_YET_VALID;
2081 case X509_V_ERR_CERT_HAS_EXPIRED:
2082 case X509_V_ERR_CRL_HAS_EXPIRED:
2083 return TLS_FAIL_EXPIRED;
2084 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
2085 case X509_V_ERR_UNABLE_TO_GET_CRL:
2086 case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
2087 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
2088 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
2089 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
2090 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
2091 case X509_V_ERR_CERT_CHAIN_TOO_LONG:
2092 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
2093 case X509_V_ERR_INVALID_CA:
2094 return TLS_FAIL_UNTRUSTED;
2095 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
2096 case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
2097 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
2098 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
2099 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
2100 case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
2101 case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
2102 case X509_V_ERR_CERT_UNTRUSTED:
2103 case X509_V_ERR_CERT_REJECTED:
2104 return TLS_FAIL_BAD_CERTIFICATE;
2106 return TLS_FAIL_UNSPECIFIED;
2111 static struct wpabuf * get_x509_cert(X509 *cert)
2116 int cert_len = i2d_X509(cert, NULL);
2120 buf = wpabuf_alloc(cert_len);
2124 tmp = wpabuf_put(buf, cert_len);
2125 i2d_X509(cert, &tmp);
2130 static void openssl_tls_fail_event(struct tls_connection *conn,
2131 X509 *err_cert, int err, int depth,
2132 const char *subject, const char *err_str,
2133 enum tls_fail_reason reason)
2135 union tls_event_data ev;
2136 struct wpabuf *cert = NULL;
2137 struct tls_context *context = conn->context;
2139 if (context->event_cb == NULL)
2142 cert = get_x509_cert(err_cert);
2143 os_memset(&ev, 0, sizeof(ev));
2144 ev.cert_fail.reason = reason != TLS_FAIL_UNSPECIFIED ?
2145 reason : openssl_tls_fail_reason(err);
2146 ev.cert_fail.depth = depth;
2147 ev.cert_fail.subject = subject;
2148 ev.cert_fail.reason_txt = err_str;
2149 ev.cert_fail.cert = cert;
2150 context->event_cb(context->cb_ctx, TLS_CERT_CHAIN_FAILURE, &ev);
2155 static void openssl_tls_cert_event(struct tls_connection *conn,
2156 X509 *err_cert, int depth,
2157 const char *subject)
2159 struct wpabuf *cert = NULL;
2160 union tls_event_data ev;
2161 struct tls_context *context = conn->context;
2162 char *altsubject[TLS_MAX_ALT_SUBJECT];
2163 int alt, num_altsubject = 0;
2168 char serial_num[128];
2169 #ifdef CONFIG_SHA256
2171 #endif /* CONFIG_SHA256 */
2173 if (context->event_cb == NULL)
2176 os_memset(&ev, 0, sizeof(ev));
2177 if (conn->cert_probe || (conn->flags & TLS_CONN_EXT_CERT_CHECK) ||
2178 context->cert_in_cb) {
2179 cert = get_x509_cert(err_cert);
2180 ev.peer_cert.cert = cert;
2182 #ifdef CONFIG_SHA256
2186 addr[0] = wpabuf_head(cert);
2187 len[0] = wpabuf_len(cert);
2188 if (sha256_vector(1, addr, len, hash) == 0) {
2189 ev.peer_cert.hash = hash;
2190 ev.peer_cert.hash_len = sizeof(hash);
2193 #endif /* CONFIG_SHA256 */
2194 ev.peer_cert.depth = depth;
2195 ev.peer_cert.subject = subject;
2197 ser = X509_get_serialNumber(err_cert);
2199 wpa_snprintf_hex_uppercase(serial_num, sizeof(serial_num),
2200 ASN1_STRING_get0_data(ser),
2201 ASN1_STRING_length(ser));
2202 ev.peer_cert.serial_num = serial_num;
2205 ext = X509_get_ext_d2i(err_cert, NID_subject_alt_name, NULL, NULL);
2206 for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
2209 if (num_altsubject == TLS_MAX_ALT_SUBJECT)
2211 gen = sk_GENERAL_NAME_value(ext, i);
2212 if (gen->type != GEN_EMAIL &&
2213 gen->type != GEN_DNS &&
2214 gen->type != GEN_URI)
2217 pos = os_malloc(10 + gen->d.ia5->length + 1);
2220 altsubject[num_altsubject++] = pos;
2222 switch (gen->type) {
2224 os_memcpy(pos, "EMAIL:", 6);
2228 os_memcpy(pos, "DNS:", 4);
2232 os_memcpy(pos, "URI:", 4);
2237 os_memcpy(pos, gen->d.ia5->data, gen->d.ia5->length);
2238 pos += gen->d.ia5->length;
2241 sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
2243 for (alt = 0; alt < num_altsubject; alt++)
2244 ev.peer_cert.altsubject[alt] = altsubject[alt];
2245 ev.peer_cert.num_altsubject = num_altsubject;
2247 context->event_cb(context->cb_ctx, TLS_PEER_CERTIFICATE, &ev);
2249 for (alt = 0; alt < num_altsubject; alt++)
2250 os_free(altsubject[alt]);
2254 static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
2260 struct tls_connection *conn;
2261 struct tls_context *context;
2262 char *match, *altmatch, *suffix_match, *domain_match;
2263 const char *check_cert_subject;
2264 const char *err_str;
2266 err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
2270 err = X509_STORE_CTX_get_error(x509_ctx);
2271 depth = X509_STORE_CTX_get_error_depth(x509_ctx);
2272 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
2273 SSL_get_ex_data_X509_STORE_CTX_idx());
2274 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
2276 conn = SSL_get_app_data(ssl);
2281 conn->peer_cert = err_cert;
2282 else if (depth == 1)
2283 conn->peer_issuer = err_cert;
2284 else if (depth == 2)
2285 conn->peer_issuer_issuer = err_cert;
2287 context = conn->context;
2288 match = conn->subject_match;
2289 altmatch = conn->altsubject_match;
2290 suffix_match = conn->suffix_match;
2291 domain_match = conn->domain_match;
2293 if (!preverify_ok && !conn->ca_cert_verify)
2295 if (!preverify_ok && depth > 0 && conn->server_cert_only)
2297 if (!preverify_ok && (conn->flags & TLS_CONN_DISABLE_TIME_CHECKS) &&
2298 (err == X509_V_ERR_CERT_HAS_EXPIRED ||
2299 err == X509_V_ERR_CERT_NOT_YET_VALID)) {
2300 wpa_printf(MSG_DEBUG, "OpenSSL: Ignore certificate validity "
2304 if (!preverify_ok && !conn->data->check_crl_strict &&
2305 (err == X509_V_ERR_CRL_HAS_EXPIRED ||
2306 err == X509_V_ERR_CRL_NOT_YET_VALID)) {
2307 wpa_printf(MSG_DEBUG,
2308 "OpenSSL: Ignore certificate validity CRL time mismatch");
2312 err_str = X509_verify_cert_error_string(err);
2314 #ifdef CONFIG_SHA256
2316 * Do not require preverify_ok so we can explicity allow otherwise
2317 * invalid pinned server certificates.
2319 if (depth == 0 && conn->server_cert_only) {
2320 struct wpabuf *cert;
2321 cert = get_x509_cert(err_cert);
2323 wpa_printf(MSG_DEBUG, "OpenSSL: Could not fetch "
2324 "server certificate data");
2330 addr[0] = wpabuf_head(cert);
2331 len[0] = wpabuf_len(cert);
2332 if (sha256_vector(1, addr, len, hash) < 0 ||
2333 os_memcmp(conn->srv_cert_hash, hash, 32) != 0) {
2334 err_str = "Server certificate mismatch";
2335 err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
2337 } else if (!preverify_ok) {
2339 * Certificate matches pinned certificate, allow
2340 * regardless of other problems.
2342 wpa_printf(MSG_DEBUG,
2343 "OpenSSL: Ignore validation issues for a pinned server certificate");
2349 #endif /* CONFIG_SHA256 */
2351 if (!preverify_ok) {
2352 wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
2353 " error %d (%s) depth %d for '%s'", err, err_str,
2355 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2356 err_str, TLS_FAIL_UNSPECIFIED);
2357 return preverify_ok;
2360 wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - preverify_ok=%d "
2361 "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
2362 preverify_ok, err, err_str,
2363 conn->ca_cert_verify, depth, buf);
2364 check_cert_subject = conn->check_cert_subject;
2365 if (!check_cert_subject)
2366 check_cert_subject = conn->data->check_cert_subject;
2367 if (check_cert_subject) {
2369 !tls_match_dn_field(err_cert, check_cert_subject)) {
2371 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2372 "Distinguished Name",
2373 TLS_FAIL_DN_MISMATCH);
2376 if (depth == 0 && match && os_strstr(buf, match) == NULL) {
2377 wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
2378 "match with '%s'", buf, match);
2380 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2382 TLS_FAIL_SUBJECT_MISMATCH);
2383 } else if (depth == 0 && altmatch &&
2384 !tls_match_altsubject(err_cert, altmatch)) {
2385 wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
2386 "'%s' not found", altmatch);
2388 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2389 "AltSubject mismatch",
2390 TLS_FAIL_ALTSUBJECT_MISMATCH);
2391 } else if (depth == 0 && suffix_match &&
2392 !tls_match_suffix(err_cert, suffix_match, 0)) {
2393 wpa_printf(MSG_WARNING, "TLS: Domain suffix match '%s' not found",
2396 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2397 "Domain suffix mismatch",
2398 TLS_FAIL_DOMAIN_SUFFIX_MISMATCH);
2399 } else if (depth == 0 && domain_match &&
2400 !tls_match_suffix(err_cert, domain_match, 1)) {
2401 wpa_printf(MSG_WARNING, "TLS: Domain match '%s' not found",
2404 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2406 TLS_FAIL_DOMAIN_MISMATCH);
2408 openssl_tls_cert_event(conn, err_cert, depth, buf);
2410 if (conn->cert_probe && preverify_ok && depth == 0) {
2411 wpa_printf(MSG_DEBUG, "OpenSSL: Reject server certificate "
2412 "on probe-only run");
2414 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2415 "Server certificate chain probe",
2416 TLS_FAIL_SERVER_CHAIN_PROBE);
2419 #ifdef CONFIG_SUITEB
2420 if (conn->flags & TLS_CONN_SUITEB) {
2425 pk = X509_get_pubkey(err_cert);
2427 rsa = EVP_PKEY_get1_RSA(pk);
2429 len = RSA_bits(rsa);
2436 wpa_printf(MSG_DEBUG,
2437 "OpenSSL: RSA modulus size: %d bits", len);
2440 openssl_tls_fail_event(
2441 conn, err_cert, err,
2443 "Insufficient RSA modulus size",
2444 TLS_FAIL_INSUFFICIENT_KEY_LEN);
2448 #endif /* CONFIG_SUITEB */
2450 #ifdef OPENSSL_IS_BORINGSSL
2451 if (depth == 0 && (conn->flags & TLS_CONN_REQUEST_OCSP) &&
2453 enum ocsp_result res;
2455 res = check_ocsp_resp(conn->ssl_ctx, conn->ssl, err_cert,
2457 conn->peer_issuer_issuer);
2458 if (res == OCSP_REVOKED) {
2460 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2461 "certificate revoked",
2463 if (err == X509_V_OK)
2464 X509_STORE_CTX_set_error(
2465 x509_ctx, X509_V_ERR_CERT_REVOKED);
2466 } else if (res != OCSP_GOOD &&
2467 (conn->flags & TLS_CONN_REQUIRE_OCSP)) {
2469 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2470 "bad certificate status response",
2471 TLS_FAIL_UNSPECIFIED);
2474 #endif /* OPENSSL_IS_BORINGSSL */
2476 if (depth == 0 && preverify_ok && context->event_cb != NULL)
2477 context->event_cb(context->cb_ctx,
2478 TLS_CERT_CHAIN_SUCCESS, NULL);
2480 return preverify_ok;
2484 #ifndef OPENSSL_NO_STDIO
2485 static int tls_load_ca_der(struct tls_data *data, const char *ca_cert)
2487 SSL_CTX *ssl_ctx = data->ssl;
2488 X509_LOOKUP *lookup;
2491 lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(ssl_ctx),
2492 X509_LOOKUP_file());
2493 if (lookup == NULL) {
2494 tls_show_errors(MSG_WARNING, __func__,
2495 "Failed add lookup for X509 store");
2499 if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
2500 unsigned long err = ERR_peek_error();
2501 tls_show_errors(MSG_WARNING, __func__,
2502 "Failed load CA in DER format");
2503 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
2504 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
2505 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
2506 "cert already in hash table error",
2514 #endif /* OPENSSL_NO_STDIO */
2517 static int tls_connection_ca_cert(struct tls_data *data,
2518 struct tls_connection *conn,
2519 const char *ca_cert, const u8 *ca_cert_blob,
2520 size_t ca_cert_blob_len, const char *ca_path)
2522 SSL_CTX *ssl_ctx = data->ssl;
2526 * Remove previously configured trusted CA certificates before adding
2529 store = X509_STORE_new();
2530 if (store == NULL) {
2531 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
2532 "certificate store", __func__);
2535 SSL_CTX_set_cert_store(ssl_ctx, store);
2537 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
2538 conn->ca_cert_verify = 1;
2540 if (ca_cert && os_strncmp(ca_cert, "probe://", 8) == 0) {
2541 wpa_printf(MSG_DEBUG, "OpenSSL: Probe for server certificate "
2543 conn->cert_probe = 1;
2544 conn->ca_cert_verify = 0;
2548 if (ca_cert && os_strncmp(ca_cert, "hash://", 7) == 0) {
2549 #ifdef CONFIG_SHA256
2550 const char *pos = ca_cert + 7;
2551 if (os_strncmp(pos, "server/sha256/", 14) != 0) {
2552 wpa_printf(MSG_DEBUG, "OpenSSL: Unsupported ca_cert "
2553 "hash value '%s'", ca_cert);
2557 if (os_strlen(pos) != 32 * 2) {
2558 wpa_printf(MSG_DEBUG, "OpenSSL: Unexpected SHA256 "
2559 "hash length in ca_cert '%s'", ca_cert);
2562 if (hexstr2bin(pos, conn->srv_cert_hash, 32) < 0) {
2563 wpa_printf(MSG_DEBUG, "OpenSSL: Invalid SHA256 hash "
2564 "value in ca_cert '%s'", ca_cert);
2567 conn->server_cert_only = 1;
2568 wpa_printf(MSG_DEBUG, "OpenSSL: Checking only server "
2569 "certificate match");
2571 #else /* CONFIG_SHA256 */
2572 wpa_printf(MSG_INFO, "No SHA256 included in the build - "
2573 "cannot validate server certificate hash");
2575 #endif /* CONFIG_SHA256 */
2579 X509 *cert = d2i_X509(NULL,
2580 (const unsigned char **) &ca_cert_blob,
2583 tls_show_errors(MSG_WARNING, __func__,
2584 "Failed to parse ca_cert_blob");
2588 if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx),
2590 unsigned long err = ERR_peek_error();
2591 tls_show_errors(MSG_WARNING, __func__,
2592 "Failed to add ca_cert_blob to "
2593 "certificate store");
2594 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
2595 ERR_GET_REASON(err) ==
2596 X509_R_CERT_ALREADY_IN_HASH_TABLE) {
2597 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
2598 "cert already in hash table error",
2606 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
2607 "to certificate store", __func__);
2613 if (ca_cert && os_strncmp("keystore://", ca_cert, 11) == 0) {
2614 if (tls_add_ca_from_keystore(SSL_CTX_get_cert_store(ssl_ctx),
2617 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
2621 /* Multiple aliases separated by space */
2622 if (ca_cert && os_strncmp("keystores://", ca_cert, 12) == 0) {
2623 char *aliases = os_strdup(&ca_cert[12]);
2624 const char *delim = " ";
2631 alias = strtok_r(aliases, delim, &savedptr);
2632 for (; alias; alias = strtok_r(NULL, delim, &savedptr)) {
2633 if (tls_add_ca_from_keystore_encoded(
2634 SSL_CTX_get_cert_store(ssl_ctx), alias)) {
2635 wpa_printf(MSG_WARNING,
2636 "OpenSSL: %s - Failed to add ca_cert %s from keystore",
2646 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
2649 #endif /* ANDROID */
2651 #ifdef CONFIG_NATIVE_WINDOWS
2652 if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
2654 wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
2655 "system certificate store");
2658 #endif /* CONFIG_NATIVE_WINDOWS */
2660 if (ca_cert || ca_path) {
2661 #ifndef OPENSSL_NO_STDIO
2662 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
2664 tls_show_errors(MSG_WARNING, __func__,
2665 "Failed to load root certificates");
2667 tls_load_ca_der(data, ca_cert) == 0) {
2668 wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
2669 "DER format CA certificate",
2674 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
2675 "certificate(s) loaded");
2676 tls_get_errors(data);
2678 #else /* OPENSSL_NO_STDIO */
2679 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
2682 #endif /* OPENSSL_NO_STDIO */
2684 /* No ca_cert configured - do not try to verify server
2686 conn->ca_cert_verify = 0;
2693 static int tls_global_ca_cert(struct tls_data *data, const char *ca_cert)
2695 SSL_CTX *ssl_ctx = data->ssl;
2698 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
2700 tls_show_errors(MSG_WARNING, __func__,
2701 "Failed to load root certificates");
2705 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
2706 "certificate(s) loaded");
2708 #ifndef OPENSSL_NO_STDIO
2709 /* Add the same CAs to the client certificate requests */
2710 SSL_CTX_set_client_CA_list(ssl_ctx,
2711 SSL_load_client_CA_file(ca_cert));
2712 #endif /* OPENSSL_NO_STDIO */
2714 os_free(data->ca_cert);
2715 data->ca_cert = os_strdup(ca_cert);
2722 int tls_global_set_verify(void *ssl_ctx, int check_crl, int strict)
2727 struct tls_data *data = ssl_ctx;
2728 X509_STORE *cs = SSL_CTX_get_cert_store(data->ssl);
2730 tls_show_errors(MSG_INFO, __func__, "Failed to get "
2731 "certificate store when enabling "
2735 flags = X509_V_FLAG_CRL_CHECK;
2737 flags |= X509_V_FLAG_CRL_CHECK_ALL;
2738 X509_STORE_set_flags(cs, flags);
2740 data->check_crl = check_crl;
2741 data->check_crl_strict = strict;
2742 os_get_reltime(&data->crl_last_reload);
2748 static int tls_connection_set_subject_match(struct tls_connection *conn,
2749 const char *subject_match,
2750 const char *altsubject_match,
2751 const char *suffix_match,
2752 const char *domain_match,
2753 const char *check_cert_subject)
2755 os_free(conn->subject_match);
2756 conn->subject_match = NULL;
2757 if (subject_match) {
2758 conn->subject_match = os_strdup(subject_match);
2759 if (conn->subject_match == NULL)
2763 os_free(conn->altsubject_match);
2764 conn->altsubject_match = NULL;
2765 if (altsubject_match) {
2766 conn->altsubject_match = os_strdup(altsubject_match);
2767 if (conn->altsubject_match == NULL)
2771 os_free(conn->suffix_match);
2772 conn->suffix_match = NULL;
2774 conn->suffix_match = os_strdup(suffix_match);
2775 if (conn->suffix_match == NULL)
2779 os_free(conn->domain_match);
2780 conn->domain_match = NULL;
2782 conn->domain_match = os_strdup(domain_match);
2783 if (conn->domain_match == NULL)
2787 os_free(conn->check_cert_subject);
2788 conn->check_cert_subject = NULL;
2789 if (check_cert_subject) {
2790 conn->check_cert_subject = os_strdup(check_cert_subject);
2791 if (!conn->check_cert_subject)
2799 #ifdef CONFIG_SUITEB
2800 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
2801 static int suiteb_cert_cb(SSL *ssl, void *arg)
2803 struct tls_connection *conn = arg;
2806 * This cert_cb() is not really the best location for doing a
2807 * constraint check for the ServerKeyExchange message, but this seems to
2808 * be the only place where the current OpenSSL sequence can be
2809 * terminated cleanly with an TLS alert going out to the server.
2812 if (!(conn->flags & TLS_CONN_SUITEB))
2815 /* DHE is enabled only with DHE-RSA-AES256-GCM-SHA384 */
2816 if (conn->cipher_suite != 0x9f)
2819 if (conn->server_dh_prime_len >= 3072)
2822 wpa_printf(MSG_DEBUG,
2823 "OpenSSL: Server DH prime length (%d bits) not sufficient for Suite B RSA - reject handshake",
2824 conn->server_dh_prime_len);
2827 #endif /* OPENSSL_VERSION_NUMBER */
2828 #endif /* CONFIG_SUITEB */
2831 static int tls_set_conn_flags(struct tls_connection *conn, unsigned int flags,
2832 const char *openssl_ciphers)
2834 SSL *ssl = conn->ssl;
2836 #ifdef SSL_OP_NO_TICKET
2837 if (flags & TLS_CONN_DISABLE_SESSION_TICKET)
2838 SSL_set_options(ssl, SSL_OP_NO_TICKET);
2840 SSL_clear_options(ssl, SSL_OP_NO_TICKET);
2841 #endif /* SSL_OP_NO_TICKET */
2843 #ifdef SSL_OP_NO_TLSv1
2844 if (flags & TLS_CONN_DISABLE_TLSv1_0)
2845 SSL_set_options(ssl, SSL_OP_NO_TLSv1);
2847 SSL_clear_options(ssl, SSL_OP_NO_TLSv1);
2848 #endif /* SSL_OP_NO_TLSv1 */
2849 #ifdef SSL_OP_NO_TLSv1_1
2850 if (flags & TLS_CONN_DISABLE_TLSv1_1)
2851 SSL_set_options(ssl, SSL_OP_NO_TLSv1_1);
2853 SSL_clear_options(ssl, SSL_OP_NO_TLSv1_1);
2854 #endif /* SSL_OP_NO_TLSv1_1 */
2855 #ifdef SSL_OP_NO_TLSv1_2
2856 if (flags & TLS_CONN_DISABLE_TLSv1_2)
2857 SSL_set_options(ssl, SSL_OP_NO_TLSv1_2);
2859 SSL_clear_options(ssl, SSL_OP_NO_TLSv1_2);
2860 #endif /* SSL_OP_NO_TLSv1_2 */
2861 #ifdef SSL_OP_NO_TLSv1_3
2862 if (flags & TLS_CONN_DISABLE_TLSv1_3)
2863 SSL_set_options(ssl, SSL_OP_NO_TLSv1_3);
2865 SSL_clear_options(ssl, SSL_OP_NO_TLSv1_3);
2866 #endif /* SSL_OP_NO_TLSv1_3 */
2867 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
2868 if (flags & (TLS_CONN_ENABLE_TLSv1_0 |
2869 TLS_CONN_ENABLE_TLSv1_1 |
2870 TLS_CONN_ENABLE_TLSv1_2)) {
2873 /* Explicit request to enable TLS versions even if needing to
2874 * override systemwide policies. */
2875 if (flags & TLS_CONN_ENABLE_TLSv1_0) {
2876 version = TLS1_VERSION;
2877 } else if (flags & TLS_CONN_ENABLE_TLSv1_1) {
2878 if (!(flags & TLS_CONN_DISABLE_TLSv1_0))
2879 version = TLS1_1_VERSION;
2880 } else if (flags & TLS_CONN_ENABLE_TLSv1_2) {
2881 if (!(flags & (TLS_CONN_DISABLE_TLSv1_0 |
2882 TLS_CONN_DISABLE_TLSv1_1)))
2883 version = TLS1_2_VERSION;
2886 wpa_printf(MSG_DEBUG,
2887 "OpenSSL: Invalid TLS version configuration");
2891 if (SSL_set_min_proto_version(ssl, version) != 1) {
2892 wpa_printf(MSG_DEBUG,
2893 "OpenSSL: Failed to set minimum TLS version");
2897 #endif /* >= 1.1.0 */
2899 #ifdef CONFIG_SUITEB
2900 #ifdef OPENSSL_IS_BORINGSSL
2901 /* Start with defaults from BoringSSL */
2902 SSL_CTX_set_verify_algorithm_prefs(conn->ssl_ctx, NULL, 0);
2903 #endif /* OPENSSL_IS_BORINGSSL */
2904 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
2905 if (flags & TLS_CONN_SUITEB_NO_ECDH) {
2906 const char *ciphers = "DHE-RSA-AES256-GCM-SHA384";
2908 if (openssl_ciphers) {
2909 wpa_printf(MSG_DEBUG,
2910 "OpenSSL: Override ciphers for Suite B (no ECDH): %s",
2912 ciphers = openssl_ciphers;
2914 if (SSL_set_cipher_list(ssl, ciphers) != 1) {
2915 wpa_printf(MSG_INFO,
2916 "OpenSSL: Failed to set Suite B ciphers");
2919 } else if (flags & TLS_CONN_SUITEB) {
2921 const char *ciphers =
2922 "ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384";
2923 int nid[1] = { NID_secp384r1 };
2925 if (openssl_ciphers) {
2926 wpa_printf(MSG_DEBUG,
2927 "OpenSSL: Override ciphers for Suite B: %s",
2929 ciphers = openssl_ciphers;
2931 if (SSL_set_cipher_list(ssl, ciphers) != 1) {
2932 wpa_printf(MSG_INFO,
2933 "OpenSSL: Failed to set Suite B ciphers");
2937 if (SSL_set1_curves(ssl, nid, 1) != 1) {
2938 wpa_printf(MSG_INFO,
2939 "OpenSSL: Failed to set Suite B curves");
2943 ecdh = EC_KEY_new_by_curve_name(NID_secp384r1);
2944 if (!ecdh || SSL_set_tmp_ecdh(ssl, ecdh) != 1) {
2946 wpa_printf(MSG_INFO,
2947 "OpenSSL: Failed to set ECDH parameter");
2952 if (flags & (TLS_CONN_SUITEB | TLS_CONN_SUITEB_NO_ECDH)) {
2953 #ifdef OPENSSL_IS_BORINGSSL
2954 uint16_t sigalgs[1] = { SSL_SIGN_RSA_PKCS1_SHA384 };
2956 if (SSL_CTX_set_verify_algorithm_prefs(conn->ssl_ctx, sigalgs,
2958 wpa_printf(MSG_INFO,
2959 "OpenSSL: Failed to set Suite B sigalgs");
2962 #else /* OPENSSL_IS_BORINGSSL */
2963 /* ECDSA+SHA384 if need to add EC support here */
2964 if (SSL_set1_sigalgs_list(ssl, "RSA+SHA384") != 1) {
2965 wpa_printf(MSG_INFO,
2966 "OpenSSL: Failed to set Suite B sigalgs");
2969 #endif /* OPENSSL_IS_BORINGSSL */
2971 SSL_set_options(ssl, SSL_OP_NO_TLSv1);
2972 SSL_set_options(ssl, SSL_OP_NO_TLSv1_1);
2973 SSL_set_cert_cb(ssl, suiteb_cert_cb, conn);
2975 #else /* OPENSSL_VERSION_NUMBER < 0x10002000L */
2976 if (flags & (TLS_CONN_SUITEB | TLS_CONN_SUITEB_NO_ECDH)) {
2977 wpa_printf(MSG_ERROR,
2978 "OpenSSL: Suite B RSA case not supported with this OpenSSL version");
2981 #endif /* OPENSSL_VERSION_NUMBER */
2983 #ifdef OPENSSL_IS_BORINGSSL
2984 if (openssl_ciphers && os_strcmp(openssl_ciphers, "SUITEB192") == 0) {
2985 uint16_t sigalgs[1] = { SSL_SIGN_ECDSA_SECP384R1_SHA384 };
2986 int nid[1] = { NID_secp384r1 };
2988 if (SSL_set1_curves(ssl, nid, 1) != 1) {
2989 wpa_printf(MSG_INFO,
2990 "OpenSSL: Failed to set Suite B curves");
2994 if (SSL_CTX_set_verify_algorithm_prefs(conn->ssl_ctx, sigalgs,
2996 wpa_printf(MSG_INFO,
2997 "OpenSSL: Failed to set Suite B sigalgs");
3001 #else /* OPENSSL_IS_BORINGSSL */
3002 if (!(flags & (TLS_CONN_SUITEB | TLS_CONN_SUITEB_NO_ECDH)) &&
3003 openssl_ciphers && SSL_set_cipher_list(ssl, openssl_ciphers) != 1) {
3004 wpa_printf(MSG_INFO,
3005 "OpenSSL: Failed to set openssl_ciphers '%s'",
3009 #endif /* OPENSSL_IS_BORINGSSL */
3010 #else /* CONFIG_SUITEB */
3011 if (openssl_ciphers && SSL_set_cipher_list(ssl, openssl_ciphers) != 1) {
3012 wpa_printf(MSG_INFO,
3013 "OpenSSL: Failed to set openssl_ciphers '%s'",
3017 #endif /* CONFIG_SUITEB */
3023 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
3024 int verify_peer, unsigned int flags,
3025 const u8 *session_ctx, size_t session_ctx_len)
3027 static int counter = 0;
3028 struct tls_data *data = ssl_ctx;
3034 conn->ca_cert_verify = 1;
3035 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
3036 SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
3037 SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
3039 conn->ca_cert_verify = 0;
3040 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
3043 if (tls_set_conn_flags(conn, flags, NULL) < 0)
3045 conn->flags = flags;
3047 SSL_set_accept_state(conn->ssl);
3049 if (data->tls_session_lifetime == 0) {
3051 * Set session id context to a unique value to make sure
3052 * session resumption cannot be used either through session
3053 * caching or TLS ticket extension.
3056 SSL_set_session_id_context(conn->ssl,
3057 (const unsigned char *) &counter,
3059 } else if (session_ctx) {
3060 SSL_set_session_id_context(conn->ssl, session_ctx,
3068 static int tls_connection_client_cert(struct tls_connection *conn,
3069 const char *client_cert,
3070 const u8 *client_cert_blob,
3071 size_t client_cert_blob_len)
3073 if (client_cert == NULL && client_cert_blob == NULL)
3077 #if OPENSSL_VERSION_NUMBER < 0x10002000L || defined(LIBRESSL_VERSION_NUMBER)
3079 * Clear previously set extra chain certificates, if any, from PKCS#12
3080 * processing in tls_parse_pkcs12() to allow OpenSSL to build a new
3083 SSL_CTX_clear_extra_chain_certs(conn->ssl_ctx);
3084 #endif /* OPENSSL_VERSION_NUMBER < 0x10002000L */
3085 #endif /* PKCS12_FUNCS */
3087 if (client_cert_blob &&
3088 SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
3089 client_cert_blob_len) == 1) {
3090 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
3093 } else if (client_cert_blob) {
3094 tls_show_errors(MSG_DEBUG, __func__,
3095 "SSL_use_certificate_ASN1 failed");
3098 if (client_cert == NULL)
3102 if (os_strncmp("keystore://", client_cert, 11) == 0) {
3103 BIO *bio = BIO_from_keystore(&client_cert[11]);
3107 x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
3110 if (SSL_use_certificate(conn->ssl, x509) == 1)
3115 /* Read additional certificates into the chain. */
3117 x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
3119 /* Takes ownership of x509 */
3120 SSL_add0_chain_cert(conn->ssl, x509);
3128 #endif /* ANDROID */
3130 #ifndef OPENSSL_NO_STDIO
3131 if (SSL_use_certificate_file(conn->ssl, client_cert,
3132 SSL_FILETYPE_ASN1) == 1) {
3133 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
3138 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
3139 !defined(LIBRESSL_VERSION_NUMBER) && !defined(OPENSSL_IS_BORINGSSL)
3140 if (SSL_use_certificate_chain_file(conn->ssl, client_cert) == 1) {
3142 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_chain_file"
3147 if (SSL_use_certificate_file(conn->ssl, client_cert,
3148 SSL_FILETYPE_PEM) == 1) {
3150 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
3156 tls_show_errors(MSG_DEBUG, __func__,
3157 "SSL_use_certificate_file failed");
3158 #else /* OPENSSL_NO_STDIO */
3159 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
3160 #endif /* OPENSSL_NO_STDIO */
3166 static int tls_global_client_cert(struct tls_data *data,
3167 const char *client_cert)
3169 #ifndef OPENSSL_NO_STDIO
3170 SSL_CTX *ssl_ctx = data->ssl;
3172 if (client_cert == NULL)
3175 if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
3176 SSL_FILETYPE_ASN1) != 1 &&
3177 SSL_CTX_use_certificate_chain_file(ssl_ctx, client_cert) != 1 &&
3178 SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
3179 SSL_FILETYPE_PEM) != 1) {
3180 tls_show_errors(MSG_INFO, __func__,
3181 "Failed to load client certificate");
3185 #else /* OPENSSL_NO_STDIO */
3186 if (client_cert == NULL)
3188 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
3190 #endif /* OPENSSL_NO_STDIO */
3195 static int tls_parse_pkcs12(struct tls_data *data, SSL *ssl, PKCS12 *p12,
3200 STACK_OF(X509) *certs;
3209 if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
3210 tls_show_errors(MSG_DEBUG, __func__,
3211 "Failed to parse PKCS12 file");
3215 wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
3218 X509_NAME_oneline(X509_get_subject_name(cert), buf,
3220 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
3221 "subject='%s'", buf);
3223 if (SSL_use_certificate(ssl, cert) != 1)
3226 if (SSL_CTX_use_certificate(data->ssl, cert) != 1)
3233 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
3235 if (SSL_use_PrivateKey(ssl, pkey) != 1)
3238 if (SSL_CTX_use_PrivateKey(data->ssl, pkey) != 1)
3241 EVP_PKEY_free(pkey);
3245 #if OPENSSL_VERSION_NUMBER >= 0x10002000L && !defined(LIBRESSL_VERSION_NUMBER)
3247 SSL_clear_chain_certs(ssl);
3249 SSL_CTX_clear_chain_certs(data->ssl);
3250 while ((cert = sk_X509_pop(certs)) != NULL) {
3251 X509_NAME_oneline(X509_get_subject_name(cert), buf,
3253 wpa_printf(MSG_DEBUG, "TLS: additional certificate"
3254 " from PKCS12: subject='%s'", buf);
3255 if ((ssl && SSL_add1_chain_cert(ssl, cert) != 1) ||
3256 (!ssl && SSL_CTX_add1_chain_cert(data->ssl,
3258 tls_show_errors(MSG_DEBUG, __func__,
3259 "Failed to add additional certificate");
3267 /* Try to continue anyway */
3269 sk_X509_pop_free(certs, X509_free);
3270 #ifndef OPENSSL_IS_BORINGSSL
3272 res = SSL_build_cert_chain(
3274 SSL_BUILD_CHAIN_FLAG_CHECK |
3275 SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR);
3277 res = SSL_CTX_build_cert_chain(
3279 SSL_BUILD_CHAIN_FLAG_CHECK |
3280 SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR);
3282 tls_show_errors(MSG_DEBUG, __func__,
3283 "Failed to build certificate chain");
3284 } else if (res == 2) {
3285 wpa_printf(MSG_DEBUG,
3286 "TLS: Ignore certificate chain verification error when building chain with PKCS#12 extra certificates");
3288 #endif /* OPENSSL_IS_BORINGSSL */
3290 * Try to continue regardless of result since it is possible for
3291 * the extra certificates not to be required.
3294 #else /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
3295 SSL_CTX_clear_extra_chain_certs(data->ssl);
3296 while ((cert = sk_X509_pop(certs)) != NULL) {
3297 X509_NAME_oneline(X509_get_subject_name(cert), buf,
3299 wpa_printf(MSG_DEBUG, "TLS: additional certificate"
3300 " from PKCS12: subject='%s'", buf);
3302 * There is no SSL equivalent for the chain cert - so
3303 * always add it to the context...
3305 if (SSL_CTX_add_extra_chain_cert(data->ssl, cert) != 1)
3312 sk_X509_pop_free(certs, X509_free);
3313 #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
3319 tls_get_errors(data);
3323 #endif /* PKCS12_FUNCS */
3326 static int tls_read_pkcs12(struct tls_data *data, SSL *ssl,
3327 const char *private_key, const char *passwd)
3333 f = fopen(private_key, "rb");
3337 p12 = d2i_PKCS12_fp(f, NULL);
3341 tls_show_errors(MSG_INFO, __func__,
3342 "Failed to use PKCS#12 file");
3346 return tls_parse_pkcs12(data, ssl, p12, passwd);
3348 #else /* PKCS12_FUNCS */
3349 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
3352 #endif /* PKCS12_FUNCS */
3356 static int tls_read_pkcs12_blob(struct tls_data *data, SSL *ssl,
3357 const u8 *blob, size_t len, const char *passwd)
3362 p12 = d2i_PKCS12(NULL, (const unsigned char **) &blob, len);
3364 tls_show_errors(MSG_INFO, __func__,
3365 "Failed to use PKCS#12 blob");
3369 return tls_parse_pkcs12(data, ssl, p12, passwd);
3371 #else /* PKCS12_FUNCS */
3372 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
3375 #endif /* PKCS12_FUNCS */
3379 #ifndef OPENSSL_NO_ENGINE
3380 static int tls_engine_get_cert(struct tls_connection *conn,
3381 const char *cert_id,
3384 /* this runs after the private key is loaded so no PIN is required */
3386 const char *cert_id;
3389 params.cert_id = cert_id;
3392 if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
3393 0, ¶ms, NULL, 1)) {
3394 unsigned long err = ERR_get_error();
3396 wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
3397 " '%s' [%s]", cert_id,
3398 ERR_error_string(err, NULL));
3399 if (tls_is_pin_error(err))
3400 return TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
3401 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
3404 wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
3406 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
3408 *cert = params.cert;
3411 #endif /* OPENSSL_NO_ENGINE */
3414 static int tls_connection_engine_client_cert(struct tls_connection *conn,
3415 const char *cert_id)
3417 #ifndef OPENSSL_NO_ENGINE
3420 if (tls_engine_get_cert(conn, cert_id, &cert))
3423 if (!SSL_use_certificate(conn->ssl, cert)) {
3424 tls_show_errors(MSG_ERROR, __func__,
3425 "SSL_use_certificate failed");
3430 wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
3434 #else /* OPENSSL_NO_ENGINE */
3436 #endif /* OPENSSL_NO_ENGINE */
3440 static int tls_connection_engine_ca_cert(struct tls_data *data,
3441 struct tls_connection *conn,
3442 const char *ca_cert_id)
3444 #ifndef OPENSSL_NO_ENGINE
3446 SSL_CTX *ssl_ctx = data->ssl;
3449 if (tls_engine_get_cert(conn, ca_cert_id, &cert))
3452 /* start off the same as tls_connection_ca_cert */
3453 store = X509_STORE_new();
3454 if (store == NULL) {
3455 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
3456 "certificate store", __func__);
3460 SSL_CTX_set_cert_store(ssl_ctx, store);
3461 if (!X509_STORE_add_cert(store, cert)) {
3462 unsigned long err = ERR_peek_error();
3463 tls_show_errors(MSG_WARNING, __func__,
3464 "Failed to add CA certificate from engine "
3465 "to certificate store");
3466 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
3467 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
3468 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
3469 " already in hash table error",
3477 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
3478 "to certificate store", __func__);
3479 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
3480 conn->ca_cert_verify = 1;
3484 #else /* OPENSSL_NO_ENGINE */
3486 #endif /* OPENSSL_NO_ENGINE */
3490 static int tls_connection_engine_private_key(struct tls_connection *conn)
3492 #if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
3493 if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
3494 tls_show_errors(MSG_ERROR, __func__,
3495 "ENGINE: cannot use private key for TLS");
3498 if (!SSL_check_private_key(conn->ssl)) {
3499 tls_show_errors(MSG_INFO, __func__,
3500 "Private key failed verification");
3504 #else /* OPENSSL_NO_ENGINE */
3505 wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
3506 "engine support was not compiled in");
3508 #endif /* OPENSSL_NO_ENGINE */
3512 #ifndef OPENSSL_NO_STDIO
3513 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
3517 os_strlcpy(buf, (const char *) password, size);
3518 return os_strlen(buf);
3520 #endif /* OPENSSL_NO_STDIO */
3523 static int tls_use_private_key_file(struct tls_data *data, SSL *ssl,
3524 const char *private_key,
3525 const char *private_key_passwd)
3527 #ifndef OPENSSL_NO_STDIO
3532 /* First try ASN.1 (DER). */
3533 bio = BIO_new_file(private_key, "r");
3536 pkey = d2i_PrivateKey_bio(bio, NULL);
3540 wpa_printf(MSG_DEBUG, "OpenSSL: %s (DER) --> loaded", __func__);
3542 /* Try PEM with the provided password. */
3543 bio = BIO_new_file(private_key, "r");
3546 pkey = PEM_read_bio_PrivateKey(bio, NULL, tls_passwd_cb,
3547 (void *) private_key_passwd);
3551 wpa_printf(MSG_DEBUG, "OpenSSL: %s (PEM) --> loaded", __func__);
3552 /* Clear errors from the previous failed load. */
3557 ret = SSL_use_PrivateKey(ssl, pkey);
3559 ret = SSL_CTX_use_PrivateKey(data->ssl, pkey);
3561 EVP_PKEY_free(pkey);
3562 return ret == 1 ? 0 : -1;
3563 #else /* OPENSSL_NO_STDIO */
3564 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
3566 #endif /* OPENSSL_NO_STDIO */
3570 static int tls_connection_private_key(struct tls_data *data,
3571 struct tls_connection *conn,
3572 const char *private_key,
3573 const char *private_key_passwd,
3574 const u8 *private_key_blob,
3575 size_t private_key_blob_len)
3579 if (private_key == NULL && private_key_blob == NULL)
3583 while (private_key_blob) {
3584 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
3585 (u8 *) private_key_blob,
3586 private_key_blob_len) == 1) {
3587 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
3588 "ASN1(EVP_PKEY_RSA) --> OK");
3593 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
3594 (u8 *) private_key_blob,
3595 private_key_blob_len) == 1) {
3596 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
3597 "ASN1(EVP_PKEY_DSA) --> OK");
3602 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
3603 (u8 *) private_key_blob,
3604 private_key_blob_len) == 1) {
3605 wpa_printf(MSG_DEBUG, "OpenSSL: "
3606 "SSL_use_RSAPrivateKey_ASN1 --> OK");
3611 if (tls_read_pkcs12_blob(data, conn->ssl, private_key_blob,
3612 private_key_blob_len,
3613 private_key_passwd) == 0) {
3614 wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
3623 while (!ok && private_key) {
3624 if (tls_use_private_key_file(data, conn->ssl, private_key,
3625 private_key_passwd) == 0) {
3630 if (tls_read_pkcs12(data, conn->ssl, private_key,
3631 private_key_passwd) == 0) {
3632 wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
3638 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
3639 wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
3640 "access certificate store --> OK");
3649 tls_show_errors(MSG_INFO, __func__,
3650 "Failed to load private key");
3655 if (!SSL_check_private_key(conn->ssl)) {
3656 tls_show_errors(MSG_INFO, __func__, "Private key failed "
3661 wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
3666 static int tls_global_private_key(struct tls_data *data,
3667 const char *private_key,
3668 const char *private_key_passwd)
3670 SSL_CTX *ssl_ctx = data->ssl;
3672 if (private_key == NULL)
3675 if (tls_use_private_key_file(data, NULL, private_key,
3676 private_key_passwd) &&
3677 tls_read_pkcs12(data, NULL, private_key, private_key_passwd)) {
3678 tls_show_errors(MSG_INFO, __func__,
3679 "Failed to load private key");
3685 if (!SSL_CTX_check_private_key(ssl_ctx)) {
3686 tls_show_errors(MSG_INFO, __func__,
3687 "Private key failed verification");
3695 static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
3697 #ifdef OPENSSL_NO_DH
3698 if (dh_file == NULL)
3700 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
3701 "dh_file specified");
3703 #else /* OPENSSL_NO_DH */
3707 /* TODO: add support for dh_blob */
3708 if (dh_file == NULL)
3713 bio = BIO_new_file(dh_file, "r");
3715 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
3716 dh_file, ERR_error_string(ERR_get_error(), NULL));
3719 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3721 #ifndef OPENSSL_NO_DSA
3722 while (dh == NULL) {
3724 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
3725 " trying to parse as DSA params", dh_file,
3726 ERR_error_string(ERR_get_error(), NULL));
3727 bio = BIO_new_file(dh_file, "r");
3730 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
3733 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
3734 "'%s': %s", dh_file,
3735 ERR_error_string(ERR_get_error(), NULL));
3739 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
3740 dh = DSA_dup_DH(dsa);
3743 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
3744 "params into DH params");
3749 #endif /* !OPENSSL_NO_DSA */
3751 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
3756 if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
3757 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
3759 ERR_error_string(ERR_get_error(), NULL));
3765 #endif /* OPENSSL_NO_DH */
3769 static int tls_global_dh(struct tls_data *data, const char *dh_file)
3771 #ifdef OPENSSL_NO_DH
3772 if (dh_file == NULL)
3774 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
3775 "dh_file specified");
3777 #else /* OPENSSL_NO_DH */
3778 SSL_CTX *ssl_ctx = data->ssl;
3782 /* TODO: add support for dh_blob */
3783 if (dh_file == NULL)
3785 if (ssl_ctx == NULL)
3788 bio = BIO_new_file(dh_file, "r");
3790 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
3791 dh_file, ERR_error_string(ERR_get_error(), NULL));
3794 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3796 #ifndef OPENSSL_NO_DSA
3797 while (dh == NULL) {
3799 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
3800 " trying to parse as DSA params", dh_file,
3801 ERR_error_string(ERR_get_error(), NULL));
3802 bio = BIO_new_file(dh_file, "r");
3805 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
3808 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
3809 "'%s': %s", dh_file,
3810 ERR_error_string(ERR_get_error(), NULL));
3814 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
3815 dh = DSA_dup_DH(dsa);
3818 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
3819 "params into DH params");
3824 #endif /* !OPENSSL_NO_DSA */
3826 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
3831 if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
3832 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
3834 ERR_error_string(ERR_get_error(), NULL));
3840 #endif /* OPENSSL_NO_DH */
3844 int tls_connection_get_random(void *ssl_ctx, struct tls_connection *conn,
3845 struct tls_random *keys)
3849 if (conn == NULL || keys == NULL)
3855 os_memset(keys, 0, sizeof(*keys));
3856 keys->client_random = conn->client_random;
3857 keys->client_random_len = SSL_get_client_random(
3858 ssl, conn->client_random, sizeof(conn->client_random));
3859 keys->server_random = conn->server_random;
3860 keys->server_random_len = SSL_get_server_random(
3861 ssl, conn->server_random, sizeof(conn->server_random));
3867 #ifdef OPENSSL_NEED_EAP_FAST_PRF
3868 static int openssl_get_keyblock_size(SSL *ssl)
3870 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
3871 (defined(LIBRESSL_VERSION_NUMBER) && \
3872 LIBRESSL_VERSION_NUMBER < 0x20700000L)
3873 const EVP_CIPHER *c;
3877 if (ssl->enc_read_ctx == NULL || ssl->enc_read_ctx->cipher == NULL ||
3878 ssl->read_hash == NULL)
3881 c = ssl->enc_read_ctx->cipher;
3882 h = EVP_MD_CTX_md(ssl->read_hash);
3884 md_size = EVP_MD_size(h);
3886 md_size = ssl->s3->tmp.new_mac_secret_size;
3890 wpa_printf(MSG_DEBUG, "OpenSSL: keyblock size: key_len=%d MD_size=%d "
3891 "IV_len=%d", EVP_CIPHER_key_length(c), md_size,
3892 EVP_CIPHER_iv_length(c));
3893 return 2 * (EVP_CIPHER_key_length(c) +
3895 EVP_CIPHER_iv_length(c));
3897 const SSL_CIPHER *ssl_cipher;
3899 const EVP_CIPHER *c;
3902 ssl_cipher = SSL_get_current_cipher(ssl);
3905 cipher = SSL_CIPHER_get_cipher_nid(ssl_cipher);
3906 digest = SSL_CIPHER_get_digest_nid(ssl_cipher);
3907 wpa_printf(MSG_DEBUG, "OpenSSL: cipher nid %d digest nid %d",
3909 if (cipher < 0 || digest < 0)
3911 c = EVP_get_cipherbynid(cipher);
3912 h = EVP_get_digestbynid(digest);
3916 wpa_printf(MSG_DEBUG,
3917 "OpenSSL: keyblock size: key_len=%d MD_size=%d IV_len=%d",
3918 EVP_CIPHER_key_length(c), EVP_MD_size(h),
3919 EVP_CIPHER_iv_length(c));
3920 return 2 * (EVP_CIPHER_key_length(c) + EVP_MD_size(h) +
3921 EVP_CIPHER_iv_length(c));
3924 #endif /* OPENSSL_NEED_EAP_FAST_PRF */
3927 int tls_connection_export_key(void *tls_ctx, struct tls_connection *conn,
3928 const char *label, const u8 *context,
3929 size_t context_len, u8 *out, size_t out_len)
3932 SSL_export_keying_material(conn->ssl, out, out_len, label,
3933 os_strlen(label), context, context_len,
3934 context != NULL) != 1)
3940 int tls_connection_get_eap_fast_key(void *tls_ctx, struct tls_connection *conn,
3941 u8 *out, size_t out_len)
3943 #ifdef OPENSSL_NEED_EAP_FAST_PRF
3951 unsigned char client_random[SSL3_RANDOM_SIZE];
3952 unsigned char server_random[SSL3_RANDOM_SIZE];
3953 unsigned char master_key[64];
3954 size_t master_key_len;
3958 * TLS library did not support EAP-FAST key generation, so get the
3959 * needed TLS session parameters and use an internal implementation of
3960 * TLS PRF to derive the key.
3968 ver = SSL_get_version(ssl);
3969 sess = SSL_get_session(ssl);
3973 skip = openssl_get_keyblock_size(ssl);
3976 tmp_out = os_malloc(skip + out_len);
3981 rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
3987 SSL_get_client_random(ssl, client_random, sizeof(client_random));
3988 SSL_get_server_random(ssl, server_random, sizeof(server_random));
3989 master_key_len = SSL_SESSION_get_master_key(sess, master_key,
3990 sizeof(master_key));
3992 os_memcpy(rnd, server_random, SSL3_RANDOM_SIZE);
3993 os_memcpy(rnd + SSL3_RANDOM_SIZE, client_random, SSL3_RANDOM_SIZE);
3995 if (os_strcmp(ver, "TLSv1.2") == 0) {
3996 tls_prf_sha256(master_key, master_key_len,
3997 "key expansion", rnd, 2 * SSL3_RANDOM_SIZE,
3998 _out, skip + out_len);
4000 } else if (tls_prf_sha1_md5(master_key, master_key_len,
4001 "key expansion", rnd, 2 * SSL3_RANDOM_SIZE,
4002 _out, skip + out_len) == 0) {
4005 os_memset(master_key, 0, sizeof(master_key));
4008 os_memcpy(out, _out + skip, out_len);
4009 bin_clear_free(tmp_out, skip);
4012 #else /* OPENSSL_NEED_EAP_FAST_PRF */
4013 wpa_printf(MSG_ERROR,
4014 "OpenSSL: EAP-FAST keys cannot be exported in FIPS mode");
4016 #endif /* OPENSSL_NEED_EAP_FAST_PRF */
4020 static struct wpabuf *
4021 openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data)
4024 struct wpabuf *out_data;
4027 * Give TLS handshake data from the server (if available) to OpenSSL
4030 if (in_data && wpabuf_len(in_data) > 0 &&
4031 BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
4033 tls_show_errors(MSG_INFO, __func__,
4034 "Handshake failed - BIO_write");
4038 /* Initiate TLS handshake or continue the existing handshake */
4040 res = SSL_accept(conn->ssl);
4042 res = SSL_connect(conn->ssl);
4044 int err = SSL_get_error(conn->ssl, res);
4045 if (err == SSL_ERROR_WANT_READ)
4046 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
4048 else if (err == SSL_ERROR_WANT_WRITE)
4049 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
4052 tls_show_errors(MSG_INFO, __func__, "SSL_connect");
4054 if (!conn->server && !conn->client_hello_generated) {
4055 /* The server would not understand TLS Alert
4056 * before ClientHello, so simply terminate
4057 * handshake on this type of error case caused
4058 * by a likely internal error like no ciphers
4060 wpa_printf(MSG_DEBUG,
4061 "OpenSSL: Could not generate ClientHello");
4062 conn->write_alerts++;
4068 if (!conn->server && !conn->failed)
4069 conn->client_hello_generated = 1;
4071 #ifdef CONFIG_SUITEB
4072 if ((conn->flags & TLS_CONN_SUITEB) && !conn->server &&
4073 os_strncmp(SSL_get_cipher(conn->ssl), "DHE-", 4) == 0 &&
4074 conn->server_dh_prime_len < 3072) {
4075 struct tls_context *context = conn->context;
4078 * This should not be reached since earlier cert_cb should have
4079 * terminated the handshake. Keep this check here for extra
4080 * protection if anything goes wrong with the more low-level
4081 * checks based on having to parse the TLS handshake messages.
4083 wpa_printf(MSG_DEBUG,
4084 "OpenSSL: Server DH prime length: %d bits",
4085 conn->server_dh_prime_len);
4087 if (context->event_cb) {
4088 union tls_event_data ev;
4090 os_memset(&ev, 0, sizeof(ev));
4091 ev.alert.is_local = 1;
4092 ev.alert.type = "fatal";
4093 ev.alert.description = "insufficient security";
4094 context->event_cb(context->cb_ctx, TLS_ALERT, &ev);
4097 * Could send a TLS Alert to the server, but for now, simply
4098 * terminate handshake.
4101 conn->write_alerts++;
4104 #endif /* CONFIG_SUITEB */
4106 /* Get the TLS handshake data to be sent to the server */
4107 res = BIO_ctrl_pending(conn->ssl_out);
4108 wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
4109 out_data = wpabuf_alloc(res);
4110 if (out_data == NULL) {
4111 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
4112 "handshake output (%d bytes)", res);
4113 if (BIO_reset(conn->ssl_out) < 0) {
4114 tls_show_errors(MSG_INFO, __func__,
4115 "BIO_reset failed");
4119 res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
4122 tls_show_errors(MSG_INFO, __func__,
4123 "Handshake failed - BIO_read");
4124 if (BIO_reset(conn->ssl_out) < 0) {
4125 tls_show_errors(MSG_INFO, __func__,
4126 "BIO_reset failed");
4128 wpabuf_free(out_data);
4131 wpabuf_put(out_data, res);
4137 static struct wpabuf *
4138 openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
4140 struct wpabuf *appl_data;
4143 appl_data = wpabuf_alloc(max_len + 100);
4144 if (appl_data == NULL)
4147 res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
4148 wpabuf_size(appl_data));
4150 int err = SSL_get_error(conn->ssl, res);
4151 if (err == SSL_ERROR_WANT_READ ||
4152 err == SSL_ERROR_WANT_WRITE) {
4153 wpa_printf(MSG_DEBUG, "SSL: No Application Data "
4156 tls_show_errors(MSG_INFO, __func__,
4157 "Failed to read possible "
4158 "Application Data");
4160 wpabuf_free(appl_data);
4164 wpabuf_put(appl_data, res);
4165 wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
4166 "message", appl_data);
4172 static struct wpabuf *
4173 openssl_connection_handshake(struct tls_connection *conn,
4174 const struct wpabuf *in_data,
4175 struct wpabuf **appl_data)
4177 struct wpabuf *out_data;
4182 out_data = openssl_handshake(conn, in_data);
4183 if (out_data == NULL)
4185 if (conn->invalid_hb_used) {
4186 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
4187 wpabuf_free(out_data);
4191 if (SSL_is_init_finished(conn->ssl)) {
4192 wpa_printf(MSG_DEBUG,
4193 "OpenSSL: Handshake finished - resumed=%d",
4194 tls_connection_resumed(conn->ssl_ctx, conn));
4195 if (appl_data && in_data)
4196 *appl_data = openssl_get_appl_data(conn,
4197 wpabuf_len(in_data));
4200 if (conn->invalid_hb_used) {
4201 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
4203 wpabuf_free(*appl_data);
4206 wpabuf_free(out_data);
4215 tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
4216 const struct wpabuf *in_data,
4217 struct wpabuf **appl_data)
4219 return openssl_connection_handshake(conn, in_data, appl_data);
4223 struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
4224 struct tls_connection *conn,
4225 const struct wpabuf *in_data,
4226 struct wpabuf **appl_data)
4229 return openssl_connection_handshake(conn, in_data, appl_data);
4233 struct wpabuf * tls_connection_encrypt(void *tls_ctx,
4234 struct tls_connection *conn,
4235 const struct wpabuf *in_data)
4243 /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
4244 if ((res = BIO_reset(conn->ssl_in)) < 0 ||
4245 (res = BIO_reset(conn->ssl_out)) < 0) {
4246 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
4249 res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
4251 tls_show_errors(MSG_INFO, __func__,
4252 "Encryption failed - SSL_write");
4256 /* Read encrypted data to be sent to the server */
4257 buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
4260 res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
4262 tls_show_errors(MSG_INFO, __func__,
4263 "Encryption failed - BIO_read");
4267 wpabuf_put(buf, res);
4273 struct wpabuf * tls_connection_decrypt(void *tls_ctx,
4274 struct tls_connection *conn,
4275 const struct wpabuf *in_data)
4280 /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
4281 res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
4282 wpabuf_len(in_data));
4284 tls_show_errors(MSG_INFO, __func__,
4285 "Decryption failed - BIO_write");
4288 if (BIO_reset(conn->ssl_out) < 0) {
4289 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
4293 /* Read decrypted data for further processing */
4295 * Even though we try to disable TLS compression, it is possible that
4296 * this cannot be done with all TLS libraries. Add extra buffer space
4297 * to handle the possibility of the decrypted data being longer than
4300 buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
4303 res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
4305 tls_show_errors(MSG_INFO, __func__,
4306 "Decryption failed - SSL_read");
4310 wpabuf_put(buf, res);
4312 if (conn->invalid_hb_used) {
4313 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
4322 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
4324 return conn ? SSL_session_reused(conn->ssl) : 0;
4328 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
4331 char buf[500], *pos, *end;
4335 if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
4340 end = pos + sizeof(buf);
4343 while (*c != TLS_CIPHER_NONE) {
4347 case TLS_CIPHER_RC4_SHA:
4350 case TLS_CIPHER_AES128_SHA:
4351 suite = "AES128-SHA";
4353 case TLS_CIPHER_RSA_DHE_AES128_SHA:
4354 suite = "DHE-RSA-AES128-SHA";
4356 case TLS_CIPHER_ANON_DH_AES128_SHA:
4357 suite = "ADH-AES128-SHA";
4359 case TLS_CIPHER_RSA_DHE_AES256_SHA:
4360 suite = "DHE-RSA-AES256-SHA";
4362 case TLS_CIPHER_AES256_SHA:
4363 suite = "AES256-SHA";
4366 wpa_printf(MSG_DEBUG, "TLS: Unsupported "
4367 "cipher selection: %d", *c);
4370 ret = os_snprintf(pos, end - pos, ":%s", suite);
4371 if (os_snprintf_error(end - pos, ret))
4378 wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
4380 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
4381 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
4382 if (os_strstr(buf, ":ADH-")) {
4384 * Need to drop to security level 0 to allow anonymous
4385 * cipher suites for EAP-FAST.
4387 SSL_set_security_level(conn->ssl, 0);
4388 } else if (SSL_get_security_level(conn->ssl) == 0) {
4389 /* Force at least security level 1 */
4390 SSL_set_security_level(conn->ssl, 1);
4392 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4395 if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
4396 tls_show_errors(MSG_INFO, __func__,
4397 "Cipher suite configuration failed");
4405 int tls_get_version(void *ssl_ctx, struct tls_connection *conn,
4406 char *buf, size_t buflen)
4409 if (conn == NULL || conn->ssl == NULL)
4412 name = SSL_get_version(conn->ssl);
4416 os_strlcpy(buf, name, buflen);
4421 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
4422 char *buf, size_t buflen)
4425 if (conn == NULL || conn->ssl == NULL)
4428 name = SSL_get_cipher(conn->ssl);
4432 os_strlcpy(buf, name, buflen);
4437 int tls_connection_enable_workaround(void *ssl_ctx,
4438 struct tls_connection *conn)
4440 SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
4446 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
4447 /* ClientHello TLS extensions require a patch to openssl, so this function is
4448 * commented out unless explicitly needed for EAP-FAST in order to be able to
4449 * build this file with unmodified openssl. */
4450 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
4451 int ext_type, const u8 *data,
4454 if (conn == NULL || conn->ssl == NULL || ext_type != 35)
4457 if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
4463 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4466 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
4470 return conn->failed;
4474 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
4478 return conn->read_alerts;
4482 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
4486 return conn->write_alerts;
4492 static void ocsp_debug_print_resp(OCSP_RESPONSE *rsp)
4494 #ifndef CONFIG_NO_STDOUT_DEBUG
4500 if (wpa_debug_level > MSG_DEBUG)
4503 out = BIO_new(BIO_s_mem());
4507 OCSP_RESPONSE_print(out, rsp, 0);
4508 rlen = BIO_ctrl_pending(out);
4509 txt = os_malloc(rlen + 1);
4515 res = BIO_read(out, txt, rlen);
4518 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP Response\n%s", txt);
4522 #endif /* CONFIG_NO_STDOUT_DEBUG */
4526 static void debug_print_cert(X509 *cert, const char *title)
4528 #ifndef CONFIG_NO_STDOUT_DEBUG
4534 if (wpa_debug_level > MSG_DEBUG)
4537 out = BIO_new(BIO_s_mem());
4541 X509_print(out, cert);
4542 rlen = BIO_ctrl_pending(out);
4543 txt = os_malloc(rlen + 1);
4549 res = BIO_read(out, txt, rlen);
4552 wpa_printf(MSG_DEBUG, "OpenSSL: %s\n%s", title, txt);
4557 #endif /* CONFIG_NO_STDOUT_DEBUG */
4561 static int ocsp_resp_cb(SSL *s, void *arg)
4563 struct tls_connection *conn = arg;
4564 const unsigned char *p;
4565 int len, status, reason, res;
4567 OCSP_BASICRESP *basic;
4569 ASN1_GENERALIZEDTIME *produced_at, *this_update, *next_update;
4571 STACK_OF(X509) *certs = NULL;
4573 len = SSL_get_tlsext_status_ocsp_resp(s, &p);
4575 wpa_printf(MSG_DEBUG, "OpenSSL: No OCSP response received");
4576 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
4579 wpa_hexdump(MSG_DEBUG, "OpenSSL: OCSP response", p, len);
4581 rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
4583 wpa_printf(MSG_INFO, "OpenSSL: Failed to parse OCSP response");
4587 ocsp_debug_print_resp(rsp);
4589 status = OCSP_response_status(rsp);
4590 if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
4591 wpa_printf(MSG_INFO, "OpenSSL: OCSP responder error %d (%s)",
4592 status, OCSP_response_status_str(status));
4596 basic = OCSP_response_get1_basic(rsp);
4598 wpa_printf(MSG_INFO, "OpenSSL: Could not find BasicOCSPResponse");
4602 store = SSL_CTX_get_cert_store(conn->ssl_ctx);
4603 if (conn->peer_issuer) {
4604 debug_print_cert(conn->peer_issuer, "Add OCSP issuer");
4606 if (X509_STORE_add_cert(store, conn->peer_issuer) != 1) {
4607 tls_show_errors(MSG_INFO, __func__,
4608 "OpenSSL: Could not add issuer to certificate store");
4610 certs = sk_X509_new_null();
4613 cert = X509_dup(conn->peer_issuer);
4614 if (cert && !sk_X509_push(certs, cert)) {
4617 "OpenSSL: Could not add issuer to OCSP responder trust store");
4619 sk_X509_free(certs);
4622 if (certs && conn->peer_issuer_issuer) {
4623 cert = X509_dup(conn->peer_issuer_issuer);
4624 if (cert && !sk_X509_push(certs, cert)) {
4627 "OpenSSL: Could not add issuer's issuer to OCSP responder trust store");
4634 status = OCSP_basic_verify(basic, certs, store, OCSP_TRUSTOTHER);
4635 sk_X509_pop_free(certs, X509_free);
4637 tls_show_errors(MSG_INFO, __func__,
4638 "OpenSSL: OCSP response failed verification");
4639 OCSP_BASICRESP_free(basic);
4640 OCSP_RESPONSE_free(rsp);
4644 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP response verification succeeded");
4646 if (!conn->peer_cert) {
4647 wpa_printf(MSG_DEBUG, "OpenSSL: Peer certificate not available for OCSP status check");
4648 OCSP_BASICRESP_free(basic);
4649 OCSP_RESPONSE_free(rsp);
4653 if (!conn->peer_issuer) {
4654 wpa_printf(MSG_DEBUG, "OpenSSL: Peer issuer certificate not available for OCSP status check");
4655 OCSP_BASICRESP_free(basic);
4656 OCSP_RESPONSE_free(rsp);
4660 id = OCSP_cert_to_id(EVP_sha256(), conn->peer_cert, conn->peer_issuer);
4662 wpa_printf(MSG_DEBUG,
4663 "OpenSSL: Could not create OCSP certificate identifier (SHA256)");
4664 OCSP_BASICRESP_free(basic);
4665 OCSP_RESPONSE_free(rsp);
4669 res = OCSP_resp_find_status(basic, id, &status, &reason, &produced_at,
4670 &this_update, &next_update);
4672 id = OCSP_cert_to_id(NULL, conn->peer_cert, conn->peer_issuer);
4674 wpa_printf(MSG_DEBUG,
4675 "OpenSSL: Could not create OCSP certificate identifier (SHA1)");
4676 OCSP_BASICRESP_free(basic);
4677 OCSP_RESPONSE_free(rsp);
4681 res = OCSP_resp_find_status(basic, id, &status, &reason,
4682 &produced_at, &this_update,
4687 wpa_printf(MSG_INFO, "OpenSSL: Could not find current server certificate from OCSP response%s",
4688 (conn->flags & TLS_CONN_REQUIRE_OCSP) ? "" :
4689 " (OCSP not required)");
4690 OCSP_CERTID_free(id);
4691 OCSP_BASICRESP_free(basic);
4692 OCSP_RESPONSE_free(rsp);
4693 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
4695 OCSP_CERTID_free(id);
4697 if (!OCSP_check_validity(this_update, next_update, 5 * 60, -1)) {
4698 tls_show_errors(MSG_INFO, __func__,
4699 "OpenSSL: OCSP status times invalid");
4700 OCSP_BASICRESP_free(basic);
4701 OCSP_RESPONSE_free(rsp);
4705 OCSP_BASICRESP_free(basic);
4706 OCSP_RESPONSE_free(rsp);
4708 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status for server certificate: %s",
4709 OCSP_cert_status_str(status));
4711 if (status == V_OCSP_CERTSTATUS_GOOD)
4713 if (status == V_OCSP_CERTSTATUS_REVOKED)
4715 if (conn->flags & TLS_CONN_REQUIRE_OCSP) {
4716 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP required");
4719 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP was not required, so allow connection to continue");
4724 static int ocsp_status_cb(SSL *s, void *arg)
4730 if (tls_global->ocsp_stapling_response == NULL) {
4731 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - no response configured");
4732 return SSL_TLSEXT_ERR_OK;
4735 resp = os_readfile(tls_global->ocsp_stapling_response, &len);
4737 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - could not read response file");
4738 /* TODO: Build OCSPResponse with responseStatus = internalError
4740 return SSL_TLSEXT_ERR_OK;
4742 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - send cached response");
4743 tmp = OPENSSL_malloc(len);
4746 return SSL_TLSEXT_ERR_ALERT_FATAL;
4749 os_memcpy(tmp, resp, len);
4751 SSL_set_tlsext_status_ocsp_resp(s, tmp, len);
4753 return SSL_TLSEXT_ERR_OK;
4756 #endif /* HAVE_OCSP */
4759 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
4760 const struct tls_connection_params *params)
4762 struct tls_data *data = tls_ctx;
4766 const char *key_id = params->key_id;
4767 const char *cert_id = params->cert_id;
4768 const char *ca_cert_id = params->ca_cert_id;
4769 const char *engine_id = params->engine ? params->engine_id : NULL;
4770 const char *ciphers;
4775 if (params->flags & TLS_CONN_REQUIRE_OCSP_ALL) {
4776 wpa_printf(MSG_INFO,
4777 "OpenSSL: ocsp=3 not supported");
4782 * If the engine isn't explicitly configured, and any of the
4783 * cert/key fields are actually PKCS#11 URIs, then automatically
4784 * use the PKCS#11 ENGINE.
4786 if (!engine_id || os_strcmp(engine_id, "pkcs11") == 0)
4789 if (!key_id && params->private_key && can_pkcs11 &&
4790 os_strncmp(params->private_key, "pkcs11:", 7) == 0) {
4792 key_id = params->private_key;
4795 if (!cert_id && params->client_cert && can_pkcs11 &&
4796 os_strncmp(params->client_cert, "pkcs11:", 7) == 0) {
4798 cert_id = params->client_cert;
4801 if (!ca_cert_id && params->ca_cert && can_pkcs11 &&
4802 os_strncmp(params->ca_cert, "pkcs11:", 7) == 0) {
4804 ca_cert_id = params->ca_cert;
4807 /* If we need to automatically enable the PKCS#11 ENGINE, do so. */
4808 if (can_pkcs11 == 2 && !engine_id)
4809 engine_id = "pkcs11";
4811 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
4812 #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
4813 if (params->flags & TLS_CONN_EAP_FAST) {
4814 wpa_printf(MSG_DEBUG,
4815 "OpenSSL: Use TLSv1_method() for EAP-FAST");
4816 if (SSL_set_ssl_method(conn->ssl, TLSv1_method()) != 1) {
4817 tls_show_errors(MSG_INFO, __func__,
4818 "Failed to set TLSv1_method() for EAP-FAST");
4823 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
4824 #ifdef SSL_OP_NO_TLSv1_3
4825 if (params->flags & TLS_CONN_EAP_FAST) {
4826 /* Need to disable TLS v1.3 at least for now since OpenSSL 1.1.1
4827 * refuses to start the handshake with the modified ciphersuite
4828 * list (no TLS v1.3 ciphersuites included) for EAP-FAST. */
4829 wpa_printf(MSG_DEBUG, "OpenSSL: Disable TLSv1.3 for EAP-FAST");
4830 SSL_set_options(conn->ssl, SSL_OP_NO_TLSv1_3);
4832 #endif /* SSL_OP_NO_TLSv1_3 */
4834 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4836 while ((err = ERR_get_error())) {
4837 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
4838 __func__, ERR_error_string(err, NULL));
4842 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
4843 ret = tls_engine_init(conn, engine_id, params->pin,
4844 key_id, cert_id, ca_cert_id);
4848 if (tls_connection_set_subject_match(conn,
4849 params->subject_match,
4850 params->altsubject_match,
4851 params->suffix_match,
4852 params->domain_match,
4853 params->check_cert_subject))
4856 if (engine_id && ca_cert_id) {
4857 if (tls_connection_engine_ca_cert(data, conn, ca_cert_id))
4858 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
4859 } else if (tls_connection_ca_cert(data, conn, params->ca_cert,
4860 params->ca_cert_blob,
4861 params->ca_cert_blob_len,
4865 if (engine_id && cert_id) {
4866 if (tls_connection_engine_client_cert(conn, cert_id))
4867 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
4868 } else if (tls_connection_client_cert(conn, params->client_cert,
4869 params->client_cert_blob,
4870 params->client_cert_blob_len))
4873 if (engine_id && key_id) {
4874 wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
4875 if (tls_connection_engine_private_key(conn))
4876 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
4877 } else if (tls_connection_private_key(data, conn,
4878 params->private_key,
4879 params->private_key_passwd,
4880 params->private_key_blob,
4881 params->private_key_blob_len)) {
4882 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
4883 params->private_key);
4887 if (tls_connection_dh(conn, params->dh_file)) {
4888 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
4893 ciphers = params->openssl_ciphers;
4894 #ifdef CONFIG_SUITEB
4895 #ifdef OPENSSL_IS_BORINGSSL
4896 if (ciphers && os_strcmp(ciphers, "SUITEB192") == 0) {
4897 /* BoringSSL removed support for SUITEB192, so need to handle
4898 * this with hardcoded ciphersuite and additional checks for
4899 * other parameters. */
4900 ciphers = "ECDHE-ECDSA-AES256-GCM-SHA384";
4902 #endif /* OPENSSL_IS_BORINGSSL */
4903 #endif /* CONFIG_SUITEB */
4904 if (ciphers && SSL_set_cipher_list(conn->ssl, ciphers) != 1) {
4905 wpa_printf(MSG_INFO,
4906 "OpenSSL: Failed to set cipher string '%s'",
4911 if (!params->openssl_ecdh_curves) {
4912 #ifndef OPENSSL_IS_BORINGSSL
4913 #ifndef OPENSSL_NO_EC
4914 #if (OPENSSL_VERSION_NUMBER >= 0x10002000L) && \
4915 (OPENSSL_VERSION_NUMBER < 0x10100000L)
4916 if (SSL_set_ecdh_auto(conn->ssl, 1) != 1) {
4917 wpa_printf(MSG_INFO,
4918 "OpenSSL: Failed to set ECDH curves to auto");
4921 #endif /* >= 1.0.2 && < 1.1.0 */
4922 #endif /* OPENSSL_NO_EC */
4923 #endif /* OPENSSL_IS_BORINGSSL */
4924 } else if (params->openssl_ecdh_curves[0]) {
4925 #if defined(OPENSSL_IS_BORINGSSL) || (OPENSSL_VERSION_NUMBER < 0x10002000L)
4926 wpa_printf(MSG_INFO,
4927 "OpenSSL: ECDH configuration nnot supported");
4929 #else /* OPENSSL_IS_BORINGSSL || < 1.0.2 */
4930 #ifndef OPENSSL_NO_EC
4931 if (SSL_set1_curves_list(conn->ssl,
4932 params->openssl_ecdh_curves) != 1) {
4933 wpa_printf(MSG_INFO,
4934 "OpenSSL: Failed to set ECDH curves '%s'",
4935 params->openssl_ecdh_curves);
4938 #else /* OPENSSL_NO_EC */
4939 wpa_printf(MSG_INFO, "OpenSSL: ECDH not supported");
4941 #endif /* OPENSSL_NO_EC */
4942 #endif /* OPENSSL_IS_BORINGSSL */
4945 if (tls_set_conn_flags(conn, params->flags,
4946 params->openssl_ciphers) < 0)
4949 #ifdef OPENSSL_IS_BORINGSSL
4950 if (params->flags & TLS_CONN_REQUEST_OCSP) {
4951 SSL_enable_ocsp_stapling(conn->ssl);
4953 #else /* OPENSSL_IS_BORINGSSL */
4955 if (params->flags & TLS_CONN_REQUEST_OCSP) {
4956 SSL_CTX *ssl_ctx = data->ssl;
4957 SSL_set_tlsext_status_type(conn->ssl, TLSEXT_STATUSTYPE_ocsp);
4958 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
4959 SSL_CTX_set_tlsext_status_arg(ssl_ctx, conn);
4961 #else /* HAVE_OCSP */
4962 if (params->flags & TLS_CONN_REQUIRE_OCSP) {
4963 wpa_printf(MSG_INFO,
4964 "OpenSSL: No OCSP support included - reject configuration");
4967 if (params->flags & TLS_CONN_REQUEST_OCSP) {
4968 wpa_printf(MSG_DEBUG,
4969 "OpenSSL: No OCSP support included - allow optional OCSP case to continue");
4971 #endif /* HAVE_OCSP */
4972 #endif /* OPENSSL_IS_BORINGSSL */
4974 conn->flags = params->flags;
4976 tls_get_errors(data);
4982 int tls_global_set_params(void *tls_ctx,
4983 const struct tls_connection_params *params)
4985 struct tls_data *data = tls_ctx;
4986 SSL_CTX *ssl_ctx = data->ssl;
4989 while ((err = ERR_get_error())) {
4990 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
4991 __func__, ERR_error_string(err, NULL));
4994 os_free(data->check_cert_subject);
4995 data->check_cert_subject = NULL;
4996 if (params->check_cert_subject) {
4997 data->check_cert_subject =
4998 os_strdup(params->check_cert_subject);
4999 if (!data->check_cert_subject)
5003 if (tls_global_ca_cert(data, params->ca_cert) ||
5004 tls_global_client_cert(data, params->client_cert) ||
5005 tls_global_private_key(data, params->private_key,
5006 params->private_key_passwd) ||
5007 tls_global_dh(data, params->dh_file)) {
5008 wpa_printf(MSG_INFO, "TLS: Failed to set global parameters");
5012 if (params->openssl_ciphers &&
5013 SSL_CTX_set_cipher_list(ssl_ctx, params->openssl_ciphers) != 1) {
5014 wpa_printf(MSG_INFO,
5015 "OpenSSL: Failed to set cipher string '%s'",
5016 params->openssl_ciphers);
5020 if (!params->openssl_ecdh_curves) {
5021 #ifndef OPENSSL_IS_BORINGSSL
5022 #ifndef OPENSSL_NO_EC
5023 #if (OPENSSL_VERSION_NUMBER >= 0x10002000L) && \
5024 (OPENSSL_VERSION_NUMBER < 0x10100000L)
5025 if (SSL_CTX_set_ecdh_auto(ssl_ctx, 1) != 1) {
5026 wpa_printf(MSG_INFO,
5027 "OpenSSL: Failed to set ECDH curves to auto");
5030 #endif /* >= 1.0.2 && < 1.1.0 */
5031 #endif /* OPENSSL_NO_EC */
5032 #endif /* OPENSSL_IS_BORINGSSL */
5033 } else if (params->openssl_ecdh_curves[0]) {
5034 #if defined(OPENSSL_IS_BORINGSSL) || (OPENSSL_VERSION_NUMBER < 0x10002000L)
5035 wpa_printf(MSG_INFO,
5036 "OpenSSL: ECDH configuration nnot supported");
5038 #else /* OPENSSL_IS_BORINGSSL || < 1.0.2 */
5039 #ifndef OPENSSL_NO_EC
5040 #if OPENSSL_VERSION_NUMBER < 0x10100000L
5041 SSL_CTX_set_ecdh_auto(ssl_ctx, 1);
5043 if (SSL_CTX_set1_curves_list(ssl_ctx,
5044 params->openssl_ecdh_curves) !=
5046 wpa_printf(MSG_INFO,
5047 "OpenSSL: Failed to set ECDH curves '%s'",
5048 params->openssl_ecdh_curves);
5051 #else /* OPENSSL_NO_EC */
5052 wpa_printf(MSG_INFO, "OpenSSL: ECDH not supported");
5054 #endif /* OPENSSL_NO_EC */
5055 #endif /* OPENSSL_IS_BORINGSSL */
5058 #ifdef SSL_OP_NO_TICKET
5059 if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
5060 SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
5062 SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TICKET);
5063 #endif /* SSL_OP_NO_TICKET */
5066 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_status_cb);
5067 SSL_CTX_set_tlsext_status_arg(ssl_ctx, ssl_ctx);
5068 os_free(tls_global->ocsp_stapling_response);
5069 if (params->ocsp_stapling_response)
5070 tls_global->ocsp_stapling_response =
5071 os_strdup(params->ocsp_stapling_response);
5073 tls_global->ocsp_stapling_response = NULL;
5074 #endif /* HAVE_OCSP */
5080 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
5081 /* Pre-shared secred requires a patch to openssl, so this function is
5082 * commented out unless explicitly needed for EAP-FAST in order to be able to
5083 * build this file with unmodified openssl. */
5085 #if (defined(OPENSSL_IS_BORINGSSL) || OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
5086 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
5087 STACK_OF(SSL_CIPHER) *peer_ciphers,
5088 const SSL_CIPHER **cipher, void *arg)
5089 #else /* OPENSSL_IS_BORINGSSL */
5090 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
5091 STACK_OF(SSL_CIPHER) *peer_ciphers,
5092 SSL_CIPHER **cipher, void *arg)
5093 #endif /* OPENSSL_IS_BORINGSSL */
5095 struct tls_connection *conn = arg;
5098 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
5099 (defined(LIBRESSL_VERSION_NUMBER) && \
5100 LIBRESSL_VERSION_NUMBER < 0x20700000L)
5101 if (conn == NULL || conn->session_ticket_cb == NULL)
5104 ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
5105 conn->session_ticket,
5106 conn->session_ticket_len,
5107 s->s3->client_random,
5108 s->s3->server_random, secret);
5110 unsigned char client_random[SSL3_RANDOM_SIZE];
5111 unsigned char server_random[SSL3_RANDOM_SIZE];
5113 if (conn == NULL || conn->session_ticket_cb == NULL)
5116 SSL_get_client_random(s, client_random, sizeof(client_random));
5117 SSL_get_server_random(s, server_random, sizeof(server_random));
5119 ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
5120 conn->session_ticket,
5121 conn->session_ticket_len,
5123 server_random, secret);
5126 os_free(conn->session_ticket);
5127 conn->session_ticket = NULL;
5132 *secret_len = SSL_MAX_MASTER_KEY_LENGTH;
5137 static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
5140 struct tls_connection *conn = arg;
5142 if (conn == NULL || conn->session_ticket_cb == NULL)
5145 wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
5147 os_free(conn->session_ticket);
5148 conn->session_ticket = NULL;
5150 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
5151 "extension", data, len);
5153 conn->session_ticket = os_memdup(data, len);
5154 if (conn->session_ticket == NULL)
5157 conn->session_ticket_len = len;
5161 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
5164 int tls_connection_set_session_ticket_cb(void *tls_ctx,
5165 struct tls_connection *conn,
5166 tls_session_ticket_cb cb,
5169 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
5170 conn->session_ticket_cb = cb;
5171 conn->session_ticket_cb_ctx = ctx;
5174 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
5177 SSL_set_session_ticket_ext_cb(conn->ssl,
5178 tls_session_ticket_ext_cb, conn);
5180 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
5182 SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
5186 #else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
5188 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
5192 int tls_get_library_version(char *buf, size_t buf_len)
5194 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
5195 return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
5196 OPENSSL_VERSION_TEXT,
5197 OpenSSL_version(OPENSSL_VERSION));
5199 return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
5200 OPENSSL_VERSION_TEXT,
5201 SSLeay_version(SSLEAY_VERSION));
5206 void tls_connection_set_success_data(struct tls_connection *conn,
5207 struct wpabuf *data)
5212 if (tls_ex_idx_session < 0)
5214 sess = SSL_get_session(conn->ssl);
5217 old = SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
5219 wpa_printf(MSG_DEBUG, "OpenSSL: Replacing old success data %p",
5223 if (SSL_SESSION_set_ex_data(sess, tls_ex_idx_session, data) != 1)
5226 wpa_printf(MSG_DEBUG, "OpenSSL: Stored success data %p", data);
5227 conn->success_data = 1;
5231 wpa_printf(MSG_INFO, "OpenSSL: Failed to store success data");
5236 void tls_connection_set_success_data_resumed(struct tls_connection *conn)
5238 wpa_printf(MSG_DEBUG,
5239 "OpenSSL: Success data accepted for resumed session");
5240 conn->success_data = 1;
5244 const struct wpabuf *
5245 tls_connection_get_success_data(struct tls_connection *conn)
5249 if (tls_ex_idx_session < 0 ||
5250 !(sess = SSL_get_session(conn->ssl)))
5252 return SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
5256 void tls_connection_remove_session(struct tls_connection *conn)
5260 sess = SSL_get_session(conn->ssl);
5264 if (SSL_CTX_remove_session(conn->ssl_ctx, sess) != 1)
5265 wpa_printf(MSG_DEBUG,
5266 "OpenSSL: Session was not cached");
5268 wpa_printf(MSG_DEBUG,
5269 "OpenSSL: Removed cached session to disable session resumption");