]> git.ipfire.org Git - thirdparty/hostap.git/blobdiff - src/crypto/tls_openssl.c
Use os_memdup()
[thirdparty/hostap.git] / src / crypto / tls_openssl.c
index 1c2a5db7acb7a7e728c856fae397bca56ad9ee51..fc169e71e1e9c82533f13b13159d9ffa2484ee43 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * SSL/TLS interface functions for OpenSSL
- * Copyright (c) 2004-2013, Jouni Malinen <j@w1.fi>
+ * Copyright (c) 2004-2015, Jouni Malinen <j@w1.fi>
  *
  * This software may be distributed under the terms of the BSD license.
  * See README for more details.
 
 #include <openssl/ssl.h>
 #include <openssl/err.h>
+#include <openssl/opensslv.h>
 #include <openssl/pkcs12.h>
 #include <openssl/x509v3.h>
 #ifndef OPENSSL_NO_ENGINE
 #include <openssl/engine.h>
 #endif /* OPENSSL_NO_ENGINE */
+#ifndef OPENSSL_NO_DSA
+#include <openssl/dsa.h>
+#endif
+#ifndef OPENSSL_NO_DH
+#include <openssl/dh.h>
+#endif
 
 #include "common.h"
 #include "crypto.h"
+#include "sha1.h"
+#include "sha256.h"
 #include "tls.h"
+#include "tls_openssl.h"
 
-#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
-#define OPENSSL_d2i_TYPE const unsigned char **
-#else
-#define OPENSSL_d2i_TYPE unsigned char **
-#endif
-
-#if defined(SSL_CTX_get_app_data) && defined(SSL_CTX_set_app_data)
-#define OPENSSL_SUPPORTS_CTX_APP_DATA
-#endif
-
-#if OPENSSL_VERSION_NUMBER < 0x10000000L
-/* ERR_remove_thread_state replaces ERR_remove_state and the latter is
- * deprecated. However, OpenSSL 0.9.8 doesn't include
- * ERR_remove_thread_state. */
-#define ERR_remove_thread_state(tid) ERR_remove_state(0)
-#endif
-
-#if OPENSSL_VERSION_NUMBER >= 0x10000000L
-/*
- * Session ticket override patch was merged into OpenSSL 0.9.9 tree on
- * 2008-11-15. This version uses a bit different API compared to the old patch.
- */
-#define CONFIG_OPENSSL_TICKET_OVERRIDE
+#if !defined(CONFIG_FIPS) &&                             \
+    (defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) ||   \
+     defined(EAP_SERVER_FAST))
+#define OPENSSL_NEED_EAP_FAST_PRF
 #endif
 
 #if defined(OPENSSL_IS_BORINGSSL)
@@ -67,6 +58,51 @@ typedef int stack_index_t;
 #endif /* OPENSSL_NO_TLSEXT */
 #endif /* SSL_set_tlsext_status_type */
 
+#if (OPENSSL_VERSION_NUMBER < 0x10100000L || \
+     defined(LIBRESSL_VERSION_NUMBER)) &&    \
+    !defined(BORINGSSL_API_VERSION)
+/*
+ * SSL_get_client_random() and SSL_get_server_random() were added in OpenSSL
+ * 1.1.0 and newer BoringSSL revisions. Provide compatibility wrappers for
+ * older versions.
+ */
+
+static size_t SSL_get_client_random(const SSL *ssl, unsigned char *out,
+                                   size_t outlen)
+{
+       if (!ssl->s3 || outlen < SSL3_RANDOM_SIZE)
+               return 0;
+       os_memcpy(out, ssl->s3->client_random, SSL3_RANDOM_SIZE);
+       return SSL3_RANDOM_SIZE;
+}
+
+
+static size_t SSL_get_server_random(const SSL *ssl, unsigned char *out,
+                                   size_t outlen)
+{
+       if (!ssl->s3 || outlen < SSL3_RANDOM_SIZE)
+               return 0;
+       os_memcpy(out, ssl->s3->server_random, SSL3_RANDOM_SIZE);
+       return SSL3_RANDOM_SIZE;
+}
+
+
+#ifdef OPENSSL_NEED_EAP_FAST_PRF
+static size_t SSL_SESSION_get_master_key(const SSL_SESSION *session,
+                                        unsigned char *out, size_t outlen)
+{
+       if (!session || session->master_key_length < 0 ||
+           (size_t) session->master_key_length > outlen)
+               return 0;
+       if ((size_t) session->master_key_length < outlen)
+               outlen = session->master_key_length;
+       os_memcpy(out, session->master_key, outlen);
+       return outlen;
+}
+#endif /* OPENSSL_NEED_EAP_FAST_PRF */
+
+#endif
+
 #ifdef ANDROID
 #include <openssl/pem.h>
 #include <keystore/keystore_get.h>
@@ -81,9 +117,70 @@ static BIO * BIO_from_keystore(const char *key)
        free(value);
        return bio;
 }
+
+
+static int tls_add_ca_from_keystore(X509_STORE *ctx, const char *key_alias)
+{
+       BIO *bio = BIO_from_keystore(key_alias);
+       STACK_OF(X509_INFO) *stack = NULL;
+       stack_index_t i;
+
+       if (bio) {
+               stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
+               BIO_free(bio);
+       }
+
+       if (!stack) {
+               wpa_printf(MSG_WARNING, "TLS: Failed to parse certificate: %s",
+                          key_alias);
+               return -1;
+       }
+
+       for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
+               X509_INFO *info = sk_X509_INFO_value(stack, i);
+
+               if (info->x509)
+                       X509_STORE_add_cert(ctx, info->x509);
+               if (info->crl)
+                       X509_STORE_add_crl(ctx, info->crl);
+       }
+
+       sk_X509_INFO_pop_free(stack, X509_INFO_free);
+
+       return 0;
+}
+
+
+static int tls_add_ca_from_keystore_encoded(X509_STORE *ctx,
+                                           const char *encoded_key_alias)
+{
+       int rc = -1;
+       int len = os_strlen(encoded_key_alias);
+       unsigned char *decoded_alias;
+
+       if (len & 1) {
+               wpa_printf(MSG_WARNING, "Invalid hex-encoded alias: %s",
+                          encoded_key_alias);
+               return rc;
+       }
+
+       decoded_alias = os_malloc(len / 2 + 1);
+       if (decoded_alias) {
+               if (!hexstr2bin(encoded_key_alias, decoded_alias, len / 2)) {
+                       decoded_alias[len / 2] = '\0';
+                       rc = tls_add_ca_from_keystore(
+                               ctx, (const char *) decoded_alias);
+               }
+               os_free(decoded_alias);
+       }
+
+       return rc;
+}
+
 #endif /* ANDROID */
 
 static int tls_openssl_ref_count = 0;
+static int tls_ex_idx_session = -1;
 
 struct tls_context {
        void (*event_cb)(void *ctx, enum tls_event ev,
@@ -96,15 +193,21 @@ struct tls_context {
 static struct tls_context *tls_global = NULL;
 
 
+struct tls_data {
+       SSL_CTX *ssl;
+       unsigned int tls_session_lifetime;
+};
+
 struct tls_connection {
        struct tls_context *context;
+       SSL_CTX *ssl_ctx;
        SSL *ssl;
        BIO *ssl_in, *ssl_out;
-#ifndef OPENSSL_NO_ENGINE
+#if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
        ENGINE *engine;        /* functional reference to the engine */
        EVP_PKEY *private_key; /* the private key if using engine */
 #endif /* OPENSSL_NO_ENGINE */
-       char *subject_match, *altsubject_match, *suffix_match;
+       char *subject_match, *altsubject_match, *suffix_match, *domain_match;
        int read_alerts, write_alerts, failed;
 
        tls_session_ticket_cb session_ticket_cb;
@@ -118,6 +221,7 @@ struct tls_connection {
        unsigned int cert_probe:1;
        unsigned int server_cert_only:1;
        unsigned int invalid_hb_used:1;
+       unsigned int success_data:1;
 
        u8 srv_cert_hash[32];
 
@@ -126,6 +230,9 @@ struct tls_connection {
        X509 *peer_cert;
        X509 *peer_issuer;
        X509 *peer_issuer_issuer;
+
+       unsigned char client_random[SSL3_RANDOM_SIZE];
+       unsigned char server_random[SSL3_RANDOM_SIZE];
 };
 
 
@@ -408,7 +515,8 @@ static int tls_cryptoapi_cert(SSL *ssl, const char *name)
                goto err;
        }
 
-       cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &priv->cert->pbCertEncoded,
+       cert = d2i_X509(NULL,
+                       (const unsigned char **) &priv->cert->pbCertEncoded,
                        priv->cert->cbCertEncoded);
        if (cert == NULL) {
                wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
@@ -508,7 +616,8 @@ static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
        }
 
        while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
-               cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ctx->pbCertEncoded,
+               cert = d2i_X509(NULL,
+                               (const unsigned char **) &ctx->pbCertEncoded,
                                ctx->cbCertEncoded);
                if (cert == NULL) {
                        wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
@@ -521,7 +630,8 @@ static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
                wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
                           "system certificate store: subject='%s'", buf);
 
-               if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
+               if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx),
+                                        cert)) {
                        tls_show_errors(MSG_WARNING, __func__,
                                        "Failed to add ca_cert to OpenSSL "
                                        "certificate store");
@@ -619,10 +729,16 @@ static int tls_engine_load_dynamic_generic(const char *pre[],
 
        engine = ENGINE_by_id(id);
        if (engine) {
-               ENGINE_free(engine);
                wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
                           "available", id);
-               return 0;
+               /*
+                * If it was auto-loaded by ENGINE_by_id() we might still
+                * need to tell it which PKCS#11 module to use in legacy
+                * (non-p11-kit) environments. Do so now; even if it was
+                * properly initialised before, setting it again will be
+                * harmless.
+                */
+               goto found;
        }
        ERR_clear_error();
 
@@ -659,7 +775,7 @@ static int tls_engine_load_dynamic_generic(const char *pre[],
                           id, ERR_error_string(ERR_get_error(), NULL));
                return -1;
        }
-
+ found:
        while (post && post[0]) {
                wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
                if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
@@ -700,12 +816,15 @@ static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
                NULL, NULL
        };
 
-       if (!pkcs11_so_path || !pkcs11_module_path)
+       if (!pkcs11_so_path)
                return 0;
 
        pre_cmd[1] = pkcs11_so_path;
        pre_cmd[3] = engine_id;
-       post_cmd[1] = pkcs11_module_path;
+       if (pkcs11_module_path)
+               post_cmd[1] = pkcs11_module_path;
+       else
+               post_cmd[0] = NULL;
 
        wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
                   pkcs11_so_path);
@@ -743,8 +862,27 @@ static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
 #endif /* OPENSSL_NO_ENGINE */
 
 
+static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *sess)
+{
+       struct wpabuf *buf;
+
+       if (tls_ex_idx_session < 0)
+               return;
+       buf = SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
+       if (!buf)
+               return;
+       wpa_printf(MSG_DEBUG,
+                  "OpenSSL: Free application session data %p (sess %p)",
+                  buf, sess);
+       wpabuf_free(buf);
+
+       SSL_SESSION_set_ex_data(sess, tls_ex_idx_session, NULL);
+}
+
+
 void * tls_init(const struct tls_config *conf)
 {
+       struct tls_data *data;
        SSL_CTX *ssl;
        struct tls_context *context;
        const char *ciphers;
@@ -756,7 +894,9 @@ void * tls_init(const struct tls_config *conf)
 #ifdef CONFIG_FIPS
 #ifdef OPENSSL_FIPS
                if (conf && conf->fips_mode) {
-                       if (!FIPS_mode_set(1)) {
+                       static int fips_enabled = 0;
+
+                       if (!fips_enabled && !FIPS_mode_set(1)) {
                                wpa_printf(MSG_ERROR, "Failed to enable FIPS "
                                           "mode");
                                ERR_load_crypto_strings();
@@ -764,8 +904,10 @@ void * tls_init(const struct tls_config *conf)
                                os_free(tls_global);
                                tls_global = NULL;
                                return NULL;
-                       } else
+                       } else {
                                wpa_printf(MSG_INFO, "Running in FIPS mode");
+                               fips_enabled = 1;
+                       }
                }
 #else /* OPENSSL_FIPS */
                if (conf && conf->fips_mode) {
@@ -777,9 +919,10 @@ void * tls_init(const struct tls_config *conf)
                }
 #endif /* OPENSSL_FIPS */
 #endif /* CONFIG_FIPS */
+#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
                SSL_load_error_strings();
                SSL_library_init();
-#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
+#ifndef OPENSSL_NO_SHA256
                EVP_add_digest(EVP_sha256());
 #endif /* OPENSSL_NO_SHA256 */
                /* TODO: if /dev/urandom is available, PRNG is seeded
@@ -798,52 +941,82 @@ void * tls_init(const struct tls_config *conf)
 #endif /* OPENSSL_NO_RC2 */
                PKCS12_PBE_add();
 #endif  /* PKCS12_FUNCS */
+#endif /* < 1.1.0 */
        } else {
-#ifdef OPENSSL_SUPPORTS_CTX_APP_DATA
-               /* Newer OpenSSL can store app-data per-SSL */
                context = tls_context_new(conf);
                if (context == NULL)
                        return NULL;
-#else /* OPENSSL_SUPPORTS_CTX_APP_DATA */
-               context = tls_global;
-#endif /* OPENSSL_SUPPORTS_CTX_APP_DATA */
        }
        tls_openssl_ref_count++;
 
-       ssl = SSL_CTX_new(SSLv23_method());
+       data = os_zalloc(sizeof(*data));
+       if (data)
+               ssl = SSL_CTX_new(SSLv23_method());
+       else
+               ssl = NULL;
        if (ssl == NULL) {
                tls_openssl_ref_count--;
-#ifdef OPENSSL_SUPPORTS_CTX_APP_DATA
                if (context != tls_global)
                        os_free(context);
-#endif /* OPENSSL_SUPPORTS_CTX_APP_DATA */
                if (tls_openssl_ref_count == 0) {
                        os_free(tls_global);
                        tls_global = NULL;
                }
+               os_free(data);
                return NULL;
        }
+       data->ssl = ssl;
+       if (conf)
+               data->tls_session_lifetime = conf->tls_session_lifetime;
 
        SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv2);
        SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv3);
 
+#ifdef SSL_MODE_NO_AUTO_CHAIN
+       /* Number of deployed use cases assume the default OpenSSL behavior of
+        * auto chaining the local certificate is in use. BoringSSL removed this
+        * functionality by default, so we need to restore it here to avoid
+        * breaking existing use cases. */
+       SSL_CTX_clear_mode(ssl, SSL_MODE_NO_AUTO_CHAIN);
+#endif /* SSL_MODE_NO_AUTO_CHAIN */
+
        SSL_CTX_set_info_callback(ssl, ssl_info_cb);
-#ifdef OPENSSL_SUPPORTS_CTX_APP_DATA
        SSL_CTX_set_app_data(ssl, context);
-#endif /* OPENSSL_SUPPORTS_CTX_APP_DATA */
+       if (data->tls_session_lifetime > 0) {
+               SSL_CTX_set_quiet_shutdown(ssl, 1);
+               /*
+                * Set default context here. In practice, this will be replaced
+                * by the per-EAP method context in tls_connection_set_verify().
+                */
+               SSL_CTX_set_session_id_context(ssl, (u8 *) "hostapd", 7);
+               SSL_CTX_set_session_cache_mode(ssl, SSL_SESS_CACHE_SERVER);
+               SSL_CTX_set_timeout(ssl, data->tls_session_lifetime);
+               SSL_CTX_sess_set_remove_cb(ssl, remove_session_cb);
+       } else {
+               SSL_CTX_set_session_cache_mode(ssl, SSL_SESS_CACHE_OFF);
+       }
+
+       if (tls_ex_idx_session < 0) {
+               tls_ex_idx_session = SSL_SESSION_get_ex_new_index(
+                       0, NULL, NULL, NULL, NULL);
+               if (tls_ex_idx_session < 0) {
+                       tls_deinit(data);
+                       return NULL;
+               }
+       }
 
 #ifndef OPENSSL_NO_ENGINE
+       wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
+       ERR_load_ENGINE_strings();
+       ENGINE_load_dynamic();
+
        if (conf &&
            (conf->opensc_engine_path || conf->pkcs11_engine_path ||
             conf->pkcs11_module_path)) {
-               wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
-               ERR_load_ENGINE_strings();
-               ENGINE_load_dynamic();
-
                if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
                    tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
                                                   conf->pkcs11_module_path)) {
-                       tls_deinit(ssl);
+                       tls_deinit(data);
                        return NULL;
                }
        }
@@ -857,26 +1030,28 @@ void * tls_init(const struct tls_config *conf)
                wpa_printf(MSG_ERROR,
                           "OpenSSL: Failed to set cipher string '%s'",
                           ciphers);
-               tls_deinit(ssl);
+               tls_deinit(data);
                return NULL;
        }
 
-       return ssl;
+       return data;
 }
 
 
 void tls_deinit(void *ssl_ctx)
 {
-       SSL_CTX *ssl = ssl_ctx;
-#ifdef OPENSSL_SUPPORTS_CTX_APP_DATA
+       struct tls_data *data = ssl_ctx;
+       SSL_CTX *ssl = data->ssl;
        struct tls_context *context = SSL_CTX_get_app_data(ssl);
        if (context != tls_global)
                os_free(context);
-#endif /* OPENSSL_SUPPORTS_CTX_APP_DATA */
+       if (data->tls_session_lifetime > 0)
+               SSL_CTX_flush_sessions(ssl, 0);
        SSL_CTX_free(ssl);
 
        tls_openssl_ref_count--;
        if (tls_openssl_ref_count == 0) {
+#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
 #ifndef OPENSSL_NO_ENGINE
                ENGINE_cleanup();
 #endif /* OPENSSL_NO_ENGINE */
@@ -884,34 +1059,70 @@ void tls_deinit(void *ssl_ctx)
                ERR_remove_thread_state(NULL);
                ERR_free_strings();
                EVP_cleanup();
+#endif /* < 1.1.0 */
                os_free(tls_global->ocsp_stapling_response);
                tls_global->ocsp_stapling_response = NULL;
                os_free(tls_global);
                tls_global = NULL;
        }
+
+       os_free(data);
+}
+
+
+#ifndef OPENSSL_NO_ENGINE
+
+/* Cryptoki return values */
+#define CKR_PIN_INCORRECT 0x000000a0
+#define CKR_PIN_INVALID 0x000000a1
+#define CKR_PIN_LEN_RANGE 0x000000a2
+
+/* libp11 */
+#define ERR_LIB_PKCS11 ERR_LIB_USER
+
+static int tls_is_pin_error(unsigned int err)
+{
+       return ERR_GET_LIB(err) == ERR_LIB_PKCS11 &&
+               (ERR_GET_REASON(err) == CKR_PIN_INCORRECT ||
+                ERR_GET_REASON(err) == CKR_PIN_INVALID ||
+                ERR_GET_REASON(err) == CKR_PIN_LEN_RANGE);
 }
 
+#endif /* OPENSSL_NO_ENGINE */
+
+
+#ifdef ANDROID
+/* EVP_PKEY_from_keystore comes from system/security/keystore-engine. */
+EVP_PKEY * EVP_PKEY_from_keystore(const char *key_id);
+#endif /* ANDROID */
 
 static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
                           const char *pin, const char *key_id,
                           const char *cert_id, const char *ca_cert_id)
 {
+#if defined(ANDROID) && defined(OPENSSL_IS_BORINGSSL)
+#if !defined(OPENSSL_NO_ENGINE)
+#error "This code depends on OPENSSL_NO_ENGINE being defined by BoringSSL."
+#endif
+       if (!key_id)
+               return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
+       conn->engine = NULL;
+       conn->private_key = EVP_PKEY_from_keystore(key_id);
+       if (!conn->private_key) {
+               wpa_printf(MSG_ERROR,
+                          "ENGINE: cannot load private key with id '%s' [%s]",
+                          key_id,
+                          ERR_error_string(ERR_get_error(), NULL));
+               return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
+       }
+#endif /* ANDROID && OPENSSL_IS_BORINGSSL */
+
 #ifndef OPENSSL_NO_ENGINE
        int ret = -1;
        if (engine_id == NULL) {
                wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
                return -1;
        }
-#ifndef ANDROID
-       if (pin == NULL) {
-               wpa_printf(MSG_ERROR, "ENGINE: Smartcard PIN not set");
-               return -1;
-       }
-#endif
-       if (key_id == NULL) {
-               wpa_printf(MSG_ERROR, "ENGINE: Key Id not set");
-               return -1;
-       }
 
        ERR_clear_error();
 #ifdef ANDROID
@@ -932,21 +1143,39 @@ static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
        wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
 
 #ifndef ANDROID
-       if (ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
+       if (pin && ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
                wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
                           ERR_error_string(ERR_get_error(), NULL));
                goto err;
        }
 #endif
-       /* load private key first in-case PIN is required for cert */
-       conn->private_key = ENGINE_load_private_key(conn->engine,
-                                                   key_id, NULL, NULL);
-       if (!conn->private_key) {
-               wpa_printf(MSG_ERROR, "ENGINE: cannot load private key with id"
-                               " '%s' [%s]", key_id,
-                          ERR_error_string(ERR_get_error(), NULL));
-               ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
-               goto err;
+       if (key_id) {
+               /*
+                * Ensure that the ENGINE does not attempt to use the OpenSSL
+                * UI system to obtain a PIN, if we didn't provide one.
+                */
+               struct {
+                       const void *password;
+                       const char *prompt_info;
+               } key_cb = { "", NULL };
+
+               /* load private key first in-case PIN is required for cert */
+               conn->private_key = ENGINE_load_private_key(conn->engine,
+                                                           key_id, NULL,
+                                                           &key_cb);
+               if (!conn->private_key) {
+                       unsigned long err = ERR_get_error();
+
+                       wpa_printf(MSG_ERROR,
+                                  "ENGINE: cannot load private key with id '%s' [%s]",
+                                  key_id,
+                                  ERR_error_string(err, NULL));
+                       if (tls_is_pin_error(err))
+                               ret = TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
+                       else
+                               ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
+                       goto err;
+               }
        }
 
        /* handle a certificate and/or CA certificate */
@@ -985,17 +1214,19 @@ err:
 
 static void tls_engine_deinit(struct tls_connection *conn)
 {
-#ifndef OPENSSL_NO_ENGINE
+#if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
        wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
        if (conn->private_key) {
                EVP_PKEY_free(conn->private_key);
                conn->private_key = NULL;
        }
        if (conn->engine) {
+#if !defined(OPENSSL_IS_BORINGSSL)
                ENGINE_finish(conn->engine);
+#endif /* !OPENSSL_IS_BORINGSSL */
                conn->engine = NULL;
        }
-#endif /* OPENSSL_NO_ENGINE */
+#endif /* ANDROID || !OPENSSL_NO_ENGINE */
 }
 
 
@@ -1014,14 +1245,83 @@ int tls_get_errors(void *ssl_ctx)
 }
 
 
+static const char * openssl_content_type(int content_type)
+{
+       switch (content_type) {
+       case 20:
+               return "change cipher spec";
+       case 21:
+               return "alert";
+       case 22:
+               return "handshake";
+       case 23:
+               return "application data";
+       case 24:
+               return "heartbeat";
+       case 256:
+               return "TLS header info"; /* pseudo content type */
+       default:
+               return "?";
+       }
+}
+
+
+static const char * openssl_handshake_type(int content_type, const u8 *buf,
+                                          size_t len)
+{
+       if (content_type != 22 || !buf || len == 0)
+               return "";
+       switch (buf[0]) {
+       case 0:
+               return "hello request";
+       case 1:
+               return "client hello";
+       case 2:
+               return "server hello";
+       case 4:
+               return "new session ticket";
+       case 11:
+               return "certificate";
+       case 12:
+               return "server key exchange";
+       case 13:
+               return "certificate request";
+       case 14:
+               return "server hello done";
+       case 15:
+               return "certificate verify";
+       case 16:
+               return "client key exchange";
+       case 20:
+               return "finished";
+       case 21:
+               return "certificate url";
+       case 22:
+               return "certificate status";
+       default:
+               return "?";
+       }
+}
+
+
 static void tls_msg_cb(int write_p, int version, int content_type,
                       const void *buf, size_t len, SSL *ssl, void *arg)
 {
        struct tls_connection *conn = arg;
        const u8 *pos = buf;
 
-       wpa_printf(MSG_DEBUG, "OpenSSL: %s ver=0x%x content_type=%d",
-                  write_p ? "TX" : "RX", version, content_type);
+       if (write_p == 2) {
+               wpa_printf(MSG_DEBUG,
+                          "OpenSSL: session ver=0x%x content_type=%d",
+                          version, content_type);
+               wpa_hexdump_key(MSG_MSGDUMP, "OpenSSL: Data", buf, len);
+               return;
+       }
+
+       wpa_printf(MSG_DEBUG, "OpenSSL: %s ver=0x%x content_type=%d (%s/%s)",
+                  write_p ? "TX" : "RX", version, content_type,
+                  openssl_content_type(content_type),
+                  openssl_handshake_type(content_type, buf, len));
        wpa_hexdump_key(MSG_MSGDUMP, "OpenSSL: Message", buf, len);
        if (content_type == 24 && len >= 3 && pos[0] == 1) {
                size_t payload_len = WPA_GET_BE16(pos + 1);
@@ -1035,18 +1335,16 @@ static void tls_msg_cb(int write_p, int version, int content_type,
 
 struct tls_connection * tls_connection_init(void *ssl_ctx)
 {
-       SSL_CTX *ssl = ssl_ctx;
+       struct tls_data *data = ssl_ctx;
+       SSL_CTX *ssl = data->ssl;
        struct tls_connection *conn;
        long options;
-#ifdef OPENSSL_SUPPORTS_CTX_APP_DATA
        struct tls_context *context = SSL_CTX_get_app_data(ssl);
-#else /* OPENSSL_SUPPORTS_CTX_APP_DATA */
-       struct tls_context *context = tls_global;
-#endif /* OPENSSL_SUPPORTS_CTX_APP_DATA */
 
        conn = os_zalloc(sizeof(*conn));
        if (conn == NULL)
                return NULL;
+       conn->ssl_ctx = ssl;
        conn->ssl = SSL_new(ssl);
        if (conn->ssl == NULL) {
                tls_show_errors(MSG_INFO, __func__,
@@ -1095,11 +1393,20 @@ void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
 {
        if (conn == NULL)
                return;
+       if (conn->success_data) {
+               /*
+                * Make sure ssl_clear_bad_session() does not remove this
+                * session.
+                */
+               SSL_set_quiet_shutdown(conn->ssl, 1);
+               SSL_shutdown(conn->ssl);
+       }
        SSL_free(conn->ssl);
        tls_engine_deinit(conn);
        os_free(conn->subject_match);
        os_free(conn->altsubject_match);
        os_free(conn->suffix_match);
+       os_free(conn->domain_match);
        os_free(conn->session_ticket);
        os_free(conn);
 }
@@ -1121,7 +1428,7 @@ int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
         * and "close notify" shutdown alert would confuse AS. */
        SSL_set_quiet_shutdown(conn->ssl, 1);
        SSL_shutdown(conn->ssl);
-       return 0;
+       return SSL_clear(conn->ssl) == 1 ? 0 : -1;
 }
 
 
@@ -1144,6 +1451,8 @@ static int tls_match_altsubject_component(X509 *cert, int type,
                        found++;
        }
 
+       sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
+
        return found;
 }
 
@@ -1192,7 +1501,8 @@ static int tls_match_altsubject(X509 *cert, const char *match)
 
 
 #ifndef CONFIG_NATIVE_WINDOWS
-static int domain_suffix_match(const u8 *val, size_t len, const char *match)
+static int domain_suffix_match(const u8 *val, size_t len, const char *match,
+                              int full)
 {
        size_t i, match_len;
 
@@ -1205,7 +1515,7 @@ static int domain_suffix_match(const u8 *val, size_t len, const char *match)
        }
 
        match_len = os_strlen(match);
-       if (match_len > len)
+       if (match_len > len || (full && match_len != len))
                return 0;
 
        if (os_strncasecmp((const char *) val + len - match_len, match,
@@ -1224,7 +1534,7 @@ static int domain_suffix_match(const u8 *val, size_t len, const char *match)
 #endif /* CONFIG_NATIVE_WINDOWS */
 
 
-static int tls_match_suffix(X509 *cert, const char *match)
+static int tls_match_suffix(X509 *cert, const char *match, int full)
 {
 #ifdef CONFIG_NATIVE_WINDOWS
        /* wincrypt.h has conflicting X509_NAME definition */
@@ -1237,7 +1547,8 @@ static int tls_match_suffix(X509 *cert, const char *match)
        int dns_name = 0;
        X509_NAME *name;
 
-       wpa_printf(MSG_DEBUG, "TLS: Match domain against suffix %s", match);
+       wpa_printf(MSG_DEBUG, "TLS: Match domain against %s%s",
+                  full ? "": "suffix ", match);
 
        ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
 
@@ -1250,11 +1561,15 @@ static int tls_match_suffix(X509 *cert, const char *match)
                                  gen->d.dNSName->data,
                                  gen->d.dNSName->length);
                if (domain_suffix_match(gen->d.dNSName->data,
-                                       gen->d.dNSName->length, match) == 1) {
-                       wpa_printf(MSG_DEBUG, "TLS: Suffix match in dNSName found");
+                                       gen->d.dNSName->length, match, full) ==
+                   1) {
+                       wpa_printf(MSG_DEBUG, "TLS: %s in dNSName found",
+                                  full ? "Match" : "Suffix match");
+                       sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
                        return 1;
                }
        }
+       sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
 
        if (dns_name) {
                wpa_printf(MSG_DEBUG, "TLS: None of the dNSName(s) matched");
@@ -1278,13 +1593,16 @@ static int tls_match_suffix(X509 *cert, const char *match)
                        continue;
                wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate commonName",
                                  cn->data, cn->length);
-               if (domain_suffix_match(cn->data, cn->length, match) == 1) {
-                       wpa_printf(MSG_DEBUG, "TLS: Suffix match in commonName found");
+               if (domain_suffix_match(cn->data, cn->length, match, full) == 1)
+               {
+                       wpa_printf(MSG_DEBUG, "TLS: %s in commonName found",
+                                  full ? "Match" : "Suffix match");
                        return 1;
                }
        }
 
-       wpa_printf(MSG_DEBUG, "TLS: No CommonName suffix match found");
+       wpa_printf(MSG_DEBUG, "TLS: No CommonName %smatch found",
+                  full ? "": "suffix ");
        return 0;
 #endif /* CONFIG_NATIVE_WINDOWS */
 }
@@ -1379,6 +1697,11 @@ static void openssl_tls_cert_event(struct tls_connection *conn,
        struct wpabuf *cert = NULL;
        union tls_event_data ev;
        struct tls_context *context = conn->context;
+       char *altsubject[TLS_MAX_ALT_SUBJECT];
+       int alt, num_altsubject = 0;
+       GENERAL_NAME *gen;
+       void *ext;
+       stack_index_t i;
 #ifdef CONFIG_SHA256
        u8 hash[32];
 #endif /* CONFIG_SHA256 */
@@ -1387,7 +1710,8 @@ static void openssl_tls_cert_event(struct tls_connection *conn,
                return;
 
        os_memset(&ev, 0, sizeof(ev));
-       if (conn->cert_probe || context->cert_in_cb) {
+       if (conn->cert_probe || (conn->flags & TLS_CONN_EXT_CERT_CHECK) ||
+           context->cert_in_cb) {
                cert = get_x509_cert(err_cert);
                ev.peer_cert.cert = cert;
        }
@@ -1405,8 +1729,53 @@ static void openssl_tls_cert_event(struct tls_connection *conn,
 #endif /* CONFIG_SHA256 */
        ev.peer_cert.depth = depth;
        ev.peer_cert.subject = subject;
+
+       ext = X509_get_ext_d2i(err_cert, NID_subject_alt_name, NULL, NULL);
+       for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
+               char *pos;
+
+               if (num_altsubject == TLS_MAX_ALT_SUBJECT)
+                       break;
+               gen = sk_GENERAL_NAME_value(ext, i);
+               if (gen->type != GEN_EMAIL &&
+                   gen->type != GEN_DNS &&
+                   gen->type != GEN_URI)
+                       continue;
+
+               pos = os_malloc(10 + gen->d.ia5->length + 1);
+               if (pos == NULL)
+                       break;
+               altsubject[num_altsubject++] = pos;
+
+               switch (gen->type) {
+               case GEN_EMAIL:
+                       os_memcpy(pos, "EMAIL:", 6);
+                       pos += 6;
+                       break;
+               case GEN_DNS:
+                       os_memcpy(pos, "DNS:", 4);
+                       pos += 4;
+                       break;
+               case GEN_URI:
+                       os_memcpy(pos, "URI:", 4);
+                       pos += 4;
+                       break;
+               }
+
+               os_memcpy(pos, gen->d.ia5->data, gen->d.ia5->length);
+               pos += gen->d.ia5->length;
+               *pos = '\0';
+       }
+       sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
+
+       for (alt = 0; alt < num_altsubject; alt++)
+               ev.peer_cert.altsubject[alt] = altsubject[alt];
+       ev.peer_cert.num_altsubject = num_altsubject;
+
        context->event_cb(context->cb_ctx, TLS_PEER_CERTIFICATE, &ev);
        wpabuf_free(cert);
+       for (alt = 0; alt < num_altsubject; alt++)
+               os_free(altsubject[alt]);
 }
 
 
@@ -1418,7 +1787,7 @@ static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
        SSL *ssl;
        struct tls_connection *conn;
        struct tls_context *context;
-       char *match, *altmatch, *suffix_match;
+       char *match, *altmatch, *suffix_match, *domain_match;
        const char *err_str;
 
        err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
@@ -1446,6 +1815,7 @@ static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
        match = conn->subject_match;
        altmatch = conn->altsubject_match;
        suffix_match = conn->suffix_match;
+       domain_match = conn->domain_match;
 
        if (!preverify_ok && !conn->ca_cert_verify)
                preverify_ok = 1;
@@ -1462,7 +1832,11 @@ static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
        err_str = X509_verify_cert_error_string(err);
 
 #ifdef CONFIG_SHA256
-       if (preverify_ok && depth == 0 && conn->server_cert_only) {
+       /*
+        * Do not require preverify_ok so we can explicity allow otherwise
+        * invalid pinned server certificates.
+        */
+       if (depth == 0 && conn->server_cert_only) {
                struct wpabuf *cert;
                cert = get_x509_cert(err_cert);
                if (!cert) {
@@ -1480,6 +1854,14 @@ static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
                                err_str = "Server certificate mismatch";
                                err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
                                preverify_ok = 0;
+                       } else if (!preverify_ok) {
+                               /*
+                                * Certificate matches pinned certificate, allow
+                                * regardless of other problems.
+                                */
+                               wpa_printf(MSG_DEBUG,
+                                          "OpenSSL: Ignore validation issues for a pinned server certificate");
+                               preverify_ok = 1;
                        }
                        wpabuf_free(cert);
                }
@@ -1515,13 +1897,21 @@ static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
                                       "AltSubject mismatch",
                                       TLS_FAIL_ALTSUBJECT_MISMATCH);
        } else if (depth == 0 && suffix_match &&
-                  !tls_match_suffix(err_cert, suffix_match)) {
+                  !tls_match_suffix(err_cert, suffix_match, 0)) {
                wpa_printf(MSG_WARNING, "TLS: Domain suffix match '%s' not found",
                           suffix_match);
                preverify_ok = 0;
                openssl_tls_fail_event(conn, err_cert, err, depth, buf,
                                       "Domain suffix mismatch",
                                       TLS_FAIL_DOMAIN_SUFFIX_MISMATCH);
+       } else if (depth == 0 && domain_match &&
+                  !tls_match_suffix(err_cert, domain_match, 1)) {
+               wpa_printf(MSG_WARNING, "TLS: Domain match '%s' not found",
+                          domain_match);
+               preverify_ok = 0;
+               openssl_tls_fail_event(conn, err_cert, err, depth, buf,
+                                      "Domain mismatch",
+                                      TLS_FAIL_DOMAIN_MISMATCH);
        } else
                openssl_tls_cert_event(conn, err_cert, depth, buf);
 
@@ -1534,7 +1924,33 @@ static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
                                       TLS_FAIL_SERVER_CHAIN_PROBE);
        }
 
-       if (preverify_ok && context->event_cb != NULL)
+#ifdef OPENSSL_IS_BORINGSSL
+       if (depth == 0 && (conn->flags & TLS_CONN_REQUEST_OCSP) &&
+           preverify_ok) {
+               enum ocsp_result res;
+
+               res = check_ocsp_resp(conn->ssl_ctx, conn->ssl, err_cert,
+                                     conn->peer_issuer,
+                                     conn->peer_issuer_issuer);
+               if (res == OCSP_REVOKED) {
+                       preverify_ok = 0;
+                       openssl_tls_fail_event(conn, err_cert, err, depth, buf,
+                                              "certificate revoked",
+                                              TLS_FAIL_REVOKED);
+                       if (err == X509_V_OK)
+                               X509_STORE_CTX_set_error(
+                                       x509_ctx, X509_V_ERR_CERT_REVOKED);
+               } else if (res != OCSP_GOOD &&
+                          (conn->flags & TLS_CONN_REQUIRE_OCSP)) {
+                       preverify_ok = 0;
+                       openssl_tls_fail_event(conn, err_cert, err, depth, buf,
+                                              "bad certificate status response",
+                                              TLS_FAIL_UNSPECIFIED);
+               }
+       }
+#endif /* OPENSSL_IS_BORINGSSL */
+
+       if (depth == 0 && preverify_ok && context->event_cb != NULL)
                context->event_cb(context->cb_ctx,
                                  TLS_CERT_CHAIN_SUCCESS, NULL);
 
@@ -1543,13 +1959,13 @@ static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
 
 
 #ifndef OPENSSL_NO_STDIO
-static int tls_load_ca_der(void *_ssl_ctx, const char *ca_cert)
+static int tls_load_ca_der(struct tls_data *data, const char *ca_cert)
 {
-       SSL_CTX *ssl_ctx = _ssl_ctx;
+       SSL_CTX *ssl_ctx = data->ssl;
        X509_LOOKUP *lookup;
        int ret = 0;
 
-       lookup = X509_STORE_add_lookup(ssl_ctx->cert_store,
+       lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(ssl_ctx),
                                       X509_LOOKUP_file());
        if (lookup == NULL) {
                tls_show_errors(MSG_WARNING, __func__,
@@ -1575,23 +1991,25 @@ static int tls_load_ca_der(void *_ssl_ctx, const char *ca_cert)
 #endif /* OPENSSL_NO_STDIO */
 
 
-static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
+static int tls_connection_ca_cert(struct tls_data *data,
+                                 struct tls_connection *conn,
                                  const char *ca_cert, const u8 *ca_cert_blob,
                                  size_t ca_cert_blob_len, const char *ca_path)
 {
-       SSL_CTX *ssl_ctx = _ssl_ctx;
+       SSL_CTX *ssl_ctx = data->ssl;
+       X509_STORE *store;
 
        /*
         * Remove previously configured trusted CA certificates before adding
         * new ones.
         */
-       X509_STORE_free(ssl_ctx->cert_store);
-       ssl_ctx->cert_store = X509_STORE_new();
-       if (ssl_ctx->cert_store == NULL) {
+       store = X509_STORE_new();
+       if (store == NULL) {
                wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
                           "certificate store", __func__);
                return -1;
        }
+       SSL_CTX_set_cert_store(ssl_ctx, store);
 
        SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
        conn->ca_cert_verify = 1;
@@ -1635,7 +2053,8 @@ static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
        }
 
        if (ca_cert_blob) {
-               X509 *cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ca_cert_blob,
+               X509 *cert = d2i_X509(NULL,
+                                     (const unsigned char **) &ca_cert_blob,
                                      ca_cert_blob_len);
                if (cert == NULL) {
                        tls_show_errors(MSG_WARNING, __func__,
@@ -1643,7 +2062,8 @@ static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
                        return -1;
                }
 
-               if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
+               if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx),
+                                        cert)) {
                        unsigned long err = ERR_peek_error();
                        tls_show_errors(MSG_WARNING, __func__,
                                        "Failed to add ca_cert_blob to "
@@ -1666,30 +2086,40 @@ static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
        }
 
 #ifdef ANDROID
+       /* Single alias */
        if (ca_cert && os_strncmp("keystore://", ca_cert, 11) == 0) {
-               BIO *bio = BIO_from_keystore(&ca_cert[11]);
-               STACK_OF(X509_INFO) *stack = NULL;
-               stack_index_t i;
-
-               if (bio) {
-                       stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
-                       BIO_free(bio);
-               }
-               if (!stack)
+               if (tls_add_ca_from_keystore(SSL_CTX_get_cert_store(ssl_ctx),
+                                            &ca_cert[11]) < 0)
                        return -1;
+               SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
+               return 0;
+       }
 
-               for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
-                       X509_INFO *info = sk_X509_INFO_value(stack, i);
-                       if (info->x509) {
-                               X509_STORE_add_cert(ssl_ctx->cert_store,
-                                                   info->x509);
-                       }
-                       if (info->crl) {
-                               X509_STORE_add_crl(ssl_ctx->cert_store,
-                                                  info->crl);
+       /* Multiple aliases separated by space */
+       if (ca_cert && os_strncmp("keystores://", ca_cert, 12) == 0) {
+               char *aliases = os_strdup(&ca_cert[12]);
+               const char *delim = " ";
+               int rc = 0;
+               char *savedptr;
+               char *alias;
+
+               if (!aliases)
+                       return -1;
+               alias = strtok_r(aliases, delim, &savedptr);
+               for (; alias; alias = strtok_r(NULL, delim, &savedptr)) {
+                       if (tls_add_ca_from_keystore_encoded(
+                                   SSL_CTX_get_cert_store(ssl_ctx), alias)) {
+                               wpa_printf(MSG_WARNING,
+                                          "OpenSSL: %s - Failed to add ca_cert %s from keystore",
+                                          __func__, alias);
+                               rc = -1;
+                               break;
                        }
                }
-               sk_X509_INFO_pop_free(stack, X509_INFO_free);
+               os_free(aliases);
+               if (rc)
+                       return rc;
+
                SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
                return 0;
        }
@@ -1711,7 +2141,7 @@ static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
                        tls_show_errors(MSG_WARNING, __func__,
                                        "Failed to load root certificates");
                        if (ca_cert &&
-                           tls_load_ca_der(ssl_ctx, ca_cert) == 0) {
+                           tls_load_ca_der(data, ca_cert) == 0) {
                                wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
                                           "DER format CA certificate",
                                           __func__);
@@ -1720,7 +2150,7 @@ static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
                } else {
                        wpa_printf(MSG_DEBUG, "TLS: Trusted root "
                                   "certificate(s) loaded");
-                       tls_get_errors(ssl_ctx);
+                       tls_get_errors(data);
                }
 #else /* OPENSSL_NO_STDIO */
                wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
@@ -1737,8 +2167,10 @@ static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
 }
 
 
-static int tls_global_ca_cert(SSL_CTX *ssl_ctx, const char *ca_cert)
+static int tls_global_ca_cert(struct tls_data *data, const char *ca_cert)
 {
+       SSL_CTX *ssl_ctx = data->ssl;
+
        if (ca_cert) {
                if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
                {
@@ -1766,7 +2198,8 @@ int tls_global_set_verify(void *ssl_ctx, int check_crl)
        int flags;
 
        if (check_crl) {
-               X509_STORE *cs = SSL_CTX_get_cert_store(ssl_ctx);
+               struct tls_data *data = ssl_ctx;
+               X509_STORE *cs = SSL_CTX_get_cert_store(data->ssl);
                if (cs == NULL) {
                        tls_show_errors(MSG_INFO, __func__, "Failed to get "
                                        "certificate store when enabling "
@@ -1785,7 +2218,8 @@ int tls_global_set_verify(void *ssl_ctx, int check_crl)
 static int tls_connection_set_subject_match(struct tls_connection *conn,
                                            const char *subject_match,
                                            const char *altsubject_match,
-                                           const char *suffix_match)
+                                           const char *suffix_match,
+                                           const char *domain_match)
 {
        os_free(conn->subject_match);
        conn->subject_match = NULL;
@@ -1811,14 +2245,54 @@ static int tls_connection_set_subject_match(struct tls_connection *conn,
                        return -1;
        }
 
+       os_free(conn->domain_match);
+       conn->domain_match = NULL;
+       if (domain_match) {
+               conn->domain_match = os_strdup(domain_match);
+               if (conn->domain_match == NULL)
+                       return -1;
+       }
+
        return 0;
 }
 
 
+static void tls_set_conn_flags(SSL *ssl, unsigned int flags)
+{
+#ifdef SSL_OP_NO_TICKET
+       if (flags & TLS_CONN_DISABLE_SESSION_TICKET)
+               SSL_set_options(ssl, SSL_OP_NO_TICKET);
+       else
+               SSL_clear_options(ssl, SSL_OP_NO_TICKET);
+#endif /* SSL_OP_NO_TICKET */
+
+#ifdef SSL_OP_NO_TLSv1
+       if (flags & TLS_CONN_DISABLE_TLSv1_0)
+               SSL_set_options(ssl, SSL_OP_NO_TLSv1);
+       else
+               SSL_clear_options(ssl, SSL_OP_NO_TLSv1);
+#endif /* SSL_OP_NO_TLSv1 */
+#ifdef SSL_OP_NO_TLSv1_1
+       if (flags & TLS_CONN_DISABLE_TLSv1_1)
+               SSL_set_options(ssl, SSL_OP_NO_TLSv1_1);
+       else
+               SSL_clear_options(ssl, SSL_OP_NO_TLSv1_1);
+#endif /* SSL_OP_NO_TLSv1_1 */
+#ifdef SSL_OP_NO_TLSv1_2
+       if (flags & TLS_CONN_DISABLE_TLSv1_2)
+               SSL_set_options(ssl, SSL_OP_NO_TLSv1_2);
+       else
+               SSL_clear_options(ssl, SSL_OP_NO_TLSv1_2);
+#endif /* SSL_OP_NO_TLSv1_2 */
+}
+
+
 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
-                             int verify_peer)
+                             int verify_peer, unsigned int flags,
+                             const u8 *session_ctx, size_t session_ctx_len)
 {
        static int counter = 0;
+       struct tls_data *data = ssl_ctx;
 
        if (conn == NULL)
                return -1;
@@ -1833,20 +2307,25 @@ int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
                SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
        }
 
+       tls_set_conn_flags(conn->ssl, flags);
+       conn->flags = flags;
+
        SSL_set_accept_state(conn->ssl);
 
-       /*
-        * Set session id context in order to avoid fatal errors when client
-        * tries to resume a session. However, set the context to a unique
-        * value in order to effectively disable session resumption for now
-        * since not all areas of the server code are ready for it (e.g.,
-        * EAP-TTLS needs special handling for Phase 2 after abbreviated TLS
-        * handshake).
-        */
-       counter++;
-       SSL_set_session_id_context(conn->ssl,
-                                  (const unsigned char *) &counter,
-                                  sizeof(counter));
+       if (data->tls_session_lifetime == 0) {
+               /*
+                * Set session id context to a unique value to make sure
+                * session resumption cannot be used either through session
+                * caching or TLS ticket extension.
+                */
+               counter++;
+               SSL_set_session_id_context(conn->ssl,
+                                          (const unsigned char *) &counter,
+                                          sizeof(counter));
+       } else if (session_ctx) {
+               SSL_set_session_id_context(conn->ssl, session_ctx,
+                                          session_ctx_len);
+       }
 
        return 0;
 }
@@ -1860,6 +2339,17 @@ static int tls_connection_client_cert(struct tls_connection *conn,
        if (client_cert == NULL && client_cert_blob == NULL)
                return 0;
 
+#ifdef PKCS12_FUNCS
+#if OPENSSL_VERSION_NUMBER < 0x10002000L || defined(LIBRESSL_VERSION_NUMBER)
+       /*
+        * Clear previously set extra chain certificates, if any, from PKCS#12
+        * processing in tls_parse_pkcs12() to allow OpenSSL to build a new
+        * chain properly.
+        */
+       SSL_CTX_clear_extra_chain_certs(conn->ssl_ctx);
+#endif /* OPENSSL_VERSION_NUMBER < 0x10002000L */
+#endif /* PKCS12_FUNCS */
+
        if (client_cert_blob &&
            SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
                                     client_cert_blob_len) == 1) {
@@ -1881,13 +2371,24 @@ static int tls_connection_client_cert(struct tls_connection *conn,
                int ret = -1;
                if (bio) {
                        x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
-                       BIO_free(bio);
                }
                if (x509) {
                        if (SSL_use_certificate(conn->ssl, x509) == 1)
                                ret = 0;
                        X509_free(x509);
                }
+
+               /* Read additional certificates into the chain. */
+               while (bio) {
+                       x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
+                       if (x509) {
+                               /* Takes ownership of x509 */
+                               SSL_add0_chain_cert(conn->ssl, x509);
+                       } else {
+                               BIO_free(bio);
+                               bio = NULL;
+                       }
+               }
                return ret;
        }
 #endif /* ANDROID */
@@ -1918,9 +2419,12 @@ static int tls_connection_client_cert(struct tls_connection *conn,
 }
 
 
-static int tls_global_client_cert(SSL_CTX *ssl_ctx, const char *client_cert)
+static int tls_global_client_cert(struct tls_data *data,
+                                 const char *client_cert)
 {
 #ifndef OPENSSL_NO_STDIO
+       SSL_CTX *ssl_ctx = data->ssl;
+
        if (client_cert == NULL)
                return 0;
 
@@ -1954,7 +2458,7 @@ static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
 
 
 #ifdef PKCS12_FUNCS
-static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
+static int tls_parse_pkcs12(struct tls_data *data, SSL *ssl, PKCS12 *p12,
                            const char *passwd)
 {
        EVP_PKEY *pkey;
@@ -1966,6 +2470,8 @@ static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
        pkey = NULL;
        cert = NULL;
        certs = NULL;
+       if (!passwd)
+               passwd = "";
        if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
                tls_show_errors(MSG_DEBUG, __func__,
                                "Failed to parse PKCS12 file");
@@ -1983,7 +2489,7 @@ static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
                        if (SSL_use_certificate(ssl, cert) != 1)
                                res = -1;
                } else {
-                       if (SSL_CTX_use_certificate(ssl_ctx, cert) != 1)
+                       if (SSL_CTX_use_certificate(data->ssl, cert) != 1)
                                res = -1;
                }
                X509_free(cert);
@@ -1995,13 +2501,64 @@ static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
                        if (SSL_use_PrivateKey(ssl, pkey) != 1)
                                res = -1;
                } else {
-                       if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1)
+                       if (SSL_CTX_use_PrivateKey(data->ssl, pkey) != 1)
                                res = -1;
                }
                EVP_PKEY_free(pkey);
        }
 
        if (certs) {
+#if OPENSSL_VERSION_NUMBER >= 0x10002000L && !defined(LIBRESSL_VERSION_NUMBER)
+               if (ssl)
+                       SSL_clear_chain_certs(ssl);
+               else
+                       SSL_CTX_clear_chain_certs(data->ssl);
+               while ((cert = sk_X509_pop(certs)) != NULL) {
+                       X509_NAME_oneline(X509_get_subject_name(cert), buf,
+                                         sizeof(buf));
+                       wpa_printf(MSG_DEBUG, "TLS: additional certificate"
+                                  " from PKCS12: subject='%s'", buf);
+                       if ((ssl && SSL_add1_chain_cert(ssl, cert) != 1) ||
+                           (!ssl && SSL_CTX_add1_chain_cert(data->ssl,
+                                                            cert) != 1)) {
+                               tls_show_errors(MSG_DEBUG, __func__,
+                                               "Failed to add additional certificate");
+                               res = -1;
+                               X509_free(cert);
+                               break;
+                       }
+                       X509_free(cert);
+               }
+               if (!res) {
+                       /* Try to continue anyway */
+               }
+               sk_X509_pop_free(certs, X509_free);
+#ifndef OPENSSL_IS_BORINGSSL
+               if (ssl)
+                       res = SSL_build_cert_chain(
+                               ssl,
+                               SSL_BUILD_CHAIN_FLAG_CHECK |
+                               SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR);
+               else
+                       res = SSL_CTX_build_cert_chain(
+                               data->ssl,
+                               SSL_BUILD_CHAIN_FLAG_CHECK |
+                               SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR);
+               if (!res) {
+                       tls_show_errors(MSG_DEBUG, __func__,
+                                       "Failed to build certificate chain");
+               } else if (res == 2) {
+                       wpa_printf(MSG_DEBUG,
+                                  "TLS: Ignore certificate chain verification error when building chain with PKCS#12 extra certificates");
+               }
+#endif /* OPENSSL_IS_BORINGSSL */
+               /*
+                * Try to continue regardless of result since it is possible for
+                * the extra certificates not to be required.
+                */
+               res = 0;
+#else /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
+               SSL_CTX_clear_extra_chain_certs(data->ssl);
                while ((cert = sk_X509_pop(certs)) != NULL) {
                        X509_NAME_oneline(X509_get_subject_name(cert), buf,
                                          sizeof(buf));
@@ -2011,26 +2568,29 @@ static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
                         * There is no SSL equivalent for the chain cert - so
                         * always add it to the context...
                         */
-                       if (SSL_CTX_add_extra_chain_cert(ssl_ctx, cert) != 1) {
+                       if (SSL_CTX_add_extra_chain_cert(data->ssl, cert) != 1)
+                       {
+                               X509_free(cert);
                                res = -1;
                                break;
                        }
                }
-               sk_X509_free(certs);
+               sk_X509_pop_free(certs, X509_free);
+#endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
        }
 
        PKCS12_free(p12);
 
        if (res < 0)
-               tls_get_errors(ssl_ctx);
+               tls_get_errors(data);
 
        return res;
 }
 #endif  /* PKCS12_FUNCS */
 
 
-static int tls_read_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, const char *private_key,
-                          const char *passwd)
+static int tls_read_pkcs12(struct tls_data *data, SSL *ssl,
+                          const char *private_key, const char *passwd)
 {
 #ifdef PKCS12_FUNCS
        FILE *f;
@@ -2049,7 +2609,7 @@ static int tls_read_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, const char *private_key,
                return -1;
        }
 
-       return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
+       return tls_parse_pkcs12(data, ssl, p12, passwd);
 
 #else /* PKCS12_FUNCS */
        wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
@@ -2059,20 +2619,20 @@ static int tls_read_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, const char *private_key,
 }
 
 
-static int tls_read_pkcs12_blob(SSL_CTX *ssl_ctx, SSL *ssl,
+static int tls_read_pkcs12_blob(struct tls_data *data, SSL *ssl,
                                const u8 *blob, size_t len, const char *passwd)
 {
 #ifdef PKCS12_FUNCS
        PKCS12 *p12;
 
-       p12 = d2i_PKCS12(NULL, (OPENSSL_d2i_TYPE) &blob, len);
+       p12 = d2i_PKCS12(NULL, (const unsigned char **) &blob, len);
        if (p12 == NULL) {
                tls_show_errors(MSG_INFO, __func__,
                                "Failed to use PKCS#12 blob");
                return -1;
        }
 
-       return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
+       return tls_parse_pkcs12(data, ssl, p12, passwd);
 
 #else /* PKCS12_FUNCS */
        wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
@@ -2097,9 +2657,13 @@ static int tls_engine_get_cert(struct tls_connection *conn,
 
        if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
                             0, &params, NULL, 1)) {
+               unsigned long err = ERR_get_error();
+
                wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
                           " '%s' [%s]", cert_id,
-                          ERR_error_string(ERR_get_error(), NULL));
+                          ERR_error_string(err, NULL));
+               if (tls_is_pin_error(err))
+                       return TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
                return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
        }
        if (!params.cert) {
@@ -2139,27 +2703,28 @@ static int tls_connection_engine_client_cert(struct tls_connection *conn,
 }
 
 
-static int tls_connection_engine_ca_cert(void *_ssl_ctx,
+static int tls_connection_engine_ca_cert(struct tls_data *data,
                                         struct tls_connection *conn,
                                         const char *ca_cert_id)
 {
 #ifndef OPENSSL_NO_ENGINE
        X509 *cert;
-       SSL_CTX *ssl_ctx = _ssl_ctx;
+       SSL_CTX *ssl_ctx = data->ssl;
+       X509_STORE *store;
 
        if (tls_engine_get_cert(conn, ca_cert_id, &cert))
                return -1;
 
        /* start off the same as tls_connection_ca_cert */
-       X509_STORE_free(ssl_ctx->cert_store);
-       ssl_ctx->cert_store = X509_STORE_new();
-       if (ssl_ctx->cert_store == NULL) {
+       store = X509_STORE_new();
+       if (store == NULL) {
                wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
                           "certificate store", __func__);
                X509_free(cert);
                return -1;
        }
-       if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
+       SSL_CTX_set_cert_store(ssl_ctx, store);
+       if (!X509_STORE_add_cert(store, cert)) {
                unsigned long err = ERR_peek_error();
                tls_show_errors(MSG_WARNING, __func__,
                                "Failed to add CA certificate from engine "
@@ -2190,7 +2755,7 @@ static int tls_connection_engine_ca_cert(void *_ssl_ctx,
 
 static int tls_connection_engine_private_key(struct tls_connection *conn)
 {
-#ifndef OPENSSL_NO_ENGINE
+#if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
        if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
                tls_show_errors(MSG_ERROR, __func__,
                                "ENGINE: cannot use private key for TLS");
@@ -2210,14 +2775,14 @@ static int tls_connection_engine_private_key(struct tls_connection *conn)
 }
 
 
-static int tls_connection_private_key(void *_ssl_ctx,
+static int tls_connection_private_key(struct tls_data *data,
                                      struct tls_connection *conn,
                                      const char *private_key,
                                      const char *private_key_passwd,
                                      const u8 *private_key_blob,
                                      size_t private_key_blob_len)
 {
-       SSL_CTX *ssl_ctx = _ssl_ctx;
+       SSL_CTX *ssl_ctx = data->ssl;
        char *passwd;
        int ok;
 
@@ -2263,7 +2828,7 @@ static int tls_connection_private_key(void *_ssl_ctx,
                        break;
                }
 
-               if (tls_read_pkcs12_blob(ssl_ctx, conn->ssl, private_key_blob,
+               if (tls_read_pkcs12_blob(data, conn->ssl, private_key_blob,
                                         private_key_blob_len, passwd) == 0) {
                        wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
                                   "OK");
@@ -2296,7 +2861,7 @@ static int tls_connection_private_key(void *_ssl_ctx,
                           __func__);
 #endif /* OPENSSL_NO_STDIO */
 
-               if (tls_read_pkcs12(ssl_ctx, conn->ssl, private_key, passwd)
+               if (tls_read_pkcs12(data, conn->ssl, private_key, passwd)
                    == 0) {
                        wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
                                   "--> OK");
@@ -2335,9 +2900,11 @@ static int tls_connection_private_key(void *_ssl_ctx,
 }
 
 
-static int tls_global_private_key(SSL_CTX *ssl_ctx, const char *private_key,
+static int tls_global_private_key(struct tls_data *data,
+                                 const char *private_key,
                                  const char *private_key_passwd)
 {
+       SSL_CTX *ssl_ctx = data->ssl;
        char *passwd;
 
        if (private_key == NULL)
@@ -2359,7 +2926,7 @@ static int tls_global_private_key(SSL_CTX *ssl_ctx, const char *private_key,
            SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
                                        SSL_FILETYPE_PEM) != 1 &&
 #endif /* OPENSSL_NO_STDIO */
-           tls_read_pkcs12(ssl_ctx, NULL, private_key, passwd)) {
+           tls_read_pkcs12(data, NULL, private_key, passwd)) {
                tls_show_errors(MSG_INFO, __func__,
                                "Failed to load private key");
                os_free(passwd);
@@ -2454,7 +3021,7 @@ static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
 }
 
 
-static int tls_global_dh(SSL_CTX *ssl_ctx, const char *dh_file)
+static int tls_global_dh(struct tls_data *data, const char *dh_file)
 {
 #ifdef OPENSSL_NO_DH
        if (dh_file == NULL)
@@ -2463,6 +3030,7 @@ static int tls_global_dh(SSL_CTX *ssl_ctx, const char *dh_file)
                   "dh_file specified");
        return -1;
 #else /* OPENSSL_NO_DH */
+       SSL_CTX *ssl_ctx = data->ssl;
        DH *dh;
        BIO *bio;
 
@@ -2528,53 +3096,175 @@ static int tls_global_dh(SSL_CTX *ssl_ctx, const char *dh_file)
 }
 
 
-int tls_connection_get_keys(void *ssl_ctx, struct tls_connection *conn,
-                           struct tls_keys *keys)
+int tls_connection_get_random(void *ssl_ctx, struct tls_connection *conn,
+                             struct tls_random *keys)
 {
-#ifdef CONFIG_FIPS
-       wpa_printf(MSG_ERROR, "OpenSSL: TLS keys cannot be exported in FIPS "
-                  "mode");
-       return -1;
-#else /* CONFIG_FIPS */
        SSL *ssl;
 
        if (conn == NULL || keys == NULL)
                return -1;
        ssl = conn->ssl;
-       if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
+       if (ssl == NULL)
                return -1;
 
        os_memset(keys, 0, sizeof(*keys));
-       keys->master_key = ssl->session->master_key;
-       keys->master_key_len = ssl->session->master_key_length;
-       keys->client_random = ssl->s3->client_random;
-       keys->client_random_len = SSL3_RANDOM_SIZE;
-       keys->server_random = ssl->s3->server_random;
-       keys->server_random_len = SSL3_RANDOM_SIZE;
+       keys->client_random = conn->client_random;
+       keys->client_random_len = SSL_get_client_random(
+               ssl, conn->client_random, sizeof(conn->client_random));
+       keys->server_random = conn->server_random;
+       keys->server_random_len = SSL_get_server_random(
+               ssl, conn->server_random, sizeof(conn->server_random));
 
        return 0;
-#endif /* CONFIG_FIPS */
 }
 
 
-int tls_connection_prf(void *tls_ctx, struct tls_connection *conn,
-                      const char *label, int server_random_first,
-                      u8 *out, size_t out_len)
+#ifdef OPENSSL_NEED_EAP_FAST_PRF
+static int openssl_get_keyblock_size(SSL *ssl)
 {
-#if OPENSSL_VERSION_NUMBER >= 0x10001000L
+#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
+       const EVP_CIPHER *c;
+       const EVP_MD *h;
+       int md_size;
+
+       if (ssl->enc_read_ctx == NULL || ssl->enc_read_ctx->cipher == NULL ||
+           ssl->read_hash == NULL)
+               return -1;
+
+       c = ssl->enc_read_ctx->cipher;
+       h = EVP_MD_CTX_md(ssl->read_hash);
+       if (h)
+               md_size = EVP_MD_size(h);
+       else if (ssl->s3)
+               md_size = ssl->s3->tmp.new_mac_secret_size;
+       else
+               return -1;
+
+       wpa_printf(MSG_DEBUG, "OpenSSL: keyblock size: key_len=%d MD_size=%d "
+                  "IV_len=%d", EVP_CIPHER_key_length(c), md_size,
+                  EVP_CIPHER_iv_length(c));
+       return 2 * (EVP_CIPHER_key_length(c) +
+                   md_size +
+                   EVP_CIPHER_iv_length(c));
+#else
+       const SSL_CIPHER *ssl_cipher;
+       int cipher, digest;
+       const EVP_CIPHER *c;
+       const EVP_MD *h;
+
+       ssl_cipher = SSL_get_current_cipher(ssl);
+       if (!ssl_cipher)
+               return -1;
+       cipher = SSL_CIPHER_get_cipher_nid(ssl_cipher);
+       digest = SSL_CIPHER_get_digest_nid(ssl_cipher);
+       wpa_printf(MSG_DEBUG, "OpenSSL: cipher nid %d digest nid %d",
+                  cipher, digest);
+       if (cipher < 0 || digest < 0)
+               return -1;
+       c = EVP_get_cipherbynid(cipher);
+       h = EVP_get_digestbynid(digest);
+       if (!c || !h)
+               return -1;
+
+       wpa_printf(MSG_DEBUG,
+                  "OpenSSL: keyblock size: key_len=%d MD_size=%d IV_len=%d",
+                  EVP_CIPHER_key_length(c), EVP_MD_size(h),
+                  EVP_CIPHER_iv_length(c));
+       return 2 * (EVP_CIPHER_key_length(c) + EVP_MD_size(h) +
+                   EVP_CIPHER_iv_length(c));
+#endif
+}
+#endif /* OPENSSL_NEED_EAP_FAST_PRF */
+
+
+int tls_connection_export_key(void *tls_ctx, struct tls_connection *conn,
+                             const char *label, u8 *out, size_t out_len)
+{
+       if (!conn ||
+           SSL_export_keying_material(conn->ssl, out, out_len, label,
+                                      os_strlen(label), NULL, 0, 0) != 1)
+               return -1;
+       return 0;
+}
+
+
+int tls_connection_get_eap_fast_key(void *tls_ctx, struct tls_connection *conn,
+                                   u8 *out, size_t out_len)
+{
+#ifdef OPENSSL_NEED_EAP_FAST_PRF
        SSL *ssl;
+       SSL_SESSION *sess;
+       u8 *rnd;
+       int ret = -1;
+       int skip = 0;
+       u8 *tmp_out = NULL;
+       u8 *_out = out;
+       unsigned char client_random[SSL3_RANDOM_SIZE];
+       unsigned char server_random[SSL3_RANDOM_SIZE];
+       unsigned char master_key[64];
+       size_t master_key_len;
+       const char *ver;
+
+       /*
+        * TLS library did not support EAP-FAST key generation, so get the
+        * needed TLS session parameters and use an internal implementation of
+        * TLS PRF to derive the key.
+        */
+
        if (conn == NULL)
                return -1;
-       if (server_random_first)
-               return -1;
        ssl = conn->ssl;
-       if (SSL_export_keying_material(ssl, out, out_len, label,
-                                      os_strlen(label), NULL, 0, 0) == 1) {
-               wpa_printf(MSG_DEBUG, "OpenSSL: Using internal PRF");
-               return 0;
+       if (ssl == NULL)
+               return -1;
+       ver = SSL_get_version(ssl);
+       sess = SSL_get_session(ssl);
+       if (!ver || !sess)
+               return -1;
+
+       skip = openssl_get_keyblock_size(ssl);
+       if (skip < 0)
+               return -1;
+       tmp_out = os_malloc(skip + out_len);
+       if (!tmp_out)
+               return -1;
+       _out = tmp_out;
+
+       rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
+       if (!rnd) {
+               os_free(tmp_out);
+               return -1;
        }
-#endif
+
+       SSL_get_client_random(ssl, client_random, sizeof(client_random));
+       SSL_get_server_random(ssl, server_random, sizeof(server_random));
+       master_key_len = SSL_SESSION_get_master_key(sess, master_key,
+                                                   sizeof(master_key));
+
+       os_memcpy(rnd, server_random, SSL3_RANDOM_SIZE);
+       os_memcpy(rnd + SSL3_RANDOM_SIZE, client_random, SSL3_RANDOM_SIZE);
+
+       if (os_strcmp(ver, "TLSv1.2") == 0) {
+               tls_prf_sha256(master_key, master_key_len,
+                              "key expansion", rnd, 2 * SSL3_RANDOM_SIZE,
+                              _out, skip + out_len);
+               ret = 0;
+       } else if (tls_prf_sha1_md5(master_key, master_key_len,
+                                   "key expansion", rnd, 2 * SSL3_RANDOM_SIZE,
+                                   _out, skip + out_len) == 0) {
+               ret = 0;
+       }
+       os_memset(master_key, 0, sizeof(master_key));
+       os_free(rnd);
+       if (ret == 0)
+               os_memcpy(out, _out + skip, out_len);
+       bin_clear_free(tmp_out, skip);
+
+       return ret;
+#else /* OPENSSL_NEED_EAP_FAST_PRF */
+       wpa_printf(MSG_ERROR,
+                  "OpenSSL: EAP-FAST keys cannot be exported in FIPS mode");
        return -1;
+#endif /* OPENSSL_NEED_EAP_FAST_PRF */
 }
 
 
@@ -2589,7 +3279,7 @@ openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data,
         * Give TLS handshake data from the server (if available) to OpenSSL
         * for processing.
         */
-       if (in_data &&
+       if (in_data && wpabuf_len(in_data) > 0 &&
            BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
            < 0) {
                tls_show_errors(MSG_INFO, __func__,
@@ -2701,8 +3391,14 @@ openssl_connection_handshake(struct tls_connection *conn,
                return NULL;
        }
 
-       if (SSL_is_init_finished(conn->ssl) && appl_data && in_data)
-               *appl_data = openssl_get_appl_data(conn, wpabuf_len(in_data));
+       if (SSL_is_init_finished(conn->ssl)) {
+               wpa_printf(MSG_DEBUG,
+                          "OpenSSL: Handshake finished - resumed=%d",
+                          tls_connection_resumed(conn->ssl_ctx, conn));
+               if (appl_data && in_data)
+                       *appl_data = openssl_get_appl_data(conn,
+                                                          wpabuf_len(in_data));
+       }
 
        if (conn->invalid_hb_used) {
                wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
@@ -2827,14 +3523,14 @@ struct wpabuf * tls_connection_decrypt(void *tls_ctx,
 
 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
 {
-       return conn ? conn->ssl->hit : 0;
+       return conn ? SSL_cache_hit(conn->ssl) : 0;
 }
 
 
 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
                                   u8 *ciphers)
 {
-       char buf[100], *pos, *end;
+       char buf[500], *pos, *end;
        u8 *c;
        int ret;
 
@@ -2862,6 +3558,12 @@ int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
                case TLS_CIPHER_ANON_DH_AES128_SHA:
                        suite = "ADH-AES128-SHA";
                        break;
+               case TLS_CIPHER_RSA_DHE_AES256_SHA:
+                       suite = "DHE-RSA-AES256-SHA";
+                       break;
+               case TLS_CIPHER_AES256_SHA:
+                       suite = "AES256-SHA";
+                       break;
                default:
                        wpa_printf(MSG_DEBUG, "TLS: Unsupported "
                                   "cipher selection: %d", *c);
@@ -2877,6 +3579,21 @@ int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
 
        wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
 
+#if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
+#if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
+       if (os_strstr(buf, ":ADH-")) {
+               /*
+                * Need to drop to security level 0 to allow anonymous
+                * cipher suites for EAP-FAST.
+                */
+               SSL_set_security_level(conn->ssl, 0);
+       } else if (SSL_get_security_level(conn->ssl) == 0) {
+               /* Force at least security level 1 */
+               SSL_set_security_level(conn->ssl, 1);
+       }
+#endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
+#endif
+
        if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
                tls_show_errors(MSG_INFO, __func__,
                                "Cipher suite configuration failed");
@@ -2887,6 +3604,22 @@ int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
 }
 
 
+int tls_get_version(void *ssl_ctx, struct tls_connection *conn,
+                   char *buf, size_t buflen)
+{
+       const char *name;
+       if (conn == NULL || conn->ssl == NULL)
+               return -1;
+
+       name = SSL_get_version(conn->ssl);
+       if (name == NULL)
+               return -1;
+
+       os_strlcpy(buf, name, buflen);
+       return 0;
+}
+
+
 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
                   char *buf, size_t buflen)
 {
@@ -2923,15 +3656,9 @@ int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
        if (conn == NULL || conn->ssl == NULL || ext_type != 35)
                return -1;
 
-#ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
        if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
                                       data_len) != 1)
                return -1;
-#else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
-       if (SSL_set_hello_extension(conn->ssl, ext_type, (void *) data,
-                                   data_len) != 1)
-               return -1;
-#endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
 
        return 0;
 }
@@ -3074,13 +3801,13 @@ static int ocsp_resp_cb(SSL *s, void *arg)
                return 0;
        }
 
-       store = SSL_CTX_get_cert_store(s->ctx);
+       store = SSL_CTX_get_cert_store(conn->ssl_ctx);
        if (conn->peer_issuer) {
                debug_print_cert(conn->peer_issuer, "Add OCSP issuer");
 
                if (X509_STORE_add_cert(store, conn->peer_issuer) != 1) {
                        tls_show_errors(MSG_INFO, __func__,
-                                       "OpenSSL: Could not add issuer to certificate store\n");
+                                       "OpenSSL: Could not add issuer to certificate store");
                }
                certs = sk_X509_new_null();
                if (certs) {
@@ -3089,17 +3816,17 @@ static int ocsp_resp_cb(SSL *s, void *arg)
                        if (cert && !sk_X509_push(certs, cert)) {
                                tls_show_errors(
                                        MSG_INFO, __func__,
-                                       "OpenSSL: Could not add issuer to OCSP responder trust store\n");
+                                       "OpenSSL: Could not add issuer to OCSP responder trust store");
                                X509_free(cert);
                                sk_X509_free(certs);
                                certs = NULL;
                        }
-                       if (conn->peer_issuer_issuer) {
+                       if (certs && conn->peer_issuer_issuer) {
                                cert = X509_dup(conn->peer_issuer_issuer);
                                if (cert && !sk_X509_push(certs, cert)) {
                                        tls_show_errors(
                                                MSG_INFO, __func__,
-                                               "OpenSSL: Could not add issuer to OCSP responder trust store\n");
+                                               "OpenSSL: Could not add issuer's issuer to OCSP responder trust store");
                                        X509_free(cert);
                                }
                        }
@@ -3145,10 +3872,12 @@ static int ocsp_resp_cb(SSL *s, void *arg)
                wpa_printf(MSG_INFO, "OpenSSL: Could not find current server certificate from OCSP response%s",
                           (conn->flags & TLS_CONN_REQUIRE_OCSP) ? "" :
                           " (OCSP not required)");
+               OCSP_CERTID_free(id);
                OCSP_BASICRESP_free(basic);
                OCSP_RESPONSE_free(rsp);
                return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
        }
+       OCSP_CERTID_free(id);
 
        if (!OCSP_check_validity(this_update, next_update, 5 * 60, -1)) {
                tls_show_errors(MSG_INFO, __func__,
@@ -3215,54 +3944,109 @@ static int ocsp_status_cb(SSL *s, void *arg)
 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
                              const struct tls_connection_params *params)
 {
+       struct tls_data *data = tls_ctx;
        int ret;
        unsigned long err;
+       int can_pkcs11 = 0;
+       const char *key_id = params->key_id;
+       const char *cert_id = params->cert_id;
+       const char *ca_cert_id = params->ca_cert_id;
+       const char *engine_id = params->engine ? params->engine_id : NULL;
 
        if (conn == NULL)
                return -1;
 
+       if (params->flags & TLS_CONN_REQUIRE_OCSP_ALL) {
+               wpa_printf(MSG_INFO,
+                          "OpenSSL: ocsp=3 not supported");
+               return -1;
+       }
+
+       /*
+        * If the engine isn't explicitly configured, and any of the
+        * cert/key fields are actually PKCS#11 URIs, then automatically
+        * use the PKCS#11 ENGINE.
+        */
+       if (!engine_id || os_strcmp(engine_id, "pkcs11") == 0)
+               can_pkcs11 = 1;
+
+       if (!key_id && params->private_key && can_pkcs11 &&
+           os_strncmp(params->private_key, "pkcs11:", 7) == 0) {
+               can_pkcs11 = 2;
+               key_id = params->private_key;
+       }
+
+       if (!cert_id && params->client_cert && can_pkcs11 &&
+           os_strncmp(params->client_cert, "pkcs11:", 7) == 0) {
+               can_pkcs11 = 2;
+               cert_id = params->client_cert;
+       }
+
+       if (!ca_cert_id && params->ca_cert && can_pkcs11 &&
+           os_strncmp(params->ca_cert, "pkcs11:", 7) == 0) {
+               can_pkcs11 = 2;
+               ca_cert_id = params->ca_cert;
+       }
+
+       /* If we need to automatically enable the PKCS#11 ENGINE, do so. */
+       if (can_pkcs11 == 2 && !engine_id)
+               engine_id = "pkcs11";
+
+#if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
+#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
+       if (params->flags & TLS_CONN_EAP_FAST) {
+               wpa_printf(MSG_DEBUG,
+                          "OpenSSL: Use TLSv1_method() for EAP-FAST");
+               if (SSL_set_ssl_method(conn->ssl, TLSv1_method()) != 1) {
+                       tls_show_errors(MSG_INFO, __func__,
+                                       "Failed to set TLSv1_method() for EAP-FAST");
+                       return -1;
+               }
+       }
+#endif
+#endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
+
        while ((err = ERR_get_error())) {
                wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
                           __func__, ERR_error_string(err, NULL));
        }
 
-       if (params->engine) {
+       if (engine_id) {
                wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
-               ret = tls_engine_init(conn, params->engine_id, params->pin,
-                                     params->key_id, params->cert_id,
-                                     params->ca_cert_id);
+               ret = tls_engine_init(conn, engine_id, params->pin,
+                                     key_id, cert_id, ca_cert_id);
                if (ret)
                        return ret;
        }
        if (tls_connection_set_subject_match(conn,
                                             params->subject_match,
                                             params->altsubject_match,
-                                            params->suffix_match))
+                                            params->suffix_match,
+                                            params->domain_match))
                return -1;
 
-       if (params->engine && params->ca_cert_id) {
-               if (tls_connection_engine_ca_cert(tls_ctx, conn,
-                                                 params->ca_cert_id))
+       if (engine_id && ca_cert_id) {
+               if (tls_connection_engine_ca_cert(data, conn, ca_cert_id))
                        return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
-       } else if (tls_connection_ca_cert(tls_ctx, conn, params->ca_cert,
+       } else if (tls_connection_ca_cert(data, conn, params->ca_cert,
                                          params->ca_cert_blob,
                                          params->ca_cert_blob_len,
                                          params->ca_path))
                return -1;
 
-       if (params->engine && params->cert_id) {
-               if (tls_connection_engine_client_cert(conn, params->cert_id))
+       if (engine_id && cert_id) {
+               if (tls_connection_engine_client_cert(conn, cert_id))
                        return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
        } else if (tls_connection_client_cert(conn, params->client_cert,
                                              params->client_cert_blob,
                                              params->client_cert_blob_len))
                return -1;
 
-       if (params->engine && params->key_id) {
+       if (engine_id && key_id) {
                wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
                if (tls_connection_engine_private_key(conn))
                        return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
-       } else if (tls_connection_private_key(tls_ctx, conn,
+       } else if (tls_connection_private_key(data, conn,
                                              params->private_key,
                                              params->private_key_passwd,
                                              params->private_key_blob,
@@ -3286,40 +4070,36 @@ int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
                return -1;
        }
 
-#ifdef SSL_OP_NO_TICKET
-       if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
-               SSL_set_options(conn->ssl, SSL_OP_NO_TICKET);
-#ifdef SSL_clear_options
-       else
-               SSL_clear_options(conn->ssl, SSL_OP_NO_TICKET);
-#endif /* SSL_clear_options */
-#endif /*  SSL_OP_NO_TICKET */
-
-#ifdef SSL_OP_NO_TLSv1_1
-       if (params->flags & TLS_CONN_DISABLE_TLSv1_1)
-               SSL_set_options(conn->ssl, SSL_OP_NO_TLSv1_1);
-       else
-               SSL_clear_options(conn->ssl, SSL_OP_NO_TLSv1_1);
-#endif /* SSL_OP_NO_TLSv1_1 */
-#ifdef SSL_OP_NO_TLSv1_2
-       if (params->flags & TLS_CONN_DISABLE_TLSv1_2)
-               SSL_set_options(conn->ssl, SSL_OP_NO_TLSv1_2);
-       else
-               SSL_clear_options(conn->ssl, SSL_OP_NO_TLSv1_2);
-#endif /* SSL_OP_NO_TLSv1_2 */
+       tls_set_conn_flags(conn->ssl, params->flags);
 
+#ifdef OPENSSL_IS_BORINGSSL
+       if (params->flags & TLS_CONN_REQUEST_OCSP) {
+               SSL_enable_ocsp_stapling(conn->ssl);
+       }
+#else /* OPENSSL_IS_BORINGSSL */
 #ifdef HAVE_OCSP
        if (params->flags & TLS_CONN_REQUEST_OCSP) {
-               SSL_CTX *ssl_ctx = tls_ctx;
+               SSL_CTX *ssl_ctx = data->ssl;
                SSL_set_tlsext_status_type(conn->ssl, TLSEXT_STATUSTYPE_ocsp);
                SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
                SSL_CTX_set_tlsext_status_arg(ssl_ctx, conn);
        }
+#else /* HAVE_OCSP */
+       if (params->flags & TLS_CONN_REQUIRE_OCSP) {
+               wpa_printf(MSG_INFO,
+                          "OpenSSL: No OCSP support included - reject configuration");
+               return -1;
+       }
+       if (params->flags & TLS_CONN_REQUEST_OCSP) {
+               wpa_printf(MSG_DEBUG,
+                          "OpenSSL: No OCSP support included - allow optional OCSP case to continue");
+       }
 #endif /* HAVE_OCSP */
+#endif /* OPENSSL_IS_BORINGSSL */
 
        conn->flags = params->flags;
 
-       tls_get_errors(tls_ctx);
+       tls_get_errors(data);
 
        return 0;
 }
@@ -3328,7 +4108,8 @@ int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
 int tls_global_set_params(void *tls_ctx,
                          const struct tls_connection_params *params)
 {
-       SSL_CTX *ssl_ctx = tls_ctx;
+       struct tls_data *data = tls_ctx;
+       SSL_CTX *ssl_ctx = data->ssl;
        unsigned long err;
 
        while ((err = ERR_get_error())) {
@@ -3336,19 +4117,12 @@ int tls_global_set_params(void *tls_ctx,
                           __func__, ERR_error_string(err, NULL));
        }
 
-       if (tls_global_ca_cert(ssl_ctx, params->ca_cert))
-               return -1;
-
-       if (tls_global_client_cert(ssl_ctx, params->client_cert))
-               return -1;
-
-       if (tls_global_private_key(ssl_ctx, params->private_key,
-                                  params->private_key_passwd))
-               return -1;
-
-       if (tls_global_dh(ssl_ctx, params->dh_file)) {
-               wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
-                          params->dh_file);
+       if (tls_global_ca_cert(data, params->ca_cert) ||
+           tls_global_client_cert(data, params->client_cert) ||
+           tls_global_private_key(data, params->private_key,
+                                  params->private_key_passwd) ||
+           tls_global_dh(data, params->dh_file)) {
+               wpa_printf(MSG_INFO, "TLS: Failed to set global parameters");
                return -1;
        }
 
@@ -3363,10 +4137,8 @@ int tls_global_set_params(void *tls_ctx,
 #ifdef SSL_OP_NO_TICKET
        if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
                SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
-#ifdef SSL_CTX_clear_options
        else
                SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TICKET);
-#endif /* SSL_clear_options */
 #endif /*  SSL_OP_NO_TICKET */
 
 #ifdef HAVE_OCSP
@@ -3384,55 +4156,12 @@ int tls_global_set_params(void *tls_ctx,
 }
 
 
-int tls_connection_get_keyblock_size(void *tls_ctx,
-                                    struct tls_connection *conn)
-{
-       const EVP_CIPHER *c;
-       const EVP_MD *h;
-       int md_size;
-
-       if (conn == NULL || conn->ssl == NULL ||
-           conn->ssl->enc_read_ctx == NULL ||
-           conn->ssl->enc_read_ctx->cipher == NULL ||
-           conn->ssl->read_hash == NULL)
-               return -1;
-
-       c = conn->ssl->enc_read_ctx->cipher;
-#if OPENSSL_VERSION_NUMBER >= 0x00909000L
-       h = EVP_MD_CTX_md(conn->ssl->read_hash);
-#else
-       h = conn->ssl->read_hash;
-#endif
-       if (h)
-               md_size = EVP_MD_size(h);
-#if OPENSSL_VERSION_NUMBER >= 0x10000000L
-       else if (conn->ssl->s3)
-               md_size = conn->ssl->s3->tmp.new_mac_secret_size;
-#endif
-       else
-               return -1;
-
-       wpa_printf(MSG_DEBUG, "OpenSSL: keyblock size: key_len=%d MD_size=%d "
-                  "IV_len=%d", EVP_CIPHER_key_length(c), md_size,
-                  EVP_CIPHER_iv_length(c));
-       return 2 * (EVP_CIPHER_key_length(c) +
-                   md_size +
-                   EVP_CIPHER_iv_length(c));
-}
-
-
-unsigned int tls_capabilities(void *tls_ctx)
-{
-       return 0;
-}
-
-
 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
 /* Pre-shared secred requires a patch to openssl, so this function is
  * commented out unless explicitly needed for EAP-FAST in order to be able to
  * build this file with unmodified openssl. */
 
-#ifdef OPENSSL_IS_BORINGSSL
+#if (defined(OPENSSL_IS_BORINGSSL) || OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
                           STACK_OF(SSL_CIPHER) *peer_ciphers,
                           const SSL_CIPHER **cipher, void *arg)
@@ -3445,6 +4174,7 @@ static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
        struct tls_connection *conn = arg;
        int ret;
 
+#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
        if (conn == NULL || conn->session_ticket_cb == NULL)
                return 0;
 
@@ -3453,6 +4183,23 @@ static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
                                      conn->session_ticket_len,
                                      s->s3->client_random,
                                      s->s3->server_random, secret);
+#else
+       unsigned char client_random[SSL3_RANDOM_SIZE];
+       unsigned char server_random[SSL3_RANDOM_SIZE];
+
+       if (conn == NULL || conn->session_ticket_cb == NULL)
+               return 0;
+
+       SSL_get_client_random(s, client_random, sizeof(client_random));
+       SSL_get_server_random(s, server_random, sizeof(server_random));
+
+       ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
+                                     conn->session_ticket,
+                                     conn->session_ticket_len,
+                                     client_random,
+                                     server_random, secret);
+#endif
+
        os_free(conn->session_ticket);
        conn->session_ticket = NULL;
 
@@ -3464,7 +4211,6 @@ static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
 }
 
 
-#ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
 static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
                                     int len, void *arg)
 {
@@ -3481,71 +4227,14 @@ static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
        wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
                    "extension", data, len);
 
-       conn->session_ticket = os_malloc(len);
+       conn->session_ticket = os_memdup(data, len);
        if (conn->session_ticket == NULL)
                return 0;
 
-       os_memcpy(conn->session_ticket, data, len);
        conn->session_ticket_len = len;
 
        return 1;
 }
-#else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
-#ifdef SSL_OP_NO_TICKET
-static void tls_hello_ext_cb(SSL *s, int client_server, int type,
-                            unsigned char *data, int len, void *arg)
-{
-       struct tls_connection *conn = arg;
-
-       if (conn == NULL || conn->session_ticket_cb == NULL)
-               return;
-
-       wpa_printf(MSG_DEBUG, "OpenSSL: %s: type=%d length=%d", __func__,
-                  type, len);
-
-       if (type == TLSEXT_TYPE_session_ticket && !client_server) {
-               os_free(conn->session_ticket);
-               conn->session_ticket = NULL;
-
-               wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
-                           "extension", data, len);
-               conn->session_ticket = os_malloc(len);
-               if (conn->session_ticket == NULL)
-                       return;
-
-               os_memcpy(conn->session_ticket, data, len);
-               conn->session_ticket_len = len;
-       }
-}
-#else /* SSL_OP_NO_TICKET */
-static int tls_hello_ext_cb(SSL *s, TLS_EXTENSION *ext, void *arg)
-{
-       struct tls_connection *conn = arg;
-
-       if (conn == NULL || conn->session_ticket_cb == NULL)
-               return 0;
-
-       wpa_printf(MSG_DEBUG, "OpenSSL: %s: type=%d length=%d", __func__,
-                  ext->type, ext->length);
-
-       os_free(conn->session_ticket);
-       conn->session_ticket = NULL;
-
-       if (ext->type == 35) {
-               wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
-                           "extension", ext->data, ext->length);
-               conn->session_ticket = os_malloc(ext->length);
-               if (conn->session_ticket == NULL)
-                       return SSL_AD_INTERNAL_ERROR;
-
-               os_memcpy(conn->session_ticket, ext->data, ext->length);
-               conn->session_ticket_len = ext->length;
-       }
-
-       return 0;
-}
-#endif /* SSL_OP_NO_TICKET */
-#endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
 
 
@@ -3562,33 +4251,12 @@ int tls_connection_set_session_ticket_cb(void *tls_ctx,
                if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
                                              conn) != 1)
                        return -1;
-#ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
                SSL_set_session_ticket_ext_cb(conn->ssl,
                                              tls_session_ticket_ext_cb, conn);
-#else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
-#ifdef SSL_OP_NO_TICKET
-               SSL_set_tlsext_debug_callback(conn->ssl, tls_hello_ext_cb);
-               SSL_set_tlsext_debug_arg(conn->ssl, conn);
-#else /* SSL_OP_NO_TICKET */
-               if (SSL_set_hello_extension_cb(conn->ssl, tls_hello_ext_cb,
-                                              conn) != 1)
-                       return -1;
-#endif /* SSL_OP_NO_TICKET */
-#endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
        } else {
                if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
                        return -1;
-#ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
                SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
-#else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
-#ifdef SSL_OP_NO_TICKET
-               SSL_set_tlsext_debug_callback(conn->ssl, NULL);
-               SSL_set_tlsext_debug_arg(conn->ssl, conn);
-#else /* SSL_OP_NO_TICKET */
-               if (SSL_set_hello_extension_cb(conn->ssl, NULL, NULL) != 1)
-                       return -1;
-#endif /* SSL_OP_NO_TICKET */
-#endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
        }
 
        return 0;
@@ -3596,3 +4264,84 @@ int tls_connection_set_session_ticket_cb(void *tls_ctx,
        return -1;
 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
 }
+
+
+int tls_get_library_version(char *buf, size_t buf_len)
+{
+#if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
+       return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
+                          OPENSSL_VERSION_TEXT,
+                          OpenSSL_version(OPENSSL_VERSION));
+#else
+       return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
+                          OPENSSL_VERSION_TEXT,
+                          SSLeay_version(SSLEAY_VERSION));
+#endif
+}
+
+
+void tls_connection_set_success_data(struct tls_connection *conn,
+                                    struct wpabuf *data)
+{
+       SSL_SESSION *sess;
+       struct wpabuf *old;
+
+       if (tls_ex_idx_session < 0)
+               goto fail;
+       sess = SSL_get_session(conn->ssl);
+       if (!sess)
+               goto fail;
+       old = SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
+       if (old) {
+               wpa_printf(MSG_DEBUG, "OpenSSL: Replacing old success data %p",
+                          old);
+               wpabuf_free(old);
+       }
+       if (SSL_SESSION_set_ex_data(sess, tls_ex_idx_session, data) != 1)
+               goto fail;
+
+       wpa_printf(MSG_DEBUG, "OpenSSL: Stored success data %p", data);
+       conn->success_data = 1;
+       return;
+
+fail:
+       wpa_printf(MSG_INFO, "OpenSSL: Failed to store success data");
+       wpabuf_free(data);
+}
+
+
+void tls_connection_set_success_data_resumed(struct tls_connection *conn)
+{
+       wpa_printf(MSG_DEBUG,
+                  "OpenSSL: Success data accepted for resumed session");
+       conn->success_data = 1;
+}
+
+
+const struct wpabuf *
+tls_connection_get_success_data(struct tls_connection *conn)
+{
+       SSL_SESSION *sess;
+
+       if (tls_ex_idx_session < 0 ||
+           !(sess = SSL_get_session(conn->ssl)))
+               return NULL;
+       return SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
+}
+
+
+void tls_connection_remove_session(struct tls_connection *conn)
+{
+       SSL_SESSION *sess;
+
+       sess = SSL_get_session(conn->ssl);
+       if (!sess)
+               return;
+
+       if (SSL_CTX_remove_session(conn->ssl_ctx, sess) != 1)
+               wpa_printf(MSG_DEBUG,
+                          "OpenSSL: Session was not cached");
+       else
+               wpa_printf(MSG_DEBUG,
+                          "OpenSSL: Removed cached session to disable session resumption");
+}